The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

268854 lines
7.9MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /********* Start of inlined file: juce_TargetPlatform.h *********/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. /** If defined, this indicates that the processor is little-endian. */
  68. #define JUCE_LITTLE_ENDIAN 1
  69. #define JUCE_INTEL 1
  70. #endif
  71. #if JUCE_MAC
  72. #ifndef NDEBUG
  73. #define JUCE_DEBUG 1
  74. #endif
  75. #ifdef __LITTLE_ENDIAN__
  76. #define JUCE_LITTLE_ENDIAN 1
  77. #else
  78. #define JUCE_BIG_ENDIAN 1
  79. #endif
  80. #if defined (__ppc__) || defined (__ppc64__)
  81. #define JUCE_PPC 1
  82. #else
  83. #define JUCE_INTEL 1
  84. #endif
  85. #ifdef __LP64__
  86. #define JUCE_64BIT 1
  87. #else
  88. #define JUCE_32BIT 1
  89. #endif
  90. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  91. #error "Building for OSX 10.2 is no longer supported!"
  92. #endif
  93. #if (! defined (MAC_OS_X_VERSION_10_4)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  94. #define MACOS_10_3_OR_EARLIER 1
  95. #endif
  96. #if (! defined (MAC_OS_X_VERSION_10_5)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  97. #define MACOS_10_4_OR_EARLIER 1
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /********* End of inlined file: juce_TargetPlatform.h *********/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /********* Start of inlined file: juce_Config.h *********/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  152. but if you define this value, you can override this can force it to be true or
  153. false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 1
  157. #endif
  158. /** If this flag is enabled, the the jassert and jassertfalse macros will
  159. always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. // #define JUCE_LOG_ASSERTIONS 1
  167. #endif
  168. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  169. which the ASIOAudioIODevice class can't be built. See the comments in the
  170. ASIOAudioIODevice class's header file for more info about this.
  171. (This only affects a Win32 build)
  172. */
  173. #ifndef JUCE_ASIO
  174. #define JUCE_ASIO 1
  175. #endif
  176. /** Comment out this macro to disable the Windows WASAPI audio device type.
  177. */
  178. #ifndef JUCE_WASAPI
  179. // #define JUCE_WASAPI 1
  180. #endif
  181. /** Comment out this macro to disable the Windows WASAPI audio device type.
  182. */
  183. #ifndef JUCE_DIRECTSOUND
  184. #define JUCE_DIRECTSOUND 1
  185. #endif
  186. /** Comment out this macro to disable building of ALSA device support on Linux.
  187. */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  192. have the SDK installed.
  193. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  194. classes will be unavailable.
  195. On Windows, if you enable this, you'll need to have the QuickTime SDK
  196. installed, and its header files will need to be on your include path.
  197. */
  198. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  199. #define JUCE_QUICKTIME 1
  200. #endif
  201. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  202. have the appropriate headers and libraries available. If it's not enabled, the
  203. OpenGLComponent class will be unavailable.
  204. */
  205. #ifndef JUCE_OPENGL
  206. #define JUCE_OPENGL 1
  207. #endif
  208. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  209. If you're not going to need either of these formats, turn off the flags to
  210. avoid bloating your codebase with them.
  211. */
  212. #ifndef JUCE_USE_FLAC
  213. #define JUCE_USE_FLAC 1
  214. #endif
  215. #ifndef JUCE_USE_OGGVORBIS
  216. #define JUCE_USE_OGGVORBIS 1
  217. #endif
  218. /** This flag lets you enable support for CD-burning. You might want to disable
  219. it to build without the MS SDK under windows.
  220. */
  221. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  222. #define JUCE_USE_CDBURNER 1
  223. #endif
  224. /** Enabling this provides support for cameras, using the CameraDevice class
  225. */
  226. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  227. // #define JUCE_USE_CAMERA 1
  228. #endif
  229. /** Enabling this macro means that all regions that get repainted will have a coloured
  230. line drawn around them.
  231. This is handy if you're trying to optimise drawing, because it lets you easily see
  232. when anything is being repainted unnecessarily.
  233. */
  234. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  235. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  236. #endif
  237. /** Enable this under Linux to use Xinerama for multi-monitor support.
  238. */
  239. #ifndef JUCE_USE_XINERAMA
  240. #define JUCE_USE_XINERAMA 1
  241. #endif
  242. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  243. */
  244. #ifndef JUCE_USE_XSHM
  245. #define JUCE_USE_XSHM 1
  246. #endif
  247. /** Enabling this builds support for VST audio plugins.
  248. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  249. */
  250. #ifndef JUCE_PLUGINHOST_VST
  251. // #define JUCE_PLUGINHOST_VST 1
  252. #endif
  253. /** Enabling this builds support for AudioUnit audio plugins.
  254. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  255. */
  256. #ifndef JUCE_PLUGINHOST_AU
  257. // #define JUCE_PLUGINHOST_AU 1
  258. #endif
  259. /** Enabling this will avoid including any UI code in the build. This is handy for
  260. writing command-line utilities, e.g. on linux boxes which don't have some
  261. of the UI libraries installed.
  262. */
  263. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  264. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  265. #endif
  266. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  267. */
  268. #ifndef JUCE_WEB_BROWSER
  269. #define JUCE_WEB_BROWSER 1
  270. #endif
  271. /** Setting this allows the build to use old Carbon libraries that will be
  272. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  273. reasons.
  274. */
  275. #ifndef JUCE_SUPPORT_CARBON
  276. #define JUCE_SUPPORT_CARBON 1
  277. #endif
  278. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  279. codebase - you might need to use this if you're linking to some of these libraries
  280. yourself.
  281. */
  282. #ifndef JUCE_INCLUDE_ZLIB_CODE
  283. #define JUCE_INCLUDE_ZLIB_CODE 1
  284. #endif
  285. #ifndef JUCE_INCLUDE_FLAC_CODE
  286. #define JUCE_INCLUDE_FLAC_CODE 1
  287. #endif
  288. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  289. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  290. #endif
  291. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  292. #define JUCE_INCLUDE_PNGLIB_CODE 1
  293. #endif
  294. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  295. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  296. #endif
  297. /** Enable this to add extra memory-leak info to the new and delete operators.
  298. (Currently, this only affects Windows builds in debug mode).
  299. */
  300. #ifndef JUCE_CHECK_MEMORY_LEAKS
  301. #define JUCE_CHECK_MEMORY_LEAKS 1
  302. #endif
  303. /** Enable this to turn on juce's internal catching of exceptions.
  304. Turning it off will avoid any exception catching. With it on, all exceptions
  305. are passed to the JUCEApplication::unhandledException() callback for logging.
  306. */
  307. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  308. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  309. #endif
  310. /** If this macro is set, the Juce String class will use unicode as its
  311. internal representation. If it isn't set, it'll use ANSI.
  312. */
  313. #ifndef JUCE_STRINGS_ARE_UNICODE
  314. #define JUCE_STRINGS_ARE_UNICODE 1
  315. #endif
  316. #endif
  317. /********* End of inlined file: juce_Config.h *********/
  318. // FORCE_AMALGAMATOR_INCLUDE
  319. //==============================================================================
  320. #if JUCE_WINDOWS
  321. /********* Start of inlined file: juce_win32_NativeIncludes.h *********/
  322. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  323. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  324. #ifndef STRICT
  325. #define STRICT 1
  326. #endif
  327. #undef WIN32_LEAN_AND_MEAN
  328. #define WIN32_LEAN_AND_MEAN 1
  329. #ifdef _MSC_VER
  330. #pragma warning (push)
  331. #pragma warning (disable : 4100 4201 4514 4312 4995)
  332. #endif
  333. #define _WIN32_WINNT 0x0500
  334. #define _UNICODE 1
  335. #define UNICODE 1
  336. #ifndef _WIN32_IE
  337. #define _WIN32_IE 0x0400
  338. #endif
  339. #include <windows.h>
  340. #include <windowsx.h>
  341. #include <commdlg.h>
  342. #include <shellapi.h>
  343. #include <mmsystem.h>
  344. #include <vfw.h>
  345. #include <tchar.h>
  346. #include <stddef.h>
  347. #include <ctime>
  348. #include <wininet.h>
  349. #include <nb30.h>
  350. #include <iphlpapi.h>
  351. #include <mapi.h>
  352. #include <float.h>
  353. #include <crtdbg.h>
  354. #include <process.h>
  355. #include <comutil.h>
  356. #include <Exdisp.h>
  357. #include <exdispid.h>
  358. #include <shlobj.h>
  359. #if JUCE_OPENGL
  360. #include <gl/gl.h>
  361. #endif
  362. #undef PACKED
  363. #if JUCE_ASIO
  364. /*
  365. This is very frustrating - we only need to use a handful of definitions from
  366. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  367. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  368. implementation...
  369. ..unfortunately that would break Steinberg's license agreement for use of
  370. their SDK, so I'm not allowed to do this.
  371. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  372. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  373. (see www.steinberg.net/Steinberg/Developers.asp).
  374. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  375. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  376. if you prefer). Make sure that your header search path will find the
  377. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  378. files are actually needed - so to simplify things, you could just copy
  379. these into your JUCE directory).
  380. If you're compiling and you get an error here because you don't have the
  381. ASIO SDK installed, you can disable ASIO support by commenting-out the
  382. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  383. */
  384. #include "iasiodrv.h"
  385. #endif
  386. #if JUCE_USE_CDBURNER
  387. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  388. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  389. flag in juce_Config.h to avoid these includes.
  390. */
  391. #include <imapi.h>
  392. #include <imapierror.h>
  393. #endif
  394. #if JUCE_USE_CAMERA
  395. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  396. Both of these files are provided in the normal Windows SDK, but some Microsoft plonker
  397. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK!
  398. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  399. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  400. .. which is a pathetic bodge, but a lot less hassle than installing the full DShow SDK.
  401. */
  402. #include <dshow.h>
  403. #include <qedit.h>
  404. #endif
  405. #if JUCE_WASAPI
  406. #include <MMReg.h>
  407. #include <mmdeviceapi.h>
  408. #include <Audioclient.h>
  409. #include <functiondiscoverykeys.h>
  410. #endif
  411. #if JUCE_QUICKTIME
  412. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  413. add its header directory to your include path.
  414. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  415. flag in juce_Config.h
  416. */
  417. #include <Movies.h>
  418. #include <QTML.h>
  419. #include <QuickTimeComponents.h>
  420. #include <MediaHandlers.h>
  421. #include <ImageCodec.h>
  422. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  423. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  424. your include search path to make these import statements work.
  425. */
  426. #import <QTOLibrary.dll>
  427. #import <QTOControl.dll>
  428. #endif
  429. #ifdef _MSC_VER
  430. #pragma warning (pop)
  431. #endif
  432. /** A simple COM smart pointer.
  433. Avoids having to include ATL just to get one of these.
  434. */
  435. template <class T>
  436. class ComSmartPtr
  437. {
  438. public:
  439. ComSmartPtr() throw() : p (0) {}
  440. ComSmartPtr (T* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  441. ComSmartPtr (const ComSmartPtr<T>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  442. ~ComSmartPtr() { if (p != 0) p->Release(); }
  443. operator T*() const throw() { return p; }
  444. T& operator*() const throw() { return *p; }
  445. T** operator&() throw() { return &p; }
  446. T* operator->() const throw() { return p; }
  447. T* operator= (T* const newP)
  448. {
  449. if (newP != 0)
  450. newP->AddRef();
  451. if (p != 0)
  452. p->Release();
  453. p = newP;
  454. return newP;
  455. }
  456. T* operator= (const ComSmartPtr<T>& newP) { return operator= (newP.p); }
  457. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext)
  458. {
  459. #ifndef __MINGW32__
  460. operator= (0);
  461. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof(T), (void**) &p);
  462. #else
  463. return S_FALSE;
  464. #endif
  465. }
  466. T* p;
  467. };
  468. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  469. /********* End of inlined file: juce_win32_NativeIncludes.h *********/
  470. #elif JUCE_LINUX
  471. /********* Start of inlined file: juce_linux_NativeIncludes.h *********/
  472. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  473. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  474. /*
  475. This file wraps together all the linux-specific headers, so
  476. that we can include them all just once, and compile all our
  477. platform-specific stuff in one big lump, keeping it out of the
  478. way of the rest of the codebase.
  479. */
  480. #include <sched.h>
  481. #include <pthread.h>
  482. #include <sys/time.h>
  483. #include <errno.h>
  484. #include <sys/stat.h>
  485. #include <sys/dir.h>
  486. #include <sys/ptrace.h>
  487. #include <sys/vfs.h>
  488. #include <sys/wait.h>
  489. #include <fnmatch.h>
  490. #include <utime.h>
  491. #include <pwd.h>
  492. #include <fcntl.h>
  493. #include <dlfcn.h>
  494. #include <netdb.h>
  495. #include <arpa/inet.h>
  496. #include <netinet/in.h>
  497. #include <sys/types.h>
  498. #include <sys/ioctl.h>
  499. #include <sys/socket.h>
  500. #include <linux/if.h>
  501. #include <sys/sysinfo.h>
  502. #include <sys/file.h>
  503. #include <signal.h>
  504. /* Got a build error here? You'll need to install the freetype library...
  505. The name of the package to install is "libfreetype6-dev".
  506. */
  507. #include <ft2build.h>
  508. #include FT_FREETYPE_H
  509. #include <X11/Xlib.h>
  510. #include <X11/Xatom.h>
  511. #include <X11/Xresource.h>
  512. #include <X11/Xutil.h>
  513. #include <X11/Xmd.h>
  514. #include <X11/keysym.h>
  515. #include <X11/cursorfont.h>
  516. #if JUCE_USE_XINERAMA
  517. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  518. #include <X11/extensions/Xinerama.h>
  519. #endif
  520. #if JUCE_USE_XSHM
  521. #include <X11/extensions/XShm.h>
  522. #include <sys/shm.h>
  523. #include <sys/ipc.h>
  524. #endif
  525. #if JUCE_OPENGL
  526. /* Got an include error here?
  527. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  528. and "freeglut3-dev".
  529. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  530. want to disable it.
  531. */
  532. #include <GL/glx.h>
  533. #endif
  534. #undef KeyPress
  535. #if JUCE_ALSA
  536. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  537. not got your paths set up correctly to find its header files.
  538. The package you need to install to get ASLA support is "libasound2-dev".
  539. If you don't have the ALSA library and don't want to build Juce with audio support,
  540. just disable the JUCE_ALSA flag in juce_Config.h
  541. */
  542. #include <alsa/asoundlib.h>
  543. #endif
  544. #undef SIZEOF
  545. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  546. /********* End of inlined file: juce_linux_NativeIncludes.h *********/
  547. #elif JUCE_MAC || JUCE_IPHONE
  548. /********* Start of inlined file: juce_mac_NativeIncludes.h *********/
  549. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  550. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  551. /*
  552. This file wraps together all the mac-specific code, so that
  553. we can include all the native headers just once, and compile all our
  554. platform-specific stuff in one big lump, keeping it out of the way of
  555. the rest of the codebase.
  556. */
  557. #if JUCE_IPHONE
  558. #import <Foundation/Foundation.h>
  559. #import <UIKit/UIKit.h>
  560. #import <AudioToolbox/AudioToolbox.h>
  561. #import <AVFoundation/AVFoundation.h>
  562. #import <CoreData/CoreData.h>
  563. #import <MobileCoreServices/MobileCoreServices.h>
  564. #include <sys/fcntl.h>
  565. #else
  566. #import <Cocoa/Cocoa.h>
  567. #import <CoreAudio/HostTime.h>
  568. #import <CoreAudio/AudioHardware.h>
  569. #import <CoreMIDI/MIDIServices.h>
  570. #import <QTKit/QTKit.h>
  571. #import <WebKit/WebKit.h>
  572. #import <DiscRecording/DiscRecording.h>
  573. #import <IOKit/IOKitLib.h>
  574. #import <IOKit/IOCFPlugIn.h>
  575. #import <IOKit/hid/IOHIDLib.h>
  576. #import <IOKit/hid/IOHIDKeys.h>
  577. #import <IOKit/pwr_mgt/IOPMLib.h>
  578. #include <sys/dir.h>
  579. #include <sys/socket.h>
  580. #endif
  581. #include <sys/sysctl.h>
  582. #include <sys/stat.h>
  583. #include <sys/param.h>
  584. #include <sys/mount.h>
  585. #include <fnmatch.h>
  586. #include <utime.h>
  587. #include <dlfcn.h>
  588. #include <ifaddrs.h>
  589. #include <net/if_dl.h>
  590. #include <mach/mach_time.h>
  591. #if MACOS_10_4_OR_EARLIER
  592. #include <GLUT/glut.h>
  593. typedef int NSInteger;
  594. typedef unsigned int NSUInteger;
  595. #endif
  596. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  597. /********* End of inlined file: juce_mac_NativeIncludes.h *********/
  598. #else
  599. #error "Unknown platform!"
  600. #endif
  601. //==============================================================================
  602. #define DONT_SET_USING_JUCE_NAMESPACE 1
  603. #include "juce_amalgamated.h"
  604. #define NO_DUMMY_DECL
  605. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  606. #pragma warning (disable: 4309 4305)
  607. #endif
  608. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  609. BEGIN_JUCE_NAMESPACE
  610. /********* Start of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  611. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  612. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  613. /**
  614. Creates a floating carbon window that can be used to hold a carbon UI.
  615. This is a handy class that's designed to be inlined where needed, e.g.
  616. in the audio plugin hosting code.
  617. */
  618. class CarbonViewWrapperComponent : public Component,
  619. public ComponentMovementWatcher,
  620. public Timer
  621. {
  622. public:
  623. CarbonViewWrapperComponent()
  624. : ComponentMovementWatcher (this),
  625. wrapperWindow (0),
  626. embeddedView (0),
  627. recursiveResize (false)
  628. {
  629. }
  630. virtual ~CarbonViewWrapperComponent()
  631. {
  632. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  633. }
  634. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  635. virtual void removeView (HIViewRef embeddedView) = 0;
  636. virtual void mouseDown (int x, int y) {}
  637. virtual void paint() {}
  638. virtual bool getEmbeddedViewSize (int& w, int& h)
  639. {
  640. if (embeddedView == 0)
  641. return false;
  642. HIRect bounds;
  643. HIViewGetBounds (embeddedView, &bounds);
  644. w = jmax (1, roundFloatToInt (bounds.size.width));
  645. h = jmax (1, roundFloatToInt (bounds.size.height));
  646. return true;
  647. }
  648. void createWindow()
  649. {
  650. if (wrapperWindow == 0)
  651. {
  652. Rect r;
  653. r.left = getScreenX();
  654. r.top = getScreenY();
  655. r.right = r.left + getWidth();
  656. r.bottom = r.top + getHeight();
  657. CreateNewWindow (kDocumentWindowClass,
  658. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  659. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  660. &r, &wrapperWindow);
  661. jassert (wrapperWindow != 0);
  662. if (wrapperWindow == 0)
  663. return;
  664. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  665. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  666. [ownerWindow addChildWindow: carbonWindow
  667. ordered: NSWindowAbove];
  668. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  669. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  670. { kEventClassWindow, kEventWindowHandleDeactivate } };
  671. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  672. InstallWindowEventHandler (wrapperWindow, upp,
  673. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  674. windowEventTypes, this, &eventHandlerRef);
  675. setOurSizeToEmbeddedViewSize();
  676. setEmbeddedWindowToOurSize();
  677. creationTime = Time::getCurrentTime();
  678. }
  679. }
  680. void deleteWindow()
  681. {
  682. removeView (embeddedView);
  683. embeddedView = 0;
  684. if (wrapperWindow != 0)
  685. {
  686. RemoveEventHandler (eventHandlerRef);
  687. DisposeWindow (wrapperWindow);
  688. wrapperWindow = 0;
  689. }
  690. }
  691. void setOurSizeToEmbeddedViewSize()
  692. {
  693. int w, h;
  694. if (getEmbeddedViewSize (w, h))
  695. {
  696. if (w != getWidth() || h != getHeight())
  697. {
  698. startTimer (50);
  699. setSize (w, h);
  700. if (getParentComponent() != 0)
  701. getParentComponent()->setSize (w, h);
  702. }
  703. else
  704. {
  705. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  706. }
  707. }
  708. else
  709. {
  710. stopTimer();
  711. }
  712. }
  713. void setEmbeddedWindowToOurSize()
  714. {
  715. if (! recursiveResize)
  716. {
  717. recursiveResize = true;
  718. if (embeddedView != 0)
  719. {
  720. HIRect r;
  721. r.origin.x = 0;
  722. r.origin.y = 0;
  723. r.size.width = (float) getWidth();
  724. r.size.height = (float) getHeight();
  725. HIViewSetFrame (embeddedView, &r);
  726. }
  727. if (wrapperWindow != 0)
  728. {
  729. Rect wr;
  730. wr.left = getScreenX();
  731. wr.top = getScreenY();
  732. wr.right = wr.left + getWidth();
  733. wr.bottom = wr.top + getHeight();
  734. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  735. ShowWindow (wrapperWindow);
  736. }
  737. recursiveResize = false;
  738. }
  739. }
  740. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  741. {
  742. setEmbeddedWindowToOurSize();
  743. }
  744. void componentPeerChanged()
  745. {
  746. deleteWindow();
  747. createWindow();
  748. }
  749. void componentVisibilityChanged (Component&)
  750. {
  751. if (isShowing())
  752. createWindow();
  753. else
  754. deleteWindow();
  755. setEmbeddedWindowToOurSize();
  756. }
  757. static void recursiveHIViewRepaint (HIViewRef view) throw()
  758. {
  759. HIViewSetNeedsDisplay (view, true);
  760. HIViewRef child = HIViewGetFirstSubview (view);
  761. while (child != 0)
  762. {
  763. recursiveHIViewRepaint (child);
  764. child = HIViewGetNextView (child);
  765. }
  766. }
  767. void timerCallback()
  768. {
  769. setOurSizeToEmbeddedViewSize();
  770. // To avoid strange overpainting problems when the UI is first opened, we'll
  771. // repaint it a few times during the first second that it's on-screen..
  772. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  773. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  774. }
  775. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  776. EventRef event)
  777. {
  778. switch (GetEventKind (event))
  779. {
  780. case kEventWindowHandleDeactivate:
  781. ActivateWindow (wrapperWindow, TRUE);
  782. break;
  783. case kEventWindowGetClickActivation:
  784. {
  785. getTopLevelComponent()->toFront (false);
  786. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  787. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  788. sizeof (ClickActivationResult), &howToHandleClick);
  789. HIViewSetNeedsDisplay (embeddedView, true);
  790. }
  791. break;
  792. }
  793. return noErr;
  794. }
  795. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  796. EventRef event, void* userData)
  797. {
  798. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  799. }
  800. protected:
  801. WindowRef wrapperWindow;
  802. HIViewRef embeddedView;
  803. bool recursiveResize;
  804. Time creationTime;
  805. EventHandlerRef eventHandlerRef;
  806. };
  807. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  808. /********* End of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  809. END_JUCE_NAMESPACE
  810. #endif
  811. #define JUCE_AMALGAMATED_TEMPLATE 1
  812. //==============================================================================
  813. /********* Start of inlined file: juce_FileLogger.cpp *********/
  814. BEGIN_JUCE_NAMESPACE
  815. FileLogger::FileLogger (const File& logFile_,
  816. const String& welcomeMessage,
  817. const int maxInitialFileSizeBytes)
  818. : logFile (logFile_)
  819. {
  820. if (maxInitialFileSizeBytes >= 0)
  821. trimFileSize (maxInitialFileSizeBytes);
  822. if (! logFile_.exists())
  823. {
  824. // do this so that the parent directories get created..
  825. logFile_.create();
  826. }
  827. logStream = logFile_.createOutputStream (256);
  828. jassert (logStream != 0);
  829. String welcome;
  830. welcome << "\r\n**********************************************************\r\n"
  831. << welcomeMessage
  832. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  833. << "\r\n";
  834. logMessage (welcome);
  835. }
  836. FileLogger::~FileLogger()
  837. {
  838. deleteAndZero (logStream);
  839. }
  840. void FileLogger::logMessage (const String& message)
  841. {
  842. if (logStream != 0)
  843. {
  844. Logger::outputDebugString (message);
  845. const ScopedLock sl (logLock);
  846. (*logStream) << message << T("\r\n");
  847. logStream->flush();
  848. }
  849. }
  850. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  851. {
  852. if (maxFileSizeBytes <= 0)
  853. {
  854. logFile.deleteFile();
  855. }
  856. else
  857. {
  858. const int64 fileSize = logFile.getSize();
  859. if (fileSize > maxFileSizeBytes)
  860. {
  861. FileInputStream* const in = logFile.createInputStream();
  862. jassert (in != 0);
  863. if (in != 0)
  864. {
  865. in->setPosition (fileSize - maxFileSizeBytes);
  866. String content;
  867. {
  868. MemoryBlock contentToSave;
  869. contentToSave.setSize (maxFileSizeBytes + 4);
  870. contentToSave.fillWith (0);
  871. in->read (contentToSave.getData(), maxFileSizeBytes);
  872. delete in;
  873. content = contentToSave.toString();
  874. }
  875. int newStart = 0;
  876. while (newStart < fileSize
  877. && content[newStart] != '\n'
  878. && content[newStart] != '\r')
  879. ++newStart;
  880. logFile.deleteFile();
  881. logFile.appendText (content.substring (newStart), false, false);
  882. }
  883. }
  884. }
  885. }
  886. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  887. const String& logFileName,
  888. const String& welcomeMessage,
  889. const int maxInitialFileSizeBytes)
  890. {
  891. #if JUCE_MAC
  892. File logFile ("~/Library/Logs");
  893. logFile = logFile.getChildFile (logFileName);
  894. #else
  895. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  896. if (logFile.isDirectory())
  897. {
  898. logFile = logFile.getChildFile (logFileSubDirectoryName)
  899. .getChildFile (logFileName);
  900. }
  901. #endif
  902. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  903. }
  904. END_JUCE_NAMESPACE
  905. /********* End of inlined file: juce_FileLogger.cpp *********/
  906. /********* Start of inlined file: juce_Logger.cpp *********/
  907. BEGIN_JUCE_NAMESPACE
  908. Logger::Logger()
  909. {
  910. }
  911. Logger::~Logger()
  912. {
  913. }
  914. static Logger* currentLogger = 0;
  915. void Logger::setCurrentLogger (Logger* const newLogger,
  916. const bool deleteOldLogger)
  917. {
  918. Logger* const oldLogger = currentLogger;
  919. currentLogger = newLogger;
  920. if (deleteOldLogger && (oldLogger != 0))
  921. delete oldLogger;
  922. }
  923. void Logger::writeToLog (const String& message)
  924. {
  925. if (currentLogger != 0)
  926. currentLogger->logMessage (message);
  927. else
  928. outputDebugString (message);
  929. }
  930. #if JUCE_LOG_ASSERTIONS
  931. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  932. {
  933. String m ("JUCE Assertion failure in ");
  934. m << filename << ", line " << lineNum;
  935. Logger::writeToLog (m);
  936. }
  937. #endif
  938. END_JUCE_NAMESPACE
  939. /********* End of inlined file: juce_Logger.cpp *********/
  940. /********* Start of inlined file: juce_Random.cpp *********/
  941. BEGIN_JUCE_NAMESPACE
  942. Random::Random (const int64 seedValue) throw()
  943. : seed (seedValue)
  944. {
  945. }
  946. Random::~Random() throw()
  947. {
  948. }
  949. void Random::setSeed (const int64 newSeed) throw()
  950. {
  951. seed = newSeed;
  952. }
  953. void Random::setSeedRandomly()
  954. {
  955. Random r1 (Time::getMillisecondCounter());
  956. Random r2 (Time::getHighResolutionTicks());
  957. Random r3 (Time::getHighResolutionTicksPerSecond());
  958. Random r4 (Time::currentTimeMillis());
  959. setSeed (nextInt64() ^ r1.nextInt64() ^ r2.nextInt64()
  960. ^ r3.nextInt64() ^ r4.nextInt64());
  961. }
  962. int Random::nextInt() throw()
  963. {
  964. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  965. return (int) (seed >> 16);
  966. }
  967. int Random::nextInt (const int maxValue) throw()
  968. {
  969. jassert (maxValue > 0);
  970. return (nextInt() & 0x7fffffff) % maxValue;
  971. }
  972. int64 Random::nextInt64() throw()
  973. {
  974. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  975. }
  976. bool Random::nextBool() throw()
  977. {
  978. return (nextInt() & 0x80000000) != 0;
  979. }
  980. float Random::nextFloat() throw()
  981. {
  982. return ((uint32) nextInt()) / (float) 0xffffffff;
  983. }
  984. double Random::nextDouble() throw()
  985. {
  986. return ((uint32) nextInt()) / (double) 0xffffffff;
  987. }
  988. const BitArray Random::nextLargeNumber (const BitArray& maximumValue) throw()
  989. {
  990. BitArray n;
  991. do
  992. {
  993. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  994. }
  995. while (n.compare (maximumValue) >= 0);
  996. return n;
  997. }
  998. void Random::fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw()
  999. {
  1000. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1001. while ((startBit & 31) != 0 && numBits > 0)
  1002. {
  1003. arrayToChange.setBit (startBit++, nextBool());
  1004. --numBits;
  1005. }
  1006. while (numBits >= 32)
  1007. {
  1008. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1009. startBit += 32;
  1010. numBits -= 32;
  1011. }
  1012. while (--numBits >= 0)
  1013. arrayToChange.setBit (startBit + numBits, nextBool());
  1014. }
  1015. Random& Random::getSystemRandom() throw()
  1016. {
  1017. static Random sysRand (1);
  1018. return sysRand;
  1019. }
  1020. END_JUCE_NAMESPACE
  1021. /********* End of inlined file: juce_Random.cpp *********/
  1022. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  1023. BEGIN_JUCE_NAMESPACE
  1024. RelativeTime::RelativeTime (const double seconds_) throw()
  1025. : seconds (seconds_)
  1026. {
  1027. }
  1028. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1029. : seconds (other.seconds)
  1030. {
  1031. }
  1032. RelativeTime::~RelativeTime() throw()
  1033. {
  1034. }
  1035. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1036. {
  1037. return RelativeTime (milliseconds * 0.001);
  1038. }
  1039. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1040. {
  1041. return RelativeTime (milliseconds * 0.001);
  1042. }
  1043. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1044. {
  1045. return RelativeTime (numberOfMinutes * 60.0);
  1046. }
  1047. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1048. {
  1049. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1050. }
  1051. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1052. {
  1053. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1054. }
  1055. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1056. {
  1057. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1058. }
  1059. int64 RelativeTime::inMilliseconds() const throw()
  1060. {
  1061. return (int64)(seconds * 1000.0);
  1062. }
  1063. double RelativeTime::inMinutes() const throw()
  1064. {
  1065. return seconds / 60.0;
  1066. }
  1067. double RelativeTime::inHours() const throw()
  1068. {
  1069. return seconds / (60.0 * 60.0);
  1070. }
  1071. double RelativeTime::inDays() const throw()
  1072. {
  1073. return seconds / (60.0 * 60.0 * 24.0);
  1074. }
  1075. double RelativeTime::inWeeks() const throw()
  1076. {
  1077. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1078. }
  1079. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1080. {
  1081. if (seconds < 0.001 && seconds > -0.001)
  1082. return returnValueForZeroTime;
  1083. String result;
  1084. if (seconds < 0)
  1085. result = T("-");
  1086. int fieldsShown = 0;
  1087. int n = abs ((int) inWeeks());
  1088. if (n > 0)
  1089. {
  1090. result << n << ((n == 1) ? TRANS(" week ")
  1091. : TRANS(" weeks "));
  1092. ++fieldsShown;
  1093. }
  1094. n = abs ((int) inDays()) % 7;
  1095. if (n > 0)
  1096. {
  1097. result << n << ((n == 1) ? TRANS(" day ")
  1098. : TRANS(" days "));
  1099. ++fieldsShown;
  1100. }
  1101. if (fieldsShown < 2)
  1102. {
  1103. n = abs ((int) inHours()) % 24;
  1104. if (n > 0)
  1105. {
  1106. result << n << ((n == 1) ? TRANS(" hr ")
  1107. : TRANS(" hrs "));
  1108. ++fieldsShown;
  1109. }
  1110. if (fieldsShown < 2)
  1111. {
  1112. n = abs ((int) inMinutes()) % 60;
  1113. if (n > 0)
  1114. {
  1115. result << n << ((n == 1) ? TRANS(" min ")
  1116. : TRANS(" mins "));
  1117. ++fieldsShown;
  1118. }
  1119. if (fieldsShown < 2)
  1120. {
  1121. n = abs ((int) inSeconds()) % 60;
  1122. if (n > 0)
  1123. {
  1124. result << n << ((n == 1) ? TRANS(" sec ")
  1125. : TRANS(" secs "));
  1126. ++fieldsShown;
  1127. }
  1128. if (fieldsShown < 1)
  1129. {
  1130. n = abs ((int) inMilliseconds()) % 1000;
  1131. if (n > 0)
  1132. {
  1133. result << n << TRANS(" ms");
  1134. ++fieldsShown;
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. return result.trimEnd();
  1141. }
  1142. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1143. {
  1144. seconds = other.seconds;
  1145. return *this;
  1146. }
  1147. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1148. {
  1149. return seconds == other.seconds;
  1150. }
  1151. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1152. {
  1153. return seconds != other.seconds;
  1154. }
  1155. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1156. {
  1157. return seconds > other.seconds;
  1158. }
  1159. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1160. {
  1161. return seconds < other.seconds;
  1162. }
  1163. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1164. {
  1165. return seconds >= other.seconds;
  1166. }
  1167. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1168. {
  1169. return seconds <= other.seconds;
  1170. }
  1171. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1172. {
  1173. return RelativeTime (seconds + timeToAdd.seconds);
  1174. }
  1175. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1176. {
  1177. return RelativeTime (seconds - timeToSubtract.seconds);
  1178. }
  1179. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1180. {
  1181. return RelativeTime (seconds + secondsToAdd);
  1182. }
  1183. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1184. {
  1185. return RelativeTime (seconds - secondsToSubtract);
  1186. }
  1187. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1188. {
  1189. seconds += timeToAdd.seconds;
  1190. return *this;
  1191. }
  1192. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1193. {
  1194. seconds -= timeToSubtract.seconds;
  1195. return *this;
  1196. }
  1197. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1198. {
  1199. seconds += secondsToAdd;
  1200. return *this;
  1201. }
  1202. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1203. {
  1204. seconds -= secondsToSubtract;
  1205. return *this;
  1206. }
  1207. END_JUCE_NAMESPACE
  1208. /********* End of inlined file: juce_RelativeTime.cpp *********/
  1209. /********* Start of inlined file: juce_SystemStats.cpp *********/
  1210. BEGIN_JUCE_NAMESPACE
  1211. void juce_initialiseStrings();
  1212. const String SystemStats::getJUCEVersion() throw()
  1213. {
  1214. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  1215. }
  1216. static bool juceInitialisedNonGUI = false;
  1217. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1218. {
  1219. if (! juceInitialisedNonGUI)
  1220. {
  1221. #if JUCE_MAC || JUCE_IPHONE
  1222. const ScopedAutoReleasePool pool;
  1223. #endif
  1224. #ifdef JUCE_DEBUG
  1225. // Some simple test code to keep an eye on things and make sure these functions
  1226. // work ok on all platforms. Let me know if any of these assertions fail!
  1227. int n = 1;
  1228. atomicIncrement (n);
  1229. jassert (atomicIncrementAndReturn (n) == 3);
  1230. atomicDecrement (n);
  1231. jassert (atomicDecrementAndReturn (n) == 1);
  1232. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  1233. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  1234. SystemStats* nullPointer = 0;
  1235. juce_free (nullPointer);
  1236. delete[] nullPointer;
  1237. delete nullPointer;
  1238. #endif
  1239. // Now the real initialisation..
  1240. juceInitialisedNonGUI = true;
  1241. DBG (SystemStats::getJUCEVersion());
  1242. juce_initialiseStrings();
  1243. SystemStats::initialiseStats();
  1244. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1245. }
  1246. }
  1247. #if JUCE_WINDOWS
  1248. // This is imported from the sockets code..
  1249. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1250. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1251. #endif
  1252. #if JUCE_DEBUG
  1253. extern void juce_CheckForDanglingStreams();
  1254. #endif
  1255. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1256. {
  1257. if (juceInitialisedNonGUI)
  1258. {
  1259. #if JUCE_MAC || JUCE_IPHONE
  1260. const ScopedAutoReleasePool pool;
  1261. #endif
  1262. #if JUCE_WINDOWS
  1263. // need to shut down sockets if they were used..
  1264. if (juce_CloseWin32SocketLib != 0)
  1265. (*juce_CloseWin32SocketLib)();
  1266. #endif
  1267. LocalisedStrings::setCurrentMappings (0);
  1268. Thread::stopAllThreads (3000);
  1269. #if JUCE_DEBUG
  1270. juce_CheckForDanglingStreams();
  1271. #endif
  1272. juceInitialisedNonGUI = false;
  1273. }
  1274. }
  1275. #ifdef JUCE_DLL
  1276. void* juce_Malloc (const int size)
  1277. {
  1278. return malloc (size);
  1279. }
  1280. void* juce_Calloc (const int size)
  1281. {
  1282. return calloc (1, size);
  1283. }
  1284. void* juce_Realloc (void* const block, const int size)
  1285. {
  1286. return realloc (block, size);
  1287. }
  1288. void juce_Free (void* const block)
  1289. {
  1290. free (block);
  1291. }
  1292. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1293. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1294. {
  1295. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1296. }
  1297. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1298. {
  1299. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1300. }
  1301. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1302. {
  1303. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1304. }
  1305. void juce_DebugFree (void* const block)
  1306. {
  1307. _free_dbg (block, _NORMAL_BLOCK);
  1308. }
  1309. #endif
  1310. #endif
  1311. END_JUCE_NAMESPACE
  1312. /********* End of inlined file: juce_SystemStats.cpp *********/
  1313. /********* Start of inlined file: juce_Time.cpp *********/
  1314. #ifdef _MSC_VER
  1315. #pragma warning (disable: 4514)
  1316. #pragma warning (push)
  1317. #endif
  1318. #ifndef JUCE_WINDOWS
  1319. #include <sys/time.h>
  1320. #else
  1321. #include <ctime>
  1322. #endif
  1323. #include <sys/timeb.h>
  1324. BEGIN_JUCE_NAMESPACE
  1325. #ifdef _MSC_VER
  1326. #pragma warning (pop)
  1327. #ifdef _INC_TIME_INL
  1328. #define USE_NEW_SECURE_TIME_FNS
  1329. #endif
  1330. #endif
  1331. static void millisToLocal (const int64 millis, struct tm& result) throw()
  1332. {
  1333. const int64 seconds = millis / 1000;
  1334. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1335. {
  1336. // use extended maths for dates beyond 1970 to 2037..
  1337. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1338. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1339. const int days = (int) (jdm / literal64bit (86400));
  1340. const int a = 32044 + days;
  1341. const int b = (4 * a + 3) / 146097;
  1342. const int c = a - (b * 146097) / 4;
  1343. const int d = (4 * c + 3) / 1461;
  1344. const int e = c - (d * 1461) / 4;
  1345. const int m = (5 * e + 2) / 153;
  1346. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1347. result.tm_mon = m + 2 - 12 * (m / 10);
  1348. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1349. result.tm_wday = (days + 1) % 7;
  1350. result.tm_yday = -1;
  1351. int t = (int) (jdm % literal64bit (86400));
  1352. result.tm_hour = t / 3600;
  1353. t %= 3600;
  1354. result.tm_min = t / 60;
  1355. result.tm_sec = t % 60;
  1356. result.tm_isdst = -1;
  1357. }
  1358. else
  1359. {
  1360. time_t now = (time_t) (seconds);
  1361. #if JUCE_WINDOWS
  1362. #ifdef USE_NEW_SECURE_TIME_FNS
  1363. if (now >= 0 && now <= 0x793406fff)
  1364. localtime_s (&result, &now);
  1365. else
  1366. zeromem (&result, sizeof (result));
  1367. #else
  1368. result = *localtime (&now);
  1369. #endif
  1370. #else
  1371. // more thread-safe
  1372. localtime_r (&now, &result);
  1373. #endif
  1374. }
  1375. }
  1376. Time::Time() throw()
  1377. : millisSinceEpoch (0)
  1378. {
  1379. }
  1380. Time::Time (const Time& other) throw()
  1381. : millisSinceEpoch (other.millisSinceEpoch)
  1382. {
  1383. }
  1384. Time::Time (const int64 ms) throw()
  1385. : millisSinceEpoch (ms)
  1386. {
  1387. }
  1388. Time::Time (const int year,
  1389. const int month,
  1390. const int day,
  1391. const int hours,
  1392. const int minutes,
  1393. const int seconds,
  1394. const int milliseconds,
  1395. const bool useLocalTime) throw()
  1396. {
  1397. jassert (year > 100); // year must be a 4-digit version
  1398. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1399. {
  1400. // use extended maths for dates beyond 1970 to 2037..
  1401. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1402. : 0;
  1403. const int a = (13 - month) / 12;
  1404. const int y = year + 4800 - a;
  1405. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1406. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1407. - 32045;
  1408. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1409. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1410. + milliseconds;
  1411. }
  1412. else
  1413. {
  1414. struct tm t;
  1415. t.tm_year = year - 1900;
  1416. t.tm_mon = month;
  1417. t.tm_mday = day;
  1418. t.tm_hour = hours;
  1419. t.tm_min = minutes;
  1420. t.tm_sec = seconds;
  1421. t.tm_isdst = -1;
  1422. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1423. if (millisSinceEpoch < 0)
  1424. millisSinceEpoch = 0;
  1425. else
  1426. millisSinceEpoch += milliseconds;
  1427. }
  1428. }
  1429. Time::~Time() throw()
  1430. {
  1431. }
  1432. const Time& Time::operator= (const Time& other) throw()
  1433. {
  1434. millisSinceEpoch = other.millisSinceEpoch;
  1435. return *this;
  1436. }
  1437. int64 Time::currentTimeMillis() throw()
  1438. {
  1439. static uint32 lastCounterResult = 0xffffffff;
  1440. static int64 correction = 0;
  1441. const uint32 now = getMillisecondCounter();
  1442. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1443. if (now < lastCounterResult)
  1444. {
  1445. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1446. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1447. {
  1448. // get the time once using normal library calls, and store the difference needed to
  1449. // turn the millisecond counter into a real time.
  1450. #if JUCE_WINDOWS
  1451. struct _timeb t;
  1452. #ifdef USE_NEW_SECURE_TIME_FNS
  1453. _ftime_s (&t);
  1454. #else
  1455. _ftime (&t);
  1456. #endif
  1457. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1458. #else
  1459. struct timeval tv;
  1460. struct timezone tz;
  1461. gettimeofday (&tv, &tz);
  1462. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1463. #endif
  1464. }
  1465. }
  1466. lastCounterResult = now;
  1467. return correction + now;
  1468. }
  1469. uint32 juce_millisecondsSinceStartup() throw();
  1470. static uint32 lastMSCounterValue = 0;
  1471. uint32 Time::getMillisecondCounter() throw()
  1472. {
  1473. const uint32 now = juce_millisecondsSinceStartup();
  1474. if (now < lastMSCounterValue)
  1475. {
  1476. // in multi-threaded apps this might be called concurrently, so
  1477. // make sure that our last counter value only increases and doesn't
  1478. // go backwards..
  1479. if (now < lastMSCounterValue - 1000)
  1480. lastMSCounterValue = now;
  1481. }
  1482. else
  1483. {
  1484. lastMSCounterValue = now;
  1485. }
  1486. return now;
  1487. }
  1488. uint32 Time::getApproximateMillisecondCounter() throw()
  1489. {
  1490. jassert (lastMSCounterValue != 0);
  1491. return lastMSCounterValue;
  1492. }
  1493. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1494. {
  1495. for (;;)
  1496. {
  1497. const uint32 now = getMillisecondCounter();
  1498. if (now >= targetTime)
  1499. break;
  1500. const int toWait = targetTime - now;
  1501. if (toWait > 2)
  1502. {
  1503. Thread::sleep (jmin (20, toWait >> 1));
  1504. }
  1505. else
  1506. {
  1507. // xxx should consider using mutex_pause on the mac as it apparently
  1508. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1509. for (int i = 10; --i >= 0;)
  1510. Thread::yield();
  1511. }
  1512. }
  1513. }
  1514. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1515. {
  1516. return ticks / (double) getHighResolutionTicksPerSecond();
  1517. }
  1518. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1519. {
  1520. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1521. }
  1522. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1523. {
  1524. return Time (currentTimeMillis());
  1525. }
  1526. const String Time::toString (const bool includeDate,
  1527. const bool includeTime,
  1528. const bool includeSeconds,
  1529. const bool use24HourClock) const throw()
  1530. {
  1531. String result;
  1532. if (includeDate)
  1533. {
  1534. result << getDayOfMonth() << ' '
  1535. << getMonthName (true) << ' '
  1536. << getYear();
  1537. if (includeTime)
  1538. result << ' ';
  1539. }
  1540. if (includeTime)
  1541. {
  1542. if (includeSeconds)
  1543. {
  1544. result += String::formatted (T("%d:%02d:%02d "),
  1545. (use24HourClock) ? getHours()
  1546. : getHoursInAmPmFormat(),
  1547. getMinutes(),
  1548. getSeconds());
  1549. }
  1550. else
  1551. {
  1552. result += String::formatted (T("%d.%02d"),
  1553. (use24HourClock) ? getHours()
  1554. : getHoursInAmPmFormat(),
  1555. getMinutes());
  1556. }
  1557. if (! use24HourClock)
  1558. result << (isAfternoon() ? "pm" : "am");
  1559. }
  1560. return result.trimEnd();
  1561. }
  1562. const String Time::formatted (const tchar* const format) const throw()
  1563. {
  1564. tchar buffer[80];
  1565. struct tm t;
  1566. millisToLocal (millisSinceEpoch, t);
  1567. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  1568. {
  1569. int bufferSize = 128;
  1570. for (;;)
  1571. {
  1572. MemoryBlock mb (bufferSize * sizeof (tchar));
  1573. tchar* const b = (tchar*) mb.getData();
  1574. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  1575. return String (b);
  1576. bufferSize += 128;
  1577. }
  1578. }
  1579. return String (buffer);
  1580. }
  1581. int Time::getYear() const throw()
  1582. {
  1583. struct tm t;
  1584. millisToLocal (millisSinceEpoch, t);
  1585. return t.tm_year + 1900;
  1586. }
  1587. int Time::getMonth() const throw()
  1588. {
  1589. struct tm t;
  1590. millisToLocal (millisSinceEpoch, t);
  1591. return t.tm_mon;
  1592. }
  1593. int Time::getDayOfMonth() const throw()
  1594. {
  1595. struct tm t;
  1596. millisToLocal (millisSinceEpoch, t);
  1597. return t.tm_mday;
  1598. }
  1599. int Time::getDayOfWeek() const throw()
  1600. {
  1601. struct tm t;
  1602. millisToLocal (millisSinceEpoch, t);
  1603. return t.tm_wday;
  1604. }
  1605. int Time::getHours() const throw()
  1606. {
  1607. struct tm t;
  1608. millisToLocal (millisSinceEpoch, t);
  1609. return t.tm_hour;
  1610. }
  1611. int Time::getHoursInAmPmFormat() const throw()
  1612. {
  1613. const int hours = getHours();
  1614. if (hours == 0)
  1615. return 12;
  1616. else if (hours <= 12)
  1617. return hours;
  1618. else
  1619. return hours - 12;
  1620. }
  1621. bool Time::isAfternoon() const throw()
  1622. {
  1623. return getHours() >= 12;
  1624. }
  1625. static int extendedModulo (const int64 value, const int modulo) throw()
  1626. {
  1627. return (int) (value >= 0 ? (value % modulo)
  1628. : (value - ((value / modulo) + 1) * modulo));
  1629. }
  1630. int Time::getMinutes() const throw()
  1631. {
  1632. struct tm t;
  1633. millisToLocal (millisSinceEpoch, t);
  1634. return t.tm_min;
  1635. }
  1636. int Time::getSeconds() const throw()
  1637. {
  1638. return extendedModulo (millisSinceEpoch / 1000, 60);
  1639. }
  1640. int Time::getMilliseconds() const throw()
  1641. {
  1642. return extendedModulo (millisSinceEpoch, 1000);
  1643. }
  1644. bool Time::isDaylightSavingTime() const throw()
  1645. {
  1646. struct tm t;
  1647. millisToLocal (millisSinceEpoch, t);
  1648. return t.tm_isdst != 0;
  1649. }
  1650. const String Time::getTimeZone() const throw()
  1651. {
  1652. String zone[2];
  1653. #if JUCE_WINDOWS
  1654. _tzset();
  1655. #ifdef USE_NEW_SECURE_TIME_FNS
  1656. {
  1657. char name [128];
  1658. size_t length;
  1659. for (int i = 0; i < 2; ++i)
  1660. {
  1661. zeromem (name, sizeof (name));
  1662. _get_tzname (&length, name, 127, i);
  1663. zone[i] = name;
  1664. }
  1665. }
  1666. #else
  1667. const char** const zonePtr = (const char**) _tzname;
  1668. zone[0] = zonePtr[0];
  1669. zone[1] = zonePtr[1];
  1670. #endif
  1671. #else
  1672. tzset();
  1673. const char** const zonePtr = (const char**) tzname;
  1674. zone[0] = zonePtr[0];
  1675. zone[1] = zonePtr[1];
  1676. #endif
  1677. if (isDaylightSavingTime())
  1678. {
  1679. zone[0] = zone[1];
  1680. if (zone[0].length() > 3
  1681. && zone[0].containsIgnoreCase (T("daylight"))
  1682. && zone[0].contains (T("GMT")))
  1683. zone[0] = "BST";
  1684. }
  1685. return zone[0].substring (0, 3);
  1686. }
  1687. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1688. {
  1689. return getMonthName (getMonth(), threeLetterVersion);
  1690. }
  1691. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1692. {
  1693. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1694. }
  1695. const String Time::getMonthName (int monthNumber,
  1696. const bool threeLetterVersion) throw()
  1697. {
  1698. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1699. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1700. monthNumber %= 12;
  1701. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1702. : longMonthNames [monthNumber]);
  1703. }
  1704. const String Time::getWeekdayName (int day,
  1705. const bool threeLetterVersion) throw()
  1706. {
  1707. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1708. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1709. day %= 7;
  1710. return TRANS (threeLetterVersion ? shortDayNames [day]
  1711. : longDayNames [day]);
  1712. }
  1713. END_JUCE_NAMESPACE
  1714. /********* End of inlined file: juce_Time.cpp *********/
  1715. /********* Start of inlined file: juce_BitArray.cpp *********/
  1716. BEGIN_JUCE_NAMESPACE
  1717. BitArray::BitArray() throw()
  1718. : numValues (4),
  1719. highestBit (-1),
  1720. negative (false)
  1721. {
  1722. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1723. }
  1724. BitArray::BitArray (const int value) throw()
  1725. : numValues (4),
  1726. highestBit (31),
  1727. negative (value < 0)
  1728. {
  1729. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1730. values[0] = abs (value);
  1731. highestBit = getHighestBit();
  1732. }
  1733. BitArray::BitArray (int64 value) throw()
  1734. : numValues (4),
  1735. highestBit (63),
  1736. negative (value < 0)
  1737. {
  1738. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1739. if (value < 0)
  1740. value = -value;
  1741. values[0] = (unsigned int) value;
  1742. values[1] = (unsigned int) (value >> 32);
  1743. highestBit = getHighestBit();
  1744. }
  1745. BitArray::BitArray (const unsigned int value) throw()
  1746. : numValues (4),
  1747. highestBit (31),
  1748. negative (false)
  1749. {
  1750. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1751. values[0] = value;
  1752. highestBit = getHighestBit();
  1753. }
  1754. BitArray::BitArray (const BitArray& other) throw()
  1755. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1756. highestBit (other.getHighestBit()),
  1757. negative (other.negative)
  1758. {
  1759. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1760. values = (unsigned int*) juce_malloc (bytes);
  1761. memcpy (values, other.values, bytes);
  1762. }
  1763. BitArray::~BitArray() throw()
  1764. {
  1765. juce_free (values);
  1766. }
  1767. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1768. {
  1769. if (this != &other)
  1770. {
  1771. juce_free (values);
  1772. highestBit = other.getHighestBit();
  1773. numValues = jmax (4, (highestBit >> 5) + 1);
  1774. negative = other.negative;
  1775. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1776. values = (unsigned int*)juce_malloc (memSize);
  1777. memcpy (values, other.values, memSize);
  1778. }
  1779. return *this;
  1780. }
  1781. // result == 0 = the same
  1782. // result < 0 = this number is smaller
  1783. // result > 0 = this number is bigger
  1784. int BitArray::compare (const BitArray& other) const throw()
  1785. {
  1786. if (isNegative() == other.isNegative())
  1787. {
  1788. const int absComp = compareAbsolute (other);
  1789. return isNegative() ? -absComp : absComp;
  1790. }
  1791. else
  1792. {
  1793. return isNegative() ? -1 : 1;
  1794. }
  1795. }
  1796. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1797. {
  1798. const int h1 = getHighestBit();
  1799. const int h2 = other.getHighestBit();
  1800. if (h1 > h2)
  1801. return 1;
  1802. else if (h1 < h2)
  1803. return -1;
  1804. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1805. if (values[i] != other.values[i])
  1806. return (values[i] > other.values[i]) ? 1 : -1;
  1807. return 0;
  1808. }
  1809. bool BitArray::operator== (const BitArray& other) const throw()
  1810. {
  1811. return compare (other) == 0;
  1812. }
  1813. bool BitArray::operator!= (const BitArray& other) const throw()
  1814. {
  1815. return compare (other) != 0;
  1816. }
  1817. bool BitArray::operator[] (const int bit) const throw()
  1818. {
  1819. return bit >= 0 && bit <= highestBit
  1820. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1821. }
  1822. bool BitArray::isEmpty() const throw()
  1823. {
  1824. return getHighestBit() < 0;
  1825. }
  1826. void BitArray::clear() throw()
  1827. {
  1828. if (numValues > 16)
  1829. {
  1830. juce_free (values);
  1831. numValues = 4;
  1832. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1833. }
  1834. else
  1835. {
  1836. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1837. }
  1838. highestBit = -1;
  1839. negative = false;
  1840. }
  1841. void BitArray::setBit (const int bit) throw()
  1842. {
  1843. if (bit >= 0)
  1844. {
  1845. if (bit > highestBit)
  1846. {
  1847. ensureSize (bit >> 5);
  1848. highestBit = bit;
  1849. }
  1850. values [bit >> 5] |= (1 << (bit & 31));
  1851. }
  1852. }
  1853. void BitArray::setBit (const int bit,
  1854. const bool shouldBeSet) throw()
  1855. {
  1856. if (shouldBeSet)
  1857. setBit (bit);
  1858. else
  1859. clearBit (bit);
  1860. }
  1861. void BitArray::clearBit (const int bit) throw()
  1862. {
  1863. if (bit >= 0 && bit <= highestBit)
  1864. values [bit >> 5] &= ~(1 << (bit & 31));
  1865. }
  1866. void BitArray::setRange (int startBit,
  1867. int numBits,
  1868. const bool shouldBeSet) throw()
  1869. {
  1870. while (--numBits >= 0)
  1871. setBit (startBit++, shouldBeSet);
  1872. }
  1873. void BitArray::insertBit (const int bit,
  1874. const bool shouldBeSet) throw()
  1875. {
  1876. if (bit >= 0)
  1877. shiftBits (1, bit);
  1878. setBit (bit, shouldBeSet);
  1879. }
  1880. void BitArray::andWith (const BitArray& other) throw()
  1881. {
  1882. // this operation will only work with the absolute values
  1883. jassert (isNegative() == other.isNegative());
  1884. int n = numValues;
  1885. while (n > other.numValues)
  1886. values[--n] = 0;
  1887. while (--n >= 0)
  1888. values[n] &= other.values[n];
  1889. if (other.highestBit < highestBit)
  1890. highestBit = other.highestBit;
  1891. highestBit = getHighestBit();
  1892. }
  1893. void BitArray::orWith (const BitArray& other) throw()
  1894. {
  1895. if (other.highestBit < 0)
  1896. return;
  1897. // this operation will only work with the absolute values
  1898. jassert (isNegative() == other.isNegative());
  1899. ensureSize (other.highestBit >> 5);
  1900. int n = (other.highestBit >> 5) + 1;
  1901. while (--n >= 0)
  1902. values[n] |= other.values[n];
  1903. if (other.highestBit > highestBit)
  1904. highestBit = other.highestBit;
  1905. highestBit = getHighestBit();
  1906. }
  1907. void BitArray::xorWith (const BitArray& other) throw()
  1908. {
  1909. if (other.highestBit < 0)
  1910. return;
  1911. // this operation will only work with the absolute values
  1912. jassert (isNegative() == other.isNegative());
  1913. ensureSize (other.highestBit >> 5);
  1914. int n = (other.highestBit >> 5) + 1;
  1915. while (--n >= 0)
  1916. values[n] ^= other.values[n];
  1917. if (other.highestBit > highestBit)
  1918. highestBit = other.highestBit;
  1919. highestBit = getHighestBit();
  1920. }
  1921. void BitArray::add (const BitArray& other) throw()
  1922. {
  1923. if (other.isNegative())
  1924. {
  1925. BitArray o (other);
  1926. o.negate();
  1927. subtract (o);
  1928. return;
  1929. }
  1930. if (isNegative())
  1931. {
  1932. if (compareAbsolute (other) < 0)
  1933. {
  1934. BitArray temp (*this);
  1935. temp.negate();
  1936. *this = other;
  1937. subtract (temp);
  1938. }
  1939. else
  1940. {
  1941. negate();
  1942. subtract (other);
  1943. negate();
  1944. }
  1945. return;
  1946. }
  1947. if (other.highestBit > highestBit)
  1948. highestBit = other.highestBit;
  1949. ++highestBit;
  1950. const int numInts = (highestBit >> 5) + 1;
  1951. ensureSize (numInts);
  1952. int64 remainder = 0;
  1953. for (int i = 0; i <= numInts; ++i)
  1954. {
  1955. if (i < numValues)
  1956. remainder += values[i];
  1957. if (i < other.numValues)
  1958. remainder += other.values[i];
  1959. values[i] = (unsigned int) remainder;
  1960. remainder >>= 32;
  1961. }
  1962. jassert (remainder == 0);
  1963. highestBit = getHighestBit();
  1964. }
  1965. void BitArray::subtract (const BitArray& other) throw()
  1966. {
  1967. if (other.isNegative())
  1968. {
  1969. BitArray o (other);
  1970. o.negate();
  1971. add (o);
  1972. return;
  1973. }
  1974. if (! isNegative())
  1975. {
  1976. if (compareAbsolute (other) < 0)
  1977. {
  1978. BitArray temp (*this);
  1979. *this = other;
  1980. subtract (temp);
  1981. negate();
  1982. return;
  1983. }
  1984. }
  1985. else
  1986. {
  1987. negate();
  1988. add (other);
  1989. negate();
  1990. return;
  1991. }
  1992. const int numInts = (highestBit >> 5) + 1;
  1993. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1994. int64 amountToSubtract = 0;
  1995. for (int i = 0; i <= numInts; ++i)
  1996. {
  1997. if (i <= maxOtherInts)
  1998. amountToSubtract += (int64)other.values[i];
  1999. if (values[i] >= amountToSubtract)
  2000. {
  2001. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2002. amountToSubtract = 0;
  2003. }
  2004. else
  2005. {
  2006. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2007. values[i] = (unsigned int) n;
  2008. amountToSubtract = 1;
  2009. }
  2010. }
  2011. }
  2012. void BitArray::multiplyBy (const BitArray& other) throw()
  2013. {
  2014. BitArray total;
  2015. highestBit = getHighestBit();
  2016. const bool wasNegative = isNegative();
  2017. setNegative (false);
  2018. for (int i = 0; i <= highestBit; ++i)
  2019. {
  2020. if (operator[](i))
  2021. {
  2022. BitArray n (other);
  2023. n.setNegative (false);
  2024. n.shiftBits (i);
  2025. total.add (n);
  2026. }
  2027. }
  2028. *this = total;
  2029. negative = wasNegative ^ other.isNegative();
  2030. }
  2031. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  2032. {
  2033. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2034. const int divHB = divisor.getHighestBit();
  2035. const int ourHB = getHighestBit();
  2036. if (divHB < 0 || ourHB < 0)
  2037. {
  2038. // division by zero
  2039. remainder.clear();
  2040. clear();
  2041. }
  2042. else
  2043. {
  2044. remainder = *this;
  2045. remainder.setNegative (false);
  2046. const bool wasNegative = isNegative();
  2047. clear();
  2048. BitArray temp (divisor);
  2049. temp.setNegative (false);
  2050. int leftShift = ourHB - divHB;
  2051. temp.shiftBits (leftShift);
  2052. while (leftShift >= 0)
  2053. {
  2054. if (remainder.compareAbsolute (temp) >= 0)
  2055. {
  2056. remainder.subtract (temp);
  2057. setBit (leftShift);
  2058. }
  2059. if (--leftShift >= 0)
  2060. temp.shiftBits (-1);
  2061. }
  2062. negative = wasNegative ^ divisor.isNegative();
  2063. remainder.setNegative (wasNegative);
  2064. }
  2065. }
  2066. void BitArray::modulo (const BitArray& divisor) throw()
  2067. {
  2068. BitArray remainder;
  2069. divideBy (divisor, remainder);
  2070. *this = remainder;
  2071. }
  2072. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  2073. {
  2074. while (! m->isEmpty())
  2075. {
  2076. if (n->compareAbsolute (*m) > 0)
  2077. swapVariables (m, n);
  2078. m->subtract (*n);
  2079. }
  2080. return *n;
  2081. }
  2082. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  2083. {
  2084. BitArray m (*this);
  2085. while (! n.isEmpty())
  2086. {
  2087. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2088. return simpleGCD (&m, &n);
  2089. BitArray temp1 (m), temp2;
  2090. temp1.divideBy (n, temp2);
  2091. m = n;
  2092. n = temp2;
  2093. }
  2094. return m;
  2095. }
  2096. void BitArray::exponentModulo (const BitArray& exponent,
  2097. const BitArray& modulus) throw()
  2098. {
  2099. BitArray exp (exponent);
  2100. exp.modulo (modulus);
  2101. BitArray value (*this);
  2102. value.modulo (modulus);
  2103. clear();
  2104. setBit (0);
  2105. while (! exp.isEmpty())
  2106. {
  2107. if (exp [0])
  2108. {
  2109. multiplyBy (value);
  2110. this->modulo (modulus);
  2111. }
  2112. value.multiplyBy (value);
  2113. value.modulo (modulus);
  2114. exp.shiftBits (-1);
  2115. }
  2116. }
  2117. void BitArray::inverseModulo (const BitArray& modulus) throw()
  2118. {
  2119. const BitArray one (1);
  2120. if (modulus == one || modulus.isNegative())
  2121. {
  2122. clear();
  2123. return;
  2124. }
  2125. if (isNegative() || compareAbsolute (modulus) >= 0)
  2126. this->modulo (modulus);
  2127. if (*this == one)
  2128. return;
  2129. if (! (*this)[0])
  2130. {
  2131. // not invertible
  2132. clear();
  2133. return;
  2134. }
  2135. BitArray a1 (modulus);
  2136. BitArray a2 (*this);
  2137. BitArray b1 (modulus);
  2138. BitArray b2 (1);
  2139. while (a2 != one)
  2140. {
  2141. BitArray temp1, temp2, multiplier (a1);
  2142. multiplier.divideBy (a2, temp1);
  2143. temp1 = a2;
  2144. temp1.multiplyBy (multiplier);
  2145. temp2 = a1;
  2146. temp2.subtract (temp1);
  2147. a1 = a2;
  2148. a2 = temp2;
  2149. temp1 = b2;
  2150. temp1.multiplyBy (multiplier);
  2151. temp2 = b1;
  2152. temp2.subtract (temp1);
  2153. b1 = b2;
  2154. b2 = temp2;
  2155. }
  2156. while (b2.isNegative())
  2157. b2.add (modulus);
  2158. b2.modulo (modulus);
  2159. *this = b2;
  2160. }
  2161. void BitArray::shiftBits (int bits, const int startBit) throw()
  2162. {
  2163. if (highestBit < 0)
  2164. return;
  2165. if (startBit > 0)
  2166. {
  2167. if (bits < 0)
  2168. {
  2169. // right shift
  2170. for (int i = startBit; i <= highestBit; ++i)
  2171. setBit (i, operator[] (i - bits));
  2172. highestBit = getHighestBit();
  2173. }
  2174. else if (bits > 0)
  2175. {
  2176. // left shift
  2177. for (int i = highestBit + 1; --i >= startBit;)
  2178. setBit (i + bits, operator[] (i));
  2179. while (--bits >= 0)
  2180. clearBit (bits + startBit);
  2181. }
  2182. }
  2183. else
  2184. {
  2185. if (bits < 0)
  2186. {
  2187. // right shift
  2188. bits = -bits;
  2189. if (bits > highestBit)
  2190. {
  2191. clear();
  2192. }
  2193. else
  2194. {
  2195. const int wordsToMove = bits >> 5;
  2196. int top = 1 + (highestBit >> 5) - wordsToMove;
  2197. highestBit -= bits;
  2198. if (wordsToMove > 0)
  2199. {
  2200. int i;
  2201. for (i = 0; i < top; ++i)
  2202. values [i] = values [i + wordsToMove];
  2203. for (i = 0; i < wordsToMove; ++i)
  2204. values [top + i] = 0;
  2205. bits &= 31;
  2206. }
  2207. if (bits != 0)
  2208. {
  2209. const int invBits = 32 - bits;
  2210. --top;
  2211. for (int i = 0; i < top; ++i)
  2212. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2213. values[top] = (values[top] >> bits);
  2214. }
  2215. highestBit = getHighestBit();
  2216. }
  2217. }
  2218. else if (bits > 0)
  2219. {
  2220. // left shift
  2221. ensureSize (((highestBit + bits) >> 5) + 1);
  2222. const int wordsToMove = bits >> 5;
  2223. int top = 1 + (highestBit >> 5);
  2224. highestBit += bits;
  2225. if (wordsToMove > 0)
  2226. {
  2227. int i;
  2228. for (i = top; --i >= 0;)
  2229. values [i + wordsToMove] = values [i];
  2230. for (i = 0; i < wordsToMove; ++i)
  2231. values [i] = 0;
  2232. bits &= 31;
  2233. }
  2234. if (bits != 0)
  2235. {
  2236. const int invBits = 32 - bits;
  2237. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2238. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2239. values [wordsToMove] = values [wordsToMove] << bits;
  2240. }
  2241. highestBit = getHighestBit();
  2242. }
  2243. }
  2244. }
  2245. const BitArray BitArray::getBitRange (int startBit, int numBits) const throw()
  2246. {
  2247. BitArray r;
  2248. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2249. r.ensureSize (numBits >> 5);
  2250. r.highestBit = numBits;
  2251. int i = 0;
  2252. while (numBits > 0)
  2253. {
  2254. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2255. numBits -= 32;
  2256. startBit += 32;
  2257. }
  2258. r.highestBit = r.getHighestBit();
  2259. return r;
  2260. }
  2261. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2262. {
  2263. if (numBits > 32)
  2264. {
  2265. jassertfalse // use getBitRange() if you need more than 32 bits..
  2266. numBits = 32;
  2267. }
  2268. numBits = jmin (numBits, highestBit + 1 - startBit);
  2269. if (numBits <= 0)
  2270. return 0;
  2271. const int pos = startBit >> 5;
  2272. const int offset = startBit & 31;
  2273. const int endSpace = 32 - numBits;
  2274. uint32 n = ((uint32) values [pos]) >> offset;
  2275. if (offset > endSpace)
  2276. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2277. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2278. }
  2279. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  2280. {
  2281. if (numBits > 32)
  2282. {
  2283. jassertfalse
  2284. numBits = 32;
  2285. }
  2286. for (int i = 0; i < numBits; ++i)
  2287. {
  2288. setBit (startBit + i, (valueToSet & 1) != 0);
  2289. valueToSet >>= 1;
  2290. }
  2291. }
  2292. bool BitArray::isNegative() const throw()
  2293. {
  2294. return negative && ! isEmpty();
  2295. }
  2296. void BitArray::setNegative (const bool neg) throw()
  2297. {
  2298. negative = neg;
  2299. }
  2300. void BitArray::negate() throw()
  2301. {
  2302. negative = (! negative) && ! isEmpty();
  2303. }
  2304. int BitArray::countNumberOfSetBits() const throw()
  2305. {
  2306. int total = 0;
  2307. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2308. {
  2309. unsigned int n = values[i];
  2310. if (n == 0xffffffff)
  2311. {
  2312. total += 32;
  2313. }
  2314. else
  2315. {
  2316. while (n != 0)
  2317. {
  2318. total += (n & 1);
  2319. n >>= 1;
  2320. }
  2321. }
  2322. }
  2323. return total;
  2324. }
  2325. int BitArray::getHighestBit() const throw()
  2326. {
  2327. for (int i = highestBit + 1; --i >= 0;)
  2328. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2329. return i;
  2330. return -1;
  2331. }
  2332. int BitArray::findNextSetBit (int i) const throw()
  2333. {
  2334. for (; i <= highestBit; ++i)
  2335. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2336. return i;
  2337. return -1;
  2338. }
  2339. int BitArray::findNextClearBit (int i) const throw()
  2340. {
  2341. for (; i <= highestBit; ++i)
  2342. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2343. break;
  2344. return i;
  2345. }
  2346. void BitArray::ensureSize (const int numVals) throw()
  2347. {
  2348. if (numVals + 2 >= numValues)
  2349. {
  2350. int oldSize = numValues;
  2351. numValues = ((numVals + 2) * 3) / 2;
  2352. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  2353. while (oldSize < numValues)
  2354. values [oldSize++] = 0;
  2355. }
  2356. }
  2357. const String BitArray::toString (const int base, const int minimumNumCharacters) const throw()
  2358. {
  2359. String s;
  2360. BitArray v (*this);
  2361. if (base == 2 || base == 8 || base == 16)
  2362. {
  2363. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2364. static const tchar* const hexDigits = T("0123456789abcdef");
  2365. for (;;)
  2366. {
  2367. const int remainder = v.getBitRangeAsInt (0, bits);
  2368. v.shiftBits (-bits);
  2369. if (remainder == 0 && v.isEmpty())
  2370. break;
  2371. s = String::charToString (hexDigits [remainder]) + s;
  2372. }
  2373. }
  2374. else if (base == 10)
  2375. {
  2376. const BitArray ten (10);
  2377. BitArray remainder;
  2378. for (;;)
  2379. {
  2380. v.divideBy (ten, remainder);
  2381. if (remainder.isEmpty() && v.isEmpty())
  2382. break;
  2383. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2384. }
  2385. }
  2386. else
  2387. {
  2388. jassertfalse // can't do the specified base
  2389. return String::empty;
  2390. }
  2391. const int length = s.length();
  2392. if (length < minimumNumCharacters)
  2393. s = String::repeatedString (T("0"), minimumNumCharacters - length);
  2394. return isNegative() ? T("-") + s : s;
  2395. }
  2396. void BitArray::parseString (const String& text,
  2397. const int base) throw()
  2398. {
  2399. clear();
  2400. const tchar* t = (const tchar*) text;
  2401. if (base == 2 || base == 8 || base == 16)
  2402. {
  2403. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2404. for (;;)
  2405. {
  2406. const tchar c = *t++;
  2407. const int digit = CharacterFunctions::getHexDigitValue (c);
  2408. if (((unsigned int) digit) < (unsigned int) base)
  2409. {
  2410. shiftBits (bits);
  2411. add (digit);
  2412. }
  2413. else if (c == 0)
  2414. {
  2415. break;
  2416. }
  2417. }
  2418. }
  2419. else if (base == 10)
  2420. {
  2421. const BitArray ten ((unsigned int) 10);
  2422. for (;;)
  2423. {
  2424. const tchar c = *t++;
  2425. if (c >= T('0') && c <= T('9'))
  2426. {
  2427. multiplyBy (ten);
  2428. add ((int) (c - T('0')));
  2429. }
  2430. else if (c == 0)
  2431. {
  2432. break;
  2433. }
  2434. }
  2435. }
  2436. setNegative (text.trimStart().startsWithChar (T('-')));
  2437. }
  2438. const MemoryBlock BitArray::toMemoryBlock() const throw()
  2439. {
  2440. const int numBytes = (getHighestBit() + 8) >> 3;
  2441. MemoryBlock mb (numBytes);
  2442. for (int i = 0; i < numBytes; ++i)
  2443. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2444. return mb;
  2445. }
  2446. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  2447. {
  2448. clear();
  2449. for (int i = data.getSize(); --i >= 0;)
  2450. this->setBitRangeAsInt (i << 3, 8, data [i]);
  2451. }
  2452. END_JUCE_NAMESPACE
  2453. /********* End of inlined file: juce_BitArray.cpp *********/
  2454. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  2455. BEGIN_JUCE_NAMESPACE
  2456. MemoryBlock::MemoryBlock() throw()
  2457. : data (0),
  2458. size (0)
  2459. {
  2460. }
  2461. MemoryBlock::MemoryBlock (const int initialSize,
  2462. const bool initialiseToZero) throw()
  2463. {
  2464. if (initialSize > 0)
  2465. {
  2466. size = initialSize;
  2467. if (initialiseToZero)
  2468. data = (char*) juce_calloc (initialSize);
  2469. else
  2470. data = (char*) juce_malloc (initialSize);
  2471. }
  2472. else
  2473. {
  2474. data = 0;
  2475. size = 0;
  2476. }
  2477. }
  2478. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2479. : data (0),
  2480. size (other.size)
  2481. {
  2482. if (size > 0)
  2483. {
  2484. jassert (other.data != 0);
  2485. data = (char*) juce_malloc (size);
  2486. memcpy (data, other.data, size);
  2487. }
  2488. }
  2489. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2490. const int sizeInBytes) throw()
  2491. : data (0),
  2492. size (jmax (0, sizeInBytes))
  2493. {
  2494. jassert (sizeInBytes >= 0);
  2495. if (size > 0)
  2496. {
  2497. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2498. data = (char*) juce_malloc (size);
  2499. if (dataToInitialiseFrom != 0)
  2500. memcpy (data, dataToInitialiseFrom, size);
  2501. }
  2502. }
  2503. MemoryBlock::~MemoryBlock() throw()
  2504. {
  2505. jassert (size >= 0); // should never happen
  2506. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2507. juce_free (data);
  2508. }
  2509. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2510. {
  2511. if (this != &other)
  2512. {
  2513. setSize (other.size, false);
  2514. memcpy (data, other.data, size);
  2515. }
  2516. return *this;
  2517. }
  2518. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2519. {
  2520. return (size == other.size)
  2521. && (memcmp (data, other.data, size) == 0);
  2522. }
  2523. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2524. {
  2525. return ! operator== (other);
  2526. }
  2527. // this will resize the block to this size
  2528. void MemoryBlock::setSize (const int newSize,
  2529. const bool initialiseToZero) throw()
  2530. {
  2531. if (size != newSize)
  2532. {
  2533. if (newSize <= 0)
  2534. {
  2535. juce_free (data);
  2536. data = 0;
  2537. size = 0;
  2538. }
  2539. else
  2540. {
  2541. if (data != 0)
  2542. {
  2543. data = (char*) juce_realloc (data, newSize);
  2544. if (initialiseToZero && (newSize > size))
  2545. zeromem (data + size, newSize - size);
  2546. }
  2547. else
  2548. {
  2549. if (initialiseToZero)
  2550. data = (char*) juce_calloc (newSize);
  2551. else
  2552. data = (char*) juce_malloc (newSize);
  2553. }
  2554. size = newSize;
  2555. }
  2556. }
  2557. }
  2558. void MemoryBlock::ensureSize (const int minimumSize,
  2559. const bool initialiseToZero) throw()
  2560. {
  2561. if (size < minimumSize)
  2562. setSize (minimumSize, initialiseToZero);
  2563. }
  2564. void MemoryBlock::fillWith (const uint8 value) throw()
  2565. {
  2566. memset (data, (int) value, size);
  2567. }
  2568. void MemoryBlock::append (const void* const srcData,
  2569. const int numBytes) throw()
  2570. {
  2571. if (numBytes > 0)
  2572. {
  2573. const int oldSize = size;
  2574. setSize (size + numBytes);
  2575. memcpy (data + oldSize, srcData, numBytes);
  2576. }
  2577. }
  2578. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  2579. {
  2580. const char* d = (const char*) src;
  2581. if (offset < 0)
  2582. {
  2583. d -= offset;
  2584. num -= offset;
  2585. offset = 0;
  2586. }
  2587. if (offset + num > size)
  2588. num = size - offset;
  2589. if (num > 0)
  2590. memcpy (data + offset, d, num);
  2591. }
  2592. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  2593. {
  2594. char* d = (char*) dst;
  2595. if (offset < 0)
  2596. {
  2597. zeromem (d, -offset);
  2598. d -= offset;
  2599. num += offset;
  2600. offset = 0;
  2601. }
  2602. if (offset + num > size)
  2603. {
  2604. const int newNum = size - offset;
  2605. zeromem (d + newNum, num - newNum);
  2606. num = newNum;
  2607. }
  2608. if (num > 0)
  2609. memcpy (d, data + offset, num);
  2610. }
  2611. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  2612. {
  2613. if (startByte < 0)
  2614. {
  2615. numBytesToRemove += startByte;
  2616. startByte = 0;
  2617. }
  2618. if (startByte + numBytesToRemove >= size)
  2619. {
  2620. setSize (startByte);
  2621. }
  2622. else if (numBytesToRemove > 0)
  2623. {
  2624. memmove (data + startByte,
  2625. data + startByte + numBytesToRemove,
  2626. size - (startByte + numBytesToRemove));
  2627. setSize (size - numBytesToRemove);
  2628. }
  2629. }
  2630. const String MemoryBlock::toString() const throw()
  2631. {
  2632. return String (data, size);
  2633. }
  2634. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  2635. {
  2636. int res = 0;
  2637. int byte = bitRangeStart >> 3;
  2638. int offsetInByte = bitRangeStart & 7;
  2639. int bitsSoFar = 0;
  2640. while (numBits > 0 && byte < size)
  2641. {
  2642. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2643. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2644. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2645. bitsSoFar += bitsThisTime;
  2646. numBits -= bitsThisTime;
  2647. ++byte;
  2648. offsetInByte = 0;
  2649. }
  2650. return res;
  2651. }
  2652. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  2653. {
  2654. int byte = bitRangeStart >> 3;
  2655. int offsetInByte = bitRangeStart & 7;
  2656. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2657. while (numBits > 0 && byte < size)
  2658. {
  2659. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2660. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  2661. const unsigned int tempBits = bitsToSet << offsetInByte;
  2662. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  2663. ++byte;
  2664. numBits -= bitsThisTime;
  2665. bitsToSet >>= bitsThisTime;
  2666. mask >>= bitsThisTime;
  2667. offsetInByte = 0;
  2668. }
  2669. }
  2670. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2671. {
  2672. ensureSize (hex.length() >> 1);
  2673. char* dest = data;
  2674. int i = 0;
  2675. for (;;)
  2676. {
  2677. int byte = 0;
  2678. for (int loop = 2; --loop >= 0;)
  2679. {
  2680. byte <<= 4;
  2681. for (;;)
  2682. {
  2683. const tchar c = hex [i++];
  2684. if (c >= T('0') && c <= T('9'))
  2685. {
  2686. byte |= c - T('0');
  2687. break;
  2688. }
  2689. else if (c >= T('a') && c <= T('z'))
  2690. {
  2691. byte |= c - (T('a') - 10);
  2692. break;
  2693. }
  2694. else if (c >= T('A') && c <= T('Z'))
  2695. {
  2696. byte |= c - (T('A') - 10);
  2697. break;
  2698. }
  2699. else if (c == 0)
  2700. {
  2701. setSize ((int) (dest - data));
  2702. return;
  2703. }
  2704. }
  2705. }
  2706. *dest++ = (char) byte;
  2707. }
  2708. }
  2709. static const char* const encodingTable
  2710. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2711. const String MemoryBlock::toBase64Encoding() const throw()
  2712. {
  2713. const int numChars = ((size << 3) + 5) / 6;
  2714. String destString (size); // store the length, followed by a '.', and then the data.
  2715. const int initialLen = destString.length();
  2716. destString.preallocateStorage (initialLen + 2 + numChars);
  2717. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  2718. *d++ = T('.');
  2719. for (int i = 0; i < numChars; ++i)
  2720. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2721. *d++ = 0;
  2722. return destString;
  2723. }
  2724. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2725. {
  2726. const int startPos = s.indexOfChar (T('.')) + 1;
  2727. if (startPos <= 0)
  2728. return false;
  2729. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2730. setSize (numBytesNeeded, true);
  2731. const int numChars = s.length() - startPos;
  2732. const tchar* const srcChars = ((const tchar*) s) + startPos;
  2733. int pos = 0;
  2734. for (int i = 0; i < numChars; ++i)
  2735. {
  2736. const char c = (char) srcChars[i];
  2737. for (int j = 0; j < 64; ++j)
  2738. {
  2739. if (encodingTable[j] == c)
  2740. {
  2741. setBitRange (pos, 6, j);
  2742. pos += 6;
  2743. break;
  2744. }
  2745. }
  2746. }
  2747. return true;
  2748. }
  2749. END_JUCE_NAMESPACE
  2750. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2751. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2752. BEGIN_JUCE_NAMESPACE
  2753. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2754. : properties (ignoreCaseOfKeyNames),
  2755. fallbackProperties (0),
  2756. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2757. {
  2758. }
  2759. PropertySet::PropertySet (const PropertySet& other) throw()
  2760. : properties (other.properties),
  2761. fallbackProperties (other.fallbackProperties),
  2762. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2763. {
  2764. }
  2765. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2766. {
  2767. properties = other.properties;
  2768. fallbackProperties = other.fallbackProperties;
  2769. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2770. propertyChanged();
  2771. return *this;
  2772. }
  2773. PropertySet::~PropertySet()
  2774. {
  2775. }
  2776. void PropertySet::clear()
  2777. {
  2778. const ScopedLock sl (lock);
  2779. if (properties.size() > 0)
  2780. {
  2781. properties.clear();
  2782. propertyChanged();
  2783. }
  2784. }
  2785. const String PropertySet::getValue (const String& keyName,
  2786. const String& defaultValue) const throw()
  2787. {
  2788. const ScopedLock sl (lock);
  2789. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2790. if (index >= 0)
  2791. return properties.getAllValues() [index];
  2792. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2793. : defaultValue;
  2794. }
  2795. int PropertySet::getIntValue (const String& keyName,
  2796. const int defaultValue) const throw()
  2797. {
  2798. const ScopedLock sl (lock);
  2799. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2800. if (index >= 0)
  2801. return properties.getAllValues() [index].getIntValue();
  2802. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2803. : defaultValue;
  2804. }
  2805. double PropertySet::getDoubleValue (const String& keyName,
  2806. const double defaultValue) const throw()
  2807. {
  2808. const ScopedLock sl (lock);
  2809. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2810. if (index >= 0)
  2811. return properties.getAllValues()[index].getDoubleValue();
  2812. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2813. : defaultValue;
  2814. }
  2815. bool PropertySet::getBoolValue (const String& keyName,
  2816. const bool defaultValue) const throw()
  2817. {
  2818. const ScopedLock sl (lock);
  2819. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2820. if (index >= 0)
  2821. return properties.getAllValues() [index].getIntValue() != 0;
  2822. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2823. : defaultValue;
  2824. }
  2825. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2826. {
  2827. XmlDocument doc (getValue (keyName));
  2828. return doc.getDocumentElement();
  2829. }
  2830. void PropertySet::setValue (const String& keyName,
  2831. const String& value) throw()
  2832. {
  2833. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2834. if (keyName.isNotEmpty())
  2835. {
  2836. const ScopedLock sl (lock);
  2837. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2838. if (index < 0 || properties.getAllValues() [index] != value)
  2839. {
  2840. properties.set (keyName, value);
  2841. propertyChanged();
  2842. }
  2843. }
  2844. }
  2845. void PropertySet::removeValue (const String& keyName) throw()
  2846. {
  2847. if (keyName.isNotEmpty())
  2848. {
  2849. const ScopedLock sl (lock);
  2850. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2851. if (index >= 0)
  2852. {
  2853. properties.remove (keyName);
  2854. propertyChanged();
  2855. }
  2856. }
  2857. }
  2858. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2859. {
  2860. setValue (keyName, String (value));
  2861. }
  2862. void PropertySet::setValue (const String& keyName, const int value) throw()
  2863. {
  2864. setValue (keyName, String (value));
  2865. }
  2866. void PropertySet::setValue (const String& keyName, const double value) throw()
  2867. {
  2868. setValue (keyName, String (value));
  2869. }
  2870. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2871. {
  2872. setValue (keyName, String ((value) ? T("1") : T("0")));
  2873. }
  2874. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2875. {
  2876. setValue (keyName, (xml == 0) ? String::empty
  2877. : xml->createDocument (String::empty, true));
  2878. }
  2879. bool PropertySet::containsKey (const String& keyName) const throw()
  2880. {
  2881. const ScopedLock sl (lock);
  2882. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2883. }
  2884. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2885. {
  2886. const ScopedLock sl (lock);
  2887. fallbackProperties = fallbackProperties_;
  2888. }
  2889. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2890. {
  2891. const ScopedLock sl (lock);
  2892. XmlElement* const xml = new XmlElement (nodeName);
  2893. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2894. {
  2895. XmlElement* const e = new XmlElement (T("VALUE"));
  2896. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2897. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2898. xml->addChildElement (e);
  2899. }
  2900. return xml;
  2901. }
  2902. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2903. {
  2904. const ScopedLock sl (lock);
  2905. clear();
  2906. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2907. {
  2908. if (e->hasAttribute (T("name"))
  2909. && e->hasAttribute (T("val")))
  2910. {
  2911. properties.set (e->getStringAttribute (T("name")),
  2912. e->getStringAttribute (T("val")));
  2913. }
  2914. }
  2915. if (properties.size() > 0)
  2916. propertyChanged();
  2917. }
  2918. void PropertySet::propertyChanged()
  2919. {
  2920. }
  2921. END_JUCE_NAMESPACE
  2922. /********* End of inlined file: juce_PropertySet.cpp *********/
  2923. /********* Start of inlined file: juce_Variant.cpp *********/
  2924. BEGIN_JUCE_NAMESPACE
  2925. var::var() throw()
  2926. : type (voidType)
  2927. {
  2928. value.doubleValue = 0;
  2929. }
  2930. void var::releaseValue() throw()
  2931. {
  2932. if (type == stringType)
  2933. delete value.stringValue;
  2934. else if (type == objectType && value.objectValue != 0)
  2935. value.objectValue->decReferenceCount();
  2936. }
  2937. var::~var()
  2938. {
  2939. releaseValue();
  2940. }
  2941. var::var (const var& valueToCopy) throw()
  2942. : type (valueToCopy.type),
  2943. value (valueToCopy.value)
  2944. {
  2945. if (type == stringType)
  2946. value.stringValue = new String (*(value.stringValue));
  2947. else if (type == objectType && value.objectValue != 0)
  2948. value.objectValue->incReferenceCount();
  2949. }
  2950. var::var (const int value_) throw()
  2951. : type (intType)
  2952. {
  2953. value.intValue = value_;
  2954. }
  2955. var::var (const bool value_) throw()
  2956. : type (boolType)
  2957. {
  2958. value.boolValue = value_;
  2959. }
  2960. var::var (const double value_) throw()
  2961. : type (doubleType)
  2962. {
  2963. value.doubleValue = value_;
  2964. }
  2965. var::var (const String& value_) throw()
  2966. : type (stringType)
  2967. {
  2968. value.stringValue = new String (value_);
  2969. }
  2970. var::var (const char* const value_) throw()
  2971. : type (stringType)
  2972. {
  2973. value.stringValue = new String (value_);
  2974. }
  2975. var::var (const juce_wchar* const value_) throw()
  2976. : type (stringType)
  2977. {
  2978. value.stringValue = new String (value_);
  2979. }
  2980. var::var (DynamicObject* const object) throw()
  2981. : type (objectType)
  2982. {
  2983. value.objectValue = object;
  2984. if (object != 0)
  2985. object->incReferenceCount();
  2986. }
  2987. var::var (MethodFunction method_) throw()
  2988. : type (methodType)
  2989. {
  2990. value.methodValue = method_;
  2991. }
  2992. const var& var::operator= (const var& valueToCopy) throw()
  2993. {
  2994. if (this != &valueToCopy)
  2995. {
  2996. if (type == stringType)
  2997. delete value.stringValue;
  2998. DynamicObject* const oldObject = getObject();
  2999. type = valueToCopy.type;
  3000. value = valueToCopy.value;
  3001. if (type == stringType)
  3002. value.stringValue = new String (*(value.stringValue));
  3003. else if (type == objectType && value.objectValue != 0)
  3004. value.objectValue->incReferenceCount();
  3005. if (oldObject != 0)
  3006. oldObject->decReferenceCount();
  3007. }
  3008. return *this;
  3009. }
  3010. const var& var::operator= (const int value_) throw()
  3011. {
  3012. releaseValue();
  3013. type = intType;
  3014. value.intValue = value_;
  3015. return *this;
  3016. }
  3017. const var& var::operator= (const bool value_) throw()
  3018. {
  3019. releaseValue();
  3020. type = boolType;
  3021. value.boolValue = value_;
  3022. return *this;
  3023. }
  3024. const var& var::operator= (const double value_) throw()
  3025. {
  3026. releaseValue();
  3027. type = doubleType;
  3028. value.doubleValue = value_;
  3029. return *this;
  3030. }
  3031. const var& var::operator= (const char* const value_) throw()
  3032. {
  3033. releaseValue();
  3034. type = stringType;
  3035. value.stringValue = new String (value_);
  3036. return *this;
  3037. }
  3038. const var& var::operator= (const juce_wchar* const value_) throw()
  3039. {
  3040. releaseValue();
  3041. type = stringType;
  3042. value.stringValue = new String (value_);
  3043. return *this;
  3044. }
  3045. const var& var::operator= (const String& value_) throw()
  3046. {
  3047. releaseValue();
  3048. type = stringType;
  3049. value.stringValue = new String (value_);
  3050. return *this;
  3051. }
  3052. const var& var::operator= (DynamicObject* const value_) throw()
  3053. {
  3054. value_->incReferenceCount();
  3055. releaseValue();
  3056. type = objectType;
  3057. value.objectValue = value_;
  3058. return *this;
  3059. }
  3060. const var& var::operator= (MethodFunction method_) throw()
  3061. {
  3062. releaseValue();
  3063. type = doubleType;
  3064. value.methodValue = method_;
  3065. return *this;
  3066. }
  3067. var::operator int() const throw()
  3068. {
  3069. switch (type)
  3070. {
  3071. case voidType:
  3072. case objectType: break;
  3073. case intType: return value.intValue;
  3074. case boolType: return value.boolValue ? 1 : 0;
  3075. case doubleType: return (int) value.doubleValue;
  3076. case stringType: return value.stringValue->getIntValue();
  3077. default: jassertfalse; break;
  3078. }
  3079. return 0;
  3080. }
  3081. var::operator bool() const throw()
  3082. {
  3083. switch (type)
  3084. {
  3085. case voidType: break;
  3086. case objectType: return value.objectValue != 0;
  3087. case intType: return value.intValue != 0;
  3088. case boolType: return value.boolValue;
  3089. case doubleType: return value.doubleValue != 0;
  3090. case stringType: return value.stringValue->getIntValue() != 0
  3091. || value.stringValue->trim().equalsIgnoreCase (T("true"))
  3092. || value.stringValue->trim().equalsIgnoreCase (T("yes"));
  3093. default: jassertfalse; break;
  3094. }
  3095. return false;
  3096. }
  3097. var::operator double() const throw()
  3098. {
  3099. switch (type)
  3100. {
  3101. case voidType:
  3102. case objectType: break;
  3103. case intType: return value.intValue;
  3104. case boolType: return value.boolValue ? 1.0 : 0.0;
  3105. case doubleType: return value.doubleValue;
  3106. case stringType: return value.stringValue->getDoubleValue();
  3107. default: jassertfalse; break;
  3108. }
  3109. return 0;
  3110. }
  3111. const String var::toString() const throw()
  3112. {
  3113. switch (type)
  3114. {
  3115. case voidType:
  3116. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3117. case intType: return String (value.intValue);
  3118. case boolType: return value.boolValue ? T("1") : T("0");
  3119. case doubleType: return String (value.doubleValue);
  3120. case stringType: return *(value.stringValue);
  3121. default: jassertfalse; break;
  3122. }
  3123. return String::empty;
  3124. }
  3125. var::operator const String() const throw()
  3126. {
  3127. return toString();
  3128. }
  3129. DynamicObject* var::getObject() const throw()
  3130. {
  3131. return type == objectType ? value.objectValue : 0;
  3132. }
  3133. const var var::operator[] (const var::identifier& propertyName) const throw()
  3134. {
  3135. if (type == objectType && value.objectValue != 0)
  3136. return value.objectValue->getProperty (propertyName);
  3137. return var();
  3138. }
  3139. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3140. {
  3141. if (type == objectType && value.objectValue != 0)
  3142. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3143. return var();
  3144. }
  3145. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3146. {
  3147. if (isMethod())
  3148. {
  3149. DynamicObject* const target = targetObject.getObject();
  3150. if (target != 0)
  3151. return (target->*(value.methodValue)) (arguments, numArguments);
  3152. }
  3153. return var();
  3154. }
  3155. const var var::call (const var::identifier& method) const
  3156. {
  3157. return invoke (method, 0, 0);
  3158. }
  3159. const var var::call (const var::identifier& method, const var& arg1) const
  3160. {
  3161. return invoke (method, &arg1, 1);
  3162. }
  3163. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3164. {
  3165. var args[] = { arg1, arg2 };
  3166. return invoke (method, args, 2);
  3167. }
  3168. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3169. {
  3170. var args[] = { arg1, arg2, arg3 };
  3171. return invoke (method, args, 3);
  3172. }
  3173. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3174. {
  3175. var args[] = { arg1, arg2, arg3, arg4 };
  3176. return invoke (method, args, 4);
  3177. }
  3178. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3179. {
  3180. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3181. return invoke (method, args, 5);
  3182. }
  3183. var::identifier::identifier (const String& name_) throw()
  3184. : name (name_),
  3185. hashCode (name_.hashCode())
  3186. {
  3187. }
  3188. var::identifier::identifier (const char* const name_) throw()
  3189. : name (name_),
  3190. hashCode (name.hashCode())
  3191. {
  3192. }
  3193. var::identifier::~identifier() throw()
  3194. {
  3195. }
  3196. DynamicObject::DynamicObject()
  3197. {
  3198. }
  3199. DynamicObject::~DynamicObject()
  3200. {
  3201. }
  3202. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3203. {
  3204. const int index = propertyIds.indexOf (propertyName.hashCode);
  3205. return index >= 0 && ! propertyValues.getUnchecked (index)->isMethod();
  3206. }
  3207. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3208. {
  3209. const int index = propertyIds.indexOf (propertyName.hashCode);
  3210. if (index >= 0)
  3211. return *propertyValues.getUnchecked (index);
  3212. return var();
  3213. }
  3214. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3215. {
  3216. const int index = propertyIds.indexOf (propertyName.hashCode);
  3217. if (index >= 0)
  3218. {
  3219. propertyValues.set (index, new var (newValue));
  3220. }
  3221. else
  3222. {
  3223. propertyIds.add (propertyName.hashCode);
  3224. propertyValues.add (new var (newValue));
  3225. }
  3226. }
  3227. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3228. {
  3229. const int index = propertyIds.indexOf (propertyName.hashCode);
  3230. if (index >= 0)
  3231. {
  3232. propertyIds.remove (index);
  3233. propertyValues.remove (index);
  3234. }
  3235. }
  3236. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3237. {
  3238. return getProperty (methodName).isMethod();
  3239. }
  3240. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3241. const var* parameters,
  3242. int numParameters)
  3243. {
  3244. return getProperty (methodName).invoke (this, parameters, numParameters);
  3245. }
  3246. void DynamicObject::setMethod (const var::identifier& name,
  3247. var::MethodFunction methodFunction)
  3248. {
  3249. setProperty (name, methodFunction);
  3250. }
  3251. void DynamicObject::clear()
  3252. {
  3253. propertyIds.clear();
  3254. propertyValues.clear();
  3255. }
  3256. END_JUCE_NAMESPACE
  3257. /********* End of inlined file: juce_Variant.cpp *********/
  3258. /********* Start of inlined file: juce_BlowFish.cpp *********/
  3259. BEGIN_JUCE_NAMESPACE
  3260. static const uint32 initialPValues [18] =
  3261. {
  3262. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  3263. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3264. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  3265. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3266. 0x9216d5d9, 0x8979fb1b
  3267. };
  3268. static const uint32 initialSValues [4 * 256] =
  3269. {
  3270. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  3271. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3272. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  3273. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3274. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  3275. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3276. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  3277. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3278. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  3279. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3280. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  3281. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3282. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  3283. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3284. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  3285. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3286. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  3287. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3288. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  3289. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3290. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  3291. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3292. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  3293. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3294. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  3295. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3296. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  3297. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3298. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  3299. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3300. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  3301. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3302. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  3303. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3304. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  3305. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3306. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  3307. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3308. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  3309. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3310. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  3311. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3312. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  3313. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3314. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  3315. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3316. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  3317. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3318. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  3319. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3320. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  3321. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3322. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  3323. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3324. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  3325. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3326. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  3327. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3328. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  3329. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3330. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  3331. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3332. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  3333. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3334. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  3335. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3336. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  3337. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3338. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  3339. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3340. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  3341. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3342. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  3343. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3344. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  3345. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3346. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  3347. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3348. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  3349. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3350. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  3351. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3352. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  3353. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3354. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  3355. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3356. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  3357. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3358. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  3359. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3360. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  3361. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3362. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  3363. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3364. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  3365. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3366. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  3367. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3368. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  3369. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3370. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  3371. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3372. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  3373. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3374. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  3375. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3376. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  3377. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3378. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  3379. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3380. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  3381. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3382. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  3383. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3384. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  3385. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3386. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  3387. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3388. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  3389. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3390. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  3391. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3392. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  3393. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3394. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  3395. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3396. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  3397. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3398. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  3399. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3400. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  3401. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3402. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  3403. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3404. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  3405. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3406. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  3407. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3408. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  3409. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3410. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  3411. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3412. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  3413. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3414. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  3415. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3416. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  3417. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3418. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  3419. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3420. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  3421. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3422. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  3423. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3424. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  3425. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3426. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  3427. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3428. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  3429. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3430. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  3431. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3432. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  3433. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3434. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  3435. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3436. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  3437. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3438. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  3439. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3440. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  3441. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3442. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  3443. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3444. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  3445. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3446. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  3447. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3448. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  3449. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3450. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  3451. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3452. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  3453. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3454. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  3455. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3456. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  3457. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3458. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  3459. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3460. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  3461. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3462. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  3463. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3464. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  3465. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3466. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  3467. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3468. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  3469. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3470. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  3471. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3472. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  3473. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3474. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  3475. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3476. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  3477. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3478. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  3479. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3480. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  3481. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3482. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  3483. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3484. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  3485. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3486. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  3487. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3488. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  3489. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3490. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  3491. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3492. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  3493. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3494. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  3495. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3496. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  3497. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3498. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  3499. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3500. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  3501. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3502. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  3503. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3504. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  3505. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3506. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  3507. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3508. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  3509. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3510. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  3511. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3512. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  3513. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3514. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  3515. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3516. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  3517. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3518. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  3519. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3520. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  3521. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3522. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  3523. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3524. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  3525. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3526. };
  3527. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  3528. {
  3529. memcpy (p, initialPValues, sizeof (p));
  3530. int i, j;
  3531. for (i = 4; --i >= 0;)
  3532. {
  3533. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3534. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3535. }
  3536. j = 0;
  3537. for (i = 0; i < 18; ++i)
  3538. {
  3539. uint32 d = 0;
  3540. for (int k = 0; k < 4; ++k)
  3541. {
  3542. d = (d << 8) | keyData[j];
  3543. if (++j >= keyBytes)
  3544. j = 0;
  3545. }
  3546. p[i] = initialPValues[i] ^ d;
  3547. }
  3548. uint32 l = 0, r = 0;
  3549. for (i = 0; i < 18; i += 2)
  3550. {
  3551. encrypt (l, r);
  3552. p[i] = l;
  3553. p[i + 1] = r;
  3554. }
  3555. for (i = 0; i < 4; ++i)
  3556. {
  3557. for (j = 0; j < 256; j += 2)
  3558. {
  3559. encrypt (l, r);
  3560. s[i][j] = l;
  3561. s[i][j + 1] = r;
  3562. }
  3563. }
  3564. }
  3565. BlowFish::BlowFish (const BlowFish& other)
  3566. {
  3567. for (int i = 4; --i >= 0;)
  3568. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3569. operator= (other);
  3570. }
  3571. const BlowFish& BlowFish::operator= (const BlowFish& other)
  3572. {
  3573. memcpy (p, other.p, sizeof (p));
  3574. for (int i = 4; --i >= 0;)
  3575. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3576. return *this;
  3577. }
  3578. BlowFish::~BlowFish()
  3579. {
  3580. for (int i = 4; --i >= 0;)
  3581. juce_free (s[i]);
  3582. }
  3583. uint32 BlowFish::F (uint32 x) const
  3584. {
  3585. uint16 a, b, c, d;
  3586. uint32 y;
  3587. d = (uint16) (x & 0xff);
  3588. x >>= 8;
  3589. c = (uint16) (x & 0xff);
  3590. x >>= 8;
  3591. b = (uint16) (x & 0xff);
  3592. x >>= 8;
  3593. a = (uint16) (x & 0xff);
  3594. y = s[0][a] + s[1][b];
  3595. y = y ^ s[2][c];
  3596. y = y + s[3][d];
  3597. return y;
  3598. }
  3599. void BlowFish::encrypt (uint32& data1,
  3600. uint32& data2) const
  3601. {
  3602. uint32 l = data1;
  3603. uint32 r = data2;
  3604. for (int i = 0; i < 16; ++i)
  3605. {
  3606. l = l ^ p[i];
  3607. r = F (l) ^ r;
  3608. const uint32 temp = l;
  3609. l = r;
  3610. r = temp;
  3611. }
  3612. const uint32 temp = l;
  3613. l = r;
  3614. r = temp;
  3615. r = r ^ p[16];
  3616. l = l ^ p[17];
  3617. data1 = l;
  3618. data2 = r;
  3619. }
  3620. void BlowFish::decrypt (uint32& data1,
  3621. uint32& data2) const
  3622. {
  3623. uint32 l = data1;
  3624. uint32 r = data2;
  3625. for (int i = 17; i > 1; --i)
  3626. {
  3627. l =l ^ p[i];
  3628. r = F (l) ^ r;
  3629. const uint32 temp = l;
  3630. l = r;
  3631. r = temp;
  3632. }
  3633. const uint32 temp = l;
  3634. l = r;
  3635. r = temp;
  3636. r = r ^ p[1];
  3637. l = l ^ p[0];
  3638. data1 = l;
  3639. data2 = r;
  3640. }
  3641. END_JUCE_NAMESPACE
  3642. /********* End of inlined file: juce_BlowFish.cpp *********/
  3643. /********* Start of inlined file: juce_MD5.cpp *********/
  3644. BEGIN_JUCE_NAMESPACE
  3645. MD5::MD5()
  3646. {
  3647. zeromem (result, sizeof (result));
  3648. }
  3649. MD5::MD5 (const MD5& other)
  3650. {
  3651. memcpy (result, other.result, sizeof (result));
  3652. }
  3653. const MD5& MD5::operator= (const MD5& other)
  3654. {
  3655. memcpy (result, other.result, sizeof (result));
  3656. return *this;
  3657. }
  3658. MD5::MD5 (const MemoryBlock& data)
  3659. {
  3660. ProcessContext context;
  3661. context.processBlock ((const uint8*) data.getData(), data.getSize());
  3662. context.finish (result);
  3663. }
  3664. MD5::MD5 (const char* data, const int numBytes)
  3665. {
  3666. ProcessContext context;
  3667. context.processBlock ((const uint8*) data, numBytes);
  3668. context.finish (result);
  3669. }
  3670. MD5::MD5 (const String& text)
  3671. {
  3672. ProcessContext context;
  3673. const int len = text.length();
  3674. const juce_wchar* const t = text;
  3675. for (int i = 0; i < len; ++i)
  3676. {
  3677. // force the string into integer-sized unicode characters, to try to make it
  3678. // get the same results on all platforms + compilers.
  3679. uint32 unicodeChar = (uint32) t[i];
  3680. swapIfBigEndian (unicodeChar);
  3681. context.processBlock ((const uint8*) &unicodeChar,
  3682. sizeof (unicodeChar));
  3683. }
  3684. context.finish (result);
  3685. }
  3686. void MD5::processStream (InputStream& input, int numBytesToRead)
  3687. {
  3688. ProcessContext context;
  3689. if (numBytesToRead < 0)
  3690. numBytesToRead = INT_MAX;
  3691. while (numBytesToRead > 0)
  3692. {
  3693. char tempBuffer [512];
  3694. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  3695. if (bytesRead <= 0)
  3696. break;
  3697. numBytesToRead -= bytesRead;
  3698. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  3699. }
  3700. context.finish (result);
  3701. }
  3702. MD5::MD5 (InputStream& input, int numBytesToRead)
  3703. {
  3704. processStream (input, numBytesToRead);
  3705. }
  3706. MD5::MD5 (const File& file)
  3707. {
  3708. FileInputStream* const fin = file.createInputStream();
  3709. if (fin != 0)
  3710. {
  3711. processStream (*fin, -1);
  3712. delete fin;
  3713. }
  3714. else
  3715. {
  3716. zeromem (result, sizeof (result));
  3717. }
  3718. }
  3719. MD5::~MD5()
  3720. {
  3721. }
  3722. MD5::ProcessContext::ProcessContext()
  3723. {
  3724. state[0] = 0x67452301;
  3725. state[1] = 0xefcdab89;
  3726. state[2] = 0x98badcfe;
  3727. state[3] = 0x10325476;
  3728. count[0] = 0;
  3729. count[1] = 0;
  3730. }
  3731. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  3732. {
  3733. int bufferPos = ((count[0] >> 3) & 0x3F);
  3734. count[0] += (dataSize << 3);
  3735. if (count[0] < ((uint32) dataSize << 3))
  3736. count[1]++;
  3737. count[1] += (dataSize >> 29);
  3738. const int spaceLeft = 64 - bufferPos;
  3739. int i = 0;
  3740. if (dataSize >= spaceLeft)
  3741. {
  3742. memcpy (buffer + bufferPos, data, spaceLeft);
  3743. transform (buffer);
  3744. i = spaceLeft;
  3745. while (i < dataSize - 63)
  3746. {
  3747. transform (data + i);
  3748. i += 64;
  3749. }
  3750. bufferPos = 0;
  3751. }
  3752. memcpy (buffer + bufferPos, data + i, dataSize - i);
  3753. }
  3754. static void encode (uint8* const output,
  3755. const uint32* const input,
  3756. const int numBytes)
  3757. {
  3758. uint32* const o = (uint32*) output;
  3759. for (int i = 0; i < (numBytes >> 2); ++i)
  3760. o[i] = swapIfBigEndian (input [i]);
  3761. }
  3762. static void decode (uint32* const output,
  3763. const uint8* const input,
  3764. const int numBytes)
  3765. {
  3766. for (int i = 0; i < (numBytes >> 2); ++i)
  3767. output[i] = littleEndianInt ((const char*) input + (i << 2));
  3768. }
  3769. void MD5::ProcessContext::finish (uint8* const result)
  3770. {
  3771. unsigned char encodedLength[8];
  3772. encode (encodedLength, count, 8);
  3773. // Pad out to 56 mod 64.
  3774. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3775. const int paddingLength = (index < 56) ? (56 - index)
  3776. : (120 - index);
  3777. uint8 paddingBuffer [64];
  3778. zeromem (paddingBuffer, paddingLength);
  3779. paddingBuffer [0] = 0x80;
  3780. processBlock (paddingBuffer, paddingLength);
  3781. processBlock (encodedLength, 8);
  3782. encode (result, state, 16);
  3783. zeromem (buffer, sizeof (buffer));
  3784. }
  3785. #define S11 7
  3786. #define S12 12
  3787. #define S13 17
  3788. #define S14 22
  3789. #define S21 5
  3790. #define S22 9
  3791. #define S23 14
  3792. #define S24 20
  3793. #define S31 4
  3794. #define S32 11
  3795. #define S33 16
  3796. #define S34 23
  3797. #define S41 6
  3798. #define S42 10
  3799. #define S43 15
  3800. #define S44 21
  3801. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  3802. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  3803. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  3804. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  3805. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  3806. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3807. {
  3808. a += F (b, c, d) + x + ac;
  3809. a = rotateLeft (a, s) + b;
  3810. }
  3811. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3812. {
  3813. a += G (b, c, d) + x + ac;
  3814. a = rotateLeft (a, s) + b;
  3815. }
  3816. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3817. {
  3818. a += H (b, c, d) + x + ac;
  3819. a = rotateLeft (a, s) + b;
  3820. }
  3821. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3822. {
  3823. a += I (b, c, d) + x + ac;
  3824. a = rotateLeft (a, s) + b;
  3825. }
  3826. void MD5::ProcessContext::transform (const uint8* const buffer)
  3827. {
  3828. uint32 a = state[0];
  3829. uint32 b = state[1];
  3830. uint32 c = state[2];
  3831. uint32 d = state[3];
  3832. uint32 x[16];
  3833. decode (x, buffer, 64);
  3834. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  3835. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  3836. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  3837. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  3838. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  3839. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  3840. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  3841. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  3842. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  3843. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  3844. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  3845. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  3846. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  3847. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  3848. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  3849. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  3850. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  3851. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  3852. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  3853. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  3854. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  3855. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  3856. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  3857. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  3858. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  3859. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  3860. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  3861. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  3862. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  3863. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  3864. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  3865. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  3866. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  3867. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  3868. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  3869. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  3870. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  3871. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  3872. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  3873. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  3874. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  3875. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  3876. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  3877. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  3878. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  3879. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  3880. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  3881. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  3882. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  3883. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  3884. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  3885. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  3886. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  3887. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  3888. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  3889. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  3890. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  3891. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  3892. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  3893. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  3894. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  3895. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  3896. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  3897. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  3898. state[0] += a;
  3899. state[1] += b;
  3900. state[2] += c;
  3901. state[3] += d;
  3902. zeromem (x, sizeof (x));
  3903. }
  3904. const MemoryBlock MD5::getRawChecksumData() const
  3905. {
  3906. return MemoryBlock (result, 16);
  3907. }
  3908. const String MD5::toHexString() const
  3909. {
  3910. return String::toHexString (result, 16, 0);
  3911. }
  3912. bool MD5::operator== (const MD5& other) const
  3913. {
  3914. return memcmp (result, other.result, 16) == 0;
  3915. }
  3916. bool MD5::operator!= (const MD5& other) const
  3917. {
  3918. return ! operator== (other);
  3919. }
  3920. END_JUCE_NAMESPACE
  3921. /********* End of inlined file: juce_MD5.cpp *********/
  3922. /********* Start of inlined file: juce_Primes.cpp *********/
  3923. BEGIN_JUCE_NAMESPACE
  3924. static void createSmallSieve (const int numBits, BitArray& result) throw()
  3925. {
  3926. result.setBit (numBits);
  3927. result.clearBit (numBits); // to enlarge the array
  3928. result.setBit (0);
  3929. int n = 2;
  3930. do
  3931. {
  3932. for (int i = n + n; i < numBits; i += n)
  3933. result.setBit (i);
  3934. n = result.findNextClearBit (n + 1);
  3935. }
  3936. while (n <= (numBits >> 1));
  3937. }
  3938. static void bigSieve (const BitArray& base,
  3939. const int numBits,
  3940. BitArray& result,
  3941. const BitArray& smallSieve,
  3942. const int smallSieveSize) throw()
  3943. {
  3944. jassert (! base[0]); // must be even!
  3945. result.setBit (numBits);
  3946. result.clearBit (numBits); // to enlarge the array
  3947. int index = smallSieve.findNextClearBit (0);
  3948. do
  3949. {
  3950. const int prime = (index << 1) + 1;
  3951. BitArray r (base);
  3952. BitArray remainder;
  3953. r.divideBy (prime, remainder);
  3954. int i = prime - remainder.getBitRangeAsInt (0, 32);
  3955. if (r.isEmpty())
  3956. i += prime;
  3957. if ((i & 1) == 0)
  3958. i += prime;
  3959. i = (i - 1) >> 1;
  3960. while (i < numBits)
  3961. {
  3962. result.setBit (i);
  3963. i += prime;
  3964. }
  3965. index = smallSieve.findNextClearBit (index + 1);
  3966. }
  3967. while (index < smallSieveSize);
  3968. }
  3969. static bool findCandidate (const BitArray& base,
  3970. const BitArray& sieve,
  3971. const int numBits,
  3972. BitArray& result,
  3973. const int certainty) throw()
  3974. {
  3975. for (int i = 0; i < numBits; ++i)
  3976. {
  3977. if (! sieve[i])
  3978. {
  3979. result = base;
  3980. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  3981. if (Primes::isProbablyPrime (result, certainty))
  3982. return true;
  3983. }
  3984. }
  3985. return false;
  3986. }
  3987. const BitArray Primes::createProbablePrime (const int bitLength,
  3988. const int certainty,
  3989. const int* randomSeeds,
  3990. int numRandomSeeds) throw()
  3991. {
  3992. int defaultSeeds [16];
  3993. if (numRandomSeeds <= 0)
  3994. {
  3995. randomSeeds = defaultSeeds;
  3996. numRandomSeeds = numElementsInArray (defaultSeeds);
  3997. Random r (0);
  3998. for (int j = 10; --j >= 0;)
  3999. {
  4000. r.setSeedRandomly();
  4001. for (int i = numRandomSeeds; --i >= 0;)
  4002. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4003. }
  4004. }
  4005. BitArray smallSieve;
  4006. const int smallSieveSize = 15000;
  4007. createSmallSieve (smallSieveSize, smallSieve);
  4008. BitArray p;
  4009. for (int i = numRandomSeeds; --i >= 0;)
  4010. {
  4011. BitArray p2;
  4012. Random r (randomSeeds[i]);
  4013. r.fillBitsRandomly (p2, 0, bitLength);
  4014. p.xorWith (p2);
  4015. }
  4016. p.setBit (bitLength - 1);
  4017. p.clearBit (0);
  4018. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4019. while (p.getHighestBit() < bitLength)
  4020. {
  4021. p.add (2 * searchLen);
  4022. BitArray sieve;
  4023. bigSieve (p, searchLen, sieve,
  4024. smallSieve, smallSieveSize);
  4025. BitArray candidate;
  4026. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4027. return candidate;
  4028. }
  4029. jassertfalse
  4030. return BitArray();
  4031. }
  4032. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  4033. {
  4034. const BitArray one (1);
  4035. const BitArray two (2);
  4036. BitArray nMinusOne (n);
  4037. nMinusOne.subtract (one);
  4038. BitArray d (nMinusOne);
  4039. const int s = d.findNextSetBit (0);
  4040. d.shiftBits (-s);
  4041. BitArray smallPrimes;
  4042. int numBitsInSmallPrimes = 0;
  4043. for (;;)
  4044. {
  4045. numBitsInSmallPrimes += 256;
  4046. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4047. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4048. if (numPrimesFound > iterations + 1)
  4049. break;
  4050. }
  4051. int smallPrime = 2;
  4052. while (--iterations >= 0)
  4053. {
  4054. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4055. BitArray r (smallPrime);
  4056. //r.createRandomNumber (nMinusOne);
  4057. r.exponentModulo (d, n);
  4058. if (! (r == one || r == nMinusOne))
  4059. {
  4060. for (int j = 0; j < s; ++j)
  4061. {
  4062. r.exponentModulo (two, n);
  4063. if (r == nMinusOne)
  4064. break;
  4065. }
  4066. if (r != nMinusOne)
  4067. return false;
  4068. }
  4069. }
  4070. return true;
  4071. }
  4072. bool Primes::isProbablyPrime (const BitArray& number,
  4073. const int certainty) throw()
  4074. {
  4075. if (! number[0])
  4076. return false;
  4077. if (number.getHighestBit() <= 10)
  4078. {
  4079. const int num = number.getBitRangeAsInt (0, 10);
  4080. for (int i = num / 2; --i > 1;)
  4081. if (num % i == 0)
  4082. return false;
  4083. return true;
  4084. }
  4085. else
  4086. {
  4087. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  4088. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  4089. return false;
  4090. return passesMillerRabin (number, certainty);
  4091. }
  4092. }
  4093. END_JUCE_NAMESPACE
  4094. /********* End of inlined file: juce_Primes.cpp *********/
  4095. /********* Start of inlined file: juce_RSAKey.cpp *********/
  4096. BEGIN_JUCE_NAMESPACE
  4097. RSAKey::RSAKey() throw()
  4098. {
  4099. }
  4100. RSAKey::RSAKey (const String& s) throw()
  4101. {
  4102. if (s.containsChar (T(',')))
  4103. {
  4104. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  4105. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  4106. }
  4107. else
  4108. {
  4109. // the string needs to be two hex numbers, comma-separated..
  4110. jassertfalse;
  4111. }
  4112. }
  4113. RSAKey::~RSAKey() throw()
  4114. {
  4115. }
  4116. const String RSAKey::toString() const throw()
  4117. {
  4118. return part1.toString (16) + T(",") + part2.toString (16);
  4119. }
  4120. bool RSAKey::applyToValue (BitArray& value) const throw()
  4121. {
  4122. if (part1.isEmpty() || part2.isEmpty()
  4123. || value.compare (0) <= 0)
  4124. {
  4125. jassertfalse // using an uninitialised key
  4126. value.clear();
  4127. return false;
  4128. }
  4129. BitArray result;
  4130. while (! value.isEmpty())
  4131. {
  4132. result.multiplyBy (part2);
  4133. BitArray remainder;
  4134. value.divideBy (part2, remainder);
  4135. remainder.exponentModulo (part1, part2);
  4136. result.add (remainder);
  4137. }
  4138. value = result;
  4139. return true;
  4140. }
  4141. static const BitArray findBestCommonDivisor (const BitArray& p,
  4142. const BitArray& q) throw()
  4143. {
  4144. const BitArray one (1);
  4145. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4146. // are fast to divide + multiply
  4147. for (int i = 2; i <= 65536; i *= 2)
  4148. {
  4149. const BitArray e (1 + i);
  4150. if (e.findGreatestCommonDivisor (p) == one
  4151. && e.findGreatestCommonDivisor (q) == one)
  4152. {
  4153. return e;
  4154. }
  4155. }
  4156. BitArray e (4);
  4157. while (! (e.findGreatestCommonDivisor (p) == one
  4158. && e.findGreatestCommonDivisor (q) == one))
  4159. {
  4160. e.add (one);
  4161. }
  4162. return e;
  4163. }
  4164. void RSAKey::createKeyPair (RSAKey& publicKey,
  4165. RSAKey& privateKey,
  4166. const int numBits,
  4167. const int* randomSeeds,
  4168. const int numRandomSeeds) throw()
  4169. {
  4170. jassert (numBits > 16); // not much point using less than this..
  4171. BitArray p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4172. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4173. BitArray n (p);
  4174. n.multiplyBy (q); // n = pq
  4175. const BitArray one (1);
  4176. p.subtract (one);
  4177. q.subtract (one);
  4178. BitArray m (p);
  4179. m.multiplyBy (q); // m = (p - 1)(q - 1)
  4180. const BitArray e (findBestCommonDivisor (p, q));
  4181. BitArray d (e);
  4182. d.inverseModulo (m);
  4183. publicKey.part1 = e;
  4184. publicKey.part2 = n;
  4185. privateKey.part1 = d;
  4186. privateKey.part2 = n;
  4187. }
  4188. END_JUCE_NAMESPACE
  4189. /********* End of inlined file: juce_RSAKey.cpp *********/
  4190. /********* Start of inlined file: juce_InputStream.cpp *********/
  4191. BEGIN_JUCE_NAMESPACE
  4192. char InputStream::readByte()
  4193. {
  4194. char temp = 0;
  4195. read (&temp, 1);
  4196. return temp;
  4197. }
  4198. bool InputStream::readBool()
  4199. {
  4200. return readByte() != 0;
  4201. }
  4202. short InputStream::readShort()
  4203. {
  4204. char temp [2];
  4205. if (read (temp, 2) == 2)
  4206. return (short) littleEndianShort (temp);
  4207. else
  4208. return 0;
  4209. }
  4210. short InputStream::readShortBigEndian()
  4211. {
  4212. char temp [2];
  4213. if (read (temp, 2) == 2)
  4214. return (short) bigEndianShort (temp);
  4215. else
  4216. return 0;
  4217. }
  4218. int InputStream::readInt()
  4219. {
  4220. char temp [4];
  4221. if (read (temp, 4) == 4)
  4222. return (int) littleEndianInt (temp);
  4223. else
  4224. return 0;
  4225. }
  4226. int InputStream::readIntBigEndian()
  4227. {
  4228. char temp [4];
  4229. if (read (temp, 4) == 4)
  4230. return (int) bigEndianInt (temp);
  4231. else
  4232. return 0;
  4233. }
  4234. int InputStream::readCompressedInt()
  4235. {
  4236. int num = 0;
  4237. if (! isExhausted())
  4238. {
  4239. unsigned char numBytes = readByte();
  4240. const bool negative = (numBytes & 0x80) != 0;
  4241. numBytes &= 0x7f;
  4242. if (numBytes <= 4)
  4243. {
  4244. if (read (&num, numBytes) != numBytes)
  4245. return 0;
  4246. if (negative)
  4247. num = -num;
  4248. }
  4249. }
  4250. return num;
  4251. }
  4252. int64 InputStream::readInt64()
  4253. {
  4254. char temp [8];
  4255. if (read (temp, 8) == 8)
  4256. return (int64) swapIfBigEndian (*(uint64*)temp);
  4257. else
  4258. return 0;
  4259. }
  4260. int64 InputStream::readInt64BigEndian()
  4261. {
  4262. char temp [8];
  4263. if (read (temp, 8) == 8)
  4264. return (int64) swapIfLittleEndian (*(uint64*)temp);
  4265. else
  4266. return 0;
  4267. }
  4268. float InputStream::readFloat()
  4269. {
  4270. union { int asInt; float asFloat; } n;
  4271. n.asInt = readInt();
  4272. return n.asFloat;
  4273. }
  4274. float InputStream::readFloatBigEndian()
  4275. {
  4276. union { int asInt; float asFloat; } n;
  4277. n.asInt = readIntBigEndian();
  4278. return n.asFloat;
  4279. }
  4280. double InputStream::readDouble()
  4281. {
  4282. union { int64 asInt; double asDouble; } n;
  4283. n.asInt = readInt64();
  4284. return n.asDouble;
  4285. }
  4286. double InputStream::readDoubleBigEndian()
  4287. {
  4288. union { int64 asInt; double asDouble; } n;
  4289. n.asInt = readInt64BigEndian();
  4290. return n.asDouble;
  4291. }
  4292. const String InputStream::readString()
  4293. {
  4294. const int tempBufferSize = 256;
  4295. uint8 temp [tempBufferSize];
  4296. int i = 0;
  4297. while ((temp [i++] = readByte()) != 0)
  4298. {
  4299. if (i == tempBufferSize)
  4300. {
  4301. // too big for our quick buffer, so read it in blocks..
  4302. String result (String::fromUTF8 (temp, i));
  4303. i = 0;
  4304. for (;;)
  4305. {
  4306. if ((temp [i++] = readByte()) == 0)
  4307. {
  4308. result += String::fromUTF8 (temp, i - 1);
  4309. break;
  4310. }
  4311. else if (i == tempBufferSize)
  4312. {
  4313. result += String::fromUTF8 (temp, i);
  4314. i = 0;
  4315. }
  4316. }
  4317. return result;
  4318. }
  4319. }
  4320. return String::fromUTF8 (temp, i - 1);
  4321. }
  4322. const String InputStream::readNextLine()
  4323. {
  4324. String s;
  4325. const int maxChars = 256;
  4326. tchar buffer [maxChars];
  4327. int charsInBuffer = 0;
  4328. while (! isExhausted())
  4329. {
  4330. const uint8 c = readByte();
  4331. const int64 lastPos = getPosition();
  4332. if (c == '\n')
  4333. {
  4334. break;
  4335. }
  4336. else if (c == '\r')
  4337. {
  4338. if (readByte() != '\n')
  4339. setPosition (lastPos);
  4340. break;
  4341. }
  4342. buffer [charsInBuffer++] = c;
  4343. if (charsInBuffer == maxChars)
  4344. {
  4345. s.append (buffer, maxChars);
  4346. charsInBuffer = 0;
  4347. }
  4348. }
  4349. if (charsInBuffer > 0)
  4350. s.append (buffer, charsInBuffer);
  4351. return s;
  4352. }
  4353. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  4354. int numBytes)
  4355. {
  4356. const int64 totalLength = getTotalLength();
  4357. if (totalLength >= 0)
  4358. {
  4359. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4360. totalLength - getPosition());
  4361. if (numBytes < 0)
  4362. numBytes = totalBytesRemaining;
  4363. else if (numBytes > 0)
  4364. numBytes = jmin (numBytes, totalBytesRemaining);
  4365. else
  4366. return 0;
  4367. }
  4368. const int originalBlockSize = block.getSize();
  4369. int totalBytesRead = 0;
  4370. if (numBytes > 0)
  4371. {
  4372. // know how many bytes we want, so we can resize the block first..
  4373. block.setSize (originalBlockSize + numBytes, false);
  4374. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  4375. }
  4376. else
  4377. {
  4378. // read until end of stram..
  4379. const int chunkSize = 32768;
  4380. for (;;)
  4381. {
  4382. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4383. const int bytesJustIn = read (((char*) block.getData())
  4384. + originalBlockSize
  4385. + totalBytesRead,
  4386. chunkSize);
  4387. if (bytesJustIn == 0)
  4388. break;
  4389. totalBytesRead += bytesJustIn;
  4390. }
  4391. }
  4392. // trim off any excess left at the end
  4393. block.setSize (originalBlockSize + totalBytesRead, false);
  4394. return totalBytesRead;
  4395. }
  4396. const String InputStream::readEntireStreamAsString()
  4397. {
  4398. MemoryBlock mb;
  4399. const int size = readIntoMemoryBlock (mb);
  4400. return String::createStringFromData ((const char*) mb.getData(), size);
  4401. }
  4402. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4403. {
  4404. if (numBytesToSkip > 0)
  4405. {
  4406. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4407. MemoryBlock temp (skipBufferSize);
  4408. while ((numBytesToSkip > 0) && ! isExhausted())
  4409. {
  4410. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4411. }
  4412. }
  4413. }
  4414. END_JUCE_NAMESPACE
  4415. /********* End of inlined file: juce_InputStream.cpp *********/
  4416. /********* Start of inlined file: juce_OutputStream.cpp *********/
  4417. BEGIN_JUCE_NAMESPACE
  4418. #if JUCE_DEBUG
  4419. static CriticalSection activeStreamLock;
  4420. static VoidArray activeStreams;
  4421. void juce_CheckForDanglingStreams()
  4422. {
  4423. /*
  4424. It's always a bad idea to leak any object, but if you're leaking output
  4425. streams, then there's a good chance that you're failing to flush a file
  4426. to disk properly, which could result in corrupted data and other similar
  4427. nastiness..
  4428. */
  4429. jassert (activeStreams.size() == 0);
  4430. };
  4431. #endif
  4432. OutputStream::OutputStream() throw()
  4433. {
  4434. #if JUCE_DEBUG
  4435. activeStreamLock.enter();
  4436. activeStreams.add (this);
  4437. activeStreamLock.exit();
  4438. #endif
  4439. }
  4440. OutputStream::~OutputStream()
  4441. {
  4442. #if JUCE_DEBUG
  4443. activeStreamLock.enter();
  4444. activeStreams.removeValue (this);
  4445. activeStreamLock.exit();
  4446. #endif
  4447. }
  4448. void OutputStream::writeBool (bool b)
  4449. {
  4450. writeByte ((b) ? (char) 1
  4451. : (char) 0);
  4452. }
  4453. void OutputStream::writeByte (char byte)
  4454. {
  4455. write (&byte, 1);
  4456. }
  4457. void OutputStream::writeShort (short value)
  4458. {
  4459. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  4460. write (&v, 2);
  4461. }
  4462. void OutputStream::writeShortBigEndian (short value)
  4463. {
  4464. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  4465. write (&v, 2);
  4466. }
  4467. void OutputStream::writeInt (int value)
  4468. {
  4469. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  4470. write (&v, 4);
  4471. }
  4472. void OutputStream::writeIntBigEndian (int value)
  4473. {
  4474. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  4475. write (&v, 4);
  4476. }
  4477. void OutputStream::writeCompressedInt (int value)
  4478. {
  4479. unsigned int un = (value < 0) ? (unsigned int) -value
  4480. : (unsigned int) value;
  4481. unsigned int tn = un;
  4482. int numSigBytes = 0;
  4483. do
  4484. {
  4485. tn >>= 8;
  4486. numSigBytes++;
  4487. } while (tn & 0xff);
  4488. if (value < 0)
  4489. numSigBytes |= 0x80;
  4490. writeByte ((char) numSigBytes);
  4491. write (&un, numSigBytes);
  4492. }
  4493. void OutputStream::writeInt64 (int64 value)
  4494. {
  4495. const uint64 v = swapIfBigEndian ((uint64) value);
  4496. write (&v, 8);
  4497. }
  4498. void OutputStream::writeInt64BigEndian (int64 value)
  4499. {
  4500. const uint64 v = swapIfLittleEndian ((uint64) value);
  4501. write (&v, 8);
  4502. }
  4503. void OutputStream::writeFloat (float value)
  4504. {
  4505. union { int asInt; float asFloat; } n;
  4506. n.asFloat = value;
  4507. writeInt (n.asInt);
  4508. }
  4509. void OutputStream::writeFloatBigEndian (float value)
  4510. {
  4511. union { int asInt; float asFloat; } n;
  4512. n.asFloat = value;
  4513. writeIntBigEndian (n.asInt);
  4514. }
  4515. void OutputStream::writeDouble (double value)
  4516. {
  4517. union { int64 asInt; double asDouble; } n;
  4518. n.asDouble = value;
  4519. writeInt64 (n.asInt);
  4520. }
  4521. void OutputStream::writeDoubleBigEndian (double value)
  4522. {
  4523. union { int64 asInt; double asDouble; } n;
  4524. n.asDouble = value;
  4525. writeInt64BigEndian (n.asInt);
  4526. }
  4527. void OutputStream::writeString (const String& text)
  4528. {
  4529. const int numBytes = text.copyToUTF8 (0);
  4530. uint8* const temp = (uint8*) juce_malloc (numBytes);
  4531. text.copyToUTF8 (temp);
  4532. write (temp, numBytes); // (numBytes includes the terminating null).
  4533. juce_free (temp);
  4534. }
  4535. void OutputStream::printf (const char* pf, ...)
  4536. {
  4537. unsigned int bufSize = 256;
  4538. char* buf = (char*) juce_malloc (bufSize);
  4539. for (;;)
  4540. {
  4541. va_list list;
  4542. va_start (list, pf);
  4543. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  4544. va_end (list);
  4545. if (num > 0)
  4546. {
  4547. write (buf, num);
  4548. break;
  4549. }
  4550. else if (num == 0)
  4551. {
  4552. break;
  4553. }
  4554. juce_free (buf);
  4555. bufSize += 256;
  4556. buf = (char*) juce_malloc (bufSize);
  4557. }
  4558. juce_free (buf);
  4559. }
  4560. OutputStream& OutputStream::operator<< (const int number)
  4561. {
  4562. const String s (number);
  4563. write ((const char*) s, s.length());
  4564. return *this;
  4565. }
  4566. OutputStream& OutputStream::operator<< (const double number)
  4567. {
  4568. const String s (number);
  4569. write ((const char*) s, s.length());
  4570. return *this;
  4571. }
  4572. OutputStream& OutputStream::operator<< (const char character)
  4573. {
  4574. writeByte (character);
  4575. return *this;
  4576. }
  4577. OutputStream& OutputStream::operator<< (const char* const text)
  4578. {
  4579. write (text, (int) strlen (text));
  4580. return *this;
  4581. }
  4582. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  4583. {
  4584. const String s (text);
  4585. write ((const char*) s, s.length());
  4586. return *this;
  4587. }
  4588. OutputStream& OutputStream::operator<< (const String& text)
  4589. {
  4590. write ((const char*) text,
  4591. text.length());
  4592. return *this;
  4593. }
  4594. void OutputStream::writeText (const String& text,
  4595. const bool asUnicode,
  4596. const bool writeUnicodeHeaderBytes)
  4597. {
  4598. if (asUnicode)
  4599. {
  4600. if (writeUnicodeHeaderBytes)
  4601. write ("\x0ff\x0fe", 2);
  4602. const juce_wchar* src = (const juce_wchar*) text;
  4603. bool lastCharWasReturn = false;
  4604. while (*src != 0)
  4605. {
  4606. if (*src == L'\n' && ! lastCharWasReturn)
  4607. writeShort ((short) L'\r');
  4608. lastCharWasReturn = (*src == L'\r');
  4609. writeShort ((short) *src++);
  4610. }
  4611. }
  4612. else
  4613. {
  4614. const char* src = (const char*) text;
  4615. const char* t = src;
  4616. for (;;)
  4617. {
  4618. if (*t == '\n')
  4619. {
  4620. if (t > src)
  4621. write (src, (int) (t - src));
  4622. write ("\r\n", 2);
  4623. src = t + 1;
  4624. }
  4625. else if (*t == '\r')
  4626. {
  4627. if (t[1] == '\n')
  4628. ++t;
  4629. }
  4630. else if (*t == 0)
  4631. {
  4632. if (t > src)
  4633. write (src, (int) (t - src));
  4634. break;
  4635. }
  4636. ++t;
  4637. }
  4638. }
  4639. }
  4640. int OutputStream::writeFromInputStream (InputStream& source,
  4641. int numBytesToWrite)
  4642. {
  4643. if (numBytesToWrite < 0)
  4644. numBytesToWrite = 0x7fffffff;
  4645. int numWritten = 0;
  4646. while (numBytesToWrite > 0 && ! source.isExhausted())
  4647. {
  4648. char buffer [8192];
  4649. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  4650. if (num == 0)
  4651. break;
  4652. write (buffer, num);
  4653. numBytesToWrite -= num;
  4654. numWritten += num;
  4655. }
  4656. return numWritten;
  4657. }
  4658. END_JUCE_NAMESPACE
  4659. /********* End of inlined file: juce_OutputStream.cpp *********/
  4660. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  4661. BEGIN_JUCE_NAMESPACE
  4662. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4663. bool* isDirectory, bool* isHidden, int64* fileSize,
  4664. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4665. bool juce_findFileNext (void* handle, String& resultFile,
  4666. bool* isDirectory, bool* isHidden, int64* fileSize,
  4667. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4668. void juce_findFileClose (void* handle) throw();
  4669. DirectoryIterator::DirectoryIterator (const File& directory,
  4670. bool isRecursive,
  4671. const String& wc,
  4672. const int whatToLookFor_) throw()
  4673. : wildCard (wc),
  4674. index (-1),
  4675. whatToLookFor (whatToLookFor_),
  4676. subIterator (0)
  4677. {
  4678. // you have to specify the type of files you're looking for!
  4679. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4680. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4681. String path (directory.getFullPathName());
  4682. if (! path.endsWithChar (File::separator))
  4683. path += File::separator;
  4684. String filename;
  4685. bool isDirectory, isHidden;
  4686. void* const handle = juce_findFileStart (path,
  4687. isRecursive ? T("*") : wc,
  4688. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  4689. if (handle != 0)
  4690. {
  4691. do
  4692. {
  4693. if (! filename.containsOnly (T(".")))
  4694. {
  4695. bool addToList = false;
  4696. if (isDirectory)
  4697. {
  4698. if (isRecursive
  4699. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  4700. || ! isHidden))
  4701. {
  4702. dirsFound.add (new File (path + filename, 0));
  4703. }
  4704. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  4705. }
  4706. else
  4707. {
  4708. addToList = (whatToLookFor_ & File::findFiles) != 0;
  4709. }
  4710. // if it's recursive, we're not relying on the OS iterator
  4711. // to do the wildcard match, so do it now..
  4712. if (isRecursive && addToList)
  4713. addToList = filename.matchesWildcard (wc, true);
  4714. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  4715. addToList = ! isHidden;
  4716. if (addToList)
  4717. filesFound.add (new File (path + filename, 0));
  4718. }
  4719. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4720. juce_findFileClose (handle);
  4721. }
  4722. }
  4723. DirectoryIterator::~DirectoryIterator() throw()
  4724. {
  4725. if (subIterator != 0)
  4726. delete subIterator;
  4727. }
  4728. bool DirectoryIterator::next() throw()
  4729. {
  4730. if (subIterator != 0)
  4731. {
  4732. if (subIterator->next())
  4733. return true;
  4734. deleteAndZero (subIterator);
  4735. }
  4736. if (index >= filesFound.size() + dirsFound.size() - 1)
  4737. return false;
  4738. ++index;
  4739. if (index >= filesFound.size())
  4740. {
  4741. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  4742. true, wildCard, whatToLookFor);
  4743. return next();
  4744. }
  4745. return true;
  4746. }
  4747. const File DirectoryIterator::getFile() const throw()
  4748. {
  4749. if (subIterator != 0)
  4750. return subIterator->getFile();
  4751. const File* const f = filesFound [index];
  4752. return (f != 0) ? *f
  4753. : File::nonexistent;
  4754. }
  4755. float DirectoryIterator::getEstimatedProgress() const throw()
  4756. {
  4757. if (filesFound.size() + dirsFound.size() == 0)
  4758. {
  4759. return 0.0f;
  4760. }
  4761. else
  4762. {
  4763. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4764. : (float) index;
  4765. return detailedIndex / (filesFound.size() + dirsFound.size());
  4766. }
  4767. }
  4768. END_JUCE_NAMESPACE
  4769. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  4770. /********* Start of inlined file: juce_File.cpp *********/
  4771. #ifdef _MSC_VER
  4772. #pragma warning (disable: 4514)
  4773. #pragma warning (push)
  4774. #endif
  4775. #if ! JUCE_WINDOWS
  4776. #include <pwd.h>
  4777. #endif
  4778. BEGIN_JUCE_NAMESPACE
  4779. #ifdef _MSC_VER
  4780. #pragma warning (pop)
  4781. #endif
  4782. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4783. void juce_fileClose (void* handle) throw();
  4784. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4785. int64 juce_fileGetPosition (void* handle) throw();
  4786. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4787. void juce_fileFlush (void* handle) throw();
  4788. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  4789. bool juce_isDirectory (const String& fileName) throw();
  4790. int64 juce_getFileSize (const String& fileName) throw();
  4791. bool juce_canWriteToFile (const String& fileName) throw();
  4792. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  4793. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  4794. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  4795. bool juce_deleteFile (const String& fileName) throw();
  4796. bool juce_copyFile (const String& source, const String& dest) throw();
  4797. bool juce_moveFile (const String& source, const String& dest) throw();
  4798. // this must also create all paths involved in the directory.
  4799. void juce_createDirectory (const String& fileName) throw();
  4800. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  4801. const StringArray juce_getFileSystemRoots() throw();
  4802. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  4803. // starts a directory search operation with a wildcard, returning a handle for
  4804. // use in calls to juce_findFileNext.
  4805. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  4806. // the other pointers, if non-null, are set based on the properties of the file.
  4807. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4808. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  4809. Time* creationTime, bool* isReadOnly) throw();
  4810. // returns false when no more files are found
  4811. bool juce_findFileNext (void* handle, String& resultFile,
  4812. bool* isDirectory, bool* isHidden, int64* fileSize,
  4813. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4814. void juce_findFileClose (void* handle) throw();
  4815. static const String juce_addTrailingSeparator (const String& path) throw()
  4816. {
  4817. return path.endsWithChar (File::separator) ? path
  4818. : path + File::separator;
  4819. }
  4820. static const String parseAbsolutePath (String path) throw()
  4821. {
  4822. if (path.isEmpty())
  4823. return String::empty;
  4824. #if JUCE_WINDOWS
  4825. // Windows..
  4826. path = path.replaceCharacter (T('/'), T('\\'));
  4827. if (path.startsWithChar (File::separator))
  4828. {
  4829. if (path[1] != File::separator)
  4830. {
  4831. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  4832. // Windows, because it needs a drive letter, which in this case
  4833. // we'll take from the CWD.. but this is a bit of an assumption that
  4834. // could be wrong..
  4835. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4836. }
  4837. }
  4838. else if (path.indexOfChar (T(':')) < 0)
  4839. {
  4840. if (path.isEmpty())
  4841. return String::empty;
  4842. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4843. // we don't know what directory to put it in.
  4844. // Here we'll assume it's in the CWD, but this might not be what was
  4845. // intended..
  4846. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4847. }
  4848. #else
  4849. // Mac or Linux..
  4850. path = path.replaceCharacter (T('\\'), T('/'));
  4851. if (path.startsWithChar (T('~')))
  4852. {
  4853. const char* homeDir = 0;
  4854. if (path[1] == File::separator || path[1] == 0)
  4855. {
  4856. // expand a name of the form "~/abc"
  4857. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4858. + path.substring (1);
  4859. }
  4860. else
  4861. {
  4862. // expand a name of type "~dave/abc"
  4863. const String userName (path.substring (1)
  4864. .upToFirstOccurrenceOf (T("/"), false, false));
  4865. struct passwd* const pw = getpwnam (userName);
  4866. if (pw != 0)
  4867. {
  4868. String home (homeDir);
  4869. if (home.endsWithChar (File::separator))
  4870. home [home.length() - 1] = 0;
  4871. path = String (pw->pw_dir)
  4872. + path.substring (userName.length());
  4873. }
  4874. }
  4875. }
  4876. else if (! path.startsWithChar (File::separator))
  4877. {
  4878. while (path.startsWith (T("./")))
  4879. path = path.substring (2);
  4880. if (path.isEmpty())
  4881. return String::empty;
  4882. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4883. // we don't know what directory to put it in.
  4884. // Here we'll assume it's in the CWD, but this might not be what was
  4885. // intended..
  4886. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4887. }
  4888. #endif
  4889. int len = path.length();
  4890. while (--len > 0 && path [len] == File::separator)
  4891. path [len] = 0;
  4892. return path;
  4893. }
  4894. const File File::nonexistent;
  4895. File::File (const String& fullPathName) throw()
  4896. : fullPath (parseAbsolutePath (fullPathName))
  4897. {
  4898. }
  4899. File::File (const String& path, int) throw()
  4900. : fullPath (path)
  4901. {
  4902. }
  4903. File::File (const File& other) throw()
  4904. : fullPath (other.fullPath)
  4905. {
  4906. }
  4907. const File& File::operator= (const String& newPath) throw()
  4908. {
  4909. fullPath = parseAbsolutePath (newPath);
  4910. return *this;
  4911. }
  4912. const File& File::operator= (const File& other) throw()
  4913. {
  4914. fullPath = other.fullPath;
  4915. return *this;
  4916. }
  4917. #if JUCE_LINUX
  4918. #define NAMES_ARE_CASE_SENSITIVE 1
  4919. #endif
  4920. bool File::areFileNamesCaseSensitive()
  4921. {
  4922. #if NAMES_ARE_CASE_SENSITIVE
  4923. return true;
  4924. #else
  4925. return false;
  4926. #endif
  4927. }
  4928. bool File::operator== (const File& other) const throw()
  4929. {
  4930. // case-insensitive on Windows, but not on linux.
  4931. #if NAMES_ARE_CASE_SENSITIVE
  4932. return fullPath == other.fullPath;
  4933. #else
  4934. return fullPath.equalsIgnoreCase (other.fullPath);
  4935. #endif
  4936. }
  4937. bool File::operator!= (const File& other) const throw()
  4938. {
  4939. return ! operator== (other);
  4940. }
  4941. bool File::exists() const throw()
  4942. {
  4943. return juce_fileExists (fullPath, false);
  4944. }
  4945. bool File::existsAsFile() const throw()
  4946. {
  4947. return juce_fileExists (fullPath, true);
  4948. }
  4949. bool File::isDirectory() const throw()
  4950. {
  4951. return juce_isDirectory (fullPath);
  4952. }
  4953. bool File::hasWriteAccess() const throw()
  4954. {
  4955. if (exists())
  4956. return juce_canWriteToFile (fullPath);
  4957. #if ! JUCE_WINDOWS
  4958. else if ((! isDirectory()) && fullPath.containsChar (separator))
  4959. return getParentDirectory().hasWriteAccess();
  4960. else
  4961. return false;
  4962. #else
  4963. // on windows, it seems that even read-only directories can still be written into,
  4964. // so checking the parent directory's permissions would return the wrong result..
  4965. else
  4966. return true;
  4967. #endif
  4968. }
  4969. bool File::setReadOnly (const bool shouldBeReadOnly,
  4970. const bool applyRecursively) const throw()
  4971. {
  4972. bool worked = true;
  4973. if (applyRecursively && isDirectory())
  4974. {
  4975. OwnedArray <File> subFiles;
  4976. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4977. for (int i = subFiles.size(); --i >= 0;)
  4978. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  4979. }
  4980. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  4981. }
  4982. bool File::deleteFile() const throw()
  4983. {
  4984. return (! exists())
  4985. || juce_deleteFile (fullPath);
  4986. }
  4987. bool File::deleteRecursively() const throw()
  4988. {
  4989. bool worked = true;
  4990. if (isDirectory())
  4991. {
  4992. OwnedArray<File> subFiles;
  4993. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4994. for (int i = subFiles.size(); --i >= 0;)
  4995. worked = subFiles[i]->deleteRecursively() && worked;
  4996. }
  4997. return deleteFile() && worked;
  4998. }
  4999. bool File::moveFileTo (const File& newFile) const throw()
  5000. {
  5001. if (newFile.fullPath == fullPath)
  5002. return true;
  5003. #if ! NAMES_ARE_CASE_SENSITIVE
  5004. if (*this != newFile)
  5005. #endif
  5006. if (! newFile.deleteFile())
  5007. return false;
  5008. return juce_moveFile (fullPath, newFile.fullPath);
  5009. }
  5010. bool File::copyFileTo (const File& newFile) const throw()
  5011. {
  5012. if (*this == newFile)
  5013. return true;
  5014. if (! newFile.deleteFile())
  5015. return false;
  5016. return juce_copyFile (fullPath, newFile.fullPath);
  5017. }
  5018. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  5019. {
  5020. if (isDirectory() && newDirectory.createDirectory())
  5021. {
  5022. OwnedArray<File> subFiles;
  5023. findChildFiles (subFiles, File::findFiles, false);
  5024. int i;
  5025. for (i = 0; i < subFiles.size(); ++i)
  5026. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  5027. return false;
  5028. subFiles.clear();
  5029. findChildFiles (subFiles, File::findDirectories, false);
  5030. for (i = 0; i < subFiles.size(); ++i)
  5031. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  5032. return false;
  5033. return true;
  5034. }
  5035. return false;
  5036. }
  5037. const String File::getPathUpToLastSlash() const throw()
  5038. {
  5039. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5040. if (lastSlash > 0)
  5041. return fullPath.substring (0, lastSlash);
  5042. else if (lastSlash == 0)
  5043. return separatorString;
  5044. else
  5045. return fullPath;
  5046. }
  5047. const File File::getParentDirectory() const throw()
  5048. {
  5049. return File (getPathUpToLastSlash());
  5050. }
  5051. const String File::getFileName() const throw()
  5052. {
  5053. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5054. }
  5055. int File::hashCode() const throw()
  5056. {
  5057. return fullPath.hashCode();
  5058. }
  5059. int64 File::hashCode64() const throw()
  5060. {
  5061. return fullPath.hashCode64();
  5062. }
  5063. const String File::getFileNameWithoutExtension() const throw()
  5064. {
  5065. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5066. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  5067. if (lastDot > lastSlash)
  5068. return fullPath.substring (lastSlash, lastDot);
  5069. else
  5070. return fullPath.substring (lastSlash);
  5071. }
  5072. bool File::isAChildOf (const File& potentialParent) const throw()
  5073. {
  5074. const String ourPath (getPathUpToLastSlash());
  5075. #if NAMES_ARE_CASE_SENSITIVE
  5076. if (potentialParent.fullPath == ourPath)
  5077. #else
  5078. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5079. #endif
  5080. {
  5081. return true;
  5082. }
  5083. else if (potentialParent.fullPath.length() >= ourPath.length())
  5084. {
  5085. return false;
  5086. }
  5087. else
  5088. {
  5089. return getParentDirectory().isAChildOf (potentialParent);
  5090. }
  5091. }
  5092. bool File::isAbsolutePath (const String& path) throw()
  5093. {
  5094. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  5095. #if JUCE_WINDOWS
  5096. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  5097. #else
  5098. || path.startsWithChar (T('~'));
  5099. #endif
  5100. }
  5101. const File File::getChildFile (String relativePath) const throw()
  5102. {
  5103. if (isAbsolutePath (relativePath))
  5104. {
  5105. // the path is really absolute..
  5106. return File (relativePath);
  5107. }
  5108. else
  5109. {
  5110. // it's relative, so remove any ../ or ./ bits at the start.
  5111. String path (fullPath);
  5112. if (relativePath[0] == T('.'))
  5113. {
  5114. #if JUCE_WINDOWS
  5115. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  5116. #else
  5117. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  5118. #endif
  5119. while (relativePath[0] == T('.'))
  5120. {
  5121. if (relativePath[1] == T('.'))
  5122. {
  5123. if (relativePath [2] == 0 || relativePath[2] == separator)
  5124. {
  5125. const int lastSlash = path.lastIndexOfChar (separator);
  5126. if (lastSlash >= 0)
  5127. path = path.substring (0, lastSlash);
  5128. relativePath = relativePath.substring (3);
  5129. }
  5130. else
  5131. {
  5132. break;
  5133. }
  5134. }
  5135. else if (relativePath[1] == separator)
  5136. {
  5137. relativePath = relativePath.substring (2);
  5138. }
  5139. else
  5140. {
  5141. break;
  5142. }
  5143. }
  5144. }
  5145. return File (juce_addTrailingSeparator (path) + relativePath);
  5146. }
  5147. }
  5148. const File File::getSiblingFile (const String& fileName) const throw()
  5149. {
  5150. return getParentDirectory().getChildFile (fileName);
  5151. }
  5152. int64 File::getSize() const throw()
  5153. {
  5154. return juce_getFileSize (fullPath);
  5155. }
  5156. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5157. {
  5158. if (bytes == 1)
  5159. {
  5160. return "1 byte";
  5161. }
  5162. else if (bytes < 1024)
  5163. {
  5164. return String ((int) bytes) + " bytes";
  5165. }
  5166. else if (bytes < 1024 * 1024)
  5167. {
  5168. return String (bytes / 1024.0, 1) + " KB";
  5169. }
  5170. else if (bytes < 1024 * 1024 * 1024)
  5171. {
  5172. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5173. }
  5174. else
  5175. {
  5176. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5177. }
  5178. }
  5179. bool File::create() const throw()
  5180. {
  5181. if (! exists())
  5182. {
  5183. const File parentDir (getParentDirectory());
  5184. if (parentDir == *this || ! parentDir.createDirectory())
  5185. return false;
  5186. void* const fh = juce_fileOpen (fullPath, true);
  5187. if (fh == 0)
  5188. return false;
  5189. juce_fileClose (fh);
  5190. }
  5191. return true;
  5192. }
  5193. bool File::createDirectory() const throw()
  5194. {
  5195. if (! isDirectory())
  5196. {
  5197. const File parentDir (getParentDirectory());
  5198. if (parentDir == *this || ! parentDir.createDirectory())
  5199. return false;
  5200. String dir (fullPath);
  5201. while (dir.endsWithChar (separator))
  5202. dir [dir.length() - 1] = 0;
  5203. juce_createDirectory (dir);
  5204. return isDirectory();
  5205. }
  5206. return true;
  5207. }
  5208. const Time File::getCreationTime() const throw()
  5209. {
  5210. int64 m, a, c;
  5211. juce_getFileTimes (fullPath, m, a, c);
  5212. return Time (c);
  5213. }
  5214. bool File::setCreationTime (const Time& t) const throw()
  5215. {
  5216. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  5217. }
  5218. const Time File::getLastModificationTime() const throw()
  5219. {
  5220. int64 m, a, c;
  5221. juce_getFileTimes (fullPath, m, a, c);
  5222. return Time (m);
  5223. }
  5224. bool File::setLastModificationTime (const Time& t) const throw()
  5225. {
  5226. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  5227. }
  5228. const Time File::getLastAccessTime() const throw()
  5229. {
  5230. int64 m, a, c;
  5231. juce_getFileTimes (fullPath, m, a, c);
  5232. return Time (a);
  5233. }
  5234. bool File::setLastAccessTime (const Time& t) const throw()
  5235. {
  5236. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  5237. }
  5238. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  5239. {
  5240. if (! existsAsFile())
  5241. return false;
  5242. FileInputStream in (*this);
  5243. return getSize() == in.readIntoMemoryBlock (destBlock);
  5244. }
  5245. const String File::loadFileAsString() const throw()
  5246. {
  5247. if (! existsAsFile())
  5248. return String::empty;
  5249. FileInputStream in (*this);
  5250. return in.readEntireStreamAsString();
  5251. }
  5252. static inline bool fileTypeMatches (const int whatToLookFor,
  5253. const bool isDir,
  5254. const bool isHidden)
  5255. {
  5256. return (whatToLookFor & (isDir ? File::findDirectories
  5257. : File::findFiles)) != 0
  5258. && ((! isHidden)
  5259. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5260. }
  5261. int File::findChildFiles (OwnedArray<File>& results,
  5262. const int whatToLookFor,
  5263. const bool searchRecursively,
  5264. const String& wildCardPattern) const throw()
  5265. {
  5266. // you have to specify the type of files you're looking for!
  5267. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5268. int total = 0;
  5269. // find child files or directories in this directory first..
  5270. if (isDirectory())
  5271. {
  5272. const String path (juce_addTrailingSeparator (fullPath));
  5273. String filename;
  5274. bool isDirectory, isHidden;
  5275. void* const handle = juce_findFileStart (path,
  5276. wildCardPattern,
  5277. filename,
  5278. &isDirectory, &isHidden,
  5279. 0, 0, 0, 0);
  5280. if (handle != 0)
  5281. {
  5282. do
  5283. {
  5284. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5285. && ! filename.containsOnly (T(".")))
  5286. {
  5287. results.add (new File (path + filename, 0));
  5288. ++total;
  5289. }
  5290. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5291. juce_findFileClose (handle);
  5292. }
  5293. }
  5294. else
  5295. {
  5296. // trying to search for files inside a non-directory?
  5297. //jassertfalse
  5298. }
  5299. // and recurse down if required.
  5300. if (searchRecursively)
  5301. {
  5302. OwnedArray <File> subDirectories;
  5303. findChildFiles (subDirectories, File::findDirectories, false);
  5304. for (int i = 0; i < subDirectories.size(); ++i)
  5305. {
  5306. total += subDirectories.getUnchecked(i)
  5307. ->findChildFiles (results,
  5308. whatToLookFor,
  5309. true,
  5310. wildCardPattern);
  5311. }
  5312. }
  5313. return total;
  5314. }
  5315. int File::getNumberOfChildFiles (const int whatToLookFor,
  5316. const String& wildCardPattern) const throw()
  5317. {
  5318. // you have to specify the type of files you're looking for!
  5319. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5320. int count = 0;
  5321. if (isDirectory())
  5322. {
  5323. String filename;
  5324. bool isDirectory, isHidden;
  5325. void* const handle = juce_findFileStart (fullPath,
  5326. wildCardPattern,
  5327. filename,
  5328. &isDirectory, &isHidden,
  5329. 0, 0, 0, 0);
  5330. if (handle != 0)
  5331. {
  5332. do
  5333. {
  5334. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5335. && ! filename.containsOnly (T(".")))
  5336. {
  5337. ++count;
  5338. }
  5339. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5340. juce_findFileClose (handle);
  5341. }
  5342. }
  5343. else
  5344. {
  5345. // trying to search for files inside a non-directory?
  5346. jassertfalse
  5347. }
  5348. return count;
  5349. }
  5350. bool File::containsSubDirectories() const throw()
  5351. {
  5352. bool result = false;
  5353. if (isDirectory())
  5354. {
  5355. String filename;
  5356. bool isDirectory, isHidden;
  5357. void* const handle = juce_findFileStart (juce_addTrailingSeparator (fullPath),
  5358. T("*"), filename,
  5359. &isDirectory, &isHidden, 0, 0, 0, 0);
  5360. if (handle != 0)
  5361. {
  5362. do
  5363. {
  5364. if (isDirectory)
  5365. {
  5366. result = true;
  5367. break;
  5368. }
  5369. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5370. juce_findFileClose (handle);
  5371. }
  5372. }
  5373. return result;
  5374. }
  5375. const File File::getNonexistentChildFile (const String& prefix_,
  5376. const String& suffix,
  5377. bool putNumbersInBrackets) const throw()
  5378. {
  5379. File f (getChildFile (prefix_ + suffix));
  5380. if (f.exists())
  5381. {
  5382. int num = 2;
  5383. String prefix (prefix_);
  5384. // remove any bracketed numbers that may already be on the end..
  5385. if (prefix.trim().endsWithChar (T(')')))
  5386. {
  5387. putNumbersInBrackets = true;
  5388. const int openBracks = prefix.lastIndexOfChar (T('('));
  5389. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  5390. if (openBracks > 0
  5391. && closeBracks > openBracks
  5392. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  5393. {
  5394. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5395. prefix = prefix.substring (0, openBracks);
  5396. }
  5397. }
  5398. // also use brackets if it ends in a digit.
  5399. putNumbersInBrackets = putNumbersInBrackets
  5400. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5401. do
  5402. {
  5403. if (putNumbersInBrackets)
  5404. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  5405. else
  5406. f = getChildFile (prefix + String (num++) + suffix);
  5407. } while (f.exists());
  5408. }
  5409. return f;
  5410. }
  5411. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  5412. {
  5413. if (exists())
  5414. {
  5415. return getParentDirectory()
  5416. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5417. getFileExtension(),
  5418. putNumbersInBrackets);
  5419. }
  5420. else
  5421. {
  5422. return *this;
  5423. }
  5424. }
  5425. const String File::getFileExtension() const throw()
  5426. {
  5427. String ext;
  5428. if (! isDirectory())
  5429. {
  5430. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  5431. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5432. ext = fullPath.substring (indexOfDot);
  5433. }
  5434. return ext;
  5435. }
  5436. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  5437. {
  5438. if (possibleSuffix.isEmpty())
  5439. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  5440. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5441. {
  5442. if (possibleSuffix.startsWithChar (T('.')))
  5443. return true;
  5444. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5445. if (dotPos >= 0)
  5446. return fullPath [dotPos] == T('.');
  5447. }
  5448. return false;
  5449. }
  5450. const File File::withFileExtension (const String& newExtension) const throw()
  5451. {
  5452. if (fullPath.isEmpty())
  5453. return File::nonexistent;
  5454. String filePart (getFileName());
  5455. int i = filePart.lastIndexOfChar (T('.'));
  5456. if (i < 0)
  5457. i = filePart.length();
  5458. String newExt (newExtension);
  5459. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  5460. newExt = T(".") + newExt;
  5461. return getSiblingFile (filePart.substring (0, i) + newExt);
  5462. }
  5463. bool File::startAsProcess (const String& parameters) const throw()
  5464. {
  5465. return exists()
  5466. && juce_launchFile (fullPath, parameters);
  5467. }
  5468. FileInputStream* File::createInputStream() const throw()
  5469. {
  5470. if (existsAsFile())
  5471. return new FileInputStream (*this);
  5472. else
  5473. return 0;
  5474. }
  5475. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  5476. {
  5477. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  5478. if (out->failedToOpen())
  5479. {
  5480. delete out;
  5481. return 0;
  5482. }
  5483. else
  5484. {
  5485. return out;
  5486. }
  5487. }
  5488. bool File::appendData (const void* const dataToAppend,
  5489. const int numberOfBytes) const throw()
  5490. {
  5491. if (numberOfBytes > 0)
  5492. {
  5493. FileOutputStream* const out = createOutputStream();
  5494. if (out == 0)
  5495. return false;
  5496. out->write (dataToAppend, numberOfBytes);
  5497. delete out;
  5498. }
  5499. return true;
  5500. }
  5501. bool File::replaceWithData (const void* const dataToWrite,
  5502. const int numberOfBytes) const throw()
  5503. {
  5504. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5505. if (numberOfBytes <= 0)
  5506. return deleteFile();
  5507. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5508. if (tempFile.appendData (dataToWrite, numberOfBytes)
  5509. && tempFile.moveFileTo (*this))
  5510. {
  5511. return true;
  5512. }
  5513. tempFile.deleteFile();
  5514. return false;
  5515. }
  5516. bool File::appendText (const String& text,
  5517. const bool asUnicode,
  5518. const bool writeUnicodeHeaderBytes) const throw()
  5519. {
  5520. FileOutputStream* const out = createOutputStream();
  5521. if (out != 0)
  5522. {
  5523. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5524. delete out;
  5525. return true;
  5526. }
  5527. return false;
  5528. }
  5529. bool File::printf (const tchar* pf, ...) const throw()
  5530. {
  5531. va_list list;
  5532. va_start (list, pf);
  5533. String text;
  5534. text.vprintf (pf, list);
  5535. return appendData ((const char*) text, text.length());
  5536. }
  5537. bool File::replaceWithText (const String& textToWrite,
  5538. const bool asUnicode,
  5539. const bool writeUnicodeHeaderBytes) const throw()
  5540. {
  5541. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5542. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  5543. && tempFile.moveFileTo (*this))
  5544. {
  5545. return true;
  5546. }
  5547. tempFile.deleteFile();
  5548. return false;
  5549. }
  5550. const String File::createLegalPathName (const String& original) throw()
  5551. {
  5552. String s (original);
  5553. String start;
  5554. if (s[1] == T(':'))
  5555. {
  5556. start = s.substring (0, 2);
  5557. s = s.substring (2);
  5558. }
  5559. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  5560. .substring (0, 1024);
  5561. }
  5562. const String File::createLegalFileName (const String& original) throw()
  5563. {
  5564. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  5565. const int maxLength = 128; // only the length of the filename, not the whole path
  5566. const int len = s.length();
  5567. if (len > maxLength)
  5568. {
  5569. const int lastDot = s.lastIndexOfChar (T('.'));
  5570. if (lastDot > jmax (0, len - 12))
  5571. {
  5572. s = s.substring (0, maxLength - (len - lastDot))
  5573. + s.substring (lastDot);
  5574. }
  5575. else
  5576. {
  5577. s = s.substring (0, maxLength);
  5578. }
  5579. }
  5580. return s;
  5581. }
  5582. const String File::getRelativePathFrom (const File& dir) const throw()
  5583. {
  5584. String thisPath (fullPath);
  5585. {
  5586. int len = thisPath.length();
  5587. while (--len >= 0 && thisPath [len] == File::separator)
  5588. thisPath [len] = 0;
  5589. }
  5590. String dirPath (juce_addTrailingSeparator ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  5591. : dir.fullPath));
  5592. const int len = jmin (thisPath.length(), dirPath.length());
  5593. int commonBitLength = 0;
  5594. for (int i = 0; i < len; ++i)
  5595. {
  5596. #if NAMES_ARE_CASE_SENSITIVE
  5597. if (thisPath[i] != dirPath[i])
  5598. #else
  5599. if (CharacterFunctions::toLowerCase (thisPath[i])
  5600. != CharacterFunctions::toLowerCase (dirPath[i]))
  5601. #endif
  5602. {
  5603. break;
  5604. }
  5605. ++commonBitLength;
  5606. }
  5607. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5608. --commonBitLength;
  5609. // if the only common bit is the root, then just return the full path..
  5610. if (commonBitLength <= 0
  5611. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5612. return fullPath;
  5613. thisPath = thisPath.substring (commonBitLength);
  5614. dirPath = dirPath.substring (commonBitLength);
  5615. while (dirPath.isNotEmpty())
  5616. {
  5617. #if JUCE_WINDOWS
  5618. thisPath = T("..\\") + thisPath;
  5619. #else
  5620. thisPath = T("../") + thisPath;
  5621. #endif
  5622. const int sep = dirPath.indexOfChar (separator);
  5623. if (sep >= 0)
  5624. dirPath = dirPath.substring (sep + 1);
  5625. else
  5626. dirPath = String::empty;
  5627. }
  5628. return thisPath;
  5629. }
  5630. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  5631. {
  5632. const StringArray roots (juce_getFileSystemRoots());
  5633. for (int i = 0; i < roots.size(); ++i)
  5634. destArray.add (new File (roots[i]));
  5635. }
  5636. const String File::getVolumeLabel() const throw()
  5637. {
  5638. int serialNum;
  5639. return juce_getVolumeLabel (fullPath, serialNum);
  5640. }
  5641. int File::getVolumeSerialNumber() const throw()
  5642. {
  5643. int serialNum;
  5644. juce_getVolumeLabel (fullPath, serialNum);
  5645. return serialNum;
  5646. }
  5647. const File File::createTempFile (const String& fileNameEnding) throw()
  5648. {
  5649. String tempName (T("temp"));
  5650. static int tempNum = 0;
  5651. tempName << tempNum++ << fileNameEnding;
  5652. const File tempFile (getSpecialLocation (tempDirectory)
  5653. .getChildFile (tempName));
  5654. if (tempFile.exists())
  5655. return createTempFile (fileNameEnding);
  5656. else
  5657. return tempFile;
  5658. }
  5659. END_JUCE_NAMESPACE
  5660. /********* End of inlined file: juce_File.cpp *********/
  5661. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  5662. BEGIN_JUCE_NAMESPACE
  5663. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5664. void juce_fileClose (void* handle) throw();
  5665. int juce_fileRead (void* handle, void* buffer, int size) throw();
  5666. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5667. FileInputStream::FileInputStream (const File& f)
  5668. : file (f),
  5669. currentPosition (0),
  5670. needToSeek (true)
  5671. {
  5672. totalSize = f.getSize();
  5673. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  5674. }
  5675. FileInputStream::~FileInputStream()
  5676. {
  5677. juce_fileClose (fileHandle);
  5678. }
  5679. int64 FileInputStream::getTotalLength()
  5680. {
  5681. return totalSize;
  5682. }
  5683. int FileInputStream::read (void* buffer, int bytesToRead)
  5684. {
  5685. int num = 0;
  5686. if (needToSeek)
  5687. {
  5688. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5689. return 0;
  5690. needToSeek = false;
  5691. }
  5692. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5693. currentPosition += num;
  5694. return num;
  5695. }
  5696. bool FileInputStream::isExhausted()
  5697. {
  5698. return currentPosition >= totalSize;
  5699. }
  5700. int64 FileInputStream::getPosition()
  5701. {
  5702. return currentPosition;
  5703. }
  5704. bool FileInputStream::setPosition (int64 pos)
  5705. {
  5706. pos = jlimit ((int64) 0, totalSize, pos);
  5707. needToSeek |= (currentPosition != pos);
  5708. currentPosition = pos;
  5709. return true;
  5710. }
  5711. END_JUCE_NAMESPACE
  5712. /********* End of inlined file: juce_FileInputStream.cpp *********/
  5713. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  5714. BEGIN_JUCE_NAMESPACE
  5715. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5716. void juce_fileClose (void* handle) throw();
  5717. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  5718. void juce_fileFlush (void* handle) throw();
  5719. int64 juce_fileGetPosition (void* handle) throw();
  5720. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5721. FileOutputStream::FileOutputStream (const File& f,
  5722. const int bufferSize_)
  5723. : file (f),
  5724. bufferSize (bufferSize_),
  5725. bytesInBuffer (0)
  5726. {
  5727. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  5728. if (fileHandle != 0)
  5729. {
  5730. currentPosition = juce_fileGetPosition (fileHandle);
  5731. if (currentPosition < 0)
  5732. {
  5733. jassertfalse
  5734. juce_fileClose (fileHandle);
  5735. fileHandle = 0;
  5736. }
  5737. }
  5738. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  5739. }
  5740. FileOutputStream::~FileOutputStream()
  5741. {
  5742. flush();
  5743. juce_fileClose (fileHandle);
  5744. juce_free (buffer);
  5745. }
  5746. int64 FileOutputStream::getPosition()
  5747. {
  5748. return currentPosition;
  5749. }
  5750. bool FileOutputStream::setPosition (int64 newPosition)
  5751. {
  5752. if (newPosition != currentPosition)
  5753. {
  5754. flush();
  5755. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5756. }
  5757. return newPosition == currentPosition;
  5758. }
  5759. void FileOutputStream::flush()
  5760. {
  5761. if (bytesInBuffer > 0)
  5762. {
  5763. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5764. bytesInBuffer = 0;
  5765. }
  5766. juce_fileFlush (fileHandle);
  5767. }
  5768. bool FileOutputStream::write (const void* const src, const int numBytes)
  5769. {
  5770. if (bytesInBuffer + numBytes < bufferSize)
  5771. {
  5772. memcpy (buffer + bytesInBuffer, src, numBytes);
  5773. bytesInBuffer += numBytes;
  5774. currentPosition += numBytes;
  5775. }
  5776. else
  5777. {
  5778. if (bytesInBuffer > 0)
  5779. {
  5780. // flush the reservoir
  5781. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5782. bytesInBuffer = 0;
  5783. if (! wroteOk)
  5784. return false;
  5785. }
  5786. if (numBytes < bufferSize)
  5787. {
  5788. memcpy (buffer + bytesInBuffer, src, numBytes);
  5789. bytesInBuffer += numBytes;
  5790. currentPosition += numBytes;
  5791. }
  5792. else
  5793. {
  5794. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5795. currentPosition += bytesWritten;
  5796. return bytesWritten == numBytes;
  5797. }
  5798. }
  5799. return true;
  5800. }
  5801. END_JUCE_NAMESPACE
  5802. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  5803. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  5804. BEGIN_JUCE_NAMESPACE
  5805. FileSearchPath::FileSearchPath()
  5806. {
  5807. }
  5808. FileSearchPath::FileSearchPath (const String& path)
  5809. {
  5810. init (path);
  5811. }
  5812. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5813. : directories (other.directories)
  5814. {
  5815. }
  5816. FileSearchPath::~FileSearchPath()
  5817. {
  5818. }
  5819. const FileSearchPath& FileSearchPath::operator= (const String& path)
  5820. {
  5821. init (path);
  5822. return *this;
  5823. }
  5824. void FileSearchPath::init (const String& path)
  5825. {
  5826. directories.clear();
  5827. directories.addTokens (path, T(";"), T("\""));
  5828. directories.trim();
  5829. directories.removeEmptyStrings();
  5830. for (int i = directories.size(); --i >= 0;)
  5831. directories.set (i, directories[i].unquoted());
  5832. }
  5833. int FileSearchPath::getNumPaths() const
  5834. {
  5835. return directories.size();
  5836. }
  5837. const File FileSearchPath::operator[] (const int index) const
  5838. {
  5839. return File (directories [index]);
  5840. }
  5841. const String FileSearchPath::toString() const
  5842. {
  5843. StringArray directories2 (directories);
  5844. for (int i = directories2.size(); --i >= 0;)
  5845. if (directories2[i].containsChar (T(';')))
  5846. directories2.set (i, directories2[i].quoted());
  5847. return directories2.joinIntoString (T(";"));
  5848. }
  5849. void FileSearchPath::add (const File& dir, const int insertIndex)
  5850. {
  5851. directories.insert (insertIndex, dir.getFullPathName());
  5852. }
  5853. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5854. {
  5855. for (int i = 0; i < directories.size(); ++i)
  5856. if (File (directories[i]) == dir)
  5857. return;
  5858. add (dir);
  5859. }
  5860. void FileSearchPath::remove (const int index)
  5861. {
  5862. directories.remove (index);
  5863. }
  5864. void FileSearchPath::addPath (const FileSearchPath& other)
  5865. {
  5866. for (int i = 0; i < other.getNumPaths(); ++i)
  5867. addIfNotAlreadyThere (other[i]);
  5868. }
  5869. void FileSearchPath::removeRedundantPaths()
  5870. {
  5871. for (int i = directories.size(); --i >= 0;)
  5872. {
  5873. const File d1 (directories[i]);
  5874. for (int j = directories.size(); --j >= 0;)
  5875. {
  5876. const File d2 (directories[j]);
  5877. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5878. {
  5879. directories.remove (i);
  5880. break;
  5881. }
  5882. }
  5883. }
  5884. }
  5885. void FileSearchPath::removeNonExistentPaths()
  5886. {
  5887. for (int i = directories.size(); --i >= 0;)
  5888. if (! File (directories[i]).isDirectory())
  5889. directories.remove (i);
  5890. }
  5891. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  5892. const int whatToLookFor,
  5893. const bool searchRecursively,
  5894. const String& wildCardPattern) const
  5895. {
  5896. int total = 0;
  5897. for (int i = 0; i < directories.size(); ++i)
  5898. total += operator[] (i).findChildFiles (results,
  5899. whatToLookFor,
  5900. searchRecursively,
  5901. wildCardPattern);
  5902. return total;
  5903. }
  5904. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5905. const bool checkRecursively) const
  5906. {
  5907. for (int i = directories.size(); --i >= 0;)
  5908. {
  5909. const File d (directories[i]);
  5910. if (checkRecursively)
  5911. {
  5912. if (fileToCheck.isAChildOf (d))
  5913. return true;
  5914. }
  5915. else
  5916. {
  5917. if (fileToCheck.getParentDirectory() == d)
  5918. return true;
  5919. }
  5920. }
  5921. return false;
  5922. }
  5923. END_JUCE_NAMESPACE
  5924. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  5925. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  5926. BEGIN_JUCE_NAMESPACE
  5927. NamedPipe::NamedPipe()
  5928. : internal (0)
  5929. {
  5930. }
  5931. NamedPipe::~NamedPipe()
  5932. {
  5933. close();
  5934. }
  5935. bool NamedPipe::openExisting (const String& pipeName)
  5936. {
  5937. currentPipeName = pipeName;
  5938. return openInternal (pipeName, false);
  5939. }
  5940. bool NamedPipe::createNewPipe (const String& pipeName)
  5941. {
  5942. currentPipeName = pipeName;
  5943. return openInternal (pipeName, true);
  5944. }
  5945. bool NamedPipe::isOpen() const throw()
  5946. {
  5947. return internal != 0;
  5948. }
  5949. const String NamedPipe::getName() const throw()
  5950. {
  5951. return currentPipeName;
  5952. }
  5953. // other methods for this class are implemented in the platform-specific files
  5954. END_JUCE_NAMESPACE
  5955. /********* End of inlined file: juce_NamedPipe.cpp *********/
  5956. /********* Start of inlined file: juce_Socket.cpp *********/
  5957. #if JUCE_WINDOWS
  5958. #include <winsock2.h>
  5959. #ifdef _MSC_VER
  5960. #pragma warning (disable : 4127 4389 4018)
  5961. #endif
  5962. #else
  5963. #if JUCE_LINUX
  5964. #include <sys/types.h>
  5965. #include <sys/socket.h>
  5966. #include <sys/errno.h>
  5967. #include <unistd.h>
  5968. #include <netinet/in.h>
  5969. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5970. #include <CoreServices/CoreServices.h>
  5971. #endif
  5972. #include <fcntl.h>
  5973. #include <netdb.h>
  5974. #include <arpa/inet.h>
  5975. #include <netinet/tcp.h>
  5976. #endif
  5977. BEGIN_JUCE_NAMESPACE
  5978. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5979. typedef socklen_t juce_socklen_t;
  5980. #else
  5981. typedef int juce_socklen_t;
  5982. #endif
  5983. #if JUCE_WINDOWS
  5984. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5985. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5986. static void initWin32Sockets()
  5987. {
  5988. static CriticalSection lock;
  5989. const ScopedLock sl (lock);
  5990. if (juce_CloseWin32SocketLib == 0)
  5991. {
  5992. WSADATA wsaData;
  5993. const WORD wVersionRequested = MAKEWORD (1, 1);
  5994. WSAStartup (wVersionRequested, &wsaData);
  5995. juce_CloseWin32SocketLib = &WSACleanup;
  5996. }
  5997. }
  5998. #endif
  5999. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6000. {
  6001. const int sndBufSize = 65536;
  6002. const int rcvBufSize = 65536;
  6003. const int one = 1;
  6004. return handle > 0
  6005. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6006. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6007. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6008. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6009. }
  6010. static bool bindSocketToPort (const int handle, const int port) throw()
  6011. {
  6012. if (handle <= 0 || port <= 0)
  6013. return false;
  6014. struct sockaddr_in servTmpAddr;
  6015. zerostruct (servTmpAddr);
  6016. servTmpAddr.sin_family = PF_INET;
  6017. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6018. servTmpAddr.sin_port = htons ((uint16) port);
  6019. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6020. }
  6021. static int readSocket (const int handle,
  6022. void* const destBuffer, const int maxBytesToRead,
  6023. bool volatile& connected,
  6024. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6025. {
  6026. int bytesRead = 0;
  6027. while (bytesRead < maxBytesToRead)
  6028. {
  6029. int bytesThisTime;
  6030. #if JUCE_WINDOWS
  6031. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6032. #else
  6033. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6034. && errno == EINTR
  6035. && connected)
  6036. {
  6037. }
  6038. #endif
  6039. if (bytesThisTime <= 0 || ! connected)
  6040. {
  6041. if (bytesRead == 0)
  6042. bytesRead = -1;
  6043. break;
  6044. }
  6045. bytesRead += bytesThisTime;
  6046. if (! blockUntilSpecifiedAmountHasArrived)
  6047. break;
  6048. }
  6049. return bytesRead;
  6050. }
  6051. static int waitForReadiness (const int handle, const bool forReading,
  6052. const int timeoutMsecs) throw()
  6053. {
  6054. struct timeval timeout;
  6055. struct timeval* timeoutp;
  6056. if (timeoutMsecs >= 0)
  6057. {
  6058. timeout.tv_sec = timeoutMsecs / 1000;
  6059. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6060. timeoutp = &timeout;
  6061. }
  6062. else
  6063. {
  6064. timeoutp = 0;
  6065. }
  6066. fd_set rset, wset;
  6067. FD_ZERO (&rset);
  6068. FD_SET (handle, &rset);
  6069. FD_ZERO (&wset);
  6070. FD_SET (handle, &wset);
  6071. fd_set* const prset = forReading ? &rset : 0;
  6072. fd_set* const pwset = forReading ? 0 : &wset;
  6073. #if JUCE_WINDOWS
  6074. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6075. return -1;
  6076. #else
  6077. {
  6078. int result;
  6079. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6080. && errno == EINTR)
  6081. {
  6082. }
  6083. if (result < 0)
  6084. return -1;
  6085. }
  6086. #endif
  6087. {
  6088. int opt;
  6089. juce_socklen_t len = sizeof (opt);
  6090. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6091. || opt != 0)
  6092. return -1;
  6093. }
  6094. if ((forReading && FD_ISSET (handle, &rset))
  6095. || ((! forReading) && FD_ISSET (handle, &wset)))
  6096. return 1;
  6097. return 0;
  6098. }
  6099. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6100. {
  6101. #if JUCE_WINDOWS
  6102. u_long nonBlocking = shouldBlock ? 0 : 1;
  6103. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6104. return false;
  6105. #else
  6106. int socketFlags = fcntl (handle, F_GETFL, 0);
  6107. if (socketFlags == -1)
  6108. return false;
  6109. if (shouldBlock)
  6110. socketFlags &= ~O_NONBLOCK;
  6111. else
  6112. socketFlags |= O_NONBLOCK;
  6113. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6114. return false;
  6115. #endif
  6116. return true;
  6117. }
  6118. static bool connectSocket (int volatile& handle,
  6119. const bool isDatagram,
  6120. void** serverAddress,
  6121. const String& hostName,
  6122. const int portNumber,
  6123. const int timeOutMillisecs) throw()
  6124. {
  6125. struct hostent* const hostEnt = gethostbyname (hostName);
  6126. if (hostEnt == 0)
  6127. return false;
  6128. struct in_addr targetAddress;
  6129. memcpy (&targetAddress.s_addr,
  6130. *(hostEnt->h_addr_list),
  6131. sizeof (targetAddress.s_addr));
  6132. struct sockaddr_in servTmpAddr;
  6133. zerostruct (servTmpAddr);
  6134. servTmpAddr.sin_family = PF_INET;
  6135. servTmpAddr.sin_addr = targetAddress;
  6136. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6137. if (handle < 0)
  6138. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6139. if (handle < 0)
  6140. return false;
  6141. if (isDatagram)
  6142. {
  6143. *serverAddress = new struct sockaddr_in();
  6144. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6145. return true;
  6146. }
  6147. setSocketBlockingState (handle, false);
  6148. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6149. if (result < 0)
  6150. {
  6151. #if JUCE_WINDOWS
  6152. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6153. #else
  6154. if (errno == EINPROGRESS)
  6155. #endif
  6156. {
  6157. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6158. {
  6159. setSocketBlockingState (handle, true);
  6160. return false;
  6161. }
  6162. }
  6163. }
  6164. setSocketBlockingState (handle, true);
  6165. resetSocketOptions (handle, false, false);
  6166. return true;
  6167. }
  6168. StreamingSocket::StreamingSocket()
  6169. : portNumber (0),
  6170. handle (-1),
  6171. connected (false),
  6172. isListener (false)
  6173. {
  6174. #if JUCE_WINDOWS
  6175. initWin32Sockets();
  6176. #endif
  6177. }
  6178. StreamingSocket::StreamingSocket (const String& hostName_,
  6179. const int portNumber_,
  6180. const int handle_)
  6181. : hostName (hostName_),
  6182. portNumber (portNumber_),
  6183. handle (handle_),
  6184. connected (true),
  6185. isListener (false)
  6186. {
  6187. #if JUCE_WINDOWS
  6188. initWin32Sockets();
  6189. #endif
  6190. resetSocketOptions (handle_, false, false);
  6191. }
  6192. StreamingSocket::~StreamingSocket()
  6193. {
  6194. close();
  6195. }
  6196. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6197. {
  6198. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6199. : -1;
  6200. }
  6201. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6202. {
  6203. if (isListener || ! connected)
  6204. return -1;
  6205. #if JUCE_WINDOWS
  6206. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6207. #else
  6208. int result;
  6209. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6210. && errno == EINTR)
  6211. {
  6212. }
  6213. return result;
  6214. #endif
  6215. }
  6216. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6217. const int timeoutMsecs) const
  6218. {
  6219. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6220. : -1;
  6221. }
  6222. bool StreamingSocket::bindToPort (const int port)
  6223. {
  6224. return bindSocketToPort (handle, port);
  6225. }
  6226. bool StreamingSocket::connect (const String& remoteHostName,
  6227. const int remotePortNumber,
  6228. const int timeOutMillisecs)
  6229. {
  6230. if (isListener)
  6231. {
  6232. jassertfalse // a listener socket can't connect to another one!
  6233. return false;
  6234. }
  6235. if (connected)
  6236. close();
  6237. hostName = remoteHostName;
  6238. portNumber = remotePortNumber;
  6239. isListener = false;
  6240. connected = connectSocket (handle, false, 0, remoteHostName,
  6241. remotePortNumber, timeOutMillisecs);
  6242. if (! (connected && resetSocketOptions (handle, false, false)))
  6243. {
  6244. close();
  6245. return false;
  6246. }
  6247. return true;
  6248. }
  6249. void StreamingSocket::close()
  6250. {
  6251. #if JUCE_WINDOWS
  6252. closesocket (handle);
  6253. connected = false;
  6254. #else
  6255. if (connected)
  6256. {
  6257. connected = false;
  6258. if (isListener)
  6259. {
  6260. // need to do this to interrupt the accept() function..
  6261. StreamingSocket temp;
  6262. temp.connect ("localhost", portNumber, 1000);
  6263. }
  6264. }
  6265. ::close (handle);
  6266. #endif
  6267. hostName = String::empty;
  6268. portNumber = 0;
  6269. handle = -1;
  6270. isListener = false;
  6271. }
  6272. bool StreamingSocket::createListener (const int newPortNumber)
  6273. {
  6274. if (connected)
  6275. close();
  6276. hostName = "listener";
  6277. portNumber = newPortNumber;
  6278. isListener = true;
  6279. struct sockaddr_in servTmpAddr;
  6280. zerostruct (servTmpAddr);
  6281. servTmpAddr.sin_family = PF_INET;
  6282. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6283. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6284. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6285. if (handle < 0)
  6286. return false;
  6287. const int reuse = 1;
  6288. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6289. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6290. || listen (handle, SOMAXCONN) < 0)
  6291. {
  6292. close();
  6293. return false;
  6294. }
  6295. connected = true;
  6296. return true;
  6297. }
  6298. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6299. {
  6300. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6301. // prepare this socket as a listener.
  6302. if (connected && isListener)
  6303. {
  6304. struct sockaddr address;
  6305. juce_socklen_t len = sizeof (sockaddr);
  6306. const int newSocket = (int) accept (handle, &address, &len);
  6307. if (newSocket >= 0 && connected)
  6308. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6309. portNumber, newSocket);
  6310. }
  6311. return 0;
  6312. }
  6313. bool StreamingSocket::isLocal() const throw()
  6314. {
  6315. return hostName == T("127.0.0.1");
  6316. }
  6317. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6318. : portNumber (0),
  6319. handle (-1),
  6320. connected (true),
  6321. allowBroadcast (allowBroadcast_),
  6322. serverAddress (0)
  6323. {
  6324. #if JUCE_WINDOWS
  6325. initWin32Sockets();
  6326. #endif
  6327. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6328. bindToPort (localPortNumber);
  6329. }
  6330. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6331. const int handle_, const int localPortNumber)
  6332. : hostName (hostName_),
  6333. portNumber (portNumber_),
  6334. handle (handle_),
  6335. connected (true),
  6336. allowBroadcast (false),
  6337. serverAddress (0)
  6338. {
  6339. #if JUCE_WINDOWS
  6340. initWin32Sockets();
  6341. #endif
  6342. resetSocketOptions (handle_, true, allowBroadcast);
  6343. bindToPort (localPortNumber);
  6344. }
  6345. DatagramSocket::~DatagramSocket()
  6346. {
  6347. close();
  6348. delete ((struct sockaddr_in*) serverAddress);
  6349. serverAddress = 0;
  6350. }
  6351. void DatagramSocket::close()
  6352. {
  6353. #if JUCE_WINDOWS
  6354. closesocket (handle);
  6355. connected = false;
  6356. #else
  6357. connected = false;
  6358. ::close (handle);
  6359. #endif
  6360. hostName = String::empty;
  6361. portNumber = 0;
  6362. handle = -1;
  6363. }
  6364. bool DatagramSocket::bindToPort (const int port)
  6365. {
  6366. return bindSocketToPort (handle, port);
  6367. }
  6368. bool DatagramSocket::connect (const String& remoteHostName,
  6369. const int remotePortNumber,
  6370. const int timeOutMillisecs)
  6371. {
  6372. if (connected)
  6373. close();
  6374. hostName = remoteHostName;
  6375. portNumber = remotePortNumber;
  6376. connected = connectSocket (handle, true, &serverAddress,
  6377. remoteHostName, remotePortNumber,
  6378. timeOutMillisecs);
  6379. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6380. {
  6381. close();
  6382. return false;
  6383. }
  6384. return true;
  6385. }
  6386. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6387. {
  6388. struct sockaddr address;
  6389. juce_socklen_t len = sizeof (sockaddr);
  6390. while (waitUntilReady (true, -1) == 1)
  6391. {
  6392. char buf[1];
  6393. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6394. {
  6395. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6396. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6397. -1, -1);
  6398. }
  6399. }
  6400. return 0;
  6401. }
  6402. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6403. const int timeoutMsecs) const
  6404. {
  6405. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6406. : -1;
  6407. }
  6408. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6409. {
  6410. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6411. : -1;
  6412. }
  6413. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6414. {
  6415. // You need to call connect() first to set the server address..
  6416. jassert (serverAddress != 0 && connected);
  6417. return connected ? sendto (handle, (const char*) sourceBuffer,
  6418. numBytesToWrite, 0,
  6419. (const struct sockaddr*) serverAddress,
  6420. sizeof (struct sockaddr_in))
  6421. : -1;
  6422. }
  6423. bool DatagramSocket::isLocal() const throw()
  6424. {
  6425. return hostName == T("127.0.0.1");
  6426. }
  6427. END_JUCE_NAMESPACE
  6428. /********* End of inlined file: juce_Socket.cpp *********/
  6429. /********* Start of inlined file: juce_URL.cpp *********/
  6430. BEGIN_JUCE_NAMESPACE
  6431. URL::URL() throw()
  6432. {
  6433. }
  6434. URL::URL (const String& url_)
  6435. : url (url_)
  6436. {
  6437. int i = url.indexOfChar (T('?'));
  6438. if (i >= 0)
  6439. {
  6440. do
  6441. {
  6442. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  6443. const int equalsPos = url.indexOfChar (i + 1, T('='));
  6444. if (equalsPos > i + 1)
  6445. {
  6446. if (nextAmp < 0)
  6447. {
  6448. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6449. removeEscapeChars (url.substring (equalsPos + 1)));
  6450. }
  6451. else if (nextAmp > 0 && equalsPos < nextAmp)
  6452. {
  6453. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6454. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6455. }
  6456. }
  6457. i = nextAmp;
  6458. }
  6459. while (i >= 0);
  6460. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  6461. }
  6462. }
  6463. URL::URL (const URL& other)
  6464. : url (other.url),
  6465. postData (other.postData),
  6466. parameters (other.parameters),
  6467. filesToUpload (other.filesToUpload),
  6468. mimeTypes (other.mimeTypes)
  6469. {
  6470. }
  6471. const URL& URL::operator= (const URL& other)
  6472. {
  6473. url = other.url;
  6474. postData = other.postData;
  6475. parameters = other.parameters;
  6476. filesToUpload = other.filesToUpload;
  6477. mimeTypes = other.mimeTypes;
  6478. return *this;
  6479. }
  6480. URL::~URL() throw()
  6481. {
  6482. }
  6483. static const String getMangledParameters (const StringPairArray& parameters)
  6484. {
  6485. String p;
  6486. for (int i = 0; i < parameters.size(); ++i)
  6487. {
  6488. if (i > 0)
  6489. p += T("&");
  6490. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6491. << T("=")
  6492. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6493. }
  6494. return p;
  6495. }
  6496. const String URL::toString (const bool includeGetParameters) const
  6497. {
  6498. if (includeGetParameters && parameters.size() > 0)
  6499. return url + T("?") + getMangledParameters (parameters);
  6500. else
  6501. return url;
  6502. }
  6503. bool URL::isWellFormed() const
  6504. {
  6505. //xxx TODO
  6506. return url.isNotEmpty();
  6507. }
  6508. static int findStartOfDomain (const String& url)
  6509. {
  6510. int i = 0;
  6511. while (CharacterFunctions::isLetterOrDigit (url[i])
  6512. || CharacterFunctions::indexOfChar (T("+-."), url[i], false) >= 0)
  6513. ++i;
  6514. return url[i] == T(':') ? i + 1 : 0;
  6515. }
  6516. const String URL::getDomain() const
  6517. {
  6518. int start = findStartOfDomain (url);
  6519. while (url[start] == T('/'))
  6520. ++start;
  6521. const int end1 = url.indexOfChar (start, T('/'));
  6522. const int end2 = url.indexOfChar (start, T(':'));
  6523. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6524. : jmin (end1, end2);
  6525. return url.substring (start, end);
  6526. }
  6527. const String URL::getSubPath() const
  6528. {
  6529. int start = findStartOfDomain (url);
  6530. while (url[start] == T('/'))
  6531. ++start;
  6532. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6533. return startOfPath <= 0 ? String::empty
  6534. : url.substring (startOfPath);
  6535. }
  6536. const String URL::getScheme() const
  6537. {
  6538. return url.substring (0, findStartOfDomain (url) - 1);
  6539. }
  6540. const URL URL::withNewSubPath (const String& newPath) const
  6541. {
  6542. int start = findStartOfDomain (url);
  6543. while (url[start] == T('/'))
  6544. ++start;
  6545. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6546. URL u (*this);
  6547. if (startOfPath > 0)
  6548. u.url = url.substring (0, startOfPath);
  6549. if (! u.url.endsWithChar (T('/')))
  6550. u.url << '/';
  6551. if (newPath.startsWithChar (T('/')))
  6552. u.url << newPath.substring (1);
  6553. else
  6554. u.url << newPath;
  6555. return u;
  6556. }
  6557. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6558. {
  6559. if (possibleURL.startsWithIgnoreCase (T("http:"))
  6560. || possibleURL.startsWithIgnoreCase (T("ftp:")))
  6561. return true;
  6562. if (possibleURL.startsWithIgnoreCase (T("file:"))
  6563. || possibleURL.containsChar (T('@'))
  6564. || possibleURL.endsWithChar (T('.'))
  6565. || (! possibleURL.containsChar (T('.'))))
  6566. return false;
  6567. if (possibleURL.startsWithIgnoreCase (T("www."))
  6568. && possibleURL.substring (5).containsChar (T('.')))
  6569. return true;
  6570. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6571. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6572. if ((possibleURL + T("/")).containsIgnoreCase (T(".") + String (commonTLDs[i]) + T("/")))
  6573. return true;
  6574. return false;
  6575. }
  6576. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6577. {
  6578. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  6579. return atSign > 0
  6580. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  6581. && (! possibleEmailAddress.endsWithChar (T('.')));
  6582. }
  6583. void* juce_openInternetFile (const String& url,
  6584. const String& headers,
  6585. const MemoryBlock& optionalPostData,
  6586. const bool isPost,
  6587. URL::OpenStreamProgressCallback* callback,
  6588. void* callbackContext,
  6589. int timeOutMs);
  6590. void juce_closeInternetFile (void* handle);
  6591. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6592. int juce_seekInInternetFile (void* handle, int newPosition);
  6593. int64 juce_getInternetFileContentLength (void* handle);
  6594. class WebInputStream : public InputStream
  6595. {
  6596. public:
  6597. WebInputStream (const URL& url,
  6598. const bool isPost_,
  6599. URL::OpenStreamProgressCallback* const progressCallback_,
  6600. void* const progressCallbackContext_,
  6601. const String& extraHeaders,
  6602. int timeOutMs_)
  6603. : position (0),
  6604. finished (false),
  6605. isPost (isPost_),
  6606. progressCallback (progressCallback_),
  6607. progressCallbackContext (progressCallbackContext_),
  6608. timeOutMs (timeOutMs_)
  6609. {
  6610. server = url.toString (! isPost);
  6611. if (isPost_)
  6612. createHeadersAndPostData (url);
  6613. headers += extraHeaders;
  6614. if (! headers.endsWithChar (T('\n')))
  6615. headers << "\r\n";
  6616. handle = juce_openInternetFile (server, headers, postData, isPost,
  6617. progressCallback_, progressCallbackContext_,
  6618. timeOutMs);
  6619. }
  6620. ~WebInputStream()
  6621. {
  6622. juce_closeInternetFile (handle);
  6623. }
  6624. bool isError() const throw()
  6625. {
  6626. return handle == 0;
  6627. }
  6628. int64 getTotalLength()
  6629. {
  6630. return juce_getInternetFileContentLength (handle);
  6631. }
  6632. bool isExhausted()
  6633. {
  6634. return finished;
  6635. }
  6636. int read (void* dest, int bytes)
  6637. {
  6638. if (finished || isError())
  6639. {
  6640. return 0;
  6641. }
  6642. else
  6643. {
  6644. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6645. position += bytesRead;
  6646. if (bytesRead == 0)
  6647. finished = true;
  6648. return bytesRead;
  6649. }
  6650. }
  6651. int64 getPosition()
  6652. {
  6653. return position;
  6654. }
  6655. bool setPosition (int64 wantedPos)
  6656. {
  6657. if (wantedPos != position)
  6658. {
  6659. finished = false;
  6660. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6661. if (actualPos == wantedPos)
  6662. {
  6663. position = wantedPos;
  6664. }
  6665. else
  6666. {
  6667. if (wantedPos < position)
  6668. {
  6669. juce_closeInternetFile (handle);
  6670. position = 0;
  6671. finished = false;
  6672. handle = juce_openInternetFile (server, headers, postData, isPost,
  6673. progressCallback, progressCallbackContext,
  6674. timeOutMs);
  6675. }
  6676. skipNextBytes (wantedPos - position);
  6677. }
  6678. }
  6679. return true;
  6680. }
  6681. juce_UseDebuggingNewOperator
  6682. private:
  6683. String server, headers;
  6684. MemoryBlock postData;
  6685. int64 position;
  6686. bool finished;
  6687. const bool isPost;
  6688. void* handle;
  6689. URL::OpenStreamProgressCallback* const progressCallback;
  6690. void* const progressCallbackContext;
  6691. const int timeOutMs;
  6692. void createHeadersAndPostData (const URL& url)
  6693. {
  6694. if (url.getFilesToUpload().size() > 0)
  6695. {
  6696. // need to upload some files, so do it as multi-part...
  6697. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6698. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6699. appendUTF8ToPostData ("--" + boundary);
  6700. int i;
  6701. for (i = 0; i < url.getParameters().size(); ++i)
  6702. {
  6703. String s;
  6704. s << "\r\nContent-Disposition: form-data; name=\""
  6705. << url.getParameters().getAllKeys() [i]
  6706. << "\"\r\n\r\n"
  6707. << url.getParameters().getAllValues() [i]
  6708. << "\r\n--"
  6709. << boundary;
  6710. appendUTF8ToPostData (s);
  6711. }
  6712. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6713. {
  6714. const File f (url.getFilesToUpload().getAllValues() [i]);
  6715. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6716. String s;
  6717. s << "\r\nContent-Disposition: form-data; name=\""
  6718. << paramName
  6719. << "\"; filename=\""
  6720. << f.getFileName()
  6721. << "\"\r\n";
  6722. const String mimeType (url.getMimeTypesOfUploadFiles()
  6723. .getValue (paramName, String::empty));
  6724. if (mimeType.isNotEmpty())
  6725. s << "Content-Type: " << mimeType << "\r\n";
  6726. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  6727. appendUTF8ToPostData (s);
  6728. f.loadFileAsData (postData);
  6729. s = "\r\n--" + boundary;
  6730. appendUTF8ToPostData (s);
  6731. }
  6732. appendUTF8ToPostData ("--\r\n");
  6733. }
  6734. else
  6735. {
  6736. appendUTF8ToPostData (getMangledParameters (url.getParameters()));
  6737. appendUTF8ToPostData (url.getPostData());
  6738. // just a short text attachment, so use simple url encoding..
  6739. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6740. + String (postData.getSize())
  6741. + "\r\n";
  6742. }
  6743. }
  6744. void appendUTF8ToPostData (const String& text) throw()
  6745. {
  6746. postData.append (text.toUTF8(),
  6747. (int) strlen (text.toUTF8()));
  6748. }
  6749. WebInputStream (const WebInputStream&);
  6750. const WebInputStream& operator= (const WebInputStream&);
  6751. };
  6752. InputStream* URL::createInputStream (const bool usePostCommand,
  6753. OpenStreamProgressCallback* const progressCallback,
  6754. void* const progressCallbackContext,
  6755. const String& extraHeaders,
  6756. const int timeOutMs) const
  6757. {
  6758. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  6759. progressCallback, progressCallbackContext,
  6760. extraHeaders,
  6761. timeOutMs);
  6762. if (wi->isError())
  6763. {
  6764. delete wi;
  6765. wi = 0;
  6766. }
  6767. return wi;
  6768. }
  6769. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6770. const bool usePostCommand) const
  6771. {
  6772. InputStream* const in = createInputStream (usePostCommand);
  6773. if (in != 0)
  6774. {
  6775. in->readIntoMemoryBlock (destData, -1);
  6776. delete in;
  6777. return true;
  6778. }
  6779. return false;
  6780. }
  6781. const String URL::readEntireTextStream (const bool usePostCommand) const
  6782. {
  6783. String result;
  6784. InputStream* const in = createInputStream (usePostCommand);
  6785. if (in != 0)
  6786. {
  6787. result = in->readEntireStreamAsString();
  6788. delete in;
  6789. }
  6790. return result;
  6791. }
  6792. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6793. {
  6794. XmlDocument doc (readEntireTextStream (usePostCommand));
  6795. return doc.getDocumentElement();
  6796. }
  6797. const URL URL::withParameter (const String& parameterName,
  6798. const String& parameterValue) const
  6799. {
  6800. URL u (*this);
  6801. u.parameters.set (parameterName, parameterValue);
  6802. return u;
  6803. }
  6804. const URL URL::withFileToUpload (const String& parameterName,
  6805. const File& fileToUpload,
  6806. const String& mimeType) const
  6807. {
  6808. URL u (*this);
  6809. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6810. u.mimeTypes.set (parameterName, mimeType);
  6811. return u;
  6812. }
  6813. const URL URL::withPOSTData (const String& postData_) const
  6814. {
  6815. URL u (*this);
  6816. u.postData = postData_;
  6817. return u;
  6818. }
  6819. const StringPairArray& URL::getParameters() const throw()
  6820. {
  6821. return parameters;
  6822. }
  6823. const StringPairArray& URL::getFilesToUpload() const throw()
  6824. {
  6825. return filesToUpload;
  6826. }
  6827. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  6828. {
  6829. return mimeTypes;
  6830. }
  6831. const String URL::removeEscapeChars (const String& s)
  6832. {
  6833. const int len = s.length();
  6834. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  6835. uint8* r = resultUTF8;
  6836. for (int i = 0; i < len; ++i)
  6837. {
  6838. char c = (char) s[i];
  6839. if (c == 0)
  6840. break;
  6841. if (c == '+')
  6842. {
  6843. c = ' ';
  6844. }
  6845. else if (c == '%')
  6846. {
  6847. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  6848. i += 2;
  6849. }
  6850. *r++ = c;
  6851. }
  6852. const String stringResult (String::fromUTF8 (resultUTF8));
  6853. juce_free (resultUTF8);
  6854. return stringResult;
  6855. }
  6856. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6857. {
  6858. String result;
  6859. result.preallocateStorage (s.length() + 8);
  6860. const char* utf8 = s.toUTF8();
  6861. const char* legalChars = isParameter ? "_-.*!'()"
  6862. : "_-$.*!'(),";
  6863. while (*utf8 != 0)
  6864. {
  6865. const char c = *utf8++;
  6866. if (CharacterFunctions::isLetterOrDigit (c)
  6867. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6868. {
  6869. result << c;
  6870. }
  6871. else
  6872. {
  6873. const int v = (int) (uint8) c;
  6874. if (v < 0x10)
  6875. result << T("%0");
  6876. else
  6877. result << T('%');
  6878. result << String::toHexString (v);
  6879. }
  6880. }
  6881. return result;
  6882. }
  6883. extern bool juce_launchFile (const String& fileName,
  6884. const String& parameters) throw();
  6885. bool URL::launchInDefaultBrowser() const
  6886. {
  6887. String u (toString (true));
  6888. if (u.contains (T("@")) && ! u.contains (T(":")))
  6889. u = "mailto:" + u;
  6890. return juce_launchFile (u, String::empty);
  6891. }
  6892. END_JUCE_NAMESPACE
  6893. /********* End of inlined file: juce_URL.cpp *********/
  6894. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  6895. BEGIN_JUCE_NAMESPACE
  6896. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6897. const int bufferSize_,
  6898. const bool deleteSourceWhenDestroyed_) throw()
  6899. : source (source_),
  6900. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6901. bufferSize (jmax (256, bufferSize_)),
  6902. position (source_->getPosition()),
  6903. lastReadPos (0),
  6904. bufferOverlap (128)
  6905. {
  6906. const int sourceSize = (int) source_->getTotalLength();
  6907. if (sourceSize >= 0)
  6908. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6909. bufferStart = position;
  6910. buffer = (char*) juce_malloc (bufferSize);
  6911. }
  6912. BufferedInputStream::~BufferedInputStream() throw()
  6913. {
  6914. if (deleteSourceWhenDestroyed)
  6915. delete source;
  6916. juce_free (buffer);
  6917. }
  6918. int64 BufferedInputStream::getTotalLength()
  6919. {
  6920. return source->getTotalLength();
  6921. }
  6922. int64 BufferedInputStream::getPosition()
  6923. {
  6924. return position;
  6925. }
  6926. bool BufferedInputStream::setPosition (int64 newPosition)
  6927. {
  6928. position = jmax ((int64) 0, newPosition);
  6929. return true;
  6930. }
  6931. bool BufferedInputStream::isExhausted()
  6932. {
  6933. return (position >= lastReadPos)
  6934. && source->isExhausted();
  6935. }
  6936. void BufferedInputStream::ensureBuffered()
  6937. {
  6938. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6939. if (position < bufferStart || position >= bufferEndOverlap)
  6940. {
  6941. int bytesRead;
  6942. if (position < lastReadPos
  6943. && position >= bufferEndOverlap
  6944. && position >= bufferStart)
  6945. {
  6946. const int bytesToKeep = (int) (lastReadPos - position);
  6947. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  6948. bufferStart = position;
  6949. bytesRead = source->read (buffer + bytesToKeep,
  6950. bufferSize - bytesToKeep);
  6951. lastReadPos += bytesRead;
  6952. bytesRead += bytesToKeep;
  6953. }
  6954. else
  6955. {
  6956. bufferStart = position;
  6957. source->setPosition (bufferStart);
  6958. bytesRead = source->read (buffer, bufferSize);
  6959. lastReadPos = bufferStart + bytesRead;
  6960. }
  6961. while (bytesRead < bufferSize)
  6962. buffer [bytesRead++] = 0;
  6963. }
  6964. }
  6965. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6966. {
  6967. if (position >= bufferStart
  6968. && position + maxBytesToRead <= lastReadPos)
  6969. {
  6970. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  6971. position += maxBytesToRead;
  6972. return maxBytesToRead;
  6973. }
  6974. else
  6975. {
  6976. if (position < bufferStart || position >= lastReadPos)
  6977. ensureBuffered();
  6978. int bytesRead = 0;
  6979. while (maxBytesToRead > 0)
  6980. {
  6981. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6982. if (bytesAvailable > 0)
  6983. {
  6984. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  6985. maxBytesToRead -= bytesAvailable;
  6986. bytesRead += bytesAvailable;
  6987. position += bytesAvailable;
  6988. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  6989. }
  6990. const int64 oldLastReadPos = lastReadPos;
  6991. ensureBuffered();
  6992. if (oldLastReadPos == lastReadPos)
  6993. break; // if ensureBuffered() failed to read any more data, bail out
  6994. if (isExhausted())
  6995. break;
  6996. }
  6997. return bytesRead;
  6998. }
  6999. }
  7000. const String BufferedInputStream::readString()
  7001. {
  7002. if (position >= bufferStart
  7003. && position < lastReadPos)
  7004. {
  7005. const int maxChars = (int) (lastReadPos - position);
  7006. const char* const src = buffer + (position - bufferStart);
  7007. for (int i = 0; i < maxChars; ++i)
  7008. {
  7009. if (src[i] == 0)
  7010. {
  7011. position += i + 1;
  7012. return String::fromUTF8 ((const uint8*) src, i);
  7013. }
  7014. }
  7015. }
  7016. return InputStream::readString();
  7017. }
  7018. END_JUCE_NAMESPACE
  7019. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  7020. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  7021. BEGIN_JUCE_NAMESPACE
  7022. FileInputSource::FileInputSource (const File& file_) throw()
  7023. : file (file_)
  7024. {
  7025. }
  7026. FileInputSource::~FileInputSource()
  7027. {
  7028. }
  7029. InputStream* FileInputSource::createInputStream()
  7030. {
  7031. return file.createInputStream();
  7032. }
  7033. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7034. {
  7035. return file.getSiblingFile (relatedItemPath).createInputStream();
  7036. }
  7037. int64 FileInputSource::hashCode() const
  7038. {
  7039. return file.hashCode();
  7040. }
  7041. END_JUCE_NAMESPACE
  7042. /********* End of inlined file: juce_FileInputSource.cpp *********/
  7043. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  7044. BEGIN_JUCE_NAMESPACE
  7045. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7046. const int sourceDataSize,
  7047. const bool keepInternalCopy) throw()
  7048. : data ((const char*) sourceData),
  7049. dataSize (sourceDataSize),
  7050. position (0)
  7051. {
  7052. if (keepInternalCopy)
  7053. {
  7054. internalCopy.append (data, sourceDataSize);
  7055. data = (const char*) internalCopy.getData();
  7056. }
  7057. }
  7058. MemoryInputStream::~MemoryInputStream() throw()
  7059. {
  7060. }
  7061. int64 MemoryInputStream::getTotalLength()
  7062. {
  7063. return dataSize;
  7064. }
  7065. int MemoryInputStream::read (void* buffer, int howMany)
  7066. {
  7067. const int num = jmin (howMany, dataSize - position);
  7068. memcpy (buffer, data + position, num);
  7069. position += num;
  7070. return num;
  7071. }
  7072. bool MemoryInputStream::isExhausted()
  7073. {
  7074. return (position >= dataSize);
  7075. }
  7076. bool MemoryInputStream::setPosition (int64 pos)
  7077. {
  7078. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7079. return true;
  7080. }
  7081. int64 MemoryInputStream::getPosition()
  7082. {
  7083. return position;
  7084. }
  7085. END_JUCE_NAMESPACE
  7086. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  7087. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  7088. BEGIN_JUCE_NAMESPACE
  7089. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  7090. const int blockSizeToIncreaseBy,
  7091. MemoryBlock* const memoryBlockToWriteTo) throw()
  7092. : data (memoryBlockToWriteTo),
  7093. position (0),
  7094. size (0),
  7095. blockSize (jmax (16, blockSizeToIncreaseBy)),
  7096. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  7097. {
  7098. if (memoryBlockToWriteTo == 0)
  7099. data = new MemoryBlock (initialSize);
  7100. else
  7101. memoryBlockToWriteTo->setSize (initialSize, false);
  7102. }
  7103. MemoryOutputStream::~MemoryOutputStream() throw()
  7104. {
  7105. if (ownsMemoryBlock)
  7106. delete data;
  7107. else
  7108. flush();
  7109. }
  7110. void MemoryOutputStream::flush()
  7111. {
  7112. if (! ownsMemoryBlock)
  7113. data->setSize (size, false);
  7114. }
  7115. void MemoryOutputStream::reset() throw()
  7116. {
  7117. position = 0;
  7118. size = 0;
  7119. }
  7120. bool MemoryOutputStream::write (const void* buffer, int howMany)
  7121. {
  7122. if (howMany > 0)
  7123. {
  7124. int storageNeeded = position + howMany;
  7125. if (storageNeeded >= data->getSize())
  7126. {
  7127. // if we need more space, increase the block by at least 10%..
  7128. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7129. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7130. data->ensureSize (storageNeeded);
  7131. }
  7132. data->copyFrom (buffer, position, howMany);
  7133. position += howMany;
  7134. size = jmax (size, position);
  7135. }
  7136. return true;
  7137. }
  7138. const char* MemoryOutputStream::getData() throw()
  7139. {
  7140. if (data->getSize() > size)
  7141. ((char*) data->getData()) [size] = 0;
  7142. return (const char*) data->getData();
  7143. }
  7144. int MemoryOutputStream::getDataSize() const throw()
  7145. {
  7146. return size;
  7147. }
  7148. int64 MemoryOutputStream::getPosition()
  7149. {
  7150. return position;
  7151. }
  7152. bool MemoryOutputStream::setPosition (int64 newPosition)
  7153. {
  7154. if (newPosition <= size)
  7155. {
  7156. // ok to seek backwards
  7157. position = jlimit (0, size, (int) newPosition);
  7158. return true;
  7159. }
  7160. else
  7161. {
  7162. // trying to make it bigger isn't a good thing to do..
  7163. return false;
  7164. }
  7165. }
  7166. END_JUCE_NAMESPACE
  7167. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  7168. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  7169. BEGIN_JUCE_NAMESPACE
  7170. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7171. const int64 startPositionInSourceStream_,
  7172. const int64 lengthOfSourceStream_,
  7173. const bool deleteSourceWhenDestroyed_) throw()
  7174. : source (sourceStream),
  7175. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  7176. startPositionInSourceStream (startPositionInSourceStream_),
  7177. lengthOfSourceStream (lengthOfSourceStream_)
  7178. {
  7179. setPosition (0);
  7180. }
  7181. SubregionStream::~SubregionStream() throw()
  7182. {
  7183. if (deleteSourceWhenDestroyed)
  7184. delete source;
  7185. }
  7186. int64 SubregionStream::getTotalLength()
  7187. {
  7188. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7189. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7190. : srcLen;
  7191. }
  7192. int64 SubregionStream::getPosition()
  7193. {
  7194. return source->getPosition() - startPositionInSourceStream;
  7195. }
  7196. bool SubregionStream::setPosition (int64 newPosition)
  7197. {
  7198. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7199. }
  7200. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7201. {
  7202. if (lengthOfSourceStream < 0)
  7203. {
  7204. return source->read (destBuffer, maxBytesToRead);
  7205. }
  7206. else
  7207. {
  7208. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7209. if (maxBytesToRead <= 0)
  7210. return 0;
  7211. return source->read (destBuffer, maxBytesToRead);
  7212. }
  7213. }
  7214. bool SubregionStream::isExhausted()
  7215. {
  7216. if (lengthOfSourceStream >= 0)
  7217. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7218. else
  7219. return source->isExhausted();
  7220. }
  7221. END_JUCE_NAMESPACE
  7222. /********* End of inlined file: juce_SubregionStream.cpp *********/
  7223. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  7224. BEGIN_JUCE_NAMESPACE
  7225. PerformanceCounter::PerformanceCounter (const String& name_,
  7226. int runsPerPrintout,
  7227. const File& loggingFile)
  7228. : name (name_),
  7229. numRuns (0),
  7230. runsPerPrint (runsPerPrintout),
  7231. totalTime (0),
  7232. outputFile (loggingFile)
  7233. {
  7234. if (outputFile != File::nonexistent)
  7235. {
  7236. String s ("**** Counter for \"");
  7237. s << name_ << "\" started at: "
  7238. << Time::getCurrentTime().toString (true, true)
  7239. << "\r\n";
  7240. outputFile.appendText (s, false, false);
  7241. }
  7242. }
  7243. PerformanceCounter::~PerformanceCounter()
  7244. {
  7245. printStatistics();
  7246. }
  7247. void PerformanceCounter::start()
  7248. {
  7249. started = Time::getHighResolutionTicks();
  7250. }
  7251. void PerformanceCounter::stop()
  7252. {
  7253. const int64 now = Time::getHighResolutionTicks();
  7254. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7255. if (++numRuns == runsPerPrint)
  7256. printStatistics();
  7257. }
  7258. void PerformanceCounter::printStatistics()
  7259. {
  7260. if (numRuns > 0)
  7261. {
  7262. String s ("Performance count for \"");
  7263. s << name << "\" - average over " << numRuns << " run(s) = ";
  7264. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7265. if (micros > 10000)
  7266. s << (micros/1000) << " millisecs";
  7267. else
  7268. s << micros << " microsecs";
  7269. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7270. Logger::outputDebugString (s);
  7271. s << "\r\n";
  7272. if (outputFile != File::nonexistent)
  7273. outputFile.appendText (s, false, false);
  7274. numRuns = 0;
  7275. totalTime = 0;
  7276. }
  7277. }
  7278. END_JUCE_NAMESPACE
  7279. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  7280. /********* Start of inlined file: juce_Uuid.cpp *********/
  7281. BEGIN_JUCE_NAMESPACE
  7282. Uuid::Uuid()
  7283. {
  7284. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7285. // to make it very very unlikely that two UUIDs will ever be the same..
  7286. static int64 macAddresses[2];
  7287. static bool hasCheckedMacAddresses = false;
  7288. if (! hasCheckedMacAddresses)
  7289. {
  7290. hasCheckedMacAddresses = true;
  7291. SystemStats::getMACAddresses (macAddresses, 2);
  7292. }
  7293. value.asInt64[0] = macAddresses[0];
  7294. value.asInt64[1] = macAddresses[1];
  7295. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7296. // whose seed will carry over between calls to this method.
  7297. Random r (macAddresses[0] ^ macAddresses[1]
  7298. ^ Random::getSystemRandom().nextInt64());
  7299. for (int i = 4; --i >= 0;)
  7300. {
  7301. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7302. value.asInt[i] ^= r.nextInt();
  7303. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7304. }
  7305. }
  7306. Uuid::~Uuid() throw()
  7307. {
  7308. }
  7309. Uuid::Uuid (const Uuid& other)
  7310. : value (other.value)
  7311. {
  7312. }
  7313. Uuid& Uuid::operator= (const Uuid& other)
  7314. {
  7315. if (this != &other)
  7316. value = other.value;
  7317. return *this;
  7318. }
  7319. bool Uuid::operator== (const Uuid& other) const
  7320. {
  7321. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  7322. }
  7323. bool Uuid::operator!= (const Uuid& other) const
  7324. {
  7325. return ! operator== (other);
  7326. }
  7327. bool Uuid::isNull() const throw()
  7328. {
  7329. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7330. }
  7331. const String Uuid::toString() const
  7332. {
  7333. return String::toHexString (value.asBytes, 16, 0);
  7334. }
  7335. Uuid::Uuid (const String& uuidString)
  7336. {
  7337. operator= (uuidString);
  7338. }
  7339. Uuid& Uuid::operator= (const String& uuidString)
  7340. {
  7341. int destIndex = 0;
  7342. int i = 0;
  7343. for (;;)
  7344. {
  7345. int byte = 0;
  7346. for (int loop = 2; --loop >= 0;)
  7347. {
  7348. byte <<= 4;
  7349. for (;;)
  7350. {
  7351. const tchar c = uuidString [i++];
  7352. if (c >= T('0') && c <= T('9'))
  7353. {
  7354. byte |= c - T('0');
  7355. break;
  7356. }
  7357. else if (c >= T('a') && c <= T('z'))
  7358. {
  7359. byte |= c - (T('a') - 10);
  7360. break;
  7361. }
  7362. else if (c >= T('A') && c <= T('Z'))
  7363. {
  7364. byte |= c - (T('A') - 10);
  7365. break;
  7366. }
  7367. else if (c == 0)
  7368. {
  7369. while (destIndex < 16)
  7370. value.asBytes [destIndex++] = 0;
  7371. return *this;
  7372. }
  7373. }
  7374. }
  7375. value.asBytes [destIndex++] = (uint8) byte;
  7376. }
  7377. }
  7378. Uuid::Uuid (const uint8* const rawData)
  7379. {
  7380. operator= (rawData);
  7381. }
  7382. Uuid& Uuid::operator= (const uint8* const rawData)
  7383. {
  7384. if (rawData != 0)
  7385. memcpy (value.asBytes, rawData, 16);
  7386. else
  7387. zeromem (value.asBytes, 16);
  7388. return *this;
  7389. }
  7390. END_JUCE_NAMESPACE
  7391. /********* End of inlined file: juce_Uuid.cpp *********/
  7392. /********* Start of inlined file: juce_ZipFile.cpp *********/
  7393. BEGIN_JUCE_NAMESPACE
  7394. struct ZipEntryInfo
  7395. {
  7396. ZipFile::ZipEntry entry;
  7397. int streamOffset;
  7398. int compressedSize;
  7399. bool compressed;
  7400. };
  7401. class ZipInputStream : public InputStream
  7402. {
  7403. public:
  7404. ZipInputStream (ZipFile& file_,
  7405. ZipEntryInfo& zei) throw()
  7406. : file (file_),
  7407. zipEntryInfo (zei),
  7408. pos (0),
  7409. headerSize (0),
  7410. inputStream (0)
  7411. {
  7412. inputStream = file_.inputStream;
  7413. if (file_.inputSource != 0)
  7414. {
  7415. inputStream = file.inputSource->createInputStream();
  7416. }
  7417. else
  7418. {
  7419. #ifdef JUCE_DEBUG
  7420. file_.numOpenStreams++;
  7421. #endif
  7422. }
  7423. char buffer [30];
  7424. if (inputStream != 0
  7425. && inputStream->setPosition (zei.streamOffset)
  7426. && inputStream->read (buffer, 30) == 30
  7427. && littleEndianInt (buffer) == 0x04034b50)
  7428. {
  7429. headerSize = 30 + littleEndianShort (buffer + 26)
  7430. + littleEndianShort (buffer + 28);
  7431. }
  7432. }
  7433. ~ZipInputStream() throw()
  7434. {
  7435. #ifdef JUCE_DEBUG
  7436. if (inputStream != 0 && inputStream == file.inputStream)
  7437. file.numOpenStreams--;
  7438. #endif
  7439. if (inputStream != file.inputStream)
  7440. delete inputStream;
  7441. }
  7442. int64 getTotalLength() throw()
  7443. {
  7444. return zipEntryInfo.compressedSize;
  7445. }
  7446. int read (void* buffer, int howMany) throw()
  7447. {
  7448. if (headerSize <= 0)
  7449. return 0;
  7450. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7451. if (inputStream == 0)
  7452. return 0;
  7453. int num;
  7454. if (inputStream == file.inputStream)
  7455. {
  7456. const ScopedLock sl (file.lock);
  7457. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7458. num = inputStream->read (buffer, howMany);
  7459. }
  7460. else
  7461. {
  7462. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7463. num = inputStream->read (buffer, howMany);
  7464. }
  7465. pos += num;
  7466. return num;
  7467. }
  7468. bool isExhausted() throw()
  7469. {
  7470. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7471. }
  7472. int64 getPosition() throw()
  7473. {
  7474. return pos;
  7475. }
  7476. bool setPosition (int64 newPos) throw()
  7477. {
  7478. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7479. return true;
  7480. }
  7481. private:
  7482. ZipFile& file;
  7483. ZipEntryInfo zipEntryInfo;
  7484. int64 pos;
  7485. int headerSize;
  7486. InputStream* inputStream;
  7487. ZipInputStream (const ZipInputStream&);
  7488. const ZipInputStream& operator= (const ZipInputStream&);
  7489. };
  7490. ZipFile::ZipFile (InputStream* const source_,
  7491. const bool deleteStreamWhenDestroyed_) throw()
  7492. : inputStream (source_),
  7493. inputSource (0),
  7494. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  7495. #ifdef JUCE_DEBUG
  7496. , numOpenStreams (0)
  7497. #endif
  7498. {
  7499. init();
  7500. }
  7501. ZipFile::ZipFile (const File& file)
  7502. : inputStream (0),
  7503. deleteStreamWhenDestroyed (false)
  7504. #ifdef JUCE_DEBUG
  7505. , numOpenStreams (0)
  7506. #endif
  7507. {
  7508. inputSource = new FileInputSource (file);
  7509. init();
  7510. }
  7511. ZipFile::ZipFile (InputSource* const inputSource_)
  7512. : inputStream (0),
  7513. inputSource (inputSource_),
  7514. deleteStreamWhenDestroyed (false)
  7515. #ifdef JUCE_DEBUG
  7516. , numOpenStreams (0)
  7517. #endif
  7518. {
  7519. init();
  7520. }
  7521. ZipFile::~ZipFile() throw()
  7522. {
  7523. for (int i = entries.size(); --i >= 0;)
  7524. {
  7525. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  7526. delete zei;
  7527. }
  7528. if (deleteStreamWhenDestroyed)
  7529. delete inputStream;
  7530. delete inputSource;
  7531. #ifdef JUCE_DEBUG
  7532. // If you hit this assertion, it means you've created a stream to read
  7533. // one of the items in the zipfile, but you've forgotten to delete that
  7534. // stream object before deleting the file.. Streams can't be kept open
  7535. // after the file is deleted because they need to share the input
  7536. // stream that the file uses to read itself.
  7537. jassert (numOpenStreams == 0);
  7538. #endif
  7539. }
  7540. int ZipFile::getNumEntries() const throw()
  7541. {
  7542. return entries.size();
  7543. }
  7544. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7545. {
  7546. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  7547. return (zei != 0) ? &(zei->entry)
  7548. : 0;
  7549. }
  7550. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7551. {
  7552. for (int i = 0; i < entries.size(); ++i)
  7553. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  7554. return i;
  7555. return -1;
  7556. }
  7557. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7558. {
  7559. return getEntry (getIndexOfFileName (fileName));
  7560. }
  7561. InputStream* ZipFile::createStreamForEntry (const int index)
  7562. {
  7563. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  7564. InputStream* stream = 0;
  7565. if (zei != 0)
  7566. {
  7567. stream = new ZipInputStream (*this, *zei);
  7568. if (zei->compressed)
  7569. {
  7570. stream = new GZIPDecompressorInputStream (stream, true, true,
  7571. zei->entry.uncompressedSize);
  7572. // (much faster to unzip in big blocks using a buffer..)
  7573. stream = new BufferedInputStream (stream, 32768, true);
  7574. }
  7575. }
  7576. return stream;
  7577. }
  7578. class ZipFilenameComparator
  7579. {
  7580. public:
  7581. static int compareElements (const void* const first, const void* const second) throw()
  7582. {
  7583. return ((const ZipEntryInfo*) first)->entry.filename
  7584. .compare (((const ZipEntryInfo*) second)->entry.filename);
  7585. }
  7586. };
  7587. void ZipFile::sortEntriesByFilename()
  7588. {
  7589. ZipFilenameComparator sorter;
  7590. entries.sort (sorter);
  7591. }
  7592. void ZipFile::init()
  7593. {
  7594. InputStream* in = inputStream;
  7595. bool deleteInput = false;
  7596. if (inputSource != 0)
  7597. {
  7598. deleteInput = true;
  7599. in = inputSource->createInputStream();
  7600. }
  7601. if (in != 0)
  7602. {
  7603. numEntries = 0;
  7604. int pos = findEndOfZipEntryTable (in);
  7605. if (pos >= 0 && pos < in->getTotalLength())
  7606. {
  7607. const int size = (int) (in->getTotalLength() - pos);
  7608. in->setPosition (pos);
  7609. MemoryBlock headerData;
  7610. if (in->readIntoMemoryBlock (headerData, size) == size)
  7611. {
  7612. pos = 0;
  7613. for (int i = 0; i < numEntries; ++i)
  7614. {
  7615. if (pos + 46 > size)
  7616. break;
  7617. const char* const buffer = ((const char*) headerData.getData()) + pos;
  7618. const int fileNameLen = littleEndianShort (buffer + 28);
  7619. if (pos + 46 + fileNameLen > size)
  7620. break;
  7621. ZipEntryInfo* const zei = new ZipEntryInfo();
  7622. zei->entry.filename = String (buffer + 46, fileNameLen);
  7623. const int time = littleEndianShort (buffer + 12);
  7624. const int date = littleEndianShort (buffer + 14);
  7625. const int year = 1980 + (date >> 9);
  7626. const int month = ((date >> 5) & 15) - 1;
  7627. const int day = date & 31;
  7628. const int hours = time >> 11;
  7629. const int minutes = (time >> 5) & 63;
  7630. const int seconds = (time & 31) << 1;
  7631. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7632. zei->compressed = littleEndianShort (buffer + 10) != 0;
  7633. zei->compressedSize = littleEndianInt (buffer + 20);
  7634. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  7635. zei->streamOffset = littleEndianInt (buffer + 42);
  7636. entries.add (zei);
  7637. pos += 46 + fileNameLen
  7638. + littleEndianShort (buffer + 30)
  7639. + littleEndianShort (buffer + 32);
  7640. }
  7641. }
  7642. }
  7643. if (deleteInput)
  7644. delete in;
  7645. }
  7646. }
  7647. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  7648. {
  7649. BufferedInputStream in (input, 8192, false);
  7650. in.setPosition (in.getTotalLength());
  7651. int64 pos = in.getPosition();
  7652. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7653. char buffer [32];
  7654. zeromem (buffer, sizeof (buffer));
  7655. while (pos > lowestPos)
  7656. {
  7657. in.setPosition (pos - 22);
  7658. pos = in.getPosition();
  7659. memcpy (buffer + 22, buffer, 4);
  7660. if (in.read (buffer, 22) != 22)
  7661. return 0;
  7662. for (int i = 0; i < 22; ++i)
  7663. {
  7664. if (littleEndianInt (buffer + i) == 0x06054b50)
  7665. {
  7666. in.setPosition (pos + i);
  7667. in.read (buffer, 22);
  7668. numEntries = littleEndianShort (buffer + 10);
  7669. return littleEndianInt (buffer + 16);
  7670. }
  7671. }
  7672. }
  7673. return 0;
  7674. }
  7675. void ZipFile::uncompressTo (const File& targetDirectory,
  7676. const bool shouldOverwriteFiles)
  7677. {
  7678. for (int i = 0; i < entries.size(); ++i)
  7679. {
  7680. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  7681. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  7682. if (zei.entry.filename.endsWithChar (T('/')))
  7683. {
  7684. targetFile.createDirectory(); // (entry is a directory, not a file)
  7685. }
  7686. else
  7687. {
  7688. InputStream* const in = createStreamForEntry (i);
  7689. if (in != 0)
  7690. {
  7691. if (shouldOverwriteFiles)
  7692. targetFile.deleteFile();
  7693. if ((! targetFile.exists())
  7694. && targetFile.getParentDirectory().createDirectory())
  7695. {
  7696. FileOutputStream* const out = targetFile.createOutputStream();
  7697. if (out != 0)
  7698. {
  7699. out->writeFromInputStream (*in, -1);
  7700. delete out;
  7701. targetFile.setCreationTime (zei.entry.fileTime);
  7702. targetFile.setLastModificationTime (zei.entry.fileTime);
  7703. targetFile.setLastAccessTime (zei.entry.fileTime);
  7704. }
  7705. }
  7706. delete in;
  7707. }
  7708. }
  7709. }
  7710. }
  7711. END_JUCE_NAMESPACE
  7712. /********* End of inlined file: juce_ZipFile.cpp *********/
  7713. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  7714. #ifdef _MSC_VER
  7715. #pragma warning (disable: 4514 4996)
  7716. #pragma warning (push)
  7717. #endif
  7718. #include <cwctype>
  7719. #include <cctype>
  7720. #include <ctime>
  7721. #ifdef _MSC_VER
  7722. #pragma warning (pop)
  7723. #endif
  7724. BEGIN_JUCE_NAMESPACE
  7725. int CharacterFunctions::length (const char* const s) throw()
  7726. {
  7727. return (int) strlen (s);
  7728. }
  7729. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7730. {
  7731. return (int) wcslen (s);
  7732. }
  7733. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7734. {
  7735. strncpy (dest, src, maxChars);
  7736. }
  7737. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7738. {
  7739. wcsncpy (dest, src, maxChars);
  7740. }
  7741. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7742. {
  7743. mbstowcs (dest, src, maxChars);
  7744. }
  7745. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7746. {
  7747. wcstombs (dest, src, maxChars);
  7748. }
  7749. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7750. {
  7751. return (int) wcstombs (0, src, 0);
  7752. }
  7753. void CharacterFunctions::append (char* dest, const char* src) throw()
  7754. {
  7755. strcat (dest, src);
  7756. }
  7757. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7758. {
  7759. wcscat (dest, src);
  7760. }
  7761. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7762. {
  7763. return strcmp (s1, s2);
  7764. }
  7765. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7766. {
  7767. jassert (s1 != 0 && s2 != 0);
  7768. return wcscmp (s1, s2);
  7769. }
  7770. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7771. {
  7772. jassert (s1 != 0 && s2 != 0);
  7773. return strncmp (s1, s2, maxChars);
  7774. }
  7775. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7776. {
  7777. jassert (s1 != 0 && s2 != 0);
  7778. return wcsncmp (s1, s2, maxChars);
  7779. }
  7780. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7781. {
  7782. jassert (s1 != 0 && s2 != 0);
  7783. #if JUCE_WIN32
  7784. return stricmp (s1, s2);
  7785. #else
  7786. return strcasecmp (s1, s2);
  7787. #endif
  7788. }
  7789. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7790. {
  7791. jassert (s1 != 0 && s2 != 0);
  7792. #if JUCE_WIN32
  7793. return _wcsicmp (s1, s2);
  7794. #else
  7795. for (;;)
  7796. {
  7797. if (*s1 != *s2)
  7798. {
  7799. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7800. if (diff != 0)
  7801. return diff < 0 ? -1 : 1;
  7802. }
  7803. else if (*s1 == 0)
  7804. break;
  7805. ++s1;
  7806. ++s2;
  7807. }
  7808. return 0;
  7809. #endif
  7810. }
  7811. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7812. {
  7813. jassert (s1 != 0 && s2 != 0);
  7814. #if JUCE_WIN32
  7815. return strnicmp (s1, s2, maxChars);
  7816. #else
  7817. return strncasecmp (s1, s2, maxChars);
  7818. #endif
  7819. }
  7820. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7821. {
  7822. jassert (s1 != 0 && s2 != 0);
  7823. #if JUCE_WIN32
  7824. return _wcsnicmp (s1, s2, maxChars);
  7825. #else
  7826. while (--maxChars >= 0)
  7827. {
  7828. if (*s1 != *s2)
  7829. {
  7830. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7831. if (diff != 0)
  7832. return diff < 0 ? -1 : 1;
  7833. }
  7834. else if (*s1 == 0)
  7835. break;
  7836. ++s1;
  7837. ++s2;
  7838. }
  7839. return 0;
  7840. #endif
  7841. }
  7842. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7843. {
  7844. return strstr (haystack, needle);
  7845. }
  7846. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7847. {
  7848. return wcsstr (haystack, needle);
  7849. }
  7850. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7851. {
  7852. if (haystack != 0)
  7853. {
  7854. int i = 0;
  7855. if (ignoreCase)
  7856. {
  7857. const char n1 = toLowerCase (needle);
  7858. const char n2 = toUpperCase (needle);
  7859. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7860. {
  7861. while (haystack[i] != 0)
  7862. {
  7863. if (haystack[i] == n1 || haystack[i] == n2)
  7864. return i;
  7865. ++i;
  7866. }
  7867. return -1;
  7868. }
  7869. jassert (n1 == needle);
  7870. }
  7871. while (haystack[i] != 0)
  7872. {
  7873. if (haystack[i] == needle)
  7874. return i;
  7875. ++i;
  7876. }
  7877. }
  7878. return -1;
  7879. }
  7880. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7881. {
  7882. if (haystack != 0)
  7883. {
  7884. int i = 0;
  7885. if (ignoreCase)
  7886. {
  7887. const juce_wchar n1 = toLowerCase (needle);
  7888. const juce_wchar n2 = toUpperCase (needle);
  7889. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7890. {
  7891. while (haystack[i] != 0)
  7892. {
  7893. if (haystack[i] == n1 || haystack[i] == n2)
  7894. return i;
  7895. ++i;
  7896. }
  7897. return -1;
  7898. }
  7899. jassert (n1 == needle);
  7900. }
  7901. while (haystack[i] != 0)
  7902. {
  7903. if (haystack[i] == needle)
  7904. return i;
  7905. ++i;
  7906. }
  7907. }
  7908. return -1;
  7909. }
  7910. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7911. {
  7912. jassert (haystack != 0);
  7913. int i = 0;
  7914. while (haystack[i] != 0)
  7915. {
  7916. if (haystack[i] == needle)
  7917. return i;
  7918. ++i;
  7919. }
  7920. return -1;
  7921. }
  7922. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7923. {
  7924. jassert (haystack != 0);
  7925. int i = 0;
  7926. while (haystack[i] != 0)
  7927. {
  7928. if (haystack[i] == needle)
  7929. return i;
  7930. ++i;
  7931. }
  7932. return -1;
  7933. }
  7934. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7935. {
  7936. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7937. }
  7938. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7939. {
  7940. if (allowedChars == 0)
  7941. return 0;
  7942. int i = 0;
  7943. for (;;)
  7944. {
  7945. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7946. break;
  7947. ++i;
  7948. }
  7949. return i;
  7950. }
  7951. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7952. {
  7953. return (int) strftime (dest, maxChars, format, tm);
  7954. }
  7955. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7956. {
  7957. return (int) wcsftime (dest, maxChars, format, tm);
  7958. }
  7959. int CharacterFunctions::getIntValue (const char* const s) throw()
  7960. {
  7961. return atoi (s);
  7962. }
  7963. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7964. {
  7965. #if JUCE_WIN32
  7966. return _wtoi (s);
  7967. #else
  7968. int v = 0;
  7969. while (isWhitespace (*s))
  7970. ++s;
  7971. const bool isNeg = *s == T('-');
  7972. if (isNeg)
  7973. ++s;
  7974. for (;;)
  7975. {
  7976. const wchar_t c = *s++;
  7977. if (c >= T('0') && c <= T('9'))
  7978. v = v * 10 + (int) (c - T('0'));
  7979. else
  7980. break;
  7981. }
  7982. return isNeg ? -v : v;
  7983. #endif
  7984. }
  7985. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7986. {
  7987. #if JUCE_LINUX
  7988. return atoll (s);
  7989. #elif defined (JUCE_WIN32)
  7990. return _atoi64 (s);
  7991. #else
  7992. int64 v = 0;
  7993. while (isWhitespace (*s))
  7994. ++s;
  7995. const bool isNeg = *s == T('-');
  7996. if (isNeg)
  7997. ++s;
  7998. for (;;)
  7999. {
  8000. const char c = *s++;
  8001. if (c >= '0' && c <= '9')
  8002. v = v * 10 + (int64) (c - '0');
  8003. else
  8004. break;
  8005. }
  8006. return isNeg ? -v : v;
  8007. #endif
  8008. }
  8009. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8010. {
  8011. #if JUCE_WIN32
  8012. return _wtoi64 (s);
  8013. #else
  8014. int64 v = 0;
  8015. while (isWhitespace (*s))
  8016. ++s;
  8017. const bool isNeg = *s == T('-');
  8018. if (isNeg)
  8019. ++s;
  8020. for (;;)
  8021. {
  8022. const juce_wchar c = *s++;
  8023. if (c >= T('0') && c <= T('9'))
  8024. v = v * 10 + (int64) (c - T('0'));
  8025. else
  8026. break;
  8027. }
  8028. return isNeg ? -v : v;
  8029. #endif
  8030. }
  8031. static double juce_mulexp10 (const double value, int exponent) throw()
  8032. {
  8033. if (exponent == 0)
  8034. return value;
  8035. if (value == 0)
  8036. return 0;
  8037. const bool negative = (exponent < 0);
  8038. if (negative)
  8039. exponent = -exponent;
  8040. double result = 1.0, power = 10.0;
  8041. for (int bit = 1; exponent != 0; bit <<= 1)
  8042. {
  8043. if ((exponent & bit) != 0)
  8044. {
  8045. exponent ^= bit;
  8046. result *= power;
  8047. if (exponent == 0)
  8048. break;
  8049. }
  8050. power *= power;
  8051. }
  8052. return negative ? (value / result) : (value * result);
  8053. }
  8054. template <class CharType>
  8055. double juce_atof (const CharType* const original) throw()
  8056. {
  8057. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8058. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8059. int exponent = 0, decPointIndex = 0, digit = 0;
  8060. int lastDigit = 0, numSignificantDigits = 0;
  8061. bool isNegative = false, digitsFound = false;
  8062. const int maxSignificantDigits = 15 + 2;
  8063. const CharType* s = original;
  8064. while (CharacterFunctions::isWhitespace (*s))
  8065. ++s;
  8066. switch (*s)
  8067. {
  8068. case '-': isNegative = true; // fall-through..
  8069. case '+': ++s;
  8070. }
  8071. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8072. return atof (String (original)); // Let the c library deal with NAN and INF
  8073. for (;;)
  8074. {
  8075. if (CharacterFunctions::isDigit (*s))
  8076. {
  8077. lastDigit = digit;
  8078. digit = *s++ - '0';
  8079. digitsFound = true;
  8080. if (decPointIndex != 0)
  8081. exponentAdjustment[1]++;
  8082. if (numSignificantDigits == 0 && digit == 0)
  8083. continue;
  8084. if (++numSignificantDigits > maxSignificantDigits)
  8085. {
  8086. if (digit > 5)
  8087. ++accumulator [decPointIndex];
  8088. else if (digit == 5 && (lastDigit & 1) != 0)
  8089. ++accumulator [decPointIndex];
  8090. if (decPointIndex > 0)
  8091. exponentAdjustment[1]--;
  8092. else
  8093. exponentAdjustment[0]++;
  8094. while (CharacterFunctions::isDigit (*s))
  8095. {
  8096. ++s;
  8097. if (decPointIndex == 0)
  8098. exponentAdjustment[0]++;
  8099. }
  8100. }
  8101. else
  8102. {
  8103. const double maxAccumulatorValue = (double) ((UINT_MAX - 9) / 10);
  8104. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8105. {
  8106. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8107. + accumulator [decPointIndex];
  8108. accumulator [decPointIndex] = 0;
  8109. exponentAccumulator [decPointIndex] = 0;
  8110. }
  8111. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8112. exponentAccumulator [decPointIndex]++;
  8113. }
  8114. }
  8115. else if (decPointIndex == 0 && *s == '.')
  8116. {
  8117. ++s;
  8118. decPointIndex = 1;
  8119. if (numSignificantDigits > maxSignificantDigits)
  8120. {
  8121. while (CharacterFunctions::isDigit (*s))
  8122. ++s;
  8123. break;
  8124. }
  8125. }
  8126. else
  8127. {
  8128. break;
  8129. }
  8130. }
  8131. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8132. if (decPointIndex != 0)
  8133. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8134. if ((*s == 'e' || *s == 'E') && digitsFound)
  8135. {
  8136. bool negativeExponent = false;
  8137. switch (*++s)
  8138. {
  8139. case '-': negativeExponent = true; // fall-through..
  8140. case '+': ++s;
  8141. }
  8142. while (CharacterFunctions::isDigit (*s))
  8143. exponent = (exponent * 10) + (*s++ - '0');
  8144. if (negativeExponent)
  8145. exponent = -exponent;
  8146. }
  8147. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8148. if (decPointIndex != 0)
  8149. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8150. return isNegative ? -r : r;
  8151. }
  8152. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8153. {
  8154. return juce_atof <char> (s);
  8155. }
  8156. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8157. {
  8158. return juce_atof <juce_wchar> (s);
  8159. }
  8160. char CharacterFunctions::toUpperCase (const char character) throw()
  8161. {
  8162. return (char) toupper (character);
  8163. }
  8164. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8165. {
  8166. return towupper (character);
  8167. }
  8168. void CharacterFunctions::toUpperCase (char* s) throw()
  8169. {
  8170. #if JUCE_WIN32
  8171. strupr (s);
  8172. #else
  8173. while (*s != 0)
  8174. {
  8175. *s = toUpperCase (*s);
  8176. ++s;
  8177. }
  8178. #endif
  8179. }
  8180. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8181. {
  8182. #if JUCE_WIN32
  8183. _wcsupr (s);
  8184. #else
  8185. while (*s != 0)
  8186. {
  8187. *s = toUpperCase (*s);
  8188. ++s;
  8189. }
  8190. #endif
  8191. }
  8192. bool CharacterFunctions::isUpperCase (const char character) throw()
  8193. {
  8194. return isupper (character) != 0;
  8195. }
  8196. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8197. {
  8198. #if JUCE_WIN32
  8199. return iswupper (character) != 0;
  8200. #else
  8201. return toLowerCase (character) != character;
  8202. #endif
  8203. }
  8204. char CharacterFunctions::toLowerCase (const char character) throw()
  8205. {
  8206. return (char) tolower (character);
  8207. }
  8208. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8209. {
  8210. return towlower (character);
  8211. }
  8212. void CharacterFunctions::toLowerCase (char* s) throw()
  8213. {
  8214. #if JUCE_WIN32
  8215. strlwr (s);
  8216. #else
  8217. while (*s != 0)
  8218. {
  8219. *s = toLowerCase (*s);
  8220. ++s;
  8221. }
  8222. #endif
  8223. }
  8224. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8225. {
  8226. #if JUCE_WIN32
  8227. _wcslwr (s);
  8228. #else
  8229. while (*s != 0)
  8230. {
  8231. *s = toLowerCase (*s);
  8232. ++s;
  8233. }
  8234. #endif
  8235. }
  8236. bool CharacterFunctions::isLowerCase (const char character) throw()
  8237. {
  8238. return islower (character) != 0;
  8239. }
  8240. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8241. {
  8242. #if JUCE_WIN32
  8243. return iswlower (character) != 0;
  8244. #else
  8245. return toUpperCase (character) != character;
  8246. #endif
  8247. }
  8248. bool CharacterFunctions::isWhitespace (const char character) throw()
  8249. {
  8250. return character == T(' ') || (character <= 13 && character >= 9);
  8251. }
  8252. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8253. {
  8254. return iswspace (character) != 0;
  8255. }
  8256. bool CharacterFunctions::isDigit (const char character) throw()
  8257. {
  8258. return (character >= '0' && character <= '9');
  8259. }
  8260. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8261. {
  8262. return iswdigit (character) != 0;
  8263. }
  8264. bool CharacterFunctions::isLetter (const char character) throw()
  8265. {
  8266. return (character >= 'a' && character <= 'z')
  8267. || (character >= 'A' && character <= 'Z');
  8268. }
  8269. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8270. {
  8271. return iswalpha (character) != 0;
  8272. }
  8273. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8274. {
  8275. return (character >= 'a' && character <= 'z')
  8276. || (character >= 'A' && character <= 'Z')
  8277. || (character >= '0' && character <= '9');
  8278. }
  8279. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8280. {
  8281. return iswalnum (character) != 0;
  8282. }
  8283. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  8284. {
  8285. if (digit >= T('0') && digit <= T('9'))
  8286. return digit - T('0');
  8287. else if (digit >= T('a') && digit <= T('f'))
  8288. return digit - (T('a') - 10);
  8289. else if (digit >= T('A') && digit <= T('F'))
  8290. return digit - (T('A') - 10);
  8291. return -1;
  8292. }
  8293. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  8294. {
  8295. va_list list;
  8296. va_start (list, format);
  8297. return vprintf (dest, maxLength, format, list);
  8298. }
  8299. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  8300. {
  8301. va_list list;
  8302. va_start (list, format);
  8303. return vprintf (dest, maxLength, format, list);
  8304. }
  8305. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  8306. {
  8307. #if JUCE_WIN32
  8308. return (int) _vsnprintf (dest, maxLength, format, args);
  8309. #else
  8310. return (int) vsnprintf (dest, maxLength, format, args);
  8311. #endif
  8312. }
  8313. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  8314. {
  8315. #if MACOS_10_3_OR_EARLIER
  8316. const String formatTemp (format);
  8317. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  8318. String temp ((char*) dest);
  8319. temp.copyToBuffer (dest, num);
  8320. dest [num] = 0;
  8321. return (int) num;
  8322. #elif defined (JUCE_WIN32)
  8323. return (int) _vsnwprintf (dest, maxLength, format, args);
  8324. #else
  8325. return (int) vswprintf (dest, maxLength, format, args);
  8326. #endif
  8327. }
  8328. END_JUCE_NAMESPACE
  8329. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  8330. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  8331. BEGIN_JUCE_NAMESPACE
  8332. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  8333. {
  8334. loadFromText (fileContents);
  8335. }
  8336. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  8337. {
  8338. loadFromText (fileToLoad.loadFileAsString());
  8339. }
  8340. LocalisedStrings::~LocalisedStrings() throw()
  8341. {
  8342. }
  8343. const String LocalisedStrings::translate (const String& text) const throw()
  8344. {
  8345. return translations.getValue (text, text);
  8346. }
  8347. static int findCloseQuote (const String& text, int startPos) throw()
  8348. {
  8349. tchar lastChar = 0;
  8350. for (;;)
  8351. {
  8352. const tchar c = text [startPos];
  8353. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  8354. break;
  8355. lastChar = c;
  8356. ++startPos;
  8357. }
  8358. return startPos;
  8359. }
  8360. static const String unescapeString (const String& s) throw()
  8361. {
  8362. return s.replace (T("\\\""), T("\""))
  8363. .replace (T("\\\'"), T("\'"))
  8364. .replace (T("\\t"), T("\t"))
  8365. .replace (T("\\r"), T("\r"))
  8366. .replace (T("\\n"), T("\n"));
  8367. }
  8368. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  8369. {
  8370. StringArray lines;
  8371. lines.addLines (fileContents);
  8372. for (int i = 0; i < lines.size(); ++i)
  8373. {
  8374. String line (lines[i].trim());
  8375. if (line.startsWithChar (T('"')))
  8376. {
  8377. int closeQuote = findCloseQuote (line, 1);
  8378. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8379. if (originalText.isNotEmpty())
  8380. {
  8381. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8382. closeQuote = findCloseQuote (line, openingQuote + 1);
  8383. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8384. if (newText.isNotEmpty())
  8385. translations.set (originalText, newText);
  8386. }
  8387. }
  8388. else if (line.startsWithIgnoreCase (T("language:")))
  8389. {
  8390. languageName = line.substring (9).trim();
  8391. }
  8392. else if (line.startsWithIgnoreCase (T("countries:")))
  8393. {
  8394. countryCodes.addTokens (line.substring (10).trim(), true);
  8395. countryCodes.trim();
  8396. countryCodes.removeEmptyStrings();
  8397. }
  8398. }
  8399. }
  8400. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) throw()
  8401. {
  8402. translations.setIgnoresCase (shouldIgnoreCase);
  8403. }
  8404. static CriticalSection currentMappingsLock;
  8405. static LocalisedStrings* currentMappings = 0;
  8406. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  8407. {
  8408. const ScopedLock sl (currentMappingsLock);
  8409. delete currentMappings;
  8410. currentMappings = newTranslations;
  8411. }
  8412. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  8413. {
  8414. return currentMappings;
  8415. }
  8416. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  8417. {
  8418. const ScopedLock sl (currentMappingsLock);
  8419. if (currentMappings != 0)
  8420. return currentMappings->translate (text);
  8421. return text;
  8422. }
  8423. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  8424. {
  8425. return translateWithCurrentMappings (String (text));
  8426. }
  8427. END_JUCE_NAMESPACE
  8428. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  8429. /********* Start of inlined file: juce_String.cpp *********/
  8430. #ifdef _MSC_VER
  8431. #pragma warning (disable: 4514)
  8432. #pragma warning (push)
  8433. #endif
  8434. #include <locale>
  8435. #if JUCE_MSVC
  8436. #include <float.h>
  8437. #endif
  8438. BEGIN_JUCE_NAMESPACE
  8439. #ifdef _MSC_VER
  8440. #pragma warning (pop)
  8441. #endif
  8442. static const char* const emptyCharString = "\0\0\0\0JUCE";
  8443. static const int safeEmptyStringRefCount = 0x3fffffff;
  8444. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  8445. static tchar decimalPoint = T('.');
  8446. void juce_initialiseStrings()
  8447. {
  8448. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  8449. }
  8450. void String::deleteInternal() throw()
  8451. {
  8452. if (atomicDecrementAndReturn (text->refCount) == 0)
  8453. juce_free (text);
  8454. }
  8455. void String::createInternal (const int numChars) throw()
  8456. {
  8457. jassert (numChars > 0);
  8458. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8459. + numChars * sizeof (tchar));
  8460. text->refCount = 1;
  8461. text->allocatedNumChars = numChars;
  8462. text->text[0] = 0;
  8463. }
  8464. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  8465. {
  8466. jassert (*(textEnd - 1) == 0); // must have a null terminator
  8467. const int numChars = (int) (textEnd - t);
  8468. createInternal (numChars - 1);
  8469. memcpy (text->text, t, numChars * sizeof (tchar));
  8470. }
  8471. void String::appendInternal (const tchar* const newText,
  8472. const int numExtraChars) throw()
  8473. {
  8474. if (numExtraChars > 0)
  8475. {
  8476. const int oldLen = CharacterFunctions::length (text->text);
  8477. const int newTotalLen = oldLen + numExtraChars;
  8478. if (text->refCount > 1)
  8479. {
  8480. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  8481. InternalRefCountedStringHolder* const newTextHolder
  8482. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8483. + newTotalLen * sizeof (tchar));
  8484. newTextHolder->refCount = 1;
  8485. newTextHolder->allocatedNumChars = newTotalLen;
  8486. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  8487. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8488. InternalRefCountedStringHolder* const old = text;
  8489. text = newTextHolder;
  8490. if (atomicDecrementAndReturn (old->refCount) == 0)
  8491. juce_free (old);
  8492. }
  8493. else
  8494. {
  8495. // no other strings using it, so just expand it if needed..
  8496. if (newTotalLen > text->allocatedNumChars)
  8497. {
  8498. text = (InternalRefCountedStringHolder*)
  8499. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8500. + newTotalLen * sizeof (tchar));
  8501. text->allocatedNumChars = newTotalLen;
  8502. }
  8503. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8504. }
  8505. text->text [newTotalLen] = 0;
  8506. }
  8507. }
  8508. void String::dupeInternalIfMultiplyReferenced() throw()
  8509. {
  8510. if (text->refCount > 1)
  8511. {
  8512. InternalRefCountedStringHolder* const old = text;
  8513. const int len = old->allocatedNumChars;
  8514. InternalRefCountedStringHolder* const newTextHolder
  8515. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8516. + len * sizeof (tchar));
  8517. newTextHolder->refCount = 1;
  8518. newTextHolder->allocatedNumChars = len;
  8519. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  8520. text = newTextHolder;
  8521. if (atomicDecrementAndReturn (old->refCount) == 0)
  8522. juce_free (old);
  8523. }
  8524. }
  8525. const String String::empty;
  8526. String::String() throw()
  8527. : text (&emptyString)
  8528. {
  8529. }
  8530. String::String (const String& other) throw()
  8531. : text (other.text)
  8532. {
  8533. atomicIncrement (text->refCount);
  8534. }
  8535. String::String (const int numChars,
  8536. const int /*dummyVariable*/) throw()
  8537. {
  8538. createInternal (numChars);
  8539. }
  8540. String::String (const char* const t) throw()
  8541. {
  8542. if (t != 0 && *t != 0)
  8543. {
  8544. const int len = CharacterFunctions::length (t);
  8545. createInternal (len);
  8546. #if JUCE_STRINGS_ARE_UNICODE
  8547. CharacterFunctions::copy (text->text, t, len + 1);
  8548. #else
  8549. memcpy (text->text, t, len + 1);
  8550. #endif
  8551. }
  8552. else
  8553. {
  8554. text = &emptyString;
  8555. emptyString.refCount = safeEmptyStringRefCount;
  8556. }
  8557. }
  8558. String::String (const juce_wchar* const t) throw()
  8559. {
  8560. if (t != 0 && *t != 0)
  8561. {
  8562. #if JUCE_STRINGS_ARE_UNICODE
  8563. const int len = CharacterFunctions::length (t);
  8564. createInternal (len);
  8565. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  8566. #else
  8567. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  8568. createInternal (len);
  8569. CharacterFunctions::copy (text->text, t, len + 1);
  8570. #endif
  8571. }
  8572. else
  8573. {
  8574. text = &emptyString;
  8575. emptyString.refCount = safeEmptyStringRefCount;
  8576. }
  8577. }
  8578. String::String (const char* const t,
  8579. const int maxChars) throw()
  8580. {
  8581. int i;
  8582. for (i = 0; i < maxChars; ++i)
  8583. if (t[i] == 0)
  8584. break;
  8585. if (i > 0)
  8586. {
  8587. createInternal (i);
  8588. #if JUCE_STRINGS_ARE_UNICODE
  8589. CharacterFunctions::copy (text->text, t, i);
  8590. #else
  8591. memcpy (text->text, t, i);
  8592. #endif
  8593. text->text [i] = 0;
  8594. }
  8595. else
  8596. {
  8597. text = &emptyString;
  8598. emptyString.refCount = safeEmptyStringRefCount;
  8599. }
  8600. }
  8601. String::String (const juce_wchar* const t,
  8602. const int maxChars) throw()
  8603. {
  8604. int i;
  8605. for (i = 0; i < maxChars; ++i)
  8606. if (t[i] == 0)
  8607. break;
  8608. if (i > 0)
  8609. {
  8610. createInternal (i);
  8611. #if JUCE_STRINGS_ARE_UNICODE
  8612. memcpy (text->text, t, i * sizeof (tchar));
  8613. #else
  8614. CharacterFunctions::copy (text->text, t, i);
  8615. #endif
  8616. text->text [i] = 0;
  8617. }
  8618. else
  8619. {
  8620. text = &emptyString;
  8621. emptyString.refCount = safeEmptyStringRefCount;
  8622. }
  8623. }
  8624. const String String::charToString (const tchar character) throw()
  8625. {
  8626. tchar temp[2];
  8627. temp[0] = character;
  8628. temp[1] = 0;
  8629. return String (temp);
  8630. }
  8631. // pass in a pointer to the END of a buffer..
  8632. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  8633. {
  8634. *--t = 0;
  8635. int64 v = (n >= 0) ? n : -n;
  8636. do
  8637. {
  8638. *--t = (tchar) (T('0') + (int) (v % 10));
  8639. v /= 10;
  8640. } while (v > 0);
  8641. if (n < 0)
  8642. *--t = T('-');
  8643. return t;
  8644. }
  8645. static tchar* intToCharString (tchar* t, const int n) throw()
  8646. {
  8647. if (n == (int) 0x80000000) // (would cause an overflow)
  8648. return int64ToCharString (t, n);
  8649. *--t = 0;
  8650. int v = abs (n);
  8651. do
  8652. {
  8653. *--t = (tchar) (T('0') + (v % 10));
  8654. v /= 10;
  8655. } while (v > 0);
  8656. if (n < 0)
  8657. *--t = T('-');
  8658. return t;
  8659. }
  8660. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  8661. {
  8662. *--t = 0;
  8663. do
  8664. {
  8665. *--t = (tchar) (T('0') + (v % 10));
  8666. v /= 10;
  8667. } while (v > 0);
  8668. return t;
  8669. }
  8670. String::String (const int number) throw()
  8671. {
  8672. tchar buffer [16];
  8673. tchar* const end = buffer + 16;
  8674. createInternal (intToCharString (end, number), end);
  8675. }
  8676. String::String (const unsigned int number) throw()
  8677. {
  8678. tchar buffer [16];
  8679. tchar* const end = buffer + 16;
  8680. createInternal (uintToCharString (end, number), end);
  8681. }
  8682. String::String (const short number) throw()
  8683. {
  8684. tchar buffer [16];
  8685. tchar* const end = buffer + 16;
  8686. createInternal (intToCharString (end, (int) number), end);
  8687. }
  8688. String::String (const unsigned short number) throw()
  8689. {
  8690. tchar buffer [16];
  8691. tchar* const end = buffer + 16;
  8692. createInternal (uintToCharString (end, (unsigned int) number), end);
  8693. }
  8694. String::String (const int64 number) throw()
  8695. {
  8696. tchar buffer [32];
  8697. tchar* const end = buffer + 32;
  8698. createInternal (int64ToCharString (end, number), end);
  8699. }
  8700. String::String (const uint64 number) throw()
  8701. {
  8702. tchar buffer [32];
  8703. tchar* const end = buffer + 32;
  8704. tchar* t = end;
  8705. *--t = 0;
  8706. int64 v = number;
  8707. do
  8708. {
  8709. *--t = (tchar) (T('0') + (int) (v % 10));
  8710. v /= 10;
  8711. } while (v > 0);
  8712. createInternal (t, end);
  8713. }
  8714. // a double-to-string routine that actually uses the number of dec. places you asked for
  8715. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  8716. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  8717. {
  8718. const int bufSize = 80;
  8719. tchar buffer [bufSize];
  8720. int len;
  8721. tchar* t;
  8722. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8723. {
  8724. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8725. t = buffer + bufSize;
  8726. *--t = (tchar) 0;
  8727. while (numDecPlaces >= 0 || v > 0)
  8728. {
  8729. if (numDecPlaces == 0)
  8730. *--t = decimalPoint;
  8731. *--t = (tchar) (T('0') + (v % 10));
  8732. v /= 10;
  8733. --numDecPlaces;
  8734. }
  8735. if (n < 0)
  8736. *--t = T('-');
  8737. len = (int) ((buffer + bufSize) - t);
  8738. }
  8739. else
  8740. {
  8741. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  8742. t = buffer;
  8743. }
  8744. if (len > 1)
  8745. {
  8746. jassert (len < numElementsInArray (buffer));
  8747. createInternal (len - 1);
  8748. memcpy (text->text, t, len * sizeof (tchar));
  8749. }
  8750. else
  8751. {
  8752. jassert (*t == 0);
  8753. text = &emptyString;
  8754. emptyString.refCount = safeEmptyStringRefCount;
  8755. }
  8756. }
  8757. String::String (const float number,
  8758. const int numberOfDecimalPlaces) throw()
  8759. {
  8760. doubleToStringWithDecPlaces ((double) number,
  8761. numberOfDecimalPlaces);
  8762. }
  8763. String::String (const double number,
  8764. const int numberOfDecimalPlaces) throw()
  8765. {
  8766. doubleToStringWithDecPlaces (number,
  8767. numberOfDecimalPlaces);
  8768. }
  8769. String::~String() throw()
  8770. {
  8771. emptyString.refCount = safeEmptyStringRefCount;
  8772. if (atomicDecrementAndReturn (text->refCount) == 0)
  8773. juce_free (text);
  8774. }
  8775. void String::preallocateStorage (const int numChars) throw()
  8776. {
  8777. if (numChars > text->allocatedNumChars)
  8778. {
  8779. dupeInternalIfMultiplyReferenced();
  8780. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8781. + numChars * sizeof (tchar));
  8782. text->allocatedNumChars = numChars;
  8783. }
  8784. }
  8785. #if JUCE_STRINGS_ARE_UNICODE
  8786. String::operator const char*() const throw()
  8787. {
  8788. if (isEmpty())
  8789. {
  8790. return (const char*) emptyCharString;
  8791. }
  8792. else
  8793. {
  8794. String* const mutableThis = const_cast <String*> (this);
  8795. mutableThis->dupeInternalIfMultiplyReferenced();
  8796. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  8797. mutableThis->text = (InternalRefCountedStringHolder*)
  8798. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8799. + (len * sizeof (juce_wchar) + len));
  8800. char* otherCopy = (char*) (text->text + len);
  8801. --len;
  8802. CharacterFunctions::copy (otherCopy, text->text, len);
  8803. otherCopy [len] = 0;
  8804. return otherCopy;
  8805. }
  8806. }
  8807. #else
  8808. String::operator const juce_wchar*() const throw()
  8809. {
  8810. if (isEmpty())
  8811. {
  8812. return (const juce_wchar*) emptyCharString;
  8813. }
  8814. else
  8815. {
  8816. String* const mutableThis = const_cast <String*> (this);
  8817. mutableThis->dupeInternalIfMultiplyReferenced();
  8818. int len = CharacterFunctions::length (text->text) + 1;
  8819. mutableThis->text = (InternalRefCountedStringHolder*)
  8820. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8821. + (len * sizeof (juce_wchar) + len));
  8822. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  8823. --len;
  8824. CharacterFunctions::copy (otherCopy, text->text, len);
  8825. otherCopy [len] = 0;
  8826. return otherCopy;
  8827. }
  8828. }
  8829. #endif
  8830. void String::copyToBuffer (char* const destBuffer,
  8831. const int bufferSizeBytes) const throw()
  8832. {
  8833. #if JUCE_STRINGS_ARE_UNICODE
  8834. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  8835. CharacterFunctions::copy (destBuffer, text->text, len);
  8836. #else
  8837. const int len = jmin (bufferSizeBytes, length());
  8838. memcpy (destBuffer, text->text, len * sizeof (tchar));
  8839. #endif
  8840. destBuffer [len] = 0;
  8841. }
  8842. void String::copyToBuffer (juce_wchar* const destBuffer,
  8843. const int maxCharsToCopy) const throw()
  8844. {
  8845. const int len = jmin (maxCharsToCopy, length());
  8846. #if JUCE_STRINGS_ARE_UNICODE
  8847. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  8848. #else
  8849. CharacterFunctions::copy (destBuffer, text->text, len);
  8850. #endif
  8851. destBuffer [len] = 0;
  8852. }
  8853. int String::length() const throw()
  8854. {
  8855. return CharacterFunctions::length (text->text);
  8856. }
  8857. int String::hashCode() const throw()
  8858. {
  8859. const tchar* t = text->text;
  8860. int result = 0;
  8861. while (*t != (tchar) 0)
  8862. result = 31 * result + *t++;
  8863. return result;
  8864. }
  8865. int64 String::hashCode64() const throw()
  8866. {
  8867. const tchar* t = text->text;
  8868. int64 result = 0;
  8869. while (*t != (tchar) 0)
  8870. result = 101 * result + *t++;
  8871. return result;
  8872. }
  8873. const String& String::operator= (const tchar* const otherText) throw()
  8874. {
  8875. if (otherText != 0 && *otherText != 0)
  8876. {
  8877. const int otherLen = CharacterFunctions::length (otherText);
  8878. if (otherLen > 0)
  8879. {
  8880. // avoid resizing the memory block if the string is
  8881. // shrinking..
  8882. if (text->refCount > 1
  8883. || otherLen > text->allocatedNumChars
  8884. || otherLen <= (text->allocatedNumChars >> 1))
  8885. {
  8886. deleteInternal();
  8887. createInternal (otherLen);
  8888. }
  8889. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  8890. return *this;
  8891. }
  8892. }
  8893. deleteInternal();
  8894. text = &emptyString;
  8895. emptyString.refCount = safeEmptyStringRefCount;
  8896. return *this;
  8897. }
  8898. const String& String::operator= (const String& other) throw()
  8899. {
  8900. if (this != &other)
  8901. {
  8902. atomicIncrement (other.text->refCount);
  8903. if (atomicDecrementAndReturn (text->refCount) == 0)
  8904. juce_free (text);
  8905. text = other.text;
  8906. }
  8907. return *this;
  8908. }
  8909. bool String::operator== (const String& other) const throw()
  8910. {
  8911. return text == other.text
  8912. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  8913. }
  8914. bool String::operator== (const tchar* const t) const throw()
  8915. {
  8916. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  8917. : isEmpty();
  8918. }
  8919. bool String::equalsIgnoreCase (const tchar* t) const throw()
  8920. {
  8921. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  8922. : isEmpty();
  8923. }
  8924. bool String::equalsIgnoreCase (const String& other) const throw()
  8925. {
  8926. return text == other.text
  8927. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  8928. }
  8929. bool String::operator!= (const String& other) const throw()
  8930. {
  8931. return text != other.text
  8932. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  8933. }
  8934. bool String::operator!= (const tchar* const t) const throw()
  8935. {
  8936. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  8937. : isNotEmpty();
  8938. }
  8939. bool String::operator> (const String& other) const throw()
  8940. {
  8941. return compare (other) > 0;
  8942. }
  8943. bool String::operator< (const tchar* const other) const throw()
  8944. {
  8945. return compare (other) < 0;
  8946. }
  8947. bool String::operator>= (const String& other) const throw()
  8948. {
  8949. return compare (other) >= 0;
  8950. }
  8951. bool String::operator<= (const tchar* const other) const throw()
  8952. {
  8953. return compare (other) <= 0;
  8954. }
  8955. int String::compare (const tchar* const other) const throw()
  8956. {
  8957. return other != 0 ? CharacterFunctions::compare (text->text, other)
  8958. : isEmpty();
  8959. }
  8960. int String::compareIgnoreCase (const tchar* const other) const throw()
  8961. {
  8962. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  8963. : isEmpty();
  8964. }
  8965. int String::compareLexicographically (const tchar* other) const throw()
  8966. {
  8967. if (other == 0)
  8968. return isEmpty();
  8969. const tchar* s1 = text->text;
  8970. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8971. ++s1;
  8972. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  8973. ++other;
  8974. return CharacterFunctions::compareIgnoreCase (s1, other);
  8975. }
  8976. const String String::operator+ (const String& other) const throw()
  8977. {
  8978. if (*(other.text->text) == 0)
  8979. return *this;
  8980. if (isEmpty())
  8981. return other;
  8982. const int len = CharacterFunctions::length (text->text);
  8983. const int otherLen = CharacterFunctions::length (other.text->text);
  8984. String result (len + otherLen, (int) 0);
  8985. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8986. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  8987. result.text->text [len + otherLen] = 0;
  8988. return result;
  8989. }
  8990. const String String::operator+ (const tchar* const textToAppend) const throw()
  8991. {
  8992. if (textToAppend == 0 || *textToAppend == 0)
  8993. return *this;
  8994. const int len = CharacterFunctions::length (text->text);
  8995. const int otherLen = CharacterFunctions::length (textToAppend);
  8996. String result (len + otherLen, (int) 0);
  8997. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8998. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  8999. result.text->text [len + otherLen] = 0;
  9000. return result;
  9001. }
  9002. const String String::operator+ (const tchar characterToAppend) const throw()
  9003. {
  9004. if (characterToAppend == 0)
  9005. return *this;
  9006. const int len = CharacterFunctions::length (text->text);
  9007. String result ((int) (len + 1), (int) 0);
  9008. memcpy (result.text->text, text->text, len * sizeof (tchar));
  9009. result.text->text[len] = characterToAppend;
  9010. result.text->text[len + 1] = 0;
  9011. return result;
  9012. }
  9013. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  9014. const String& string2) throw()
  9015. {
  9016. String s (string1);
  9017. s += string2;
  9018. return s;
  9019. }
  9020. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  9021. const String& string2) throw()
  9022. {
  9023. String s (string1);
  9024. s += string2;
  9025. return s;
  9026. }
  9027. const String& String::operator+= (const tchar* const t) throw()
  9028. {
  9029. if (t != 0)
  9030. appendInternal (t, CharacterFunctions::length (t));
  9031. return *this;
  9032. }
  9033. const String& String::operator+= (const String& other) throw()
  9034. {
  9035. if (isEmpty())
  9036. operator= (other);
  9037. else
  9038. appendInternal (other.text->text,
  9039. CharacterFunctions::length (other.text->text));
  9040. return *this;
  9041. }
  9042. const String& String::operator+= (const char ch) throw()
  9043. {
  9044. char asString[2];
  9045. asString[0] = ch;
  9046. asString[1] = 0;
  9047. #if JUCE_STRINGS_ARE_UNICODE
  9048. operator+= (String (asString));
  9049. #else
  9050. appendInternal (asString, 1);
  9051. #endif
  9052. return *this;
  9053. }
  9054. const String& String::operator+= (const juce_wchar ch) throw()
  9055. {
  9056. juce_wchar asString[2];
  9057. asString[0] = ch;
  9058. asString[1] = 0;
  9059. #if JUCE_STRINGS_ARE_UNICODE
  9060. appendInternal (asString, 1);
  9061. #else
  9062. operator+= (String (asString));
  9063. #endif
  9064. return *this;
  9065. }
  9066. void String::append (const tchar* const other,
  9067. const int howMany) throw()
  9068. {
  9069. if (howMany > 0)
  9070. {
  9071. int i;
  9072. for (i = 0; i < howMany; ++i)
  9073. if (other[i] == 0)
  9074. break;
  9075. appendInternal (other, i);
  9076. }
  9077. }
  9078. String& String::operator<< (const int number) throw()
  9079. {
  9080. tchar buffer [64];
  9081. tchar* const end = buffer + 64;
  9082. const tchar* const t = intToCharString (end, number);
  9083. appendInternal (t, (int) (end - t) - 1);
  9084. return *this;
  9085. }
  9086. String& String::operator<< (const unsigned int number) throw()
  9087. {
  9088. tchar buffer [64];
  9089. tchar* const end = buffer + 64;
  9090. const tchar* const t = uintToCharString (end, number);
  9091. appendInternal (t, (int) (end - t) - 1);
  9092. return *this;
  9093. }
  9094. String& String::operator<< (const short number) throw()
  9095. {
  9096. tchar buffer [64];
  9097. tchar* const end = buffer + 64;
  9098. const tchar* const t = intToCharString (end, (int) number);
  9099. appendInternal (t, (int) (end - t) - 1);
  9100. return *this;
  9101. }
  9102. String& String::operator<< (const double number) throw()
  9103. {
  9104. operator+= (String (number));
  9105. return *this;
  9106. }
  9107. String& String::operator<< (const float number) throw()
  9108. {
  9109. operator+= (String (number));
  9110. return *this;
  9111. }
  9112. String& String::operator<< (const char character) throw()
  9113. {
  9114. operator+= (character);
  9115. return *this;
  9116. }
  9117. String& String::operator<< (const juce_wchar character) throw()
  9118. {
  9119. operator+= (character);
  9120. return *this;
  9121. }
  9122. String& String::operator<< (const char* const t) throw()
  9123. {
  9124. #if JUCE_STRINGS_ARE_UNICODE
  9125. operator+= (String (t));
  9126. #else
  9127. operator+= (t);
  9128. #endif
  9129. return *this;
  9130. }
  9131. String& String::operator<< (const juce_wchar* const t) throw()
  9132. {
  9133. #if JUCE_STRINGS_ARE_UNICODE
  9134. operator+= (t);
  9135. #else
  9136. operator+= (String (t));
  9137. #endif
  9138. return *this;
  9139. }
  9140. String& String::operator<< (const String& t) throw()
  9141. {
  9142. operator+= (t);
  9143. return *this;
  9144. }
  9145. int String::indexOfChar (const tchar character) const throw()
  9146. {
  9147. const tchar* t = text->text;
  9148. for (;;)
  9149. {
  9150. if (*t == character)
  9151. return (int) (t - text->text);
  9152. if (*t++ == 0)
  9153. return -1;
  9154. }
  9155. }
  9156. int String::lastIndexOfChar (const tchar character) const throw()
  9157. {
  9158. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9159. if (text->text[i] == character)
  9160. return i;
  9161. return -1;
  9162. }
  9163. int String::indexOf (const tchar* const t) const throw()
  9164. {
  9165. const tchar* const r = CharacterFunctions::find (text->text, t);
  9166. return (r == 0) ? -1
  9167. : (int) (r - text->text);
  9168. }
  9169. int String::indexOfChar (const int startIndex,
  9170. const tchar character) const throw()
  9171. {
  9172. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  9173. return -1;
  9174. const tchar* t = text->text + jmax (0, startIndex);
  9175. for (;;)
  9176. {
  9177. if (*t == character)
  9178. return (int) (t - text->text);
  9179. if (*t++ == 0)
  9180. return -1;
  9181. }
  9182. }
  9183. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  9184. const int startIndex,
  9185. const bool ignoreCase) const throw()
  9186. {
  9187. if (charactersToLookFor == 0
  9188. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  9189. return -1;
  9190. const tchar* t = text->text + jmax (0, startIndex);
  9191. while (*t != 0)
  9192. {
  9193. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  9194. return (int) (t - text->text);
  9195. ++t;
  9196. }
  9197. return -1;
  9198. }
  9199. int String::indexOf (const int startIndex,
  9200. const tchar* const other) const throw()
  9201. {
  9202. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  9203. return -1;
  9204. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  9205. other);
  9206. return (found == 0) ? -1
  9207. : (int) (found - text->text);
  9208. }
  9209. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  9210. {
  9211. if (other != 0 && *other != 0)
  9212. {
  9213. const int len = CharacterFunctions::length (other);
  9214. const int end = CharacterFunctions::length (text->text) - len;
  9215. for (int i = 0; i <= end; ++i)
  9216. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9217. return i;
  9218. }
  9219. return -1;
  9220. }
  9221. int String::indexOfIgnoreCase (const int startIndex,
  9222. const tchar* const other) const throw()
  9223. {
  9224. if (other != 0 && *other != 0)
  9225. {
  9226. const int len = CharacterFunctions::length (other);
  9227. const int end = length() - len;
  9228. for (int i = jmax (0, startIndex); i <= end; ++i)
  9229. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9230. return i;
  9231. }
  9232. return -1;
  9233. }
  9234. int String::lastIndexOf (const tchar* const other) const throw()
  9235. {
  9236. if (other != 0 && *other != 0)
  9237. {
  9238. const int len = CharacterFunctions::length (other);
  9239. int i = length() - len;
  9240. if (i >= 0)
  9241. {
  9242. const tchar* n = text->text + i;
  9243. while (i >= 0)
  9244. {
  9245. if (CharacterFunctions::compare (n--, other, len) == 0)
  9246. return i;
  9247. --i;
  9248. }
  9249. }
  9250. }
  9251. return -1;
  9252. }
  9253. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  9254. {
  9255. if (other != 0 && *other != 0)
  9256. {
  9257. const int len = CharacterFunctions::length (other);
  9258. int i = length() - len;
  9259. if (i >= 0)
  9260. {
  9261. const tchar* n = text->text + i;
  9262. while (i >= 0)
  9263. {
  9264. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  9265. return i;
  9266. --i;
  9267. }
  9268. }
  9269. }
  9270. return -1;
  9271. }
  9272. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  9273. const bool ignoreCase) const throw()
  9274. {
  9275. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9276. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  9277. return i;
  9278. return -1;
  9279. }
  9280. bool String::contains (const tchar* const other) const throw()
  9281. {
  9282. return indexOf (other) >= 0;
  9283. }
  9284. bool String::containsChar (const tchar character) const throw()
  9285. {
  9286. return indexOfChar (character) >= 0;
  9287. }
  9288. bool String::containsIgnoreCase (const tchar* const t) const throw()
  9289. {
  9290. return indexOfIgnoreCase (t) >= 0;
  9291. }
  9292. int String::indexOfWholeWord (const tchar* const word) const throw()
  9293. {
  9294. if (word != 0 && *word != 0)
  9295. {
  9296. const int wordLen = CharacterFunctions::length (word);
  9297. const int end = length() - wordLen;
  9298. const tchar* t = text->text;
  9299. for (int i = 0; i <= end; ++i)
  9300. {
  9301. if (CharacterFunctions::compare (t, word, wordLen) == 0
  9302. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9303. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9304. {
  9305. return i;
  9306. }
  9307. ++t;
  9308. }
  9309. }
  9310. return -1;
  9311. }
  9312. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  9313. {
  9314. if (word != 0 && *word != 0)
  9315. {
  9316. const int wordLen = CharacterFunctions::length (word);
  9317. const int end = length() - wordLen;
  9318. const tchar* t = text->text;
  9319. for (int i = 0; i <= end; ++i)
  9320. {
  9321. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  9322. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9323. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9324. {
  9325. return i;
  9326. }
  9327. ++t;
  9328. }
  9329. }
  9330. return -1;
  9331. }
  9332. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  9333. {
  9334. return indexOfWholeWord (wordToLookFor) >= 0;
  9335. }
  9336. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  9337. {
  9338. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9339. }
  9340. static int indexOfMatch (const tchar* const wildcard,
  9341. const tchar* const test,
  9342. const bool ignoreCase) throw()
  9343. {
  9344. int start = 0;
  9345. while (test [start] != 0)
  9346. {
  9347. int i = 0;
  9348. for (;;)
  9349. {
  9350. const tchar wc = wildcard [i];
  9351. const tchar c = test [i + start];
  9352. if (wc == c
  9353. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9354. || (wc == T('?') && c != 0))
  9355. {
  9356. if (wc == 0)
  9357. return start;
  9358. ++i;
  9359. }
  9360. else
  9361. {
  9362. if (wc == T('*') && (wildcard [i + 1] == 0
  9363. || indexOfMatch (wildcard + i + 1,
  9364. test + start + i,
  9365. ignoreCase) >= 0))
  9366. {
  9367. return start;
  9368. }
  9369. break;
  9370. }
  9371. }
  9372. ++start;
  9373. }
  9374. return -1;
  9375. }
  9376. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  9377. {
  9378. int i = 0;
  9379. for (;;)
  9380. {
  9381. const tchar wc = wildcard [i];
  9382. const tchar c = text->text [i];
  9383. if (wc == c
  9384. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9385. || (wc == T('?') && c != 0))
  9386. {
  9387. if (wc == 0)
  9388. return true;
  9389. ++i;
  9390. }
  9391. else
  9392. {
  9393. return wc == T('*') && (wildcard [i + 1] == 0
  9394. || indexOfMatch (wildcard + i + 1,
  9395. text->text + i,
  9396. ignoreCase) >= 0);
  9397. }
  9398. }
  9399. }
  9400. void String::printf (const tchar* const pf, ...) throw()
  9401. {
  9402. va_list list;
  9403. va_start (list, pf);
  9404. vprintf (pf, list);
  9405. }
  9406. const String String::formatted (const tchar* const pf, ...) throw()
  9407. {
  9408. va_list list;
  9409. va_start (list, pf);
  9410. String result;
  9411. result.vprintf (pf, list);
  9412. return result;
  9413. }
  9414. void String::vprintf (const tchar* const pf, va_list& args) throw()
  9415. {
  9416. tchar stackBuf [256];
  9417. unsigned int bufSize = 256;
  9418. tchar* buf = stackBuf;
  9419. deleteInternal();
  9420. do
  9421. {
  9422. #if JUCE_LINUX && JUCE_64BIT
  9423. va_list tempArgs;
  9424. va_copy (tempArgs, args);
  9425. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  9426. va_end (tempArgs);
  9427. #else
  9428. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  9429. #endif
  9430. if (num > 0)
  9431. {
  9432. createInternal (num);
  9433. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  9434. break;
  9435. }
  9436. else if (num == 0)
  9437. {
  9438. text = &emptyString;
  9439. emptyString.refCount = safeEmptyStringRefCount;
  9440. break;
  9441. }
  9442. if (buf != stackBuf)
  9443. juce_free (buf);
  9444. bufSize += 256;
  9445. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  9446. }
  9447. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  9448. // returns -1 because of an error rather than because it needs more space.
  9449. if (buf != stackBuf)
  9450. juce_free (buf);
  9451. }
  9452. const String String::repeatedString (const tchar* const stringToRepeat,
  9453. int numberOfTimesToRepeat) throw()
  9454. {
  9455. const int len = CharacterFunctions::length (stringToRepeat);
  9456. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  9457. tchar* n = result.text->text;
  9458. n[0] = 0;
  9459. while (--numberOfTimesToRepeat >= 0)
  9460. {
  9461. CharacterFunctions::append (n, stringToRepeat);
  9462. n += len;
  9463. }
  9464. return result;
  9465. }
  9466. const String String::replaceSection (int index,
  9467. int numCharsToReplace,
  9468. const tchar* const stringToInsert) const throw()
  9469. {
  9470. if (index < 0)
  9471. {
  9472. // a negative index to replace from?
  9473. jassertfalse
  9474. index = 0;
  9475. }
  9476. if (numCharsToReplace < 0)
  9477. {
  9478. // replacing a negative number of characters?
  9479. numCharsToReplace = 0;
  9480. jassertfalse;
  9481. }
  9482. const int len = length();
  9483. if (index + numCharsToReplace > len)
  9484. {
  9485. if (index > len)
  9486. {
  9487. // replacing beyond the end of the string?
  9488. index = len;
  9489. jassertfalse
  9490. }
  9491. numCharsToReplace = len - index;
  9492. }
  9493. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  9494. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9495. if (newTotalLen <= 0)
  9496. return String::empty;
  9497. String result (newTotalLen, (int) 0);
  9498. memcpy (result.text->text,
  9499. text->text,
  9500. index * sizeof (tchar));
  9501. if (newStringLen > 0)
  9502. memcpy (result.text->text + index,
  9503. stringToInsert,
  9504. newStringLen * sizeof (tchar));
  9505. const int endStringLen = newTotalLen - (index + newStringLen);
  9506. if (endStringLen > 0)
  9507. memcpy (result.text->text + (index + newStringLen),
  9508. text->text + (index + numCharsToReplace),
  9509. endStringLen * sizeof (tchar));
  9510. result.text->text [newTotalLen] = 0;
  9511. return result;
  9512. }
  9513. const String String::replace (const tchar* const stringToReplace,
  9514. const tchar* const stringToInsert,
  9515. const bool ignoreCase) const throw()
  9516. {
  9517. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  9518. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  9519. int i = 0;
  9520. String result (*this);
  9521. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9522. : result.indexOf (i, stringToReplace))) >= 0)
  9523. {
  9524. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9525. i += stringToInsertLen;
  9526. }
  9527. return result;
  9528. }
  9529. const String String::replaceCharacter (const tchar charToReplace,
  9530. const tchar charToInsert) const throw()
  9531. {
  9532. const int index = indexOfChar (charToReplace);
  9533. if (index < 0)
  9534. return *this;
  9535. String result (*this);
  9536. result.dupeInternalIfMultiplyReferenced();
  9537. tchar* t = result.text->text + index;
  9538. while (*t != 0)
  9539. {
  9540. if (*t == charToReplace)
  9541. *t = charToInsert;
  9542. ++t;
  9543. }
  9544. return result;
  9545. }
  9546. const String String::replaceCharacters (const String& charactersToReplace,
  9547. const tchar* const charactersToInsertInstead) const throw()
  9548. {
  9549. String result (*this);
  9550. result.dupeInternalIfMultiplyReferenced();
  9551. tchar* t = result.text->text;
  9552. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  9553. // the two strings passed in are supposed to be the same length!
  9554. jassert (len2 == charactersToReplace.length());
  9555. while (*t != 0)
  9556. {
  9557. const int index = charactersToReplace.indexOfChar (*t);
  9558. if (((unsigned int) index) < (unsigned int) len2)
  9559. *t = charactersToInsertInstead [index];
  9560. ++t;
  9561. }
  9562. return result;
  9563. }
  9564. bool String::startsWith (const tchar* const other) const throw()
  9565. {
  9566. return other != 0
  9567. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  9568. }
  9569. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  9570. {
  9571. return other != 0
  9572. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  9573. }
  9574. bool String::startsWithChar (const tchar character) const throw()
  9575. {
  9576. jassert (character != 0); // strings can't contain a null character!
  9577. return text->text[0] == character;
  9578. }
  9579. bool String::endsWithChar (const tchar character) const throw()
  9580. {
  9581. jassert (character != 0); // strings can't contain a null character!
  9582. return text->text[0] != 0
  9583. && text->text [length() - 1] == character;
  9584. }
  9585. bool String::endsWith (const tchar* const other) const throw()
  9586. {
  9587. if (other == 0)
  9588. return false;
  9589. const int thisLen = length();
  9590. const int otherLen = CharacterFunctions::length (other);
  9591. return thisLen >= otherLen
  9592. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  9593. }
  9594. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  9595. {
  9596. if (other == 0)
  9597. return false;
  9598. const int thisLen = length();
  9599. const int otherLen = CharacterFunctions::length (other);
  9600. return thisLen >= otherLen
  9601. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  9602. }
  9603. const String String::toUpperCase() const throw()
  9604. {
  9605. String result (*this);
  9606. result.dupeInternalIfMultiplyReferenced();
  9607. CharacterFunctions::toUpperCase (result.text->text);
  9608. return result;
  9609. }
  9610. const String String::toLowerCase() const throw()
  9611. {
  9612. String result (*this);
  9613. result.dupeInternalIfMultiplyReferenced();
  9614. CharacterFunctions::toLowerCase (result.text->text);
  9615. return result;
  9616. }
  9617. tchar& String::operator[] (const int index) throw()
  9618. {
  9619. jassert (((unsigned int) index) <= (unsigned int) length());
  9620. dupeInternalIfMultiplyReferenced();
  9621. return text->text [index];
  9622. }
  9623. tchar String::getLastCharacter() const throw()
  9624. {
  9625. return (isEmpty()) ? ((tchar) 0)
  9626. : text->text [CharacterFunctions::length (text->text) - 1];
  9627. }
  9628. const String String::substring (int start, int end) const throw()
  9629. {
  9630. if (start < 0)
  9631. start = 0;
  9632. else if (end <= start)
  9633. return empty;
  9634. int len = 0;
  9635. const tchar* const t = text->text;
  9636. while (len <= end && t [len] != 0)
  9637. ++len;
  9638. if (end >= len)
  9639. {
  9640. if (start == 0)
  9641. return *this;
  9642. end = len;
  9643. }
  9644. return String (text->text + start,
  9645. end - start);
  9646. }
  9647. const String String::substring (const int start) const throw()
  9648. {
  9649. if (start <= 0)
  9650. return *this;
  9651. const int len = CharacterFunctions::length (text->text);
  9652. if (start >= len)
  9653. return empty;
  9654. else
  9655. return String (text->text + start,
  9656. len - start);
  9657. }
  9658. const String String::dropLastCharacters (const int numberToDrop) const throw()
  9659. {
  9660. return String (text->text,
  9661. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  9662. }
  9663. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  9664. const bool includeSubString,
  9665. const bool ignoreCase) const throw()
  9666. {
  9667. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9668. : indexOf (sub);
  9669. if (i < 0)
  9670. return empty;
  9671. else
  9672. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9673. }
  9674. const String String::fromLastOccurrenceOf (const tchar* const sub,
  9675. const bool includeSubString,
  9676. const bool ignoreCase) const throw()
  9677. {
  9678. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9679. : lastIndexOf (sub);
  9680. if (i < 0)
  9681. return *this;
  9682. else
  9683. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9684. }
  9685. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  9686. const bool includeSubString,
  9687. const bool ignoreCase) const throw()
  9688. {
  9689. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9690. : indexOf (sub);
  9691. if (i < 0)
  9692. return *this;
  9693. else
  9694. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9695. }
  9696. const String String::upToLastOccurrenceOf (const tchar* const sub,
  9697. const bool includeSubString,
  9698. const bool ignoreCase) const throw()
  9699. {
  9700. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9701. : lastIndexOf (sub);
  9702. if (i < 0)
  9703. return *this;
  9704. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9705. }
  9706. bool String::isQuotedString() const throw()
  9707. {
  9708. const String trimmed (trimStart());
  9709. return trimmed[0] == T('"')
  9710. || trimmed[0] == T('\'');
  9711. }
  9712. const String String::unquoted() const throw()
  9713. {
  9714. String s (*this);
  9715. if (s[0] == T('"') || s[0] == T('\''))
  9716. s = s.substring (1);
  9717. const int lastCharIndex = s.length() - 1;
  9718. if (lastCharIndex >= 0
  9719. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  9720. s [lastCharIndex] = 0;
  9721. return s;
  9722. }
  9723. const String String::quoted (const tchar quoteCharacter) const throw()
  9724. {
  9725. if (isEmpty())
  9726. return charToString (quoteCharacter) + quoteCharacter;
  9727. String t (*this);
  9728. if (! t.startsWithChar (quoteCharacter))
  9729. t = charToString (quoteCharacter) + t;
  9730. if (! t.endsWithChar (quoteCharacter))
  9731. t += quoteCharacter;
  9732. return t;
  9733. }
  9734. const String String::trim() const throw()
  9735. {
  9736. if (isEmpty())
  9737. return empty;
  9738. int start = 0;
  9739. while (CharacterFunctions::isWhitespace (text->text [start]))
  9740. ++start;
  9741. const int len = CharacterFunctions::length (text->text);
  9742. int end = len - 1;
  9743. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  9744. --end;
  9745. ++end;
  9746. if (end <= start)
  9747. return empty;
  9748. else if (start > 0 || end < len)
  9749. return String (text->text + start, end - start);
  9750. else
  9751. return *this;
  9752. }
  9753. const String String::trimStart() const throw()
  9754. {
  9755. if (isEmpty())
  9756. return empty;
  9757. const tchar* t = text->text;
  9758. while (CharacterFunctions::isWhitespace (*t))
  9759. ++t;
  9760. if (t == text->text)
  9761. return *this;
  9762. else
  9763. return String (t);
  9764. }
  9765. const String String::trimEnd() const throw()
  9766. {
  9767. if (isEmpty())
  9768. return empty;
  9769. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  9770. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  9771. --endT;
  9772. return String (text->text, (int) (++endT - text->text));
  9773. }
  9774. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  9775. {
  9776. jassert (charactersToRetain != 0);
  9777. if (isEmpty())
  9778. return empty;
  9779. String result (text->allocatedNumChars, (int) 0);
  9780. tchar* dst = result.text->text;
  9781. const tchar* src = text->text;
  9782. while (*src != 0)
  9783. {
  9784. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  9785. *dst++ = *src;
  9786. ++src;
  9787. }
  9788. *dst = 0;
  9789. return result;
  9790. }
  9791. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  9792. {
  9793. jassert (charactersToRemove != 0);
  9794. if (isEmpty())
  9795. return empty;
  9796. String result (text->allocatedNumChars, (int) 0);
  9797. tchar* dst = result.text->text;
  9798. const tchar* src = text->text;
  9799. while (*src != 0)
  9800. {
  9801. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  9802. *dst++ = *src;
  9803. ++src;
  9804. }
  9805. *dst = 0;
  9806. return result;
  9807. }
  9808. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  9809. {
  9810. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  9811. }
  9812. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  9813. {
  9814. jassert (charactersToStopAt != 0);
  9815. const tchar* const t = text->text;
  9816. int i = 0;
  9817. while (t[i] != 0)
  9818. {
  9819. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  9820. return String (text->text, i);
  9821. ++i;
  9822. }
  9823. return empty;
  9824. }
  9825. bool String::containsOnly (const tchar* const chars) const throw()
  9826. {
  9827. jassert (chars != 0);
  9828. const tchar* t = text->text;
  9829. while (*t != 0)
  9830. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  9831. return false;
  9832. return true;
  9833. }
  9834. bool String::containsAnyOf (const tchar* const chars) const throw()
  9835. {
  9836. jassert (chars != 0);
  9837. const tchar* t = text->text;
  9838. while (*t != 0)
  9839. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  9840. return true;
  9841. return false;
  9842. }
  9843. bool String::containsNonWhitespaceChars() const throw()
  9844. {
  9845. const tchar* t = text->text;
  9846. while (*t != 0)
  9847. if (! CharacterFunctions::isWhitespace (*t++))
  9848. return true;
  9849. return false;
  9850. }
  9851. int String::getIntValue() const throw()
  9852. {
  9853. return CharacterFunctions::getIntValue (text->text);
  9854. }
  9855. int String::getTrailingIntValue() const throw()
  9856. {
  9857. int n = 0;
  9858. int mult = 1;
  9859. const tchar* t = text->text + length();
  9860. while (--t >= text->text)
  9861. {
  9862. const tchar c = *t;
  9863. if (! CharacterFunctions::isDigit (c))
  9864. {
  9865. if (c == T('-'))
  9866. n = -n;
  9867. break;
  9868. }
  9869. n += mult * (c - T('0'));
  9870. mult *= 10;
  9871. }
  9872. return n;
  9873. }
  9874. int64 String::getLargeIntValue() const throw()
  9875. {
  9876. return CharacterFunctions::getInt64Value (text->text);
  9877. }
  9878. float String::getFloatValue() const throw()
  9879. {
  9880. return (float) CharacterFunctions::getDoubleValue (text->text);
  9881. }
  9882. double String::getDoubleValue() const throw()
  9883. {
  9884. return CharacterFunctions::getDoubleValue (text->text);
  9885. }
  9886. static const tchar* const hexDigits = T("0123456789abcdef");
  9887. const String String::toHexString (const int number) throw()
  9888. {
  9889. tchar buffer[32];
  9890. tchar* const end = buffer + 32;
  9891. tchar* t = end;
  9892. *--t = 0;
  9893. unsigned int v = (unsigned int) number;
  9894. do
  9895. {
  9896. *--t = hexDigits [v & 15];
  9897. v >>= 4;
  9898. } while (v != 0);
  9899. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9900. }
  9901. const String String::toHexString (const int64 number) throw()
  9902. {
  9903. tchar buffer[32];
  9904. tchar* const end = buffer + 32;
  9905. tchar* t = end;
  9906. *--t = 0;
  9907. uint64 v = (uint64) number;
  9908. do
  9909. {
  9910. *--t = hexDigits [(int) (v & 15)];
  9911. v >>= 4;
  9912. } while (v != 0);
  9913. return String (t, (int) (((char*) end) - (char*) t));
  9914. }
  9915. const String String::toHexString (const short number) throw()
  9916. {
  9917. return toHexString ((int) (unsigned short) number);
  9918. }
  9919. const String String::toHexString (const unsigned char* data,
  9920. const int size,
  9921. const int groupSize) throw()
  9922. {
  9923. if (size <= 0)
  9924. return empty;
  9925. int numChars = (size * 2) + 2;
  9926. if (groupSize > 0)
  9927. numChars += size / groupSize;
  9928. String s (numChars, (int) 0);
  9929. tchar* d = s.text->text;
  9930. for (int i = 0; i < size; ++i)
  9931. {
  9932. *d++ = hexDigits [(*data) >> 4];
  9933. *d++ = hexDigits [(*data) & 0xf];
  9934. ++data;
  9935. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9936. *d++ = T(' ');
  9937. }
  9938. *d = 0;
  9939. return s;
  9940. }
  9941. int String::getHexValue32() const throw()
  9942. {
  9943. int result = 0;
  9944. const tchar* c = text->text;
  9945. for (;;)
  9946. {
  9947. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9948. if (hexValue >= 0)
  9949. result = (result << 4) | hexValue;
  9950. else if (*c == 0)
  9951. break;
  9952. ++c;
  9953. }
  9954. return result;
  9955. }
  9956. int64 String::getHexValue64() const throw()
  9957. {
  9958. int64 result = 0;
  9959. const tchar* c = text->text;
  9960. for (;;)
  9961. {
  9962. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9963. if (hexValue >= 0)
  9964. result = (result << 4) | hexValue;
  9965. else if (*c == 0)
  9966. break;
  9967. ++c;
  9968. }
  9969. return result;
  9970. }
  9971. const String String::createStringFromData (const void* const data_,
  9972. const int size) throw()
  9973. {
  9974. const char* const data = (const char*) data_;
  9975. if (size <= 0 || data == 0)
  9976. {
  9977. return empty;
  9978. }
  9979. else if (size < 2)
  9980. {
  9981. return charToString (data[0]);
  9982. }
  9983. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9984. || (data[0] == (char)-1 && data[1] == (char)-2))
  9985. {
  9986. // assume it's 16-bit unicode
  9987. const bool bigEndian = (data[0] == (char)-2);
  9988. const int numChars = size / 2 - 1;
  9989. String result;
  9990. result.preallocateStorage (numChars + 2);
  9991. const uint16* const src = (const uint16*) (data + 2);
  9992. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  9993. if (bigEndian)
  9994. {
  9995. for (int i = 0; i < numChars; ++i)
  9996. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  9997. }
  9998. else
  9999. {
  10000. for (int i = 0; i < numChars; ++i)
  10001. dst[i] = (tchar) swapIfBigEndian (src[i]);
  10002. }
  10003. dst [numChars] = 0;
  10004. return result;
  10005. }
  10006. else
  10007. {
  10008. return String::fromUTF8 ((const uint8*) data, size);
  10009. }
  10010. }
  10011. const char* String::toUTF8() const throw()
  10012. {
  10013. if (isEmpty())
  10014. {
  10015. return (const char*) emptyCharString;
  10016. }
  10017. else
  10018. {
  10019. String* const mutableThis = const_cast <String*> (this);
  10020. mutableThis->dupeInternalIfMultiplyReferenced();
  10021. const int currentLen = CharacterFunctions::length (text->text) + 1;
  10022. const int utf8BytesNeeded = copyToUTF8 (0);
  10023. mutableThis->text = (InternalRefCountedStringHolder*)
  10024. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  10025. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  10026. char* const otherCopy = (char*) (text->text + currentLen);
  10027. copyToUTF8 ((uint8*) otherCopy);
  10028. return otherCopy;
  10029. }
  10030. }
  10031. int String::copyToUTF8 (uint8* const buffer, const int maxBufferSizeBytes) const throw()
  10032. {
  10033. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10034. #if JUCE_STRINGS_ARE_UNICODE
  10035. int num = 0, index = 0;
  10036. for (;;)
  10037. {
  10038. const uint32 c = (uint32) text->text [index++];
  10039. if (c >= 0x80)
  10040. {
  10041. int numExtraBytes = 1;
  10042. if (c >= 0x800)
  10043. {
  10044. ++numExtraBytes;
  10045. if (c >= 0x10000)
  10046. {
  10047. ++numExtraBytes;
  10048. if (c >= 0x200000)
  10049. {
  10050. ++numExtraBytes;
  10051. if (c >= 0x4000000)
  10052. ++numExtraBytes;
  10053. }
  10054. }
  10055. }
  10056. if (buffer != 0)
  10057. {
  10058. if (num + numExtraBytes >= maxBufferSizeBytes)
  10059. {
  10060. buffer [num++] = 0;
  10061. break;
  10062. }
  10063. else
  10064. {
  10065. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10066. while (--numExtraBytes >= 0)
  10067. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10068. }
  10069. }
  10070. else
  10071. {
  10072. num += numExtraBytes + 1;
  10073. }
  10074. }
  10075. else
  10076. {
  10077. if (buffer != 0)
  10078. {
  10079. if (num + 1 >= maxBufferSizeBytes)
  10080. {
  10081. buffer [num++] = 0;
  10082. break;
  10083. }
  10084. buffer [num] = (uint8) c;
  10085. }
  10086. ++num;
  10087. }
  10088. if (c == 0)
  10089. break;
  10090. }
  10091. return num;
  10092. #else
  10093. const int numBytes = jmin (maxBufferSizeBytes, length() + 1);
  10094. if (buffer != 0)
  10095. copyToBuffer ((char*) buffer, maxBufferSizeBytes);
  10096. return numBytes;
  10097. #endif
  10098. }
  10099. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  10100. {
  10101. if (buffer == 0)
  10102. return empty;
  10103. if (bufferSizeBytes < 0)
  10104. bufferSizeBytes = INT_MAX;
  10105. int numBytes;
  10106. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  10107. if (buffer [numBytes] == 0)
  10108. break;
  10109. String result (numBytes + 1, 0);
  10110. tchar* dest = result.text->text;
  10111. int i = 0;
  10112. while (i < numBytes)
  10113. {
  10114. const uint8 c = buffer [i++];
  10115. if ((c & 0x80) != 0)
  10116. {
  10117. int mask = 0x7f;
  10118. int bit = 0x40;
  10119. int numExtraValues = 0;
  10120. while (bit != 0 && (c & bit) != 0)
  10121. {
  10122. bit >>= 1;
  10123. mask >>= 1;
  10124. ++numExtraValues;
  10125. }
  10126. int n = (c & mask);
  10127. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  10128. {
  10129. const uint8 c = buffer[i];
  10130. if ((c & 0xc0) != 0x80)
  10131. break;
  10132. n <<= 6;
  10133. n |= (c & 0x3f);
  10134. ++i;
  10135. }
  10136. *dest++ = (tchar) n;
  10137. }
  10138. else
  10139. {
  10140. *dest++ = (tchar) c;
  10141. }
  10142. }
  10143. *dest = 0;
  10144. return result;
  10145. }
  10146. END_JUCE_NAMESPACE
  10147. /********* End of inlined file: juce_String.cpp *********/
  10148. /********* Start of inlined file: juce_StringArray.cpp *********/
  10149. BEGIN_JUCE_NAMESPACE
  10150. StringArray::StringArray() throw()
  10151. {
  10152. }
  10153. StringArray::StringArray (const StringArray& other) throw()
  10154. {
  10155. addArray (other);
  10156. }
  10157. StringArray::StringArray (const juce_wchar** const strings,
  10158. const int numberOfStrings) throw()
  10159. {
  10160. for (int i = 0; i < numberOfStrings; ++i)
  10161. add (strings [i]);
  10162. }
  10163. StringArray::StringArray (const char** const strings,
  10164. const int numberOfStrings) throw()
  10165. {
  10166. for (int i = 0; i < numberOfStrings; ++i)
  10167. add (strings [i]);
  10168. }
  10169. StringArray::StringArray (const juce_wchar** const strings) throw()
  10170. {
  10171. int i = 0;
  10172. while (strings[i] != 0)
  10173. add (strings [i++]);
  10174. }
  10175. StringArray::StringArray (const char** const strings) throw()
  10176. {
  10177. int i = 0;
  10178. while (strings[i] != 0)
  10179. add (strings [i++]);
  10180. }
  10181. const StringArray& StringArray::operator= (const StringArray& other) throw()
  10182. {
  10183. if (this != &other)
  10184. {
  10185. clear();
  10186. addArray (other);
  10187. }
  10188. return *this;
  10189. }
  10190. StringArray::~StringArray() throw()
  10191. {
  10192. clear();
  10193. }
  10194. bool StringArray::operator== (const StringArray& other) const throw()
  10195. {
  10196. if (other.size() != size())
  10197. return false;
  10198. for (int i = size(); --i >= 0;)
  10199. {
  10200. if (*(String*) other.strings.getUnchecked(i)
  10201. != *(String*) strings.getUnchecked(i))
  10202. {
  10203. return false;
  10204. }
  10205. }
  10206. return true;
  10207. }
  10208. bool StringArray::operator!= (const StringArray& other) const throw()
  10209. {
  10210. return ! operator== (other);
  10211. }
  10212. void StringArray::clear() throw()
  10213. {
  10214. for (int i = size(); --i >= 0;)
  10215. {
  10216. String* const s = (String*) strings.getUnchecked(i);
  10217. delete s;
  10218. }
  10219. strings.clear();
  10220. }
  10221. const String& StringArray::operator[] (const int index) const throw()
  10222. {
  10223. if (((unsigned int) index) < (unsigned int) strings.size())
  10224. return *(const String*) (strings.getUnchecked (index));
  10225. return String::empty;
  10226. }
  10227. void StringArray::add (const String& newString) throw()
  10228. {
  10229. strings.add (new String (newString));
  10230. }
  10231. void StringArray::insert (const int index,
  10232. const String& newString) throw()
  10233. {
  10234. strings.insert (index, new String (newString));
  10235. }
  10236. void StringArray::addIfNotAlreadyThere (const String& newString,
  10237. const bool ignoreCase) throw()
  10238. {
  10239. if (! contains (newString, ignoreCase))
  10240. add (newString);
  10241. }
  10242. void StringArray::addArray (const StringArray& otherArray,
  10243. int startIndex,
  10244. int numElementsToAdd) throw()
  10245. {
  10246. if (startIndex < 0)
  10247. {
  10248. jassertfalse
  10249. startIndex = 0;
  10250. }
  10251. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10252. numElementsToAdd = otherArray.size() - startIndex;
  10253. while (--numElementsToAdd >= 0)
  10254. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  10255. }
  10256. void StringArray::set (const int index,
  10257. const String& newString) throw()
  10258. {
  10259. String* const s = (String*) strings [index];
  10260. if (s != 0)
  10261. {
  10262. *s = newString;
  10263. }
  10264. else if (index >= 0)
  10265. {
  10266. add (newString);
  10267. }
  10268. }
  10269. bool StringArray::contains (const String& stringToLookFor,
  10270. const bool ignoreCase) const throw()
  10271. {
  10272. if (ignoreCase)
  10273. {
  10274. for (int i = size(); --i >= 0;)
  10275. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  10276. return true;
  10277. }
  10278. else
  10279. {
  10280. for (int i = size(); --i >= 0;)
  10281. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  10282. return true;
  10283. }
  10284. return false;
  10285. }
  10286. int StringArray::indexOf (const String& stringToLookFor,
  10287. const bool ignoreCase,
  10288. int i) const throw()
  10289. {
  10290. if (i < 0)
  10291. i = 0;
  10292. const int numElements = size();
  10293. if (ignoreCase)
  10294. {
  10295. while (i < numElements)
  10296. {
  10297. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10298. return i;
  10299. ++i;
  10300. }
  10301. }
  10302. else
  10303. {
  10304. while (i < numElements)
  10305. {
  10306. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  10307. return i;
  10308. ++i;
  10309. }
  10310. }
  10311. return -1;
  10312. }
  10313. void StringArray::remove (const int index) throw()
  10314. {
  10315. String* const s = (String*) strings [index];
  10316. if (s != 0)
  10317. {
  10318. strings.remove (index);
  10319. delete s;
  10320. }
  10321. }
  10322. void StringArray::removeString (const String& stringToRemove,
  10323. const bool ignoreCase) throw()
  10324. {
  10325. if (ignoreCase)
  10326. {
  10327. for (int i = size(); --i >= 0;)
  10328. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10329. remove (i);
  10330. }
  10331. else
  10332. {
  10333. for (int i = size(); --i >= 0;)
  10334. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  10335. remove (i);
  10336. }
  10337. }
  10338. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  10339. {
  10340. if (removeWhitespaceStrings)
  10341. {
  10342. for (int i = size(); --i >= 0;)
  10343. if (! ((const String*) strings.getUnchecked(i))->containsNonWhitespaceChars())
  10344. remove (i);
  10345. }
  10346. else
  10347. {
  10348. for (int i = size(); --i >= 0;)
  10349. if (((const String*) strings.getUnchecked(i))->isEmpty())
  10350. remove (i);
  10351. }
  10352. }
  10353. void StringArray::trim() throw()
  10354. {
  10355. for (int i = size(); --i >= 0;)
  10356. {
  10357. String& s = *(String*) strings.getUnchecked(i);
  10358. s = s.trim();
  10359. }
  10360. }
  10361. class InternalStringArrayComparator
  10362. {
  10363. public:
  10364. static int compareElements (void* const first, void* const second) throw()
  10365. {
  10366. return ((const String*) first)->compare (*(const String*) second);
  10367. }
  10368. };
  10369. class InsensitiveInternalStringArrayComparator
  10370. {
  10371. public:
  10372. static int compareElements (void* const first, void* const second) throw()
  10373. {
  10374. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  10375. }
  10376. };
  10377. void StringArray::sort (const bool ignoreCase) throw()
  10378. {
  10379. if (ignoreCase)
  10380. {
  10381. InsensitiveInternalStringArrayComparator comp;
  10382. strings.sort (comp);
  10383. }
  10384. else
  10385. {
  10386. InternalStringArrayComparator comp;
  10387. strings.sort (comp);
  10388. }
  10389. }
  10390. void StringArray::move (const int currentIndex, int newIndex) throw()
  10391. {
  10392. strings.move (currentIndex, newIndex);
  10393. }
  10394. const String StringArray::joinIntoString (const String& separator,
  10395. int start,
  10396. int numberToJoin) const throw()
  10397. {
  10398. const int last = (numberToJoin < 0) ? size()
  10399. : jmin (size(), start + numberToJoin);
  10400. if (start < 0)
  10401. start = 0;
  10402. if (start >= last)
  10403. return String::empty;
  10404. if (start == last - 1)
  10405. return *(const String*) strings.getUnchecked (start);
  10406. const int separatorLen = separator.length();
  10407. int charsNeeded = separatorLen * (last - start - 1);
  10408. for (int i = start; i < last; ++i)
  10409. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  10410. String result;
  10411. result.preallocateStorage (charsNeeded);
  10412. tchar* dest = (tchar*) (const tchar*) result;
  10413. while (start < last)
  10414. {
  10415. const String& s = *(const String*) strings.getUnchecked (start);
  10416. const int len = s.length();
  10417. if (len > 0)
  10418. {
  10419. s.copyToBuffer (dest, len);
  10420. dest += len;
  10421. }
  10422. if (++start < last && separatorLen > 0)
  10423. {
  10424. separator.copyToBuffer (dest, separatorLen);
  10425. dest += separatorLen;
  10426. }
  10427. }
  10428. *dest = 0;
  10429. return result;
  10430. }
  10431. int StringArray::addTokens (const tchar* const text,
  10432. const bool preserveQuotedStrings) throw()
  10433. {
  10434. return addTokens (text,
  10435. T(" \n\r\t"),
  10436. preserveQuotedStrings ? T("\"") : 0);
  10437. }
  10438. int StringArray::addTokens (const tchar* const text,
  10439. const tchar* breakCharacters,
  10440. const tchar* quoteCharacters) throw()
  10441. {
  10442. int num = 0;
  10443. if (text != 0 && *text != 0)
  10444. {
  10445. if (breakCharacters == 0)
  10446. breakCharacters = T("");
  10447. if (quoteCharacters == 0)
  10448. quoteCharacters = T("");
  10449. bool insideQuotes = false;
  10450. tchar currentQuoteChar = 0;
  10451. int i = 0;
  10452. int tokenStart = 0;
  10453. for (;;)
  10454. {
  10455. const tchar c = text[i];
  10456. bool isBreak = (c == 0);
  10457. if (! (insideQuotes || isBreak))
  10458. {
  10459. const tchar* b = breakCharacters;
  10460. while (*b != 0)
  10461. {
  10462. if (*b++ == c)
  10463. {
  10464. isBreak = true;
  10465. break;
  10466. }
  10467. }
  10468. }
  10469. if (! isBreak)
  10470. {
  10471. bool isQuote = false;
  10472. const tchar* q = quoteCharacters;
  10473. while (*q != 0)
  10474. {
  10475. if (*q++ == c)
  10476. {
  10477. isQuote = true;
  10478. break;
  10479. }
  10480. }
  10481. if (isQuote)
  10482. {
  10483. if (insideQuotes)
  10484. {
  10485. // only break out of quotes-mode if we find a matching quote to the
  10486. // one that we opened with..
  10487. if (currentQuoteChar == c)
  10488. insideQuotes = false;
  10489. }
  10490. else
  10491. {
  10492. insideQuotes = true;
  10493. currentQuoteChar = c;
  10494. }
  10495. }
  10496. }
  10497. else
  10498. {
  10499. add (String (text + tokenStart, i - tokenStart));
  10500. ++num;
  10501. tokenStart = i + 1;
  10502. }
  10503. if (c == 0)
  10504. break;
  10505. ++i;
  10506. }
  10507. }
  10508. return num;
  10509. }
  10510. int StringArray::addLines (const tchar* text) throw()
  10511. {
  10512. int numLines = 0;
  10513. if (text != 0)
  10514. {
  10515. while (*text != 0)
  10516. {
  10517. const tchar* const startOfLine = text;
  10518. while (*text != 0)
  10519. {
  10520. if (*text == T('\r'))
  10521. {
  10522. ++text;
  10523. if (*text == T('\n'))
  10524. ++text;
  10525. break;
  10526. }
  10527. if (*text == T('\n'))
  10528. {
  10529. ++text;
  10530. break;
  10531. }
  10532. ++text;
  10533. }
  10534. const tchar* endOfLine = text;
  10535. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10536. --endOfLine;
  10537. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10538. --endOfLine;
  10539. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10540. ++numLines;
  10541. }
  10542. }
  10543. return numLines;
  10544. }
  10545. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  10546. {
  10547. for (int i = 0; i < size() - 1; ++i)
  10548. {
  10549. const String& s = *(String*) strings.getUnchecked(i);
  10550. int nextIndex = i + 1;
  10551. for (;;)
  10552. {
  10553. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10554. if (nextIndex < 0)
  10555. break;
  10556. remove (nextIndex);
  10557. }
  10558. }
  10559. }
  10560. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10561. const bool appendNumberToFirstInstance,
  10562. const tchar* const preNumberString,
  10563. const tchar* const postNumberString) throw()
  10564. {
  10565. for (int i = 0; i < size() - 1; ++i)
  10566. {
  10567. String& s = *(String*) strings.getUnchecked(i);
  10568. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10569. if (nextIndex >= 0)
  10570. {
  10571. const String original (s);
  10572. int number = 0;
  10573. if (appendNumberToFirstInstance)
  10574. s = original + preNumberString + String (++number) + postNumberString;
  10575. else
  10576. ++number;
  10577. while (nextIndex >= 0)
  10578. {
  10579. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10580. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10581. }
  10582. }
  10583. }
  10584. }
  10585. void StringArray::minimiseStorageOverheads() throw()
  10586. {
  10587. strings.minimiseStorageOverheads();
  10588. }
  10589. END_JUCE_NAMESPACE
  10590. /********* End of inlined file: juce_StringArray.cpp *********/
  10591. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  10592. BEGIN_JUCE_NAMESPACE
  10593. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  10594. : ignoreCase (ignoreCase_)
  10595. {
  10596. }
  10597. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  10598. : keys (other.keys),
  10599. values (other.values),
  10600. ignoreCase (other.ignoreCase)
  10601. {
  10602. }
  10603. StringPairArray::~StringPairArray() throw()
  10604. {
  10605. }
  10606. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  10607. {
  10608. keys = other.keys;
  10609. values = other.values;
  10610. return *this;
  10611. }
  10612. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  10613. {
  10614. for (int i = keys.size(); --i >= 0;)
  10615. if (other [keys[i]] != values[i])
  10616. return false;
  10617. return true;
  10618. }
  10619. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  10620. {
  10621. return ! operator== (other);
  10622. }
  10623. const String& StringPairArray::operator[] (const String& key) const throw()
  10624. {
  10625. return values [keys.indexOf (key, ignoreCase)];
  10626. }
  10627. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10628. {
  10629. const int i = keys.indexOf (key, ignoreCase);
  10630. if (i >= 0)
  10631. return values[i];
  10632. return defaultReturnValue;
  10633. }
  10634. void StringPairArray::set (const String& key,
  10635. const String& value) throw()
  10636. {
  10637. const int i = keys.indexOf (key, ignoreCase);
  10638. if (i >= 0)
  10639. {
  10640. values.set (i, value);
  10641. }
  10642. else
  10643. {
  10644. keys.add (key);
  10645. values.add (value);
  10646. }
  10647. }
  10648. void StringPairArray::addArray (const StringPairArray& other)
  10649. {
  10650. for (int i = 0; i < other.size(); ++i)
  10651. set (other.keys[i], other.values[i]);
  10652. }
  10653. void StringPairArray::clear() throw()
  10654. {
  10655. keys.clear();
  10656. values.clear();
  10657. }
  10658. void StringPairArray::remove (const String& key) throw()
  10659. {
  10660. remove (keys.indexOf (key, ignoreCase));
  10661. }
  10662. void StringPairArray::remove (const int index) throw()
  10663. {
  10664. keys.remove (index);
  10665. values.remove (index);
  10666. }
  10667. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase) throw()
  10668. {
  10669. ignoreCase = shouldIgnoreCase;
  10670. }
  10671. const String StringPairArray::getDescription() const
  10672. {
  10673. String s;
  10674. for (int i = 0; i < keys.size(); ++i)
  10675. {
  10676. s << keys[i] << T(" = ") << values[i];
  10677. if (i < keys.size())
  10678. s << T(", ");
  10679. }
  10680. return s;
  10681. }
  10682. void StringPairArray::minimiseStorageOverheads() throw()
  10683. {
  10684. keys.minimiseStorageOverheads();
  10685. values.minimiseStorageOverheads();
  10686. }
  10687. END_JUCE_NAMESPACE
  10688. /********* End of inlined file: juce_StringPairArray.cpp *********/
  10689. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  10690. BEGIN_JUCE_NAMESPACE
  10691. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  10692. {
  10693. return CharacterFunctions::isLetterOrDigit (c)
  10694. || c == T('_')
  10695. || c == T('-')
  10696. || c == T(':')
  10697. || c == T('.');
  10698. }
  10699. #define isXmlIdentifierChar(c) \
  10700. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  10701. XmlDocument::XmlDocument (const String& documentText) throw()
  10702. : originalText (documentText),
  10703. ignoreEmptyTextElements (true),
  10704. inputSource (0)
  10705. {
  10706. }
  10707. XmlDocument::XmlDocument (const File& file)
  10708. {
  10709. inputSource = new FileInputSource (file);
  10710. }
  10711. XmlDocument::~XmlDocument() throw()
  10712. {
  10713. delete inputSource;
  10714. }
  10715. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10716. {
  10717. if (inputSource != newSource)
  10718. {
  10719. delete inputSource;
  10720. inputSource = newSource;
  10721. }
  10722. }
  10723. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10724. {
  10725. ignoreEmptyTextElements = shouldBeIgnored;
  10726. }
  10727. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10728. {
  10729. String textToParse (originalText);
  10730. if (textToParse.isEmpty() && inputSource != 0)
  10731. {
  10732. InputStream* const in = inputSource->createInputStream();
  10733. if (in != 0)
  10734. {
  10735. MemoryBlock data;
  10736. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10737. delete in;
  10738. if (data.getSize() >= 2
  10739. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10740. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10741. {
  10742. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  10743. }
  10744. else
  10745. {
  10746. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  10747. }
  10748. if (! onlyReadOuterDocumentElement)
  10749. originalText = textToParse;
  10750. }
  10751. }
  10752. input = textToParse;
  10753. lastError = String::empty;
  10754. errorOccurred = false;
  10755. outOfData = false;
  10756. needToLoadDTD = true;
  10757. for (int i = 0; i < 128; ++i)
  10758. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  10759. if (textToParse.isEmpty())
  10760. {
  10761. lastError = "not enough input";
  10762. }
  10763. else
  10764. {
  10765. skipHeader();
  10766. if (input != 0)
  10767. {
  10768. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  10769. if (errorOccurred)
  10770. delete result;
  10771. else
  10772. return result;
  10773. }
  10774. else
  10775. {
  10776. lastError = "incorrect xml header";
  10777. }
  10778. }
  10779. return 0;
  10780. }
  10781. const String& XmlDocument::getLastParseError() const throw()
  10782. {
  10783. return lastError;
  10784. }
  10785. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  10786. {
  10787. lastError = desc;
  10788. errorOccurred = ! carryOn;
  10789. }
  10790. const String XmlDocument::getFileContents (const String& filename) const
  10791. {
  10792. String result;
  10793. if (inputSource != 0)
  10794. {
  10795. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  10796. if (in != 0)
  10797. {
  10798. result = in->readEntireStreamAsString();
  10799. delete in;
  10800. }
  10801. }
  10802. return result;
  10803. }
  10804. tchar XmlDocument::readNextChar() throw()
  10805. {
  10806. if (*input != 0)
  10807. {
  10808. return *input++;
  10809. }
  10810. else
  10811. {
  10812. outOfData = true;
  10813. return 0;
  10814. }
  10815. }
  10816. int XmlDocument::findNextTokenLength() throw()
  10817. {
  10818. int len = 0;
  10819. tchar c = *input;
  10820. while (isXmlIdentifierChar (c))
  10821. c = input [++len];
  10822. return len;
  10823. }
  10824. void XmlDocument::skipHeader() throw()
  10825. {
  10826. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10827. if (found != 0)
  10828. {
  10829. input = found;
  10830. input = CharacterFunctions::find (input, T("?>"));
  10831. if (input == 0)
  10832. return;
  10833. input += 2;
  10834. }
  10835. skipNextWhiteSpace();
  10836. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10837. if (docType == 0)
  10838. return;
  10839. input = docType + 9;
  10840. int n = 1;
  10841. while (n > 0)
  10842. {
  10843. const tchar c = readNextChar();
  10844. if (outOfData)
  10845. return;
  10846. if (c == T('<'))
  10847. ++n;
  10848. else if (c == T('>'))
  10849. --n;
  10850. }
  10851. docType += 9;
  10852. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10853. }
  10854. void XmlDocument::skipNextWhiteSpace() throw()
  10855. {
  10856. for (;;)
  10857. {
  10858. tchar c = *input;
  10859. while (CharacterFunctions::isWhitespace (c))
  10860. c = *++input;
  10861. if (c == 0)
  10862. {
  10863. outOfData = true;
  10864. break;
  10865. }
  10866. else if (c == T('<'))
  10867. {
  10868. if (input[1] == T('!')
  10869. && input[2] == T('-')
  10870. && input[3] == T('-'))
  10871. {
  10872. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10873. if (closeComment == 0)
  10874. {
  10875. outOfData = true;
  10876. break;
  10877. }
  10878. input = closeComment + 3;
  10879. continue;
  10880. }
  10881. else if (input[1] == T('?'))
  10882. {
  10883. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10884. if (closeBracket == 0)
  10885. {
  10886. outOfData = true;
  10887. break;
  10888. }
  10889. input = closeBracket + 2;
  10890. continue;
  10891. }
  10892. }
  10893. break;
  10894. }
  10895. }
  10896. void XmlDocument::readQuotedString (String& result) throw()
  10897. {
  10898. const tchar quote = readNextChar();
  10899. while (! outOfData)
  10900. {
  10901. const tchar character = readNextChar();
  10902. if (character == quote)
  10903. break;
  10904. if (character == T('&'))
  10905. {
  10906. --input;
  10907. readEntity (result);
  10908. }
  10909. else
  10910. {
  10911. --input;
  10912. const tchar* const start = input;
  10913. for (;;)
  10914. {
  10915. const tchar character = *input;
  10916. if (character == quote)
  10917. {
  10918. result.append (start, (int) (input - start));
  10919. ++input;
  10920. return;
  10921. }
  10922. else if (character == T('&'))
  10923. {
  10924. result.append (start, (int) (input - start));
  10925. break;
  10926. }
  10927. else if (character == 0)
  10928. {
  10929. outOfData = true;
  10930. setLastError ("unmatched quotes", false);
  10931. break;
  10932. }
  10933. ++input;
  10934. }
  10935. }
  10936. }
  10937. }
  10938. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  10939. {
  10940. XmlElement* node = 0;
  10941. skipNextWhiteSpace();
  10942. if (outOfData)
  10943. return 0;
  10944. input = CharacterFunctions::find (input, T("<"));
  10945. if (input != 0)
  10946. {
  10947. ++input;
  10948. int tagLen = findNextTokenLength();
  10949. if (tagLen == 0)
  10950. {
  10951. // no tag name - but allow for a gap after the '<' before giving an error
  10952. skipNextWhiteSpace();
  10953. tagLen = findNextTokenLength();
  10954. if (tagLen == 0)
  10955. {
  10956. setLastError ("tag name missing", false);
  10957. return node;
  10958. }
  10959. }
  10960. node = new XmlElement (input, tagLen);
  10961. input += tagLen;
  10962. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10963. // look for attributes
  10964. for (;;)
  10965. {
  10966. skipNextWhiteSpace();
  10967. const tchar c = *input;
  10968. // empty tag..
  10969. if (c == T('/') && input[1] == T('>'))
  10970. {
  10971. input += 2;
  10972. break;
  10973. }
  10974. // parse the guts of the element..
  10975. if (c == T('>'))
  10976. {
  10977. ++input;
  10978. skipNextWhiteSpace();
  10979. if (alsoParseSubElements)
  10980. readChildElements (node);
  10981. break;
  10982. }
  10983. // get an attribute..
  10984. if (isXmlIdentifierChar (c))
  10985. {
  10986. const int attNameLen = findNextTokenLength();
  10987. if (attNameLen > 0)
  10988. {
  10989. const tchar* attNameStart = input;
  10990. input += attNameLen;
  10991. skipNextWhiteSpace();
  10992. if (readNextChar() == T('='))
  10993. {
  10994. skipNextWhiteSpace();
  10995. const tchar c = *input;
  10996. if (c == T('"') || c == T('\''))
  10997. {
  10998. XmlElement::XmlAttributeNode* const newAtt
  10999. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  11000. String::empty);
  11001. readQuotedString (newAtt->value);
  11002. if (lastAttribute == 0)
  11003. node->attributes = newAtt;
  11004. else
  11005. lastAttribute->next = newAtt;
  11006. lastAttribute = newAtt;
  11007. continue;
  11008. }
  11009. }
  11010. }
  11011. }
  11012. else
  11013. {
  11014. if (! outOfData)
  11015. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11016. }
  11017. break;
  11018. }
  11019. }
  11020. return node;
  11021. }
  11022. void XmlDocument::readChildElements (XmlElement* parent) throw()
  11023. {
  11024. XmlElement* lastChildNode = 0;
  11025. for (;;)
  11026. {
  11027. skipNextWhiteSpace();
  11028. if (outOfData)
  11029. {
  11030. setLastError ("unmatched tags", false);
  11031. break;
  11032. }
  11033. if (*input == T('<'))
  11034. {
  11035. if (input[1] == T('/'))
  11036. {
  11037. // our close tag..
  11038. input = CharacterFunctions::find (input, T(">"));
  11039. ++input;
  11040. break;
  11041. }
  11042. else if (input[1] == T('!')
  11043. && input[2] == T('[')
  11044. && input[3] == T('C')
  11045. && input[4] == T('D')
  11046. && input[5] == T('A')
  11047. && input[6] == T('T')
  11048. && input[7] == T('A')
  11049. && input[8] == T('['))
  11050. {
  11051. input += 9;
  11052. const tchar* const inputStart = input;
  11053. int len = 0;
  11054. for (;;)
  11055. {
  11056. if (*input == 0)
  11057. {
  11058. setLastError ("unterminated CDATA section", false);
  11059. outOfData = true;
  11060. break;
  11061. }
  11062. else if (input[0] == T(']')
  11063. && input[1] == T(']')
  11064. && input[2] == T('>'))
  11065. {
  11066. input += 3;
  11067. break;
  11068. }
  11069. ++input;
  11070. ++len;
  11071. }
  11072. XmlElement* const e = new XmlElement ((int) 0);
  11073. e->setText (String (inputStart, len));
  11074. if (lastChildNode != 0)
  11075. lastChildNode->nextElement = e;
  11076. else
  11077. parent->addChildElement (e);
  11078. lastChildNode = e;
  11079. }
  11080. else
  11081. {
  11082. // this is some other element, so parse and add it..
  11083. XmlElement* const n = readNextElement (true);
  11084. if (n != 0)
  11085. {
  11086. if (lastChildNode == 0)
  11087. parent->addChildElement (n);
  11088. else
  11089. lastChildNode->nextElement = n;
  11090. lastChildNode = n;
  11091. }
  11092. else
  11093. {
  11094. return;
  11095. }
  11096. }
  11097. }
  11098. else
  11099. {
  11100. // read character block..
  11101. XmlElement* const e = new XmlElement ((int)0);
  11102. if (lastChildNode != 0)
  11103. lastChildNode->nextElement = e;
  11104. else
  11105. parent->addChildElement (e);
  11106. lastChildNode = e;
  11107. String textElementContent;
  11108. for (;;)
  11109. {
  11110. const tchar c = *input;
  11111. if (c == T('<'))
  11112. break;
  11113. if (c == 0)
  11114. {
  11115. setLastError ("unmatched tags", false);
  11116. outOfData = true;
  11117. return;
  11118. }
  11119. if (c == T('&'))
  11120. {
  11121. String entity;
  11122. readEntity (entity);
  11123. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  11124. {
  11125. const tchar* const oldInput = input;
  11126. const bool oldOutOfData = outOfData;
  11127. input = (const tchar*) entity;
  11128. outOfData = false;
  11129. for (;;)
  11130. {
  11131. XmlElement* const n = readNextElement (true);
  11132. if (n == 0)
  11133. break;
  11134. if (lastChildNode == 0)
  11135. parent->addChildElement (n);
  11136. else
  11137. lastChildNode->nextElement = n;
  11138. lastChildNode = n;
  11139. }
  11140. input = oldInput;
  11141. outOfData = oldOutOfData;
  11142. }
  11143. else
  11144. {
  11145. textElementContent += entity;
  11146. }
  11147. }
  11148. else
  11149. {
  11150. const tchar* start = input;
  11151. int len = 0;
  11152. for (;;)
  11153. {
  11154. const tchar c = *input;
  11155. if (c == T('<') || c == T('&'))
  11156. {
  11157. break;
  11158. }
  11159. else if (c == 0)
  11160. {
  11161. setLastError ("unmatched tags", false);
  11162. outOfData = true;
  11163. return;
  11164. }
  11165. ++input;
  11166. ++len;
  11167. }
  11168. textElementContent.append (start, len);
  11169. }
  11170. }
  11171. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11172. : textElementContent.isNotEmpty())
  11173. e->setText (textElementContent);
  11174. }
  11175. }
  11176. }
  11177. void XmlDocument::readEntity (String& result) throw()
  11178. {
  11179. // skip over the ampersand
  11180. ++input;
  11181. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  11182. {
  11183. input += 4;
  11184. result += T("&");
  11185. }
  11186. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  11187. {
  11188. input += 5;
  11189. result += T("\"");
  11190. }
  11191. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  11192. {
  11193. input += 5;
  11194. result += T("\'");
  11195. }
  11196. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  11197. {
  11198. input += 3;
  11199. result += T("<");
  11200. }
  11201. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  11202. {
  11203. input += 3;
  11204. result += T(">");
  11205. }
  11206. else if (*input == T('#'))
  11207. {
  11208. int charCode = 0;
  11209. ++input;
  11210. if (*input == T('x') || *input == T('X'))
  11211. {
  11212. ++input;
  11213. int numChars = 0;
  11214. while (input[0] != T(';'))
  11215. {
  11216. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11217. if (hexValue < 0 || ++numChars > 8)
  11218. {
  11219. setLastError ("illegal escape sequence", true);
  11220. break;
  11221. }
  11222. charCode = (charCode << 4) | hexValue;
  11223. ++input;
  11224. }
  11225. ++input;
  11226. }
  11227. else if (input[0] >= T('0') && input[0] <= T('9'))
  11228. {
  11229. int numChars = 0;
  11230. while (input[0] != T(';'))
  11231. {
  11232. if (++numChars > 12)
  11233. {
  11234. setLastError ("illegal escape sequence", true);
  11235. break;
  11236. }
  11237. charCode = charCode * 10 + (input[0] - T('0'));
  11238. ++input;
  11239. }
  11240. ++input;
  11241. }
  11242. else
  11243. {
  11244. setLastError ("illegal escape sequence", true);
  11245. result += T("&");
  11246. return;
  11247. }
  11248. result << (tchar) charCode;
  11249. }
  11250. else
  11251. {
  11252. const tchar* const entityNameStart = input;
  11253. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  11254. if (closingSemiColon == 0)
  11255. {
  11256. outOfData = true;
  11257. result += T("&");
  11258. }
  11259. else
  11260. {
  11261. input = closingSemiColon + 1;
  11262. result += expandExternalEntity (String (entityNameStart,
  11263. (int) (closingSemiColon - entityNameStart)));
  11264. }
  11265. }
  11266. }
  11267. const String XmlDocument::expandEntity (const String& ent)
  11268. {
  11269. if (ent.equalsIgnoreCase (T("amp")))
  11270. {
  11271. return T("&");
  11272. }
  11273. else if (ent.equalsIgnoreCase (T("quot")))
  11274. {
  11275. return T("\"");
  11276. }
  11277. else if (ent.equalsIgnoreCase (T("apos")))
  11278. {
  11279. return T("\'");
  11280. }
  11281. else if (ent.equalsIgnoreCase (T("lt")))
  11282. {
  11283. return T("<");
  11284. }
  11285. else if (ent.equalsIgnoreCase (T("gt")))
  11286. {
  11287. return T(">");
  11288. }
  11289. else if (ent[0] == T('#'))
  11290. {
  11291. if (ent[1] == T('x') || ent[1] == T('X'))
  11292. {
  11293. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  11294. }
  11295. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  11296. {
  11297. return String::charToString ((tchar) ent.substring (1).getIntValue());
  11298. }
  11299. setLastError ("illegal escape sequence", false);
  11300. return T("&");
  11301. }
  11302. else
  11303. {
  11304. return expandExternalEntity (ent);
  11305. }
  11306. }
  11307. const String XmlDocument::expandExternalEntity (const String& entity)
  11308. {
  11309. if (needToLoadDTD)
  11310. {
  11311. if (dtdText.isNotEmpty())
  11312. {
  11313. while (dtdText.endsWithChar (T('>')))
  11314. dtdText = dtdText.dropLastCharacters (1);
  11315. tokenisedDTD.addTokens (dtdText, true);
  11316. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  11317. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11318. {
  11319. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11320. tokenisedDTD.clear();
  11321. tokenisedDTD.addTokens (getFileContents (fn), true);
  11322. }
  11323. else
  11324. {
  11325. tokenisedDTD.clear();
  11326. const int openBracket = dtdText.indexOfChar (T('['));
  11327. if (openBracket > 0)
  11328. {
  11329. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  11330. if (closeBracket > openBracket)
  11331. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11332. closeBracket), true);
  11333. }
  11334. }
  11335. for (int i = tokenisedDTD.size(); --i >= 0;)
  11336. {
  11337. if (tokenisedDTD[i].startsWithChar (T('%'))
  11338. && tokenisedDTD[i].endsWithChar (T(';')))
  11339. {
  11340. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11341. StringArray newToks;
  11342. newToks.addTokens (parsed, true);
  11343. tokenisedDTD.remove (i);
  11344. for (int j = newToks.size(); --j >= 0;)
  11345. tokenisedDTD.insert (i, newToks[j]);
  11346. }
  11347. }
  11348. }
  11349. needToLoadDTD = false;
  11350. }
  11351. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11352. {
  11353. if (tokenisedDTD[i] == entity)
  11354. {
  11355. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  11356. {
  11357. String ent (tokenisedDTD [i + 1]);
  11358. while (ent.endsWithChar (T('>')))
  11359. ent = ent.dropLastCharacters (1);
  11360. ent = ent.trim().unquoted();
  11361. // check for sub-entities..
  11362. int ampersand = ent.indexOfChar (T('&'));
  11363. while (ampersand >= 0)
  11364. {
  11365. const int semiColon = ent.indexOf (i + 1, T(";"));
  11366. if (semiColon < 0)
  11367. {
  11368. setLastError ("entity without terminating semi-colon", false);
  11369. break;
  11370. }
  11371. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11372. ent = ent.substring (0, ampersand)
  11373. + resolved
  11374. + ent.substring (semiColon + 1);
  11375. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  11376. }
  11377. return ent;
  11378. }
  11379. }
  11380. }
  11381. setLastError ("unknown entity", true);
  11382. return entity;
  11383. }
  11384. const String XmlDocument::getParameterEntity (const String& entity)
  11385. {
  11386. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11387. {
  11388. if (tokenisedDTD[i] == entity)
  11389. {
  11390. if (tokenisedDTD [i - 1] == T("%")
  11391. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  11392. {
  11393. String ent (tokenisedDTD [i + 1]);
  11394. while (ent.endsWithChar (T('>')))
  11395. ent = ent.dropLastCharacters (1);
  11396. if (ent.equalsIgnoreCase (T("system")))
  11397. {
  11398. String filename (tokenisedDTD [i + 2]);
  11399. while (filename.endsWithChar (T('>')))
  11400. filename = filename.dropLastCharacters (1);
  11401. return getFileContents (filename);
  11402. }
  11403. else
  11404. {
  11405. return ent.trim().unquoted();
  11406. }
  11407. }
  11408. }
  11409. }
  11410. return entity;
  11411. }
  11412. END_JUCE_NAMESPACE
  11413. /********* End of inlined file: juce_XmlDocument.cpp *********/
  11414. /********* Start of inlined file: juce_XmlElement.cpp *********/
  11415. BEGIN_JUCE_NAMESPACE
  11416. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11417. : name (other.name),
  11418. value (other.value),
  11419. next (0)
  11420. {
  11421. }
  11422. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  11423. const String& value_) throw()
  11424. : name (name_),
  11425. value (value_),
  11426. next (0)
  11427. {
  11428. }
  11429. XmlElement::XmlElement (const String& tagName_) throw()
  11430. : tagName (tagName_),
  11431. firstChildElement (0),
  11432. nextElement (0),
  11433. attributes (0)
  11434. {
  11435. // the tag name mustn't be empty, or it'll look like a text element!
  11436. jassert (tagName_.containsNonWhitespaceChars())
  11437. }
  11438. XmlElement::XmlElement (int /*dummy*/) throw()
  11439. : firstChildElement (0),
  11440. nextElement (0),
  11441. attributes (0)
  11442. {
  11443. }
  11444. XmlElement::XmlElement (const tchar* const tagName_,
  11445. const int nameLen) throw()
  11446. : tagName (tagName_, nameLen),
  11447. firstChildElement (0),
  11448. nextElement (0),
  11449. attributes (0)
  11450. {
  11451. }
  11452. XmlElement::XmlElement (const XmlElement& other) throw()
  11453. : tagName (other.tagName),
  11454. firstChildElement (0),
  11455. nextElement (0),
  11456. attributes (0)
  11457. {
  11458. copyChildrenAndAttributesFrom (other);
  11459. }
  11460. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11461. {
  11462. if (this != &other)
  11463. {
  11464. removeAllAttributes();
  11465. deleteAllChildElements();
  11466. tagName = other.tagName;
  11467. copyChildrenAndAttributesFrom (other);
  11468. }
  11469. return *this;
  11470. }
  11471. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11472. {
  11473. XmlElement* child = other.firstChildElement;
  11474. XmlElement* lastChild = 0;
  11475. while (child != 0)
  11476. {
  11477. XmlElement* const copiedChild = new XmlElement (*child);
  11478. if (lastChild != 0)
  11479. lastChild->nextElement = copiedChild;
  11480. else
  11481. firstChildElement = copiedChild;
  11482. lastChild = copiedChild;
  11483. child = child->nextElement;
  11484. }
  11485. const XmlAttributeNode* att = other.attributes;
  11486. XmlAttributeNode* lastAtt = 0;
  11487. while (att != 0)
  11488. {
  11489. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11490. if (lastAtt != 0)
  11491. lastAtt->next = newAtt;
  11492. else
  11493. attributes = newAtt;
  11494. lastAtt = newAtt;
  11495. att = att->next;
  11496. }
  11497. }
  11498. XmlElement::~XmlElement() throw()
  11499. {
  11500. XmlElement* child = firstChildElement;
  11501. while (child != 0)
  11502. {
  11503. XmlElement* const nextChild = child->nextElement;
  11504. delete child;
  11505. child = nextChild;
  11506. }
  11507. XmlAttributeNode* att = attributes;
  11508. while (att != 0)
  11509. {
  11510. XmlAttributeNode* const nextAtt = att->next;
  11511. delete att;
  11512. att = nextAtt;
  11513. }
  11514. }
  11515. static bool isLegalXmlChar (const juce_wchar character)
  11516. {
  11517. if ((character >= 'a' && character <= 'z')
  11518. || (character >= 'A' && character <= 'Z')
  11519. || (character >= '0' && character <= '9'))
  11520. return true;
  11521. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11522. do
  11523. {
  11524. if (((juce_wchar) (uint8) *t) == character)
  11525. return true;
  11526. }
  11527. while (*++t != 0);
  11528. return false;
  11529. }
  11530. static void escapeIllegalXmlChars (OutputStream& outputStream,
  11531. const String& text,
  11532. const bool changeNewLines) throw()
  11533. {
  11534. const juce_wchar* t = (const juce_wchar*) text;
  11535. for (;;)
  11536. {
  11537. const juce_wchar character = *t++;
  11538. if (character == 0)
  11539. {
  11540. break;
  11541. }
  11542. else if (isLegalXmlChar (character))
  11543. {
  11544. outputStream.writeByte ((char) character);
  11545. }
  11546. else
  11547. {
  11548. switch (character)
  11549. {
  11550. case '&':
  11551. outputStream.write ("&amp;", 5);
  11552. break;
  11553. case '"':
  11554. outputStream.write ("&quot;", 6);
  11555. break;
  11556. case '>':
  11557. outputStream.write ("&gt;", 4);
  11558. break;
  11559. case '<':
  11560. outputStream.write ("&lt;", 4);
  11561. break;
  11562. case '\n':
  11563. if (changeNewLines)
  11564. outputStream.write ("&#10;", 5);
  11565. else
  11566. outputStream.writeByte ((char) character);
  11567. break;
  11568. case '\r':
  11569. if (changeNewLines)
  11570. outputStream.write ("&#13;", 5);
  11571. else
  11572. outputStream.writeByte ((char) character);
  11573. break;
  11574. default:
  11575. {
  11576. String encoded (T("&#"));
  11577. encoded << String ((int) (unsigned int) character).trim()
  11578. << T(';');
  11579. outputStream.write ((const char*) encoded, encoded.length());
  11580. }
  11581. }
  11582. }
  11583. }
  11584. }
  11585. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  11586. {
  11587. if (numSpaces > 0)
  11588. {
  11589. const char* const blanks = " ";
  11590. const int blankSize = (int) sizeof (blanks) - 1;
  11591. while (numSpaces > blankSize)
  11592. {
  11593. out.write (blanks, blankSize);
  11594. numSpaces -= blankSize;
  11595. }
  11596. out.write (blanks, numSpaces);
  11597. }
  11598. }
  11599. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11600. const int indentationLevel,
  11601. const int lineWrapLength) const throw()
  11602. {
  11603. writeSpaces (outputStream, indentationLevel);
  11604. if (! isTextElement())
  11605. {
  11606. outputStream.writeByte ('<');
  11607. const int nameLen = tagName.length();
  11608. outputStream.write ((const char*) tagName, nameLen);
  11609. const int attIndent = indentationLevel + nameLen + 1;
  11610. int lineLen = 0;
  11611. const XmlAttributeNode* att = attributes;
  11612. while (att != 0)
  11613. {
  11614. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11615. {
  11616. outputStream.write ("\r\n", 2);
  11617. writeSpaces (outputStream, attIndent);
  11618. lineLen = 0;
  11619. }
  11620. const int attNameLen = att->name.length();
  11621. outputStream.writeByte (' ');
  11622. outputStream.write ((const char*) (att->name), attNameLen);
  11623. outputStream.write ("=\"", 2);
  11624. escapeIllegalXmlChars (outputStream, att->value, true);
  11625. outputStream.writeByte ('"');
  11626. lineLen += 4 + attNameLen + att->value.length();
  11627. att = att->next;
  11628. }
  11629. if (firstChildElement != 0)
  11630. {
  11631. XmlElement* child = firstChildElement;
  11632. if (child->nextElement == 0 && child->isTextElement())
  11633. {
  11634. outputStream.writeByte ('>');
  11635. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11636. }
  11637. else
  11638. {
  11639. if (indentationLevel >= 0)
  11640. outputStream.write (">\r\n", 3);
  11641. else
  11642. outputStream.writeByte ('>');
  11643. bool lastWasTextNode = false;
  11644. while (child != 0)
  11645. {
  11646. if (child->isTextElement())
  11647. {
  11648. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11649. writeSpaces (outputStream, indentationLevel + 2);
  11650. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11651. lastWasTextNode = true;
  11652. }
  11653. else
  11654. {
  11655. if (indentationLevel >= 0)
  11656. {
  11657. if (lastWasTextNode)
  11658. outputStream.write ("\r\n", 2);
  11659. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11660. }
  11661. else
  11662. {
  11663. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11664. }
  11665. lastWasTextNode = false;
  11666. }
  11667. child = child->nextElement;
  11668. }
  11669. if (indentationLevel >= 0)
  11670. {
  11671. if (lastWasTextNode)
  11672. outputStream.write ("\r\n", 2);
  11673. writeSpaces (outputStream, indentationLevel);
  11674. }
  11675. }
  11676. outputStream.write ("</", 2);
  11677. outputStream.write ((const char*) tagName, nameLen);
  11678. if (indentationLevel >= 0)
  11679. outputStream.write (">\r\n", 3);
  11680. else
  11681. outputStream.writeByte ('>');
  11682. }
  11683. else
  11684. {
  11685. if (indentationLevel >= 0)
  11686. outputStream.write ("/>\r\n", 4);
  11687. else
  11688. outputStream.write ("/>", 2);
  11689. }
  11690. }
  11691. else
  11692. {
  11693. if (indentationLevel >= 0)
  11694. writeSpaces (outputStream, indentationLevel + 2);
  11695. escapeIllegalXmlChars (outputStream, getText(), false);
  11696. }
  11697. }
  11698. const String XmlElement::createDocument (const String& dtd,
  11699. const bool allOnOneLine,
  11700. const bool includeXmlHeader,
  11701. const tchar* const encoding,
  11702. const int lineWrapLength) const throw()
  11703. {
  11704. String doc;
  11705. doc.preallocateStorage (1024);
  11706. if (includeXmlHeader)
  11707. {
  11708. doc << "<?xml version=\"1.0\" encoding=\""
  11709. << encoding;
  11710. if (allOnOneLine)
  11711. doc += "\"?> ";
  11712. else
  11713. doc += "\"?>\n\n";
  11714. }
  11715. if (dtd.isNotEmpty())
  11716. {
  11717. if (allOnOneLine)
  11718. doc << dtd << " ";
  11719. else
  11720. doc << dtd << "\r\n";
  11721. }
  11722. MemoryOutputStream mem (2048, 4096);
  11723. writeElementAsText (mem, allOnOneLine ? -1 : 0, lineWrapLength);
  11724. return doc + String (mem.getData(),
  11725. mem.getDataSize());
  11726. }
  11727. bool XmlElement::writeToFile (const File& f,
  11728. const String& dtd,
  11729. const tchar* const encoding,
  11730. const int lineWrapLength) const throw()
  11731. {
  11732. if (f.hasWriteAccess())
  11733. {
  11734. const File tempFile (f.getNonexistentSibling());
  11735. FileOutputStream* const out = tempFile.createOutputStream();
  11736. if (out != 0)
  11737. {
  11738. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  11739. << dtd << "\r\n";
  11740. writeElementAsText (*out, 0, lineWrapLength);
  11741. delete out;
  11742. if (tempFile.moveFileTo (f))
  11743. return true;
  11744. tempFile.deleteFile();
  11745. }
  11746. }
  11747. return false;
  11748. }
  11749. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  11750. {
  11751. #ifdef JUCE_DEBUG
  11752. // if debugging, check that the case is actually the same, because
  11753. // valid xml is case-sensitive, and although this lets it pass, it's
  11754. // better not to..
  11755. if (tagName.equalsIgnoreCase (tagNameWanted))
  11756. {
  11757. jassert (tagName == tagNameWanted);
  11758. return true;
  11759. }
  11760. else
  11761. {
  11762. return false;
  11763. }
  11764. #else
  11765. return tagName.equalsIgnoreCase (tagNameWanted);
  11766. #endif
  11767. }
  11768. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  11769. {
  11770. XmlElement* e = nextElement;
  11771. while (e != 0 && ! e->hasTagName (requiredTagName))
  11772. e = e->nextElement;
  11773. return e;
  11774. }
  11775. int XmlElement::getNumAttributes() const throw()
  11776. {
  11777. const XmlAttributeNode* att = attributes;
  11778. int count = 0;
  11779. while (att != 0)
  11780. {
  11781. att = att->next;
  11782. ++count;
  11783. }
  11784. return count;
  11785. }
  11786. const String& XmlElement::getAttributeName (const int index) const throw()
  11787. {
  11788. const XmlAttributeNode* att = attributes;
  11789. int count = 0;
  11790. while (att != 0)
  11791. {
  11792. if (count == index)
  11793. return att->name;
  11794. att = att->next;
  11795. ++count;
  11796. }
  11797. return String::empty;
  11798. }
  11799. const String& XmlElement::getAttributeValue (const int index) const throw()
  11800. {
  11801. const XmlAttributeNode* att = attributes;
  11802. int count = 0;
  11803. while (att != 0)
  11804. {
  11805. if (count == index)
  11806. return att->value;
  11807. att = att->next;
  11808. ++count;
  11809. }
  11810. return String::empty;
  11811. }
  11812. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  11813. {
  11814. const XmlAttributeNode* att = attributes;
  11815. while (att != 0)
  11816. {
  11817. if (att->name.equalsIgnoreCase (attributeName))
  11818. return true;
  11819. att = att->next;
  11820. }
  11821. return false;
  11822. }
  11823. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  11824. const tchar* const defaultReturnValue) const throw()
  11825. {
  11826. const XmlAttributeNode* att = attributes;
  11827. while (att != 0)
  11828. {
  11829. if (att->name.equalsIgnoreCase (attributeName))
  11830. return att->value;
  11831. att = att->next;
  11832. }
  11833. return defaultReturnValue;
  11834. }
  11835. int XmlElement::getIntAttribute (const tchar* const attributeName,
  11836. const int defaultReturnValue) const throw()
  11837. {
  11838. const XmlAttributeNode* att = attributes;
  11839. while (att != 0)
  11840. {
  11841. if (att->name.equalsIgnoreCase (attributeName))
  11842. return att->value.getIntValue();
  11843. att = att->next;
  11844. }
  11845. return defaultReturnValue;
  11846. }
  11847. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  11848. const double defaultReturnValue) const throw()
  11849. {
  11850. const XmlAttributeNode* att = attributes;
  11851. while (att != 0)
  11852. {
  11853. if (att->name.equalsIgnoreCase (attributeName))
  11854. return att->value.getDoubleValue();
  11855. att = att->next;
  11856. }
  11857. return defaultReturnValue;
  11858. }
  11859. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  11860. const bool defaultReturnValue) const throw()
  11861. {
  11862. const XmlAttributeNode* att = attributes;
  11863. while (att != 0)
  11864. {
  11865. if (att->name.equalsIgnoreCase (attributeName))
  11866. {
  11867. tchar firstChar = att->value[0];
  11868. if (CharacterFunctions::isWhitespace (firstChar))
  11869. firstChar = att->value.trimStart() [0];
  11870. return firstChar == T('1')
  11871. || firstChar == T('t')
  11872. || firstChar == T('y')
  11873. || firstChar == T('T')
  11874. || firstChar == T('Y');
  11875. }
  11876. att = att->next;
  11877. }
  11878. return defaultReturnValue;
  11879. }
  11880. bool XmlElement::compareAttribute (const tchar* const attributeName,
  11881. const tchar* const stringToCompareAgainst,
  11882. const bool ignoreCase) const throw()
  11883. {
  11884. const XmlAttributeNode* att = attributes;
  11885. while (att != 0)
  11886. {
  11887. if (att->name.equalsIgnoreCase (attributeName))
  11888. {
  11889. if (ignoreCase)
  11890. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11891. else
  11892. return att->value == stringToCompareAgainst;
  11893. }
  11894. att = att->next;
  11895. }
  11896. return false;
  11897. }
  11898. void XmlElement::setAttribute (const tchar* const attributeName,
  11899. const String& value) throw()
  11900. {
  11901. #ifdef JUCE_DEBUG
  11902. // check the identifier being passed in is legal..
  11903. const tchar* t = attributeName;
  11904. while (*t != 0)
  11905. {
  11906. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11907. || *t == T('_')
  11908. || *t == T('-')
  11909. || *t == T(':'));
  11910. ++t;
  11911. }
  11912. #endif
  11913. if (attributes == 0)
  11914. {
  11915. attributes = new XmlAttributeNode (attributeName, value);
  11916. }
  11917. else
  11918. {
  11919. XmlAttributeNode* att = attributes;
  11920. for (;;)
  11921. {
  11922. if (att->name.equalsIgnoreCase (attributeName))
  11923. {
  11924. att->value = value;
  11925. break;
  11926. }
  11927. else if (att->next == 0)
  11928. {
  11929. att->next = new XmlAttributeNode (attributeName, value);
  11930. break;
  11931. }
  11932. att = att->next;
  11933. }
  11934. }
  11935. }
  11936. void XmlElement::setAttribute (const tchar* const attributeName,
  11937. const tchar* const text) throw()
  11938. {
  11939. setAttribute (attributeName, String (text));
  11940. }
  11941. void XmlElement::setAttribute (const tchar* const attributeName,
  11942. const int number) throw()
  11943. {
  11944. setAttribute (attributeName, String (number));
  11945. }
  11946. void XmlElement::setAttribute (const tchar* const attributeName,
  11947. const double number) throw()
  11948. {
  11949. tchar buffer [40];
  11950. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  11951. setAttribute (attributeName, buffer);
  11952. }
  11953. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  11954. {
  11955. XmlAttributeNode* att = attributes;
  11956. XmlAttributeNode* lastAtt = 0;
  11957. while (att != 0)
  11958. {
  11959. if (att->name.equalsIgnoreCase (attributeName))
  11960. {
  11961. if (lastAtt == 0)
  11962. attributes = att->next;
  11963. else
  11964. lastAtt->next = att->next;
  11965. delete att;
  11966. break;
  11967. }
  11968. lastAtt = att;
  11969. att = att->next;
  11970. }
  11971. }
  11972. void XmlElement::removeAllAttributes() throw()
  11973. {
  11974. while (attributes != 0)
  11975. {
  11976. XmlAttributeNode* const nextAtt = attributes->next;
  11977. delete attributes;
  11978. attributes = nextAtt;
  11979. }
  11980. }
  11981. int XmlElement::getNumChildElements() const throw()
  11982. {
  11983. int count = 0;
  11984. const XmlElement* child = firstChildElement;
  11985. while (child != 0)
  11986. {
  11987. ++count;
  11988. child = child->nextElement;
  11989. }
  11990. return count;
  11991. }
  11992. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11993. {
  11994. int count = 0;
  11995. XmlElement* child = firstChildElement;
  11996. while (child != 0 && count < index)
  11997. {
  11998. child = child->nextElement;
  11999. ++count;
  12000. }
  12001. return child;
  12002. }
  12003. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  12004. {
  12005. XmlElement* child = firstChildElement;
  12006. while (child != 0)
  12007. {
  12008. if (child->hasTagName (childName))
  12009. break;
  12010. child = child->nextElement;
  12011. }
  12012. return child;
  12013. }
  12014. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12015. {
  12016. if (newNode != 0)
  12017. {
  12018. if (firstChildElement == 0)
  12019. {
  12020. firstChildElement = newNode;
  12021. }
  12022. else
  12023. {
  12024. XmlElement* child = firstChildElement;
  12025. while (child->nextElement != 0)
  12026. child = child->nextElement;
  12027. child->nextElement = newNode;
  12028. // if this is non-zero, then something's probably
  12029. // gone wrong..
  12030. jassert (newNode->nextElement == 0);
  12031. }
  12032. }
  12033. }
  12034. void XmlElement::insertChildElement (XmlElement* const newNode,
  12035. int indexToInsertAt) throw()
  12036. {
  12037. if (newNode != 0)
  12038. {
  12039. removeChildElement (newNode, false);
  12040. if (indexToInsertAt == 0)
  12041. {
  12042. newNode->nextElement = firstChildElement;
  12043. firstChildElement = newNode;
  12044. }
  12045. else
  12046. {
  12047. if (firstChildElement == 0)
  12048. {
  12049. firstChildElement = newNode;
  12050. }
  12051. else
  12052. {
  12053. if (indexToInsertAt < 0)
  12054. indexToInsertAt = INT_MAX;
  12055. XmlElement* child = firstChildElement;
  12056. while (child->nextElement != 0 && --indexToInsertAt > 0)
  12057. child = child->nextElement;
  12058. newNode->nextElement = child->nextElement;
  12059. child->nextElement = newNode;
  12060. }
  12061. }
  12062. }
  12063. }
  12064. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12065. XmlElement* const newNode) throw()
  12066. {
  12067. if (newNode != 0)
  12068. {
  12069. XmlElement* child = firstChildElement;
  12070. XmlElement* previousNode = 0;
  12071. while (child != 0)
  12072. {
  12073. if (child == currentChildElement)
  12074. {
  12075. if (child != newNode)
  12076. {
  12077. if (previousNode == 0)
  12078. firstChildElement = newNode;
  12079. else
  12080. previousNode->nextElement = newNode;
  12081. newNode->nextElement = child->nextElement;
  12082. delete child;
  12083. }
  12084. return true;
  12085. }
  12086. previousNode = child;
  12087. child = child->nextElement;
  12088. }
  12089. }
  12090. return false;
  12091. }
  12092. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12093. const bool shouldDeleteTheChild) throw()
  12094. {
  12095. if (childToRemove != 0)
  12096. {
  12097. if (firstChildElement == childToRemove)
  12098. {
  12099. firstChildElement = childToRemove->nextElement;
  12100. childToRemove->nextElement = 0;
  12101. }
  12102. else
  12103. {
  12104. XmlElement* child = firstChildElement;
  12105. XmlElement* last = 0;
  12106. while (child != 0)
  12107. {
  12108. if (child == childToRemove)
  12109. {
  12110. if (last == 0)
  12111. firstChildElement = child->nextElement;
  12112. else
  12113. last->nextElement = child->nextElement;
  12114. childToRemove->nextElement = 0;
  12115. break;
  12116. }
  12117. last = child;
  12118. child = child->nextElement;
  12119. }
  12120. }
  12121. if (shouldDeleteTheChild)
  12122. delete childToRemove;
  12123. }
  12124. }
  12125. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12126. const bool ignoreOrderOfAttributes) const throw()
  12127. {
  12128. if (this != other)
  12129. {
  12130. if (other == 0 || tagName != other->tagName)
  12131. {
  12132. return false;
  12133. }
  12134. if (ignoreOrderOfAttributes)
  12135. {
  12136. int totalAtts = 0;
  12137. const XmlAttributeNode* att = attributes;
  12138. while (att != 0)
  12139. {
  12140. if (! other->compareAttribute (att->name, att->value))
  12141. return false;
  12142. att = att->next;
  12143. ++totalAtts;
  12144. }
  12145. if (totalAtts != other->getNumAttributes())
  12146. return false;
  12147. }
  12148. else
  12149. {
  12150. const XmlAttributeNode* thisAtt = attributes;
  12151. const XmlAttributeNode* otherAtt = other->attributes;
  12152. for (;;)
  12153. {
  12154. if (thisAtt == 0 || otherAtt == 0)
  12155. {
  12156. if (thisAtt == otherAtt) // both 0, so it's a match
  12157. break;
  12158. return false;
  12159. }
  12160. if (thisAtt->name != otherAtt->name
  12161. || thisAtt->value != otherAtt->value)
  12162. {
  12163. return false;
  12164. }
  12165. thisAtt = thisAtt->next;
  12166. otherAtt = otherAtt->next;
  12167. }
  12168. }
  12169. const XmlElement* thisChild = firstChildElement;
  12170. const XmlElement* otherChild = other->firstChildElement;
  12171. for (;;)
  12172. {
  12173. if (thisChild == 0 || otherChild == 0)
  12174. {
  12175. if (thisChild == otherChild) // both 0, so it's a match
  12176. break;
  12177. return false;
  12178. }
  12179. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12180. return false;
  12181. thisChild = thisChild->nextElement;
  12182. otherChild = otherChild->nextElement;
  12183. }
  12184. }
  12185. return true;
  12186. }
  12187. void XmlElement::deleteAllChildElements() throw()
  12188. {
  12189. while (firstChildElement != 0)
  12190. {
  12191. XmlElement* const nextChild = firstChildElement->nextElement;
  12192. delete firstChildElement;
  12193. firstChildElement = nextChild;
  12194. }
  12195. }
  12196. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  12197. {
  12198. XmlElement* child = firstChildElement;
  12199. while (child != 0)
  12200. {
  12201. if (child->hasTagName (name))
  12202. {
  12203. XmlElement* const nextChild = child->nextElement;
  12204. removeChildElement (child, true);
  12205. child = nextChild;
  12206. }
  12207. else
  12208. {
  12209. child = child->nextElement;
  12210. }
  12211. }
  12212. }
  12213. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12214. {
  12215. const XmlElement* child = firstChildElement;
  12216. while (child != 0)
  12217. {
  12218. if (child == possibleChild)
  12219. return true;
  12220. child = child->nextElement;
  12221. }
  12222. return false;
  12223. }
  12224. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12225. {
  12226. if (this == elementToLookFor || elementToLookFor == 0)
  12227. return 0;
  12228. XmlElement* child = firstChildElement;
  12229. while (child != 0)
  12230. {
  12231. if (elementToLookFor == child)
  12232. return this;
  12233. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12234. if (found != 0)
  12235. return found;
  12236. child = child->nextElement;
  12237. }
  12238. return 0;
  12239. }
  12240. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  12241. {
  12242. XmlElement** const elems = new XmlElement* [num];
  12243. XmlElement* e = firstChildElement;
  12244. int i = 0;
  12245. while (e != 0)
  12246. {
  12247. elems [i++] = e;
  12248. e = e->nextElement;
  12249. }
  12250. return elems;
  12251. }
  12252. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12253. {
  12254. XmlElement* e = firstChildElement = elems[0];
  12255. for (int i = 1; i < num; ++i)
  12256. {
  12257. e->nextElement = elems[i];
  12258. e = e->nextElement;
  12259. }
  12260. e->nextElement = 0;
  12261. }
  12262. bool XmlElement::isTextElement() const throw()
  12263. {
  12264. return tagName.isEmpty();
  12265. }
  12266. static const tchar* const juce_xmltextContentAttributeName = T("text");
  12267. const String XmlElement::getText() const throw()
  12268. {
  12269. jassert (isTextElement()); // you're trying to get the text from an element that
  12270. // isn't actually a text element.. If this contains text sub-nodes, you
  12271. // can use getAllSubText instead to
  12272. return getStringAttribute (juce_xmltextContentAttributeName);
  12273. }
  12274. void XmlElement::setText (const String& newText) throw()
  12275. {
  12276. if (isTextElement())
  12277. {
  12278. setAttribute (juce_xmltextContentAttributeName, newText);
  12279. }
  12280. else
  12281. {
  12282. jassertfalse // you can only change the text in a text element, not a normal one.
  12283. }
  12284. }
  12285. const String XmlElement::getAllSubText() const throw()
  12286. {
  12287. String result;
  12288. const XmlElement* child = firstChildElement;
  12289. while (child != 0)
  12290. {
  12291. if (child->isTextElement())
  12292. result += child->getText();
  12293. child = child->nextElement;
  12294. }
  12295. return result;
  12296. }
  12297. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  12298. const String& defaultReturnValue) const throw()
  12299. {
  12300. const XmlElement* const child = getChildByName (childTagName);
  12301. if (child != 0)
  12302. return child->getAllSubText();
  12303. return defaultReturnValue;
  12304. }
  12305. XmlElement* XmlElement::createTextElement (const String& text) throw()
  12306. {
  12307. XmlElement* const e = new XmlElement ((int) 0);
  12308. e->setAttribute (juce_xmltextContentAttributeName, text);
  12309. return e;
  12310. }
  12311. void XmlElement::addTextElement (const String& text) throw()
  12312. {
  12313. addChildElement (createTextElement (text));
  12314. }
  12315. void XmlElement::deleteAllTextElements() throw()
  12316. {
  12317. XmlElement* child = firstChildElement;
  12318. while (child != 0)
  12319. {
  12320. XmlElement* const next = child->nextElement;
  12321. if (child->isTextElement())
  12322. removeChildElement (child, true);
  12323. child = next;
  12324. }
  12325. }
  12326. END_JUCE_NAMESPACE
  12327. /********* End of inlined file: juce_XmlElement.cpp *********/
  12328. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  12329. BEGIN_JUCE_NAMESPACE
  12330. // (implemented in the platform-specific code files)
  12331. END_JUCE_NAMESPACE
  12332. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  12333. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  12334. BEGIN_JUCE_NAMESPACE
  12335. ReadWriteLock::ReadWriteLock() throw()
  12336. : numWaitingWriters (0),
  12337. numWriters (0),
  12338. writerThreadId (0)
  12339. {
  12340. }
  12341. ReadWriteLock::~ReadWriteLock() throw()
  12342. {
  12343. jassert (readerThreads.size() == 0);
  12344. jassert (numWriters == 0);
  12345. }
  12346. void ReadWriteLock::enterRead() const throw()
  12347. {
  12348. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12349. const ScopedLock sl (accessLock);
  12350. for (;;)
  12351. {
  12352. jassert (readerThreads.size() % 2 == 0);
  12353. int i;
  12354. for (i = 0; i < readerThreads.size(); i += 2)
  12355. if (readerThreads.getUnchecked(i) == threadId)
  12356. break;
  12357. if (i < readerThreads.size()
  12358. || numWriters + numWaitingWriters == 0
  12359. || (threadId == writerThreadId && numWriters > 0))
  12360. {
  12361. if (i < readerThreads.size())
  12362. {
  12363. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12364. }
  12365. else
  12366. {
  12367. readerThreads.add (threadId);
  12368. readerThreads.add ((Thread::ThreadID) 1);
  12369. }
  12370. return;
  12371. }
  12372. const ScopedUnlock ul (accessLock);
  12373. waitEvent.wait (100);
  12374. }
  12375. }
  12376. void ReadWriteLock::exitRead() const throw()
  12377. {
  12378. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12379. const ScopedLock sl (accessLock);
  12380. for (int i = 0; i < readerThreads.size(); i += 2)
  12381. {
  12382. if (readerThreads.getUnchecked(i) == threadId)
  12383. {
  12384. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12385. if (newCount == 0)
  12386. {
  12387. readerThreads.removeRange (i, 2);
  12388. waitEvent.signal();
  12389. }
  12390. else
  12391. {
  12392. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12393. }
  12394. return;
  12395. }
  12396. }
  12397. jassertfalse // unlocking a lock that wasn't locked..
  12398. }
  12399. void ReadWriteLock::enterWrite() const throw()
  12400. {
  12401. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12402. const ScopedLock sl (accessLock);
  12403. for (;;)
  12404. {
  12405. if (readerThreads.size() + numWriters == 0
  12406. || threadId == writerThreadId
  12407. || (readerThreads.size() == 2
  12408. && readerThreads.getUnchecked(0) == threadId))
  12409. {
  12410. writerThreadId = threadId;
  12411. ++numWriters;
  12412. break;
  12413. }
  12414. ++numWaitingWriters;
  12415. accessLock.exit();
  12416. waitEvent.wait (100);
  12417. accessLock.enter();
  12418. --numWaitingWriters;
  12419. }
  12420. }
  12421. bool ReadWriteLock::tryEnterWrite() const throw()
  12422. {
  12423. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12424. const ScopedLock sl (accessLock);
  12425. if (readerThreads.size() + numWriters == 0
  12426. || threadId == writerThreadId
  12427. || (readerThreads.size() == 2
  12428. && readerThreads.getUnchecked(0) == threadId))
  12429. {
  12430. writerThreadId = threadId;
  12431. ++numWriters;
  12432. return true;
  12433. }
  12434. return false;
  12435. }
  12436. void ReadWriteLock::exitWrite() const throw()
  12437. {
  12438. const ScopedLock sl (accessLock);
  12439. // check this thread actually had the lock..
  12440. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12441. if (--numWriters == 0)
  12442. {
  12443. writerThreadId = 0;
  12444. waitEvent.signal();
  12445. }
  12446. }
  12447. END_JUCE_NAMESPACE
  12448. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  12449. /********* Start of inlined file: juce_Thread.cpp *********/
  12450. BEGIN_JUCE_NAMESPACE
  12451. // these functions are implemented in the platform-specific code.
  12452. void* juce_createThread (void* userData) throw();
  12453. void juce_killThread (void* handle) throw();
  12454. bool juce_setThreadPriority (void* handle, int priority) throw();
  12455. void juce_setCurrentThreadName (const String& name) throw();
  12456. #if JUCE_WIN32
  12457. void juce_CloseThreadHandle (void* handle) throw();
  12458. #endif
  12459. static VoidArray runningThreads (4);
  12460. static CriticalSection runningThreadsLock;
  12461. void Thread::threadEntryPoint (Thread* const thread) throw()
  12462. {
  12463. {
  12464. const ScopedLock sl (runningThreadsLock);
  12465. runningThreads.add (thread);
  12466. }
  12467. JUCE_TRY
  12468. {
  12469. thread->threadId_ = Thread::getCurrentThreadId();
  12470. if (thread->threadName_.isNotEmpty())
  12471. juce_setCurrentThreadName (thread->threadName_);
  12472. if (thread->startSuspensionEvent_.wait (10000))
  12473. {
  12474. if (thread->affinityMask_ != 0)
  12475. setCurrentThreadAffinityMask (thread->affinityMask_);
  12476. thread->run();
  12477. }
  12478. }
  12479. JUCE_CATCH_ALL_ASSERT
  12480. {
  12481. const ScopedLock sl (runningThreadsLock);
  12482. jassert (runningThreads.contains (thread));
  12483. runningThreads.removeValue (thread);
  12484. }
  12485. #if JUCE_WIN32
  12486. juce_CloseThreadHandle (thread->threadHandle_);
  12487. #endif
  12488. thread->threadHandle_ = 0;
  12489. thread->threadId_ = 0;
  12490. }
  12491. // used to wrap the incoming call from the platform-specific code
  12492. void JUCE_API juce_threadEntryPoint (void* userData)
  12493. {
  12494. Thread::threadEntryPoint ((Thread*) userData);
  12495. }
  12496. Thread::Thread (const String& threadName)
  12497. : threadName_ (threadName),
  12498. threadHandle_ (0),
  12499. threadPriority_ (5),
  12500. threadId_ (0),
  12501. affinityMask_ (0),
  12502. threadShouldExit_ (false)
  12503. {
  12504. }
  12505. Thread::~Thread()
  12506. {
  12507. stopThread (100);
  12508. }
  12509. void Thread::startThread() throw()
  12510. {
  12511. const ScopedLock sl (startStopLock);
  12512. threadShouldExit_ = false;
  12513. if (threadHandle_ == 0)
  12514. {
  12515. threadHandle_ = juce_createThread ((void*) this);
  12516. juce_setThreadPriority (threadHandle_, threadPriority_);
  12517. startSuspensionEvent_.signal();
  12518. }
  12519. }
  12520. void Thread::startThread (const int priority) throw()
  12521. {
  12522. const ScopedLock sl (startStopLock);
  12523. if (threadHandle_ == 0)
  12524. {
  12525. threadPriority_ = priority;
  12526. startThread();
  12527. }
  12528. else
  12529. {
  12530. setPriority (priority);
  12531. }
  12532. }
  12533. bool Thread::isThreadRunning() const throw()
  12534. {
  12535. return threadHandle_ != 0;
  12536. }
  12537. void Thread::signalThreadShouldExit() throw()
  12538. {
  12539. threadShouldExit_ = true;
  12540. }
  12541. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  12542. {
  12543. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12544. jassert (getThreadId() != getCurrentThreadId());
  12545. const int sleepMsPerIteration = 5;
  12546. int count = timeOutMilliseconds / sleepMsPerIteration;
  12547. while (isThreadRunning())
  12548. {
  12549. if (timeOutMilliseconds > 0 && --count < 0)
  12550. return false;
  12551. sleep (sleepMsPerIteration);
  12552. }
  12553. return true;
  12554. }
  12555. void Thread::stopThread (const int timeOutMilliseconds) throw()
  12556. {
  12557. // agh! You can't stop the thread that's calling this method! How on earth
  12558. // would that work??
  12559. jassert (getCurrentThreadId() != getThreadId());
  12560. const ScopedLock sl (startStopLock);
  12561. if (isThreadRunning())
  12562. {
  12563. signalThreadShouldExit();
  12564. notify();
  12565. if (timeOutMilliseconds != 0)
  12566. waitForThreadToExit (timeOutMilliseconds);
  12567. if (isThreadRunning())
  12568. {
  12569. // very bad karma if this point is reached, as
  12570. // there are bound to be locks and events left in
  12571. // silly states when a thread is killed by force..
  12572. jassertfalse
  12573. Logger::writeToLog ("!! killing thread by force !!");
  12574. juce_killThread (threadHandle_);
  12575. threadHandle_ = 0;
  12576. threadId_ = 0;
  12577. const ScopedLock sl (runningThreadsLock);
  12578. runningThreads.removeValue (this);
  12579. }
  12580. }
  12581. }
  12582. bool Thread::setPriority (const int priority) throw()
  12583. {
  12584. const ScopedLock sl (startStopLock);
  12585. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12586. if (worked)
  12587. threadPriority_ = priority;
  12588. return worked;
  12589. }
  12590. bool Thread::setCurrentThreadPriority (const int priority) throw()
  12591. {
  12592. return juce_setThreadPriority (0, priority);
  12593. }
  12594. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  12595. {
  12596. affinityMask_ = affinityMask;
  12597. }
  12598. Thread::ThreadID Thread::getThreadId() const throw()
  12599. {
  12600. return threadId_;
  12601. }
  12602. bool Thread::wait (const int timeOutMilliseconds) const throw()
  12603. {
  12604. return defaultEvent_.wait (timeOutMilliseconds);
  12605. }
  12606. void Thread::notify() const throw()
  12607. {
  12608. defaultEvent_.signal();
  12609. }
  12610. int Thread::getNumRunningThreads() throw()
  12611. {
  12612. return runningThreads.size();
  12613. }
  12614. Thread* Thread::getCurrentThread() throw()
  12615. {
  12616. const ThreadID thisId = getCurrentThreadId();
  12617. const ScopedLock sl (runningThreadsLock);
  12618. for (int i = runningThreads.size(); --i >= 0;)
  12619. {
  12620. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  12621. if (t->threadId_ == thisId)
  12622. return t;
  12623. }
  12624. return 0;
  12625. }
  12626. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  12627. {
  12628. {
  12629. const ScopedLock sl (runningThreadsLock);
  12630. for (int i = runningThreads.size(); --i >= 0;)
  12631. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  12632. }
  12633. for (;;)
  12634. {
  12635. runningThreadsLock.enter();
  12636. Thread* const t = (Thread*) runningThreads[0];
  12637. runningThreadsLock.exit();
  12638. if (t == 0)
  12639. break;
  12640. t->stopThread (timeOutMilliseconds);
  12641. }
  12642. }
  12643. END_JUCE_NAMESPACE
  12644. /********* End of inlined file: juce_Thread.cpp *********/
  12645. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  12646. BEGIN_JUCE_NAMESPACE
  12647. ThreadPoolJob::ThreadPoolJob (const String& name)
  12648. : jobName (name),
  12649. pool (0),
  12650. shouldStop (false),
  12651. isActive (false),
  12652. shouldBeDeleted (false)
  12653. {
  12654. }
  12655. ThreadPoolJob::~ThreadPoolJob()
  12656. {
  12657. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12658. // to remove it first!
  12659. jassert (pool == 0 || ! pool->contains (this));
  12660. }
  12661. const String ThreadPoolJob::getJobName() const throw()
  12662. {
  12663. return jobName;
  12664. }
  12665. void ThreadPoolJob::setJobName (const String& newName) throw()
  12666. {
  12667. jobName = newName;
  12668. }
  12669. void ThreadPoolJob::signalJobShouldExit() throw()
  12670. {
  12671. shouldStop = true;
  12672. }
  12673. class ThreadPoolThread : public Thread
  12674. {
  12675. ThreadPool& pool;
  12676. bool volatile busy;
  12677. ThreadPoolThread (const ThreadPoolThread&);
  12678. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  12679. public:
  12680. ThreadPoolThread (ThreadPool& pool_)
  12681. : Thread (T("Pool")),
  12682. pool (pool_),
  12683. busy (false)
  12684. {
  12685. }
  12686. ~ThreadPoolThread()
  12687. {
  12688. }
  12689. void run()
  12690. {
  12691. while (! threadShouldExit())
  12692. {
  12693. if (! pool.runNextJob())
  12694. wait (500);
  12695. }
  12696. }
  12697. };
  12698. ThreadPool::ThreadPool (const int numThreads_,
  12699. const bool startThreadsOnlyWhenNeeded,
  12700. const int stopThreadsWhenNotUsedTimeoutMs)
  12701. : numThreads (jmax (1, numThreads_)),
  12702. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12703. priority (5)
  12704. {
  12705. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  12706. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  12707. for (int i = numThreads; --i >= 0;)
  12708. threads[i] = new ThreadPoolThread (*this);
  12709. if (! startThreadsOnlyWhenNeeded)
  12710. for (int i = numThreads; --i >= 0;)
  12711. threads[i]->startThread (priority);
  12712. }
  12713. ThreadPool::~ThreadPool()
  12714. {
  12715. removeAllJobs (true, 4000);
  12716. int i;
  12717. for (i = numThreads; --i >= 0;)
  12718. threads[i]->signalThreadShouldExit();
  12719. for (i = numThreads; --i >= 0;)
  12720. {
  12721. threads[i]->stopThread (500);
  12722. delete threads[i];
  12723. }
  12724. juce_free (threads);
  12725. }
  12726. void ThreadPool::addJob (ThreadPoolJob* const job)
  12727. {
  12728. jassert (job->pool == 0);
  12729. if (job->pool == 0)
  12730. {
  12731. job->pool = this;
  12732. job->shouldStop = false;
  12733. job->isActive = false;
  12734. lock.enter();
  12735. jobs.add (job);
  12736. int numRunning = 0;
  12737. int i;
  12738. for (i = numThreads; --i >= 0;)
  12739. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  12740. ++numRunning;
  12741. if (numRunning < numThreads)
  12742. {
  12743. bool startedOne = false;
  12744. int n = 1000;
  12745. while (--n >= 0 && ! startedOne)
  12746. {
  12747. for (int i = numThreads; --i >= 0;)
  12748. {
  12749. if (! threads[i]->isThreadRunning())
  12750. {
  12751. threads[i]->startThread (priority);
  12752. startedOne = true;
  12753. break;
  12754. }
  12755. }
  12756. if (! startedOne)
  12757. Thread::sleep (2);
  12758. }
  12759. }
  12760. lock.exit();
  12761. for (i = numThreads; --i >= 0;)
  12762. threads[i]->notify();
  12763. }
  12764. }
  12765. int ThreadPool::getNumJobs() const throw()
  12766. {
  12767. return jobs.size();
  12768. }
  12769. ThreadPoolJob* ThreadPool::getJob (const int index) const throw()
  12770. {
  12771. const ScopedLock sl (lock);
  12772. return (ThreadPoolJob*) jobs [index];
  12773. }
  12774. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  12775. {
  12776. const ScopedLock sl (lock);
  12777. return jobs.contains ((void*) job);
  12778. }
  12779. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12780. {
  12781. const ScopedLock sl (lock);
  12782. return jobs.contains ((void*) job) && job->isActive;
  12783. }
  12784. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12785. const int timeOutMs) const
  12786. {
  12787. if (job != 0)
  12788. {
  12789. const uint32 start = Time::getMillisecondCounter();
  12790. while (contains (job))
  12791. {
  12792. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12793. return false;
  12794. jobFinishedSignal.wait (2);
  12795. }
  12796. }
  12797. return true;
  12798. }
  12799. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12800. const bool interruptIfRunning,
  12801. const int timeOutMs)
  12802. {
  12803. if (job != 0)
  12804. {
  12805. lock.enter();
  12806. if (jobs.contains (job))
  12807. {
  12808. if (job->isActive)
  12809. {
  12810. if (interruptIfRunning)
  12811. job->signalJobShouldExit();
  12812. lock.exit();
  12813. return waitForJobToFinish (job, timeOutMs);
  12814. }
  12815. else
  12816. {
  12817. jobs.removeValue (job);
  12818. }
  12819. }
  12820. lock.exit();
  12821. }
  12822. return true;
  12823. }
  12824. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12825. const int timeOutMs,
  12826. const bool deleteInactiveJobs)
  12827. {
  12828. lock.enter();
  12829. for (int i = jobs.size(); --i >= 0;)
  12830. {
  12831. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  12832. if (job->isActive)
  12833. {
  12834. if (interruptRunningJobs)
  12835. job->signalJobShouldExit();
  12836. }
  12837. else
  12838. {
  12839. jobs.remove (i);
  12840. if (deleteInactiveJobs)
  12841. delete job;
  12842. }
  12843. }
  12844. lock.exit();
  12845. const uint32 start = Time::getMillisecondCounter();
  12846. while (jobs.size() > 0)
  12847. {
  12848. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12849. return false;
  12850. jobFinishedSignal.wait (2);
  12851. }
  12852. return true;
  12853. }
  12854. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const throw()
  12855. {
  12856. StringArray s;
  12857. const ScopedLock sl (lock);
  12858. for (int i = 0; i < jobs.size(); ++i)
  12859. {
  12860. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  12861. if (job->isActive || ! onlyReturnActiveJobs)
  12862. s.add (job->getJobName());
  12863. }
  12864. return s;
  12865. }
  12866. bool ThreadPool::setThreadPriorities (const int newPriority)
  12867. {
  12868. bool ok = true;
  12869. if (priority != newPriority)
  12870. {
  12871. priority = newPriority;
  12872. for (int i = numThreads; --i >= 0;)
  12873. if (! threads[i]->setPriority (newPriority))
  12874. ok = false;
  12875. }
  12876. return ok;
  12877. }
  12878. bool ThreadPool::runNextJob()
  12879. {
  12880. lock.enter();
  12881. ThreadPoolJob* job = 0;
  12882. for (int i = 0; i < jobs.size(); ++i)
  12883. {
  12884. job = (ThreadPoolJob*) jobs [i];
  12885. if (job != 0 && ! (job->isActive || job->shouldStop))
  12886. break;
  12887. job = 0;
  12888. }
  12889. if (job != 0)
  12890. {
  12891. job->isActive = true;
  12892. lock.exit();
  12893. JUCE_TRY
  12894. {
  12895. ThreadPoolJob::JobStatus result = job->runJob();
  12896. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12897. const ScopedLock sl (lock);
  12898. if (jobs.contains (job))
  12899. {
  12900. job->isActive = false;
  12901. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12902. {
  12903. job->pool = 0;
  12904. job->shouldStop = true;
  12905. jobs.removeValue (job);
  12906. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12907. delete job;
  12908. jobFinishedSignal.signal();
  12909. }
  12910. else
  12911. {
  12912. // move the job to the end of the queue if it wants another go
  12913. jobs.move (jobs.indexOf (job), -1);
  12914. }
  12915. }
  12916. }
  12917. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12918. catch (...)
  12919. {
  12920. lock.enter();
  12921. jobs.removeValue (job);
  12922. lock.exit();
  12923. }
  12924. #endif
  12925. }
  12926. else
  12927. {
  12928. lock.exit();
  12929. if (threadStopTimeout > 0
  12930. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12931. {
  12932. const ScopedLock sl (lock);
  12933. if (jobs.size() == 0)
  12934. for (int i = numThreads; --i >= 0;)
  12935. threads[i]->signalThreadShouldExit();
  12936. }
  12937. else
  12938. {
  12939. return false;
  12940. }
  12941. }
  12942. return true;
  12943. }
  12944. END_JUCE_NAMESPACE
  12945. /********* End of inlined file: juce_ThreadPool.cpp *********/
  12946. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  12947. BEGIN_JUCE_NAMESPACE
  12948. TimeSliceThread::TimeSliceThread (const String& threadName)
  12949. : Thread (threadName),
  12950. index (0),
  12951. clientBeingCalled (0),
  12952. clientsChanged (false)
  12953. {
  12954. }
  12955. TimeSliceThread::~TimeSliceThread()
  12956. {
  12957. stopThread (2000);
  12958. }
  12959. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12960. {
  12961. const ScopedLock sl (listLock);
  12962. clients.addIfNotAlreadyThere (client);
  12963. clientsChanged = true;
  12964. notify();
  12965. }
  12966. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12967. {
  12968. const ScopedLock sl1 (listLock);
  12969. clientsChanged = true;
  12970. // if there's a chance we're in the middle of calling this client, we need to
  12971. // also lock the outer lock..
  12972. if (clientBeingCalled == client)
  12973. {
  12974. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12975. const ScopedLock sl1 (callbackLock);
  12976. const ScopedLock sl2 (listLock);
  12977. clients.removeValue (client);
  12978. }
  12979. else
  12980. {
  12981. clients.removeValue (client);
  12982. }
  12983. }
  12984. int TimeSliceThread::getNumClients() const throw()
  12985. {
  12986. return clients.size();
  12987. }
  12988. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  12989. {
  12990. const ScopedLock sl (listLock);
  12991. return clients [index];
  12992. }
  12993. void TimeSliceThread::run()
  12994. {
  12995. int numCallsSinceBusy = 0;
  12996. while (! threadShouldExit())
  12997. {
  12998. int timeToWait = 500;
  12999. {
  13000. const ScopedLock sl (callbackLock);
  13001. {
  13002. const ScopedLock sl (listLock);
  13003. if (clients.size() > 0)
  13004. {
  13005. index = (index + 1) % clients.size();
  13006. clientBeingCalled = clients [index];
  13007. }
  13008. else
  13009. {
  13010. index = 0;
  13011. clientBeingCalled = 0;
  13012. }
  13013. if (clientsChanged)
  13014. {
  13015. clientsChanged = false;
  13016. numCallsSinceBusy = 0;
  13017. }
  13018. }
  13019. if (clientBeingCalled != 0)
  13020. {
  13021. if (clientBeingCalled->useTimeSlice())
  13022. numCallsSinceBusy = 0;
  13023. else
  13024. ++numCallsSinceBusy;
  13025. if (numCallsSinceBusy >= clients.size())
  13026. timeToWait = 500;
  13027. else if (index == 0)
  13028. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13029. else
  13030. timeToWait = 0;
  13031. }
  13032. }
  13033. if (timeToWait > 0)
  13034. wait (timeToWait);
  13035. }
  13036. }
  13037. END_JUCE_NAMESPACE
  13038. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  13039. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  13040. /********* Start of inlined file: juce_Application.cpp *********/
  13041. #if JUCE_MSVC
  13042. #pragma warning (push)
  13043. #pragma warning (disable: 4245 4514 4100)
  13044. #include <crtdbg.h>
  13045. #pragma warning (pop)
  13046. #endif
  13047. BEGIN_JUCE_NAMESPACE
  13048. void juce_setCurrentThreadName (const String& name) throw();
  13049. static JUCEApplication* appInstance = 0;
  13050. JUCEApplication::JUCEApplication()
  13051. : appReturnValue (0),
  13052. stillInitialising (true),
  13053. appLock (0)
  13054. {
  13055. }
  13056. JUCEApplication::~JUCEApplication()
  13057. {
  13058. if (appLock != 0)
  13059. {
  13060. appLock->exit();
  13061. delete appLock;
  13062. }
  13063. }
  13064. JUCEApplication* JUCEApplication::getInstance() throw()
  13065. {
  13066. return appInstance;
  13067. }
  13068. bool JUCEApplication::isInitialising() const throw()
  13069. {
  13070. return stillInitialising;
  13071. }
  13072. const String JUCEApplication::getApplicationVersion()
  13073. {
  13074. return String::empty;
  13075. }
  13076. bool JUCEApplication::moreThanOneInstanceAllowed()
  13077. {
  13078. return true;
  13079. }
  13080. void JUCEApplication::anotherInstanceStarted (const String&)
  13081. {
  13082. }
  13083. void JUCEApplication::systemRequestedQuit()
  13084. {
  13085. quit();
  13086. }
  13087. void JUCEApplication::quit()
  13088. {
  13089. MessageManager::getInstance()->stopDispatchLoop();
  13090. }
  13091. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13092. {
  13093. appReturnValue = newReturnValue;
  13094. }
  13095. void JUCEApplication::unhandledException (const std::exception*,
  13096. const String&,
  13097. const int)
  13098. {
  13099. jassertfalse
  13100. }
  13101. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13102. const char* const sourceFile,
  13103. const int lineNumber)
  13104. {
  13105. if (appInstance != 0)
  13106. appInstance->unhandledException (e, sourceFile, lineNumber);
  13107. }
  13108. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13109. {
  13110. return 0;
  13111. }
  13112. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13113. {
  13114. commands.add (StandardApplicationCommandIDs::quit);
  13115. }
  13116. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13117. {
  13118. if (commandID == StandardApplicationCommandIDs::quit)
  13119. {
  13120. result.setInfo ("Quit",
  13121. "Quits the application",
  13122. "Application",
  13123. 0);
  13124. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  13125. }
  13126. }
  13127. bool JUCEApplication::perform (const InvocationInfo& info)
  13128. {
  13129. if (info.commandID == StandardApplicationCommandIDs::quit)
  13130. {
  13131. systemRequestedQuit();
  13132. return true;
  13133. }
  13134. return false;
  13135. }
  13136. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13137. {
  13138. if (! app->initialiseApp (commandLine))
  13139. return 0;
  13140. // now loop until a quit message is received..
  13141. JUCE_TRY
  13142. {
  13143. MessageManager::getInstance()->runDispatchLoop();
  13144. }
  13145. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13146. catch (const std::exception& e)
  13147. {
  13148. app->unhandledException (&e, __FILE__, __LINE__);
  13149. }
  13150. catch (...)
  13151. {
  13152. app->unhandledException (0, __FILE__, __LINE__);
  13153. }
  13154. #endif
  13155. return shutdownAppAndClearUp();
  13156. }
  13157. bool JUCEApplication::initialiseApp (String& commandLine)
  13158. {
  13159. jassert (appInstance == 0);
  13160. appInstance = this;
  13161. commandLineParameters = commandLine.trim();
  13162. commandLine = String::empty;
  13163. initialiseJuce_GUI();
  13164. InterProcessLock* appLock = 0;
  13165. if (! moreThanOneInstanceAllowed())
  13166. {
  13167. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13168. if (! appLock->enter(0))
  13169. {
  13170. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13171. delete appInstance;
  13172. appInstance = 0;
  13173. DBG ("Another instance is running - quitting...");
  13174. return false;
  13175. }
  13176. }
  13177. // let the app do its setting-up..
  13178. initialise (commandLineParameters);
  13179. // register for broadcast new app messages
  13180. MessageManager::getInstance()->registerBroadcastListener (this);
  13181. stillInitialising = false;
  13182. return true;
  13183. }
  13184. int JUCEApplication::shutdownAppAndClearUp()
  13185. {
  13186. jassert (appInstance != 0);
  13187. JUCEApplication* const app = appInstance;
  13188. int returnValue = 0;
  13189. MessageManager::getInstance()->deregisterBroadcastListener (app);
  13190. static bool reentrancyCheck = false;
  13191. if (! reentrancyCheck)
  13192. {
  13193. reentrancyCheck = true;
  13194. JUCE_TRY
  13195. {
  13196. // give the app a chance to clean up..
  13197. app->shutdown();
  13198. }
  13199. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13200. catch (const std::exception& e)
  13201. {
  13202. app->unhandledException (&e, __FILE__, __LINE__);
  13203. }
  13204. catch (...)
  13205. {
  13206. app->unhandledException (0, __FILE__, __LINE__);
  13207. }
  13208. #endif
  13209. JUCE_TRY
  13210. {
  13211. shutdownJuce_GUI();
  13212. returnValue = app->getApplicationReturnValue();
  13213. appInstance = 0;
  13214. delete app;
  13215. }
  13216. JUCE_CATCH_ALL_ASSERT
  13217. reentrancyCheck = false;
  13218. }
  13219. return returnValue;
  13220. }
  13221. #if JUCE_IPHONE
  13222. extern int juce_IPhoneMain (int argc, char* argv[], JUCEApplication* app);
  13223. #endif
  13224. int JUCEApplication::main (int argc, char* argv[],
  13225. JUCEApplication* const newApp)
  13226. {
  13227. #if JUCE_IPHONE
  13228. const ScopedAutoReleasePool pool;
  13229. return juce_IPhoneMain (argc, argv, newApp);
  13230. #else
  13231. #if JUCE_MAC
  13232. const ScopedAutoReleasePool pool;
  13233. #endif
  13234. String cmd;
  13235. for (int i = 1; i < argc; ++i)
  13236. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  13237. return JUCEApplication::main (cmd, newApp);
  13238. #endif
  13239. }
  13240. void JUCEApplication::actionListenerCallback (const String& message)
  13241. {
  13242. if (message.startsWith (getApplicationName() + "/"))
  13243. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13244. }
  13245. static bool juceInitialisedGUI = false;
  13246. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13247. {
  13248. if (! juceInitialisedGUI)
  13249. {
  13250. #if JUCE_MAC || JUCE_IPHONE
  13251. const ScopedAutoReleasePool pool;
  13252. #endif
  13253. juceInitialisedGUI = true;
  13254. initialiseJuce_NonGUI();
  13255. MessageManager::getInstance();
  13256. LookAndFeel::setDefaultLookAndFeel (0);
  13257. juce_setCurrentThreadName ("Juce Message Thread");
  13258. #if JUCE_WINDOWS && JUCE_DEBUG
  13259. // This section is just for catching people who mess up their project settings and
  13260. // turn RTTI off..
  13261. try
  13262. {
  13263. TextButton tb (String::empty);
  13264. Component* c = &tb;
  13265. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13266. c = dynamic_cast <Button*> (c);
  13267. }
  13268. catch (...)
  13269. {
  13270. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13271. // got as far as this catch statement, then why haven't you got exception catching
  13272. // turned on in the debugger???
  13273. jassertfalse
  13274. }
  13275. #endif
  13276. }
  13277. }
  13278. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13279. {
  13280. if (juceInitialisedGUI)
  13281. {
  13282. #if JUCE_MAC
  13283. const ScopedAutoReleasePool pool;
  13284. #endif
  13285. {
  13286. DeletedAtShutdown::deleteAll();
  13287. LookAndFeel::clearDefaultLookAndFeel();
  13288. }
  13289. delete MessageManager::getInstance();
  13290. shutdownJuce_NonGUI();
  13291. juceInitialisedGUI = false;
  13292. }
  13293. }
  13294. END_JUCE_NAMESPACE
  13295. /********* End of inlined file: juce_Application.cpp *********/
  13296. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13297. BEGIN_JUCE_NAMESPACE
  13298. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13299. : commandID (commandID_),
  13300. flags (0)
  13301. {
  13302. }
  13303. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13304. const String& description_,
  13305. const String& categoryName_,
  13306. const int flags_) throw()
  13307. {
  13308. shortName = shortName_;
  13309. description = description_;
  13310. categoryName = categoryName_;
  13311. flags = flags_;
  13312. }
  13313. void ApplicationCommandInfo::setActive (const bool b) throw()
  13314. {
  13315. if (b)
  13316. flags &= ~isDisabled;
  13317. else
  13318. flags |= isDisabled;
  13319. }
  13320. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13321. {
  13322. if (b)
  13323. flags |= isTicked;
  13324. else
  13325. flags &= ~isTicked;
  13326. }
  13327. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13328. {
  13329. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13330. }
  13331. END_JUCE_NAMESPACE
  13332. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13333. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  13334. BEGIN_JUCE_NAMESPACE
  13335. ApplicationCommandManager::ApplicationCommandManager()
  13336. : listeners (8),
  13337. firstTarget (0)
  13338. {
  13339. keyMappings = new KeyPressMappingSet (this);
  13340. Desktop::getInstance().addFocusChangeListener (this);
  13341. }
  13342. ApplicationCommandManager::~ApplicationCommandManager()
  13343. {
  13344. Desktop::getInstance().removeFocusChangeListener (this);
  13345. deleteAndZero (keyMappings);
  13346. }
  13347. void ApplicationCommandManager::clearCommands()
  13348. {
  13349. commands.clear();
  13350. keyMappings->clearAllKeyPresses();
  13351. triggerAsyncUpdate();
  13352. }
  13353. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13354. {
  13355. // zero isn't a valid command ID!
  13356. jassert (newCommand.commandID != 0);
  13357. // the name isn't optional!
  13358. jassert (newCommand.shortName.isNotEmpty());
  13359. if (getCommandForID (newCommand.commandID) == 0)
  13360. {
  13361. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13362. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13363. commands.add (newInfo);
  13364. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13365. triggerAsyncUpdate();
  13366. }
  13367. else
  13368. {
  13369. // trying to re-register the same command with different parameters?
  13370. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13371. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13372. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13373. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13374. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13375. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13376. }
  13377. }
  13378. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13379. {
  13380. if (target != 0)
  13381. {
  13382. Array <CommandID> commandIDs;
  13383. target->getAllCommands (commandIDs);
  13384. for (int i = 0; i < commandIDs.size(); ++i)
  13385. {
  13386. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13387. target->getCommandInfo (info.commandID, info);
  13388. registerCommand (info);
  13389. }
  13390. }
  13391. }
  13392. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13393. {
  13394. for (int i = commands.size(); --i >= 0;)
  13395. {
  13396. if (commands.getUnchecked (i)->commandID == commandID)
  13397. {
  13398. commands.remove (i);
  13399. triggerAsyncUpdate();
  13400. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13401. for (int j = keys.size(); --j >= 0;)
  13402. keyMappings->removeKeyPress (keys.getReference (j));
  13403. }
  13404. }
  13405. }
  13406. void ApplicationCommandManager::commandStatusChanged()
  13407. {
  13408. triggerAsyncUpdate();
  13409. }
  13410. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13411. {
  13412. for (int i = commands.size(); --i >= 0;)
  13413. if (commands.getUnchecked(i)->commandID == commandID)
  13414. return commands.getUnchecked(i);
  13415. return 0;
  13416. }
  13417. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13418. {
  13419. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13420. return (ci != 0) ? ci->shortName : String::empty;
  13421. }
  13422. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13423. {
  13424. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13425. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13426. : String::empty;
  13427. }
  13428. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13429. {
  13430. StringArray s;
  13431. for (int i = 0; i < commands.size(); ++i)
  13432. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13433. return s;
  13434. }
  13435. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13436. {
  13437. Array <CommandID> results (4);
  13438. for (int i = 0; i < commands.size(); ++i)
  13439. if (commands.getUnchecked(i)->categoryName == categoryName)
  13440. results.add (commands.getUnchecked(i)->commandID);
  13441. return results;
  13442. }
  13443. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13444. {
  13445. ApplicationCommandTarget::InvocationInfo info (commandID);
  13446. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13447. return invoke (info, asynchronously);
  13448. }
  13449. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13450. {
  13451. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13452. // manager first..
  13453. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13454. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13455. if (target == 0)
  13456. return false;
  13457. ApplicationCommandInfo commandInfo (0);
  13458. target->getCommandInfo (info_.commandID, commandInfo);
  13459. ApplicationCommandTarget::InvocationInfo info (info_);
  13460. info.commandFlags = commandInfo.flags;
  13461. sendListenerInvokeCallback (info);
  13462. const bool ok = target->invoke (info, asynchronously);
  13463. commandStatusChanged();
  13464. return ok;
  13465. }
  13466. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13467. {
  13468. return firstTarget != 0 ? firstTarget
  13469. : findDefaultComponentTarget();
  13470. }
  13471. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13472. {
  13473. firstTarget = newTarget;
  13474. }
  13475. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13476. ApplicationCommandInfo& upToDateInfo)
  13477. {
  13478. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13479. if (target == 0)
  13480. target = JUCEApplication::getInstance();
  13481. if (target != 0)
  13482. target = target->getTargetForCommand (commandID);
  13483. if (target != 0)
  13484. target->getCommandInfo (commandID, upToDateInfo);
  13485. return target;
  13486. }
  13487. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13488. {
  13489. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13490. if (target == 0 && c != 0)
  13491. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13492. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13493. return target;
  13494. }
  13495. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13496. {
  13497. Component* c = Component::getCurrentlyFocusedComponent();
  13498. if (c == 0)
  13499. {
  13500. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13501. if (activeWindow != 0)
  13502. {
  13503. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13504. if (c == 0)
  13505. c = activeWindow;
  13506. }
  13507. }
  13508. if (c == 0 && Process::isForegroundProcess())
  13509. {
  13510. // getting a bit desperate now - try all desktop comps..
  13511. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13512. {
  13513. ApplicationCommandTarget* const target
  13514. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13515. ->getPeer()->getLastFocusedSubcomponent());
  13516. if (target != 0)
  13517. return target;
  13518. }
  13519. }
  13520. if (c != 0)
  13521. {
  13522. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  13523. // if we're focused on a ResizableWindow, chances are that it's the content
  13524. // component that really should get the event. And if not, the event will
  13525. // still be passed up to the top level window anyway, so let's send it to the
  13526. // content comp.
  13527. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  13528. c = resizableWindow->getContentComponent();
  13529. ApplicationCommandTarget* const target = findTargetForComponent (c);
  13530. if (target != 0)
  13531. return target;
  13532. }
  13533. return JUCEApplication::getInstance();
  13534. }
  13535. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  13536. {
  13537. jassert (listener != 0);
  13538. if (listener != 0)
  13539. listeners.add (listener);
  13540. }
  13541. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  13542. {
  13543. listeners.removeValue (listener);
  13544. }
  13545. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  13546. {
  13547. for (int i = listeners.size(); --i >= 0;)
  13548. {
  13549. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  13550. i = jmin (i, listeners.size());
  13551. }
  13552. }
  13553. void ApplicationCommandManager::handleAsyncUpdate()
  13554. {
  13555. for (int i = listeners.size(); --i >= 0;)
  13556. {
  13557. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  13558. i = jmin (i, listeners.size());
  13559. }
  13560. }
  13561. void ApplicationCommandManager::globalFocusChanged (Component*)
  13562. {
  13563. commandStatusChanged();
  13564. }
  13565. END_JUCE_NAMESPACE
  13566. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  13567. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13568. BEGIN_JUCE_NAMESPACE
  13569. ApplicationCommandTarget::ApplicationCommandTarget()
  13570. : messageInvoker (0)
  13571. {
  13572. }
  13573. ApplicationCommandTarget::~ApplicationCommandTarget()
  13574. {
  13575. deleteAndZero (messageInvoker);
  13576. }
  13577. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  13578. {
  13579. if (isCommandActive (info.commandID))
  13580. {
  13581. if (async)
  13582. {
  13583. if (messageInvoker == 0)
  13584. messageInvoker = new CommandTargetMessageInvoker (this);
  13585. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  13586. return true;
  13587. }
  13588. else
  13589. {
  13590. const bool success = perform (info);
  13591. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  13592. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  13593. // returns the command's info.
  13594. return success;
  13595. }
  13596. }
  13597. return false;
  13598. }
  13599. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  13600. {
  13601. Component* c = dynamic_cast <Component*> (this);
  13602. if (c != 0)
  13603. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13604. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13605. return 0;
  13606. }
  13607. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  13608. {
  13609. ApplicationCommandTarget* target = this;
  13610. int depth = 0;
  13611. while (target != 0)
  13612. {
  13613. Array <CommandID> commandIDs;
  13614. target->getAllCommands (commandIDs);
  13615. if (commandIDs.contains (commandID))
  13616. return target;
  13617. target = target->getNextCommandTarget();
  13618. ++depth;
  13619. jassert (depth < 100); // could be a recursive command chain??
  13620. jassert (target != this); // definitely a recursive command chain!
  13621. if (depth > 100 || target == this)
  13622. break;
  13623. }
  13624. if (target == 0)
  13625. {
  13626. target = JUCEApplication::getInstance();
  13627. if (target != 0)
  13628. {
  13629. Array <CommandID> commandIDs;
  13630. target->getAllCommands (commandIDs);
  13631. if (commandIDs.contains (commandID))
  13632. return target;
  13633. }
  13634. }
  13635. return 0;
  13636. }
  13637. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  13638. {
  13639. ApplicationCommandInfo info (commandID);
  13640. info.flags = ApplicationCommandInfo::isDisabled;
  13641. getCommandInfo (commandID, info);
  13642. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  13643. }
  13644. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  13645. {
  13646. ApplicationCommandTarget* target = this;
  13647. int depth = 0;
  13648. while (target != 0)
  13649. {
  13650. if (target->tryToInvoke (info, async))
  13651. return true;
  13652. target = target->getNextCommandTarget();
  13653. ++depth;
  13654. jassert (depth < 100); // could be a recursive command chain??
  13655. jassert (target != this); // definitely a recursive command chain!
  13656. if (depth > 100 || target == this)
  13657. break;
  13658. }
  13659. if (target == 0)
  13660. {
  13661. target = JUCEApplication::getInstance();
  13662. if (target != 0)
  13663. return target->tryToInvoke (info, async);
  13664. }
  13665. return false;
  13666. }
  13667. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13668. {
  13669. ApplicationCommandTarget::InvocationInfo info (commandID);
  13670. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13671. return invoke (info, asynchronously);
  13672. }
  13673. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  13674. : commandID (commandID_),
  13675. commandFlags (0),
  13676. invocationMethod (direct),
  13677. originatingComponent (0),
  13678. isKeyDown (false),
  13679. millisecsSinceKeyPressed (0)
  13680. {
  13681. }
  13682. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  13683. : owner (owner_)
  13684. {
  13685. }
  13686. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  13687. {
  13688. }
  13689. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  13690. {
  13691. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  13692. owner->tryToInvoke (*info, false);
  13693. delete info;
  13694. }
  13695. END_JUCE_NAMESPACE
  13696. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13697. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  13698. BEGIN_JUCE_NAMESPACE
  13699. juce_ImplementSingleton (ApplicationProperties)
  13700. ApplicationProperties::ApplicationProperties() throw()
  13701. : userProps (0),
  13702. commonProps (0),
  13703. msBeforeSaving (3000),
  13704. options (PropertiesFile::storeAsBinary),
  13705. commonSettingsAreReadOnly (0)
  13706. {
  13707. }
  13708. ApplicationProperties::~ApplicationProperties()
  13709. {
  13710. closeFiles();
  13711. clearSingletonInstance();
  13712. }
  13713. void ApplicationProperties::setStorageParameters (const String& applicationName,
  13714. const String& fileNameSuffix,
  13715. const String& folderName_,
  13716. const int millisecondsBeforeSaving,
  13717. const int propertiesFileOptions) throw()
  13718. {
  13719. appName = applicationName;
  13720. fileSuffix = fileNameSuffix;
  13721. folderName = folderName_;
  13722. msBeforeSaving = millisecondsBeforeSaving;
  13723. options = propertiesFileOptions;
  13724. }
  13725. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  13726. const bool testCommonSettings,
  13727. const bool showWarningDialogOnFailure)
  13728. {
  13729. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  13730. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  13731. if (! (userOk && commonOk))
  13732. {
  13733. if (showWarningDialogOnFailure)
  13734. {
  13735. String filenames;
  13736. if (userProps != 0 && ! userOk)
  13737. filenames << '\n' << userProps->getFile().getFullPathName();
  13738. if (commonProps != 0 && ! commonOk)
  13739. filenames << '\n' << commonProps->getFile().getFullPathName();
  13740. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13741. appName + TRANS(" - Unable to save settings"),
  13742. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  13743. + appName + TRANS(" needs to be able to write to the following files:\n")
  13744. + filenames
  13745. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  13746. }
  13747. return false;
  13748. }
  13749. return true;
  13750. }
  13751. void ApplicationProperties::openFiles() throw()
  13752. {
  13753. // You need to call setStorageParameters() before trying to get hold of the
  13754. // properties!
  13755. jassert (appName.isNotEmpty());
  13756. if (appName.isNotEmpty())
  13757. {
  13758. if (userProps == 0)
  13759. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13760. false, msBeforeSaving, options);
  13761. if (commonProps == 0)
  13762. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13763. true, msBeforeSaving, options);
  13764. userProps->setFallbackPropertySet (commonProps);
  13765. }
  13766. }
  13767. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  13768. {
  13769. if (userProps == 0)
  13770. openFiles();
  13771. return userProps;
  13772. }
  13773. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  13774. {
  13775. if (commonProps == 0)
  13776. openFiles();
  13777. if (returnUserPropsIfReadOnly)
  13778. {
  13779. if (commonSettingsAreReadOnly == 0)
  13780. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  13781. if (commonSettingsAreReadOnly > 0)
  13782. return userProps;
  13783. }
  13784. return commonProps;
  13785. }
  13786. bool ApplicationProperties::saveIfNeeded()
  13787. {
  13788. return (userProps == 0 || userProps->saveIfNeeded())
  13789. && (commonProps == 0 || commonProps->saveIfNeeded());
  13790. }
  13791. void ApplicationProperties::closeFiles()
  13792. {
  13793. deleteAndZero (userProps);
  13794. deleteAndZero (commonProps);
  13795. }
  13796. END_JUCE_NAMESPACE
  13797. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  13798. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  13799. BEGIN_JUCE_NAMESPACE
  13800. static VoidArray objectsToDelete (16);
  13801. static CriticalSection lock;
  13802. DeletedAtShutdown::DeletedAtShutdown() throw()
  13803. {
  13804. const ScopedLock sl (lock);
  13805. objectsToDelete.add (this);
  13806. }
  13807. DeletedAtShutdown::~DeletedAtShutdown()
  13808. {
  13809. const ScopedLock sl (lock);
  13810. objectsToDelete.removeValue (this);
  13811. }
  13812. void DeletedAtShutdown::deleteAll()
  13813. {
  13814. // make a local copy of the array, so it can't get into a loop if something
  13815. // creates another DeletedAtShutdown object during its destructor.
  13816. lock.enter();
  13817. const VoidArray localCopy (objectsToDelete);
  13818. lock.exit();
  13819. for (int i = localCopy.size(); --i >= 0;)
  13820. {
  13821. JUCE_TRY
  13822. {
  13823. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  13824. // double-check that it's not already been deleted during another object's destructor.
  13825. lock.enter();
  13826. const bool okToDelete = objectsToDelete.contains (deletee);
  13827. lock.exit();
  13828. if (okToDelete)
  13829. delete deletee;
  13830. }
  13831. JUCE_CATCH_EXCEPTION
  13832. }
  13833. // if no objects got re-created during shutdown, this should have been emptied by their
  13834. // destructors
  13835. jassert (objectsToDelete.size() == 0);
  13836. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  13837. }
  13838. END_JUCE_NAMESPACE
  13839. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  13840. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  13841. BEGIN_JUCE_NAMESPACE
  13842. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  13843. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  13844. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  13845. static const tchar* const propertyTagName = T("VALUE");
  13846. PropertiesFile::PropertiesFile (const File& f,
  13847. const int millisecondsBeforeSaving,
  13848. const int options_) throw()
  13849. : PropertySet (ignoreCaseOfKeyNames),
  13850. file (f),
  13851. timerInterval (millisecondsBeforeSaving),
  13852. options (options_),
  13853. needsWriting (false)
  13854. {
  13855. // You need to correctly specify just one storage format for the file
  13856. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  13857. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  13858. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  13859. InputStream* fileStream = f.createInputStream();
  13860. if (fileStream != 0)
  13861. {
  13862. int magicNumber = fileStream->readInt();
  13863. if (magicNumber == propFileMagicNumberCompressed)
  13864. {
  13865. fileStream = new SubregionStream (fileStream, 4, -1, true);
  13866. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  13867. magicNumber = propFileMagicNumber;
  13868. }
  13869. if (magicNumber == propFileMagicNumber)
  13870. {
  13871. BufferedInputStream in (fileStream, 2048, true);
  13872. int numValues = in.readInt();
  13873. while (--numValues >= 0 && ! in.isExhausted())
  13874. {
  13875. const String key (in.readString());
  13876. const String value (in.readString());
  13877. jassert (key.isNotEmpty());
  13878. if (key.isNotEmpty())
  13879. getAllProperties().set (key, value);
  13880. }
  13881. }
  13882. else
  13883. {
  13884. // Not a binary props file - let's see if it's XML..
  13885. delete fileStream;
  13886. XmlDocument parser (f);
  13887. XmlElement* doc = parser.getDocumentElement (true);
  13888. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  13889. {
  13890. delete doc;
  13891. doc = parser.getDocumentElement();
  13892. if (doc != 0)
  13893. {
  13894. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  13895. {
  13896. const String name (e->getStringAttribute (T("name")));
  13897. if (name.isNotEmpty())
  13898. {
  13899. getAllProperties().set (name,
  13900. e->getFirstChildElement() != 0
  13901. ? e->getFirstChildElement()->createDocument (String::empty, true)
  13902. : e->getStringAttribute (T("val")));
  13903. }
  13904. }
  13905. }
  13906. else
  13907. {
  13908. // must be a pretty broken XML file we're trying to parse here!
  13909. jassertfalse
  13910. }
  13911. delete doc;
  13912. }
  13913. }
  13914. }
  13915. }
  13916. PropertiesFile::~PropertiesFile()
  13917. {
  13918. saveIfNeeded();
  13919. }
  13920. bool PropertiesFile::saveIfNeeded()
  13921. {
  13922. const ScopedLock sl (getLock());
  13923. return (! needsWriting) || save();
  13924. }
  13925. bool PropertiesFile::needsToBeSaved() const throw()
  13926. {
  13927. const ScopedLock sl (getLock());
  13928. return needsWriting;
  13929. }
  13930. bool PropertiesFile::save()
  13931. {
  13932. const ScopedLock sl (getLock());
  13933. stopTimer();
  13934. if (file == File::nonexistent
  13935. || file.isDirectory()
  13936. || ! file.getParentDirectory().createDirectory())
  13937. return false;
  13938. if ((options & storeAsXML) != 0)
  13939. {
  13940. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  13941. for (int i = 0; i < getAllProperties().size(); ++i)
  13942. {
  13943. XmlElement* const e = new XmlElement (propertyTagName);
  13944. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  13945. // if the value seems to contain xml, store it as such..
  13946. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  13947. XmlElement* const childElement = xmlContent.getDocumentElement();
  13948. if (childElement != 0)
  13949. e->addChildElement (childElement);
  13950. else
  13951. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  13952. doc->addChildElement (e);
  13953. }
  13954. const bool ok = doc->writeToFile (file, String::empty);
  13955. delete doc;
  13956. return ok;
  13957. }
  13958. else
  13959. {
  13960. const File tempFile (file.getNonexistentSibling (false));
  13961. OutputStream* out = tempFile.createOutputStream();
  13962. if (out != 0)
  13963. {
  13964. if ((options & storeAsCompressedBinary) != 0)
  13965. {
  13966. out->writeInt (propFileMagicNumberCompressed);
  13967. out->flush();
  13968. out = new GZIPCompressorOutputStream (out, 9, true);
  13969. }
  13970. else
  13971. {
  13972. // have you set up the storage option flags correctly?
  13973. jassert ((options & storeAsBinary) != 0);
  13974. out->writeInt (propFileMagicNumber);
  13975. }
  13976. const int numProperties = getAllProperties().size();
  13977. out->writeInt (numProperties);
  13978. for (int i = 0; i < numProperties; ++i)
  13979. {
  13980. out->writeString (getAllProperties().getAllKeys() [i]);
  13981. out->writeString (getAllProperties().getAllValues() [i]);
  13982. }
  13983. out->flush();
  13984. delete out;
  13985. if (tempFile.moveFileTo (file))
  13986. {
  13987. needsWriting = false;
  13988. return true;
  13989. }
  13990. tempFile.deleteFile();
  13991. }
  13992. }
  13993. return false;
  13994. }
  13995. void PropertiesFile::timerCallback()
  13996. {
  13997. saveIfNeeded();
  13998. }
  13999. void PropertiesFile::propertyChanged()
  14000. {
  14001. sendChangeMessage (this);
  14002. needsWriting = true;
  14003. if (timerInterval > 0)
  14004. startTimer (timerInterval);
  14005. else if (timerInterval == 0)
  14006. saveIfNeeded();
  14007. }
  14008. const File PropertiesFile::getFile() const throw()
  14009. {
  14010. return file;
  14011. }
  14012. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14013. const String& fileNameSuffix,
  14014. const String& folderName,
  14015. const bool commonToAllUsers)
  14016. {
  14017. // mustn't have illegal characters in this name..
  14018. jassert (applicationName == File::createLegalFileName (applicationName));
  14019. #if JUCE_MAC || JUCE_IPHONE
  14020. File dir (commonToAllUsers ? "/Library/Preferences"
  14021. : "~/Library/Preferences");
  14022. if (folderName.isNotEmpty())
  14023. dir = dir.getChildFile (folderName);
  14024. #endif
  14025. #ifdef JUCE_LINUX
  14026. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  14027. + (folderName.isNotEmpty() ? folderName
  14028. : (T(".") + applicationName)));
  14029. #endif
  14030. #if JUCE_WIN32
  14031. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14032. : File::userApplicationDataDirectory));
  14033. if (dir == File::nonexistent)
  14034. return File::nonexistent;
  14035. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14036. : applicationName);
  14037. #endif
  14038. return dir.getChildFile (applicationName)
  14039. .withFileExtension (fileNameSuffix);
  14040. }
  14041. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14042. const String& fileNameSuffix,
  14043. const String& folderName,
  14044. const bool commonToAllUsers,
  14045. const int millisecondsBeforeSaving,
  14046. const int propertiesFileOptions)
  14047. {
  14048. const File file (getDefaultAppSettingsFile (applicationName,
  14049. fileNameSuffix,
  14050. folderName,
  14051. commonToAllUsers));
  14052. jassert (file != File::nonexistent);
  14053. if (file == File::nonexistent)
  14054. return 0;
  14055. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  14056. }
  14057. END_JUCE_NAMESPACE
  14058. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  14059. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  14060. BEGIN_JUCE_NAMESPACE
  14061. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14062. const String& fileWildcard_,
  14063. const String& openFileDialogTitle_,
  14064. const String& saveFileDialogTitle_)
  14065. : changedSinceSave (false),
  14066. fileExtension (fileExtension_),
  14067. fileWildcard (fileWildcard_),
  14068. openFileDialogTitle (openFileDialogTitle_),
  14069. saveFileDialogTitle (saveFileDialogTitle_)
  14070. {
  14071. }
  14072. FileBasedDocument::~FileBasedDocument()
  14073. {
  14074. }
  14075. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14076. {
  14077. changedSinceSave = hasChanged;
  14078. }
  14079. void FileBasedDocument::changed()
  14080. {
  14081. changedSinceSave = true;
  14082. sendChangeMessage (this);
  14083. }
  14084. void FileBasedDocument::setFile (const File& newFile)
  14085. {
  14086. if (documentFile != newFile)
  14087. {
  14088. documentFile = newFile;
  14089. changedSinceSave = true;
  14090. }
  14091. }
  14092. bool FileBasedDocument::loadFrom (const File& newFile,
  14093. const bool showMessageOnFailure)
  14094. {
  14095. MouseCursor::showWaitCursor();
  14096. const File oldFile (documentFile);
  14097. documentFile = newFile;
  14098. String error;
  14099. if (newFile.existsAsFile())
  14100. {
  14101. error = loadDocument (newFile);
  14102. if (error.isEmpty())
  14103. {
  14104. setChangedFlag (false);
  14105. MouseCursor::hideWaitCursor();
  14106. setLastDocumentOpened (newFile);
  14107. return true;
  14108. }
  14109. }
  14110. else
  14111. {
  14112. error = "The file doesn't exist";
  14113. }
  14114. documentFile = oldFile;
  14115. MouseCursor::hideWaitCursor();
  14116. if (showMessageOnFailure)
  14117. {
  14118. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14119. TRANS("Failed to open file..."),
  14120. TRANS("There was an error while trying to load the file:\n\n")
  14121. + newFile.getFullPathName()
  14122. + T("\n\n")
  14123. + error);
  14124. }
  14125. return false;
  14126. }
  14127. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14128. {
  14129. FileChooser fc (openFileDialogTitle,
  14130. getLastDocumentOpened(),
  14131. fileWildcard);
  14132. if (fc.browseForFileToOpen())
  14133. return loadFrom (fc.getResult(), showMessageOnFailure);
  14134. return false;
  14135. }
  14136. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14137. const bool showMessageOnFailure)
  14138. {
  14139. return saveAs (documentFile,
  14140. false,
  14141. askUserForFileIfNotSpecified,
  14142. showMessageOnFailure);
  14143. }
  14144. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14145. const bool warnAboutOverwritingExistingFiles,
  14146. const bool askUserForFileIfNotSpecified,
  14147. const bool showMessageOnFailure)
  14148. {
  14149. if (newFile == File::nonexistent)
  14150. {
  14151. if (askUserForFileIfNotSpecified)
  14152. {
  14153. return saveAsInteractive (true);
  14154. }
  14155. else
  14156. {
  14157. // can't save to an unspecified file
  14158. jassertfalse
  14159. return failedToWriteToFile;
  14160. }
  14161. }
  14162. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14163. {
  14164. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14165. TRANS("File already exists"),
  14166. TRANS("There's already a file called:\n\n")
  14167. + newFile.getFullPathName()
  14168. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14169. TRANS("overwrite"),
  14170. TRANS("cancel")))
  14171. {
  14172. return userCancelledSave;
  14173. }
  14174. }
  14175. MouseCursor::showWaitCursor();
  14176. const File oldFile (documentFile);
  14177. documentFile = newFile;
  14178. String error (saveDocument (newFile));
  14179. if (error.isEmpty())
  14180. {
  14181. setChangedFlag (false);
  14182. MouseCursor::hideWaitCursor();
  14183. return savedOk;
  14184. }
  14185. documentFile = oldFile;
  14186. MouseCursor::hideWaitCursor();
  14187. if (showMessageOnFailure)
  14188. {
  14189. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14190. TRANS("Error writing to file..."),
  14191. TRANS("An error occurred while trying to save \"")
  14192. + getDocumentTitle()
  14193. + TRANS("\" to the file:\n\n")
  14194. + newFile.getFullPathName()
  14195. + T("\n\n")
  14196. + error);
  14197. }
  14198. return failedToWriteToFile;
  14199. }
  14200. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14201. {
  14202. if (! hasChangedSinceSaved())
  14203. return savedOk;
  14204. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14205. TRANS("Closing document..."),
  14206. TRANS("Do you want to save the changes to \"")
  14207. + getDocumentTitle() + T("\"?"),
  14208. TRANS("save"),
  14209. TRANS("discard changes"),
  14210. TRANS("cancel"));
  14211. if (r == 1)
  14212. {
  14213. // save changes
  14214. return save (true, true);
  14215. }
  14216. else if (r == 2)
  14217. {
  14218. // discard changes
  14219. return savedOk;
  14220. }
  14221. return userCancelledSave;
  14222. }
  14223. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14224. {
  14225. File f;
  14226. if (documentFile.existsAsFile())
  14227. f = documentFile;
  14228. else
  14229. f = getLastDocumentOpened();
  14230. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14231. if (legalFilename.isEmpty())
  14232. legalFilename = "unnamed";
  14233. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14234. f = f.getSiblingFile (legalFilename);
  14235. else
  14236. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14237. f = f.withFileExtension (fileExtension)
  14238. .getNonexistentSibling (true);
  14239. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14240. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14241. {
  14242. setLastDocumentOpened (fc.getResult());
  14243. File chosen (fc.getResult());
  14244. if (chosen.getFileExtension().isEmpty())
  14245. chosen = chosen.withFileExtension (fileExtension);
  14246. return saveAs (chosen, false, false, true);
  14247. }
  14248. return userCancelledSave;
  14249. }
  14250. END_JUCE_NAMESPACE
  14251. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  14252. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14253. BEGIN_JUCE_NAMESPACE
  14254. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14255. : maxNumberOfItems (10)
  14256. {
  14257. }
  14258. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14259. {
  14260. }
  14261. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14262. {
  14263. maxNumberOfItems = jmax (1, newMaxNumber);
  14264. while (getNumFiles() > maxNumberOfItems)
  14265. files.remove (getNumFiles() - 1);
  14266. }
  14267. int RecentlyOpenedFilesList::getNumFiles() const
  14268. {
  14269. return files.size();
  14270. }
  14271. const File RecentlyOpenedFilesList::getFile (const int index) const
  14272. {
  14273. return File (files [index]);
  14274. }
  14275. void RecentlyOpenedFilesList::clear()
  14276. {
  14277. files.clear();
  14278. }
  14279. void RecentlyOpenedFilesList::addFile (const File& file)
  14280. {
  14281. const String path (file.getFullPathName());
  14282. files.removeString (path, true);
  14283. files.insert (0, path);
  14284. setMaxNumberOfItems (maxNumberOfItems);
  14285. }
  14286. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14287. {
  14288. for (int i = getNumFiles(); --i >= 0;)
  14289. if (! getFile(i).exists())
  14290. files.remove (i);
  14291. }
  14292. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14293. const int baseItemId,
  14294. const bool showFullPaths,
  14295. const bool dontAddNonExistentFiles,
  14296. const File** filesToAvoid)
  14297. {
  14298. int num = 0;
  14299. for (int i = 0; i < getNumFiles(); ++i)
  14300. {
  14301. const File f (getFile(i));
  14302. if ((! dontAddNonExistentFiles) || f.exists())
  14303. {
  14304. bool needsAvoiding = false;
  14305. if (filesToAvoid != 0)
  14306. {
  14307. const File** files = filesToAvoid;
  14308. while (*files != 0)
  14309. {
  14310. if (f == **files)
  14311. {
  14312. needsAvoiding = true;
  14313. break;
  14314. }
  14315. ++files;
  14316. }
  14317. }
  14318. if (! needsAvoiding)
  14319. {
  14320. menuToAddTo.addItem (baseItemId + i,
  14321. showFullPaths ? f.getFullPathName()
  14322. : f.getFileName());
  14323. ++num;
  14324. }
  14325. }
  14326. }
  14327. return num;
  14328. }
  14329. const String RecentlyOpenedFilesList::toString() const
  14330. {
  14331. return files.joinIntoString (T("\n"));
  14332. }
  14333. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14334. {
  14335. clear();
  14336. files.addLines (stringifiedVersion);
  14337. setMaxNumberOfItems (maxNumberOfItems);
  14338. }
  14339. END_JUCE_NAMESPACE
  14340. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14341. /********* Start of inlined file: juce_UndoManager.cpp *********/
  14342. BEGIN_JUCE_NAMESPACE
  14343. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14344. const int minimumTransactions)
  14345. : totalUnitsStored (0),
  14346. nextIndex (0),
  14347. newTransaction (true),
  14348. reentrancyCheck (false)
  14349. {
  14350. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14351. minimumTransactions);
  14352. }
  14353. UndoManager::~UndoManager()
  14354. {
  14355. clearUndoHistory();
  14356. }
  14357. void UndoManager::clearUndoHistory()
  14358. {
  14359. transactions.clear();
  14360. transactionNames.clear();
  14361. totalUnitsStored = 0;
  14362. nextIndex = 0;
  14363. sendChangeMessage (this);
  14364. }
  14365. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14366. {
  14367. return totalUnitsStored;
  14368. }
  14369. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14370. const int minimumTransactions)
  14371. {
  14372. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14373. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14374. }
  14375. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14376. {
  14377. if (command != 0)
  14378. {
  14379. if (actionName.isNotEmpty())
  14380. currentTransactionName = actionName;
  14381. if (reentrancyCheck)
  14382. {
  14383. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14384. // undo() methods, or else these actions won't actually get done.
  14385. return false;
  14386. }
  14387. else
  14388. {
  14389. bool success = false;
  14390. JUCE_TRY
  14391. {
  14392. success = command->perform();
  14393. }
  14394. JUCE_CATCH_EXCEPTION
  14395. jassert (success);
  14396. if (success)
  14397. {
  14398. if (nextIndex > 0 && ! newTransaction)
  14399. {
  14400. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14401. jassert (commandSet != 0);
  14402. if (commandSet == 0)
  14403. return false;
  14404. commandSet->add (command);
  14405. }
  14406. else
  14407. {
  14408. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14409. commandSet->add (command);
  14410. transactions.insert (nextIndex, commandSet);
  14411. transactionNames.insert (nextIndex, currentTransactionName);
  14412. ++nextIndex;
  14413. }
  14414. totalUnitsStored += command->getSizeInUnits();
  14415. newTransaction = false;
  14416. }
  14417. while (nextIndex < transactions.size())
  14418. {
  14419. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14420. for (int i = lastSet->size(); --i >= 0;)
  14421. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14422. transactions.removeLast();
  14423. transactionNames.remove (transactionNames.size() - 1);
  14424. }
  14425. while (nextIndex > 0
  14426. && totalUnitsStored > maxNumUnitsToKeep
  14427. && transactions.size() > minimumTransactionsToKeep)
  14428. {
  14429. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14430. for (int i = firstSet->size(); --i >= 0;)
  14431. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14432. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14433. transactions.remove (0);
  14434. transactionNames.remove (0);
  14435. --nextIndex;
  14436. }
  14437. sendChangeMessage (this);
  14438. return success;
  14439. }
  14440. }
  14441. return false;
  14442. }
  14443. void UndoManager::beginNewTransaction (const String& actionName)
  14444. {
  14445. newTransaction = true;
  14446. currentTransactionName = actionName;
  14447. }
  14448. void UndoManager::setCurrentTransactionName (const String& newName)
  14449. {
  14450. currentTransactionName = newName;
  14451. }
  14452. bool UndoManager::canUndo() const
  14453. {
  14454. return nextIndex > 0;
  14455. }
  14456. bool UndoManager::canRedo() const
  14457. {
  14458. return nextIndex < transactions.size();
  14459. }
  14460. const String UndoManager::getUndoDescription() const
  14461. {
  14462. return transactionNames [nextIndex - 1];
  14463. }
  14464. const String UndoManager::getRedoDescription() const
  14465. {
  14466. return transactionNames [nextIndex];
  14467. }
  14468. bool UndoManager::undo()
  14469. {
  14470. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14471. if (commandSet == 0)
  14472. return false;
  14473. reentrancyCheck = true;
  14474. bool failed = false;
  14475. for (int i = commandSet->size(); --i >= 0;)
  14476. {
  14477. if (! commandSet->getUnchecked(i)->undo())
  14478. {
  14479. jassertfalse
  14480. failed = true;
  14481. break;
  14482. }
  14483. }
  14484. reentrancyCheck = false;
  14485. if (failed)
  14486. {
  14487. clearUndoHistory();
  14488. }
  14489. else
  14490. {
  14491. --nextIndex;
  14492. }
  14493. beginNewTransaction();
  14494. sendChangeMessage (this);
  14495. return true;
  14496. }
  14497. bool UndoManager::redo()
  14498. {
  14499. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  14500. if (commandSet == 0)
  14501. return false;
  14502. reentrancyCheck = true;
  14503. bool failed = false;
  14504. for (int i = 0; i < commandSet->size(); ++i)
  14505. {
  14506. if (! commandSet->getUnchecked(i)->perform())
  14507. {
  14508. jassertfalse
  14509. failed = true;
  14510. break;
  14511. }
  14512. }
  14513. reentrancyCheck = false;
  14514. if (failed)
  14515. {
  14516. clearUndoHistory();
  14517. }
  14518. else
  14519. {
  14520. ++nextIndex;
  14521. }
  14522. beginNewTransaction();
  14523. sendChangeMessage (this);
  14524. return true;
  14525. }
  14526. bool UndoManager::undoCurrentTransactionOnly()
  14527. {
  14528. return newTransaction ? false
  14529. : undo();
  14530. }
  14531. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  14532. {
  14533. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14534. if (commandSet != 0 && ! newTransaction)
  14535. {
  14536. for (int i = 0; i < commandSet->size(); ++i)
  14537. actionsFound.add (commandSet->getUnchecked(i));
  14538. }
  14539. }
  14540. END_JUCE_NAMESPACE
  14541. /********* End of inlined file: juce_UndoManager.cpp *********/
  14542. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  14543. BEGIN_JUCE_NAMESPACE
  14544. #undef chunkName
  14545. #define chunkName(a) (int)littleEndianInt(a)
  14546. #define aiffFormatName TRANS("AIFF file")
  14547. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  14548. class AiffAudioFormatReader : public AudioFormatReader
  14549. {
  14550. public:
  14551. int bytesPerFrame;
  14552. int64 dataChunkStart;
  14553. bool littleEndian;
  14554. AiffAudioFormatReader (InputStream* in)
  14555. : AudioFormatReader (in, aiffFormatName)
  14556. {
  14557. if (input->readInt() == chunkName ("FORM"))
  14558. {
  14559. const int len = input->readIntBigEndian();
  14560. const int64 end = input->getPosition() + len;
  14561. const int nextType = input->readInt();
  14562. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  14563. {
  14564. bool hasGotVer = false;
  14565. bool hasGotData = false;
  14566. bool hasGotType = false;
  14567. while (input->getPosition() < end)
  14568. {
  14569. const int type = input->readInt();
  14570. const uint32 length = (uint32) input->readIntBigEndian();
  14571. const int64 chunkEnd = input->getPosition() + length;
  14572. if (type == chunkName ("FVER"))
  14573. {
  14574. hasGotVer = true;
  14575. const int ver = input->readIntBigEndian();
  14576. if (ver != 0 && ver != (int)0xa2805140)
  14577. break;
  14578. }
  14579. else if (type == chunkName ("COMM"))
  14580. {
  14581. hasGotType = true;
  14582. numChannels = (unsigned int)input->readShortBigEndian();
  14583. lengthInSamples = input->readIntBigEndian();
  14584. bitsPerSample = input->readShortBigEndian();
  14585. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  14586. unsigned char sampleRateBytes[10];
  14587. input->read (sampleRateBytes, 10);
  14588. const int byte0 = sampleRateBytes[0];
  14589. if ((byte0 & 0x80) != 0
  14590. || byte0 <= 0x3F || byte0 > 0x40
  14591. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  14592. break;
  14593. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  14594. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  14595. sampleRate = (int)sampRate;
  14596. if (length <= 18)
  14597. {
  14598. // some types don't have a chunk large enough to include a compression
  14599. // type, so assume it's just big-endian pcm
  14600. littleEndian = false;
  14601. }
  14602. else
  14603. {
  14604. const int compType = input->readInt();
  14605. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  14606. {
  14607. littleEndian = false;
  14608. }
  14609. else if (compType == chunkName ("sowt"))
  14610. {
  14611. littleEndian = true;
  14612. }
  14613. else
  14614. {
  14615. sampleRate = 0;
  14616. break;
  14617. }
  14618. }
  14619. }
  14620. else if (type == chunkName ("SSND"))
  14621. {
  14622. hasGotData = true;
  14623. const int offset = input->readIntBigEndian();
  14624. dataChunkStart = input->getPosition() + 4 + offset;
  14625. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  14626. }
  14627. else if ((hasGotVer && hasGotData && hasGotType)
  14628. || chunkEnd < input->getPosition()
  14629. || input->isExhausted())
  14630. {
  14631. break;
  14632. }
  14633. input->setPosition (chunkEnd);
  14634. }
  14635. }
  14636. }
  14637. }
  14638. ~AiffAudioFormatReader()
  14639. {
  14640. }
  14641. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  14642. int64 startSampleInFile, int numSamples)
  14643. {
  14644. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  14645. if (samplesAvailable < numSamples)
  14646. {
  14647. for (int i = numDestChannels; --i >= 0;)
  14648. if (destSamples[i] != 0)
  14649. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  14650. numSamples = (int) samplesAvailable;
  14651. }
  14652. if (numSamples <= 0)
  14653. return true;
  14654. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  14655. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  14656. char tempBuffer [tempBufSize];
  14657. while (numSamples > 0)
  14658. {
  14659. int* left = destSamples[0];
  14660. if (left != 0)
  14661. left += startOffsetInDestBuffer;
  14662. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  14663. if (right != 0)
  14664. right += startOffsetInDestBuffer;
  14665. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  14666. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  14667. if (bytesRead < numThisTime * bytesPerFrame)
  14668. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  14669. if (bitsPerSample == 16)
  14670. {
  14671. if (littleEndian)
  14672. {
  14673. const short* src = (const short*) tempBuffer;
  14674. if (numChannels > 1)
  14675. {
  14676. if (left == 0)
  14677. {
  14678. for (int i = numThisTime; --i >= 0;)
  14679. {
  14680. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14681. ++src;
  14682. }
  14683. }
  14684. else if (right == 0)
  14685. {
  14686. for (int i = numThisTime; --i >= 0;)
  14687. {
  14688. ++src;
  14689. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14690. }
  14691. }
  14692. else
  14693. {
  14694. for (int i = numThisTime; --i >= 0;)
  14695. {
  14696. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14697. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14698. }
  14699. }
  14700. }
  14701. else
  14702. {
  14703. for (int i = numThisTime; --i >= 0;)
  14704. {
  14705. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14706. }
  14707. }
  14708. }
  14709. else
  14710. {
  14711. const char* src = (const char*) tempBuffer;
  14712. if (numChannels > 1)
  14713. {
  14714. if (left == 0)
  14715. {
  14716. for (int i = numThisTime; --i >= 0;)
  14717. {
  14718. *right++ = bigEndianShort (src) << 16;
  14719. src += 4;
  14720. }
  14721. }
  14722. else if (right == 0)
  14723. {
  14724. for (int i = numThisTime; --i >= 0;)
  14725. {
  14726. src += 2;
  14727. *left++ = bigEndianShort (src) << 16;
  14728. src += 2;
  14729. }
  14730. }
  14731. else
  14732. {
  14733. for (int i = numThisTime; --i >= 0;)
  14734. {
  14735. *left++ = bigEndianShort (src) << 16;
  14736. src += 2;
  14737. *right++ = bigEndianShort (src) << 16;
  14738. src += 2;
  14739. }
  14740. }
  14741. }
  14742. else
  14743. {
  14744. for (int i = numThisTime; --i >= 0;)
  14745. {
  14746. *left++ = bigEndianShort (src) << 16;
  14747. src += 2;
  14748. }
  14749. }
  14750. }
  14751. }
  14752. else if (bitsPerSample == 24)
  14753. {
  14754. const char* src = (const char*)tempBuffer;
  14755. if (littleEndian)
  14756. {
  14757. if (numChannels > 1)
  14758. {
  14759. if (left == 0)
  14760. {
  14761. for (int i = numThisTime; --i >= 0;)
  14762. {
  14763. *right++ = littleEndian24Bit (src) << 8;
  14764. src += 6;
  14765. }
  14766. }
  14767. else if (right == 0)
  14768. {
  14769. for (int i = numThisTime; --i >= 0;)
  14770. {
  14771. src += 3;
  14772. *left++ = littleEndian24Bit (src) << 8;
  14773. src += 3;
  14774. }
  14775. }
  14776. else
  14777. {
  14778. for (int i = numThisTime; --i >= 0;)
  14779. {
  14780. *left++ = littleEndian24Bit (src) << 8;
  14781. src += 3;
  14782. *right++ = littleEndian24Bit (src) << 8;
  14783. src += 3;
  14784. }
  14785. }
  14786. }
  14787. else
  14788. {
  14789. for (int i = numThisTime; --i >= 0;)
  14790. {
  14791. *left++ = littleEndian24Bit (src) << 8;
  14792. src += 3;
  14793. }
  14794. }
  14795. }
  14796. else
  14797. {
  14798. if (numChannels > 1)
  14799. {
  14800. if (left == 0)
  14801. {
  14802. for (int i = numThisTime; --i >= 0;)
  14803. {
  14804. *right++ = bigEndian24Bit (src) << 8;
  14805. src += 6;
  14806. }
  14807. }
  14808. else if (right == 0)
  14809. {
  14810. for (int i = numThisTime; --i >= 0;)
  14811. {
  14812. src += 3;
  14813. *left++ = bigEndian24Bit (src) << 8;
  14814. src += 3;
  14815. }
  14816. }
  14817. else
  14818. {
  14819. for (int i = numThisTime; --i >= 0;)
  14820. {
  14821. *left++ = bigEndian24Bit (src) << 8;
  14822. src += 3;
  14823. *right++ = bigEndian24Bit (src) << 8;
  14824. src += 3;
  14825. }
  14826. }
  14827. }
  14828. else
  14829. {
  14830. for (int i = numThisTime; --i >= 0;)
  14831. {
  14832. *left++ = bigEndian24Bit (src) << 8;
  14833. src += 3;
  14834. }
  14835. }
  14836. }
  14837. }
  14838. else if (bitsPerSample == 32)
  14839. {
  14840. const unsigned int* src = (const unsigned int*) tempBuffer;
  14841. unsigned int* l = (unsigned int*) left;
  14842. unsigned int* r = (unsigned int*) right;
  14843. if (littleEndian)
  14844. {
  14845. if (numChannels > 1)
  14846. {
  14847. if (l == 0)
  14848. {
  14849. for (int i = numThisTime; --i >= 0;)
  14850. {
  14851. ++src;
  14852. *r++ = swapIfBigEndian (*src++);
  14853. }
  14854. }
  14855. else if (r == 0)
  14856. {
  14857. for (int i = numThisTime; --i >= 0;)
  14858. {
  14859. *l++ = swapIfBigEndian (*src++);
  14860. ++src;
  14861. }
  14862. }
  14863. else
  14864. {
  14865. for (int i = numThisTime; --i >= 0;)
  14866. {
  14867. *l++ = swapIfBigEndian (*src++);
  14868. *r++ = swapIfBigEndian (*src++);
  14869. }
  14870. }
  14871. }
  14872. else
  14873. {
  14874. for (int i = numThisTime; --i >= 0;)
  14875. {
  14876. *l++ = swapIfBigEndian (*src++);
  14877. }
  14878. }
  14879. }
  14880. else
  14881. {
  14882. if (numChannels > 1)
  14883. {
  14884. if (l == 0)
  14885. {
  14886. for (int i = numThisTime; --i >= 0;)
  14887. {
  14888. ++src;
  14889. *r++ = swapIfLittleEndian (*src++);
  14890. }
  14891. }
  14892. else if (r == 0)
  14893. {
  14894. for (int i = numThisTime; --i >= 0;)
  14895. {
  14896. *l++ = swapIfLittleEndian (*src++);
  14897. ++src;
  14898. }
  14899. }
  14900. else
  14901. {
  14902. for (int i = numThisTime; --i >= 0;)
  14903. {
  14904. *l++ = swapIfLittleEndian (*src++);
  14905. *r++ = swapIfLittleEndian (*src++);
  14906. }
  14907. }
  14908. }
  14909. else
  14910. {
  14911. for (int i = numThisTime; --i >= 0;)
  14912. {
  14913. *l++ = swapIfLittleEndian (*src++);
  14914. }
  14915. }
  14916. }
  14917. left = (int*) l;
  14918. right = (int*) r;
  14919. }
  14920. else if (bitsPerSample == 8)
  14921. {
  14922. const char* src = (const char*) tempBuffer;
  14923. if (numChannels > 1)
  14924. {
  14925. if (left == 0)
  14926. {
  14927. for (int i = numThisTime; --i >= 0;)
  14928. {
  14929. *right++ = ((int) *src++) << 24;
  14930. ++src;
  14931. }
  14932. }
  14933. else if (right == 0)
  14934. {
  14935. for (int i = numThisTime; --i >= 0;)
  14936. {
  14937. ++src;
  14938. *left++ = ((int) *src++) << 24;
  14939. }
  14940. }
  14941. else
  14942. {
  14943. for (int i = numThisTime; --i >= 0;)
  14944. {
  14945. *left++ = ((int) *src++) << 24;
  14946. *right++ = ((int) *src++) << 24;
  14947. }
  14948. }
  14949. }
  14950. else
  14951. {
  14952. for (int i = numThisTime; --i >= 0;)
  14953. {
  14954. *left++ = ((int) *src++) << 24;
  14955. }
  14956. }
  14957. }
  14958. startOffsetInDestBuffer += numThisTime;
  14959. numSamples -= numThisTime;
  14960. }
  14961. if (numSamples > 0)
  14962. {
  14963. for (int i = numDestChannels; --i >= 0;)
  14964. if (destSamples[i] != 0)
  14965. zeromem (destSamples[i] + startOffsetInDestBuffer,
  14966. sizeof (int) * numSamples);
  14967. }
  14968. return true;
  14969. }
  14970. juce_UseDebuggingNewOperator
  14971. private:
  14972. AiffAudioFormatReader (const AiffAudioFormatReader&);
  14973. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  14974. };
  14975. class AiffAudioFormatWriter : public AudioFormatWriter
  14976. {
  14977. MemoryBlock tempBlock;
  14978. uint32 lengthInSamples, bytesWritten;
  14979. int64 headerPosition;
  14980. bool writeFailed;
  14981. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  14982. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  14983. void writeHeader()
  14984. {
  14985. const bool couldSeekOk = output->setPosition (headerPosition);
  14986. (void) couldSeekOk;
  14987. // if this fails, you've given it an output stream that can't seek! It needs
  14988. // to be able to seek back to write the header
  14989. jassert (couldSeekOk);
  14990. const int headerLen = 54;
  14991. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  14992. audioBytes += (audioBytes & 1);
  14993. output->writeInt (chunkName ("FORM"));
  14994. output->writeIntBigEndian (headerLen + audioBytes - 8);
  14995. output->writeInt (chunkName ("AIFF"));
  14996. output->writeInt (chunkName ("COMM"));
  14997. output->writeIntBigEndian (18);
  14998. output->writeShortBigEndian ((short) numChannels);
  14999. output->writeIntBigEndian (lengthInSamples);
  15000. output->writeShortBigEndian ((short) bitsPerSample);
  15001. uint8 sampleRateBytes[10];
  15002. zeromem (sampleRateBytes, 10);
  15003. if (sampleRate <= 1)
  15004. {
  15005. sampleRateBytes[0] = 0x3f;
  15006. sampleRateBytes[1] = 0xff;
  15007. sampleRateBytes[2] = 0x80;
  15008. }
  15009. else
  15010. {
  15011. int mask = 0x40000000;
  15012. sampleRateBytes[0] = 0x40;
  15013. if (sampleRate >= mask)
  15014. {
  15015. jassertfalse
  15016. sampleRateBytes[1] = 0x1d;
  15017. }
  15018. else
  15019. {
  15020. int n = (int) sampleRate;
  15021. int i;
  15022. for (i = 0; i <= 32 ; ++i)
  15023. {
  15024. if ((n & mask) != 0)
  15025. break;
  15026. mask >>= 1;
  15027. }
  15028. n = n << (i + 1);
  15029. sampleRateBytes[1] = (uint8) (29 - i);
  15030. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15031. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15032. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15033. sampleRateBytes[5] = (uint8) (n & 0xff);
  15034. }
  15035. }
  15036. output->write (sampleRateBytes, 10);
  15037. output->writeInt (chunkName ("SSND"));
  15038. output->writeIntBigEndian (audioBytes + 8);
  15039. output->writeInt (0);
  15040. output->writeInt (0);
  15041. jassert (output->getPosition() == headerLen);
  15042. }
  15043. public:
  15044. AiffAudioFormatWriter (OutputStream* out,
  15045. const double sampleRate_,
  15046. const unsigned int chans,
  15047. const int bits)
  15048. : AudioFormatWriter (out,
  15049. aiffFormatName,
  15050. sampleRate_,
  15051. chans,
  15052. bits),
  15053. lengthInSamples (0),
  15054. bytesWritten (0),
  15055. writeFailed (false)
  15056. {
  15057. headerPosition = out->getPosition();
  15058. writeHeader();
  15059. }
  15060. ~AiffAudioFormatWriter()
  15061. {
  15062. if ((bytesWritten & 1) != 0)
  15063. output->writeByte (0);
  15064. writeHeader();
  15065. }
  15066. bool write (const int** data, int numSamples)
  15067. {
  15068. if (writeFailed)
  15069. return false;
  15070. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15071. tempBlock.ensureSize (bytes, false);
  15072. char* buffer = (char*) tempBlock.getData();
  15073. const int* left = data[0];
  15074. const int* right = data[1];
  15075. if (right == 0)
  15076. right = left;
  15077. if (bitsPerSample == 16)
  15078. {
  15079. short* b = (short*) buffer;
  15080. if (numChannels > 1)
  15081. {
  15082. for (int i = numSamples; --i >= 0;)
  15083. {
  15084. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  15085. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  15086. }
  15087. }
  15088. else
  15089. {
  15090. for (int i = numSamples; --i >= 0;)
  15091. {
  15092. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  15093. }
  15094. }
  15095. }
  15096. else if (bitsPerSample == 24)
  15097. {
  15098. char* b = (char*) buffer;
  15099. if (numChannels > 1)
  15100. {
  15101. for (int i = numSamples; --i >= 0;)
  15102. {
  15103. bigEndian24BitToChars (*left++ >> 8, b);
  15104. b += 3;
  15105. bigEndian24BitToChars (*right++ >> 8, b);
  15106. b += 3;
  15107. }
  15108. }
  15109. else
  15110. {
  15111. for (int i = numSamples; --i >= 0;)
  15112. {
  15113. bigEndian24BitToChars (*left++ >> 8, b);
  15114. b += 3;
  15115. }
  15116. }
  15117. }
  15118. else if (bitsPerSample == 32)
  15119. {
  15120. unsigned int* b = (unsigned int*) buffer;
  15121. if (numChannels > 1)
  15122. {
  15123. for (int i = numSamples; --i >= 0;)
  15124. {
  15125. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  15126. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  15127. }
  15128. }
  15129. else
  15130. {
  15131. for (int i = numSamples; --i >= 0;)
  15132. {
  15133. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  15134. }
  15135. }
  15136. }
  15137. else if (bitsPerSample == 8)
  15138. {
  15139. char* b = (char*)buffer;
  15140. if (numChannels > 1)
  15141. {
  15142. for (int i = numSamples; --i >= 0;)
  15143. {
  15144. *b++ = (char) (*left++ >> 24);
  15145. *b++ = (char) (*right++ >> 24);
  15146. }
  15147. }
  15148. else
  15149. {
  15150. for (int i = numSamples; --i >= 0;)
  15151. {
  15152. *b++ = (char) (*left++ >> 24);
  15153. }
  15154. }
  15155. }
  15156. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15157. || ! output->write (buffer, bytes))
  15158. {
  15159. // failed to write to disk, so let's try writing the header.
  15160. // If it's just run out of disk space, then if it does manage
  15161. // to write the header, we'll still have a useable file..
  15162. writeHeader();
  15163. writeFailed = true;
  15164. return false;
  15165. }
  15166. else
  15167. {
  15168. bytesWritten += bytes;
  15169. lengthInSamples += numSamples;
  15170. return true;
  15171. }
  15172. }
  15173. juce_UseDebuggingNewOperator
  15174. };
  15175. AiffAudioFormat::AiffAudioFormat()
  15176. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  15177. {
  15178. }
  15179. AiffAudioFormat::~AiffAudioFormat()
  15180. {
  15181. }
  15182. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15183. {
  15184. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15185. return Array <int> (rates);
  15186. }
  15187. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15188. {
  15189. const int depths[] = { 8, 16, 24, 0 };
  15190. return Array <int> (depths);
  15191. }
  15192. bool AiffAudioFormat::canDoStereo()
  15193. {
  15194. return true;
  15195. }
  15196. bool AiffAudioFormat::canDoMono()
  15197. {
  15198. return true;
  15199. }
  15200. #if JUCE_MAC
  15201. bool AiffAudioFormat::canHandleFile (const File& f)
  15202. {
  15203. if (AudioFormat::canHandleFile (f))
  15204. return true;
  15205. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15206. return type == 'AIFF' || type == 'AIFC'
  15207. || type == 'aiff' || type == 'aifc';
  15208. }
  15209. #endif
  15210. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15211. const bool deleteStreamIfOpeningFails)
  15212. {
  15213. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  15214. if (w->sampleRate == 0)
  15215. {
  15216. if (! deleteStreamIfOpeningFails)
  15217. w->input = 0;
  15218. deleteAndZero (w);
  15219. }
  15220. return w;
  15221. }
  15222. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15223. double sampleRate,
  15224. unsigned int chans,
  15225. int bitsPerSample,
  15226. const StringPairArray& /*metadataValues*/,
  15227. int /*qualityOptionIndex*/)
  15228. {
  15229. if (getPossibleBitDepths().contains (bitsPerSample))
  15230. {
  15231. return new AiffAudioFormatWriter (out,
  15232. sampleRate,
  15233. chans,
  15234. bitsPerSample);
  15235. }
  15236. return 0;
  15237. }
  15238. END_JUCE_NAMESPACE
  15239. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  15240. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  15241. BEGIN_JUCE_NAMESPACE
  15242. #if JUCE_MAC
  15243. // Mac version doesn't need any native code because it's all done with files..
  15244. // Windows + Linux versions are in the platform-dependent code sections.
  15245. static void findCDs (OwnedArray<File>& cds)
  15246. {
  15247. File volumes ("/Volumes");
  15248. volumes.findChildFiles (cds, File::findDirectories, false);
  15249. for (int i = cds.size(); --i >= 0;)
  15250. if (! cds[i]->getChildFile (".TOC.plist").exists())
  15251. cds.remove (i);
  15252. }
  15253. const StringArray AudioCDReader::getAvailableCDNames()
  15254. {
  15255. OwnedArray<File> cds;
  15256. findCDs (cds);
  15257. StringArray names;
  15258. for (int i = 0; i < cds.size(); ++i)
  15259. names.add (cds[i]->getFileName());
  15260. return names;
  15261. }
  15262. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15263. {
  15264. OwnedArray<File> cds;
  15265. findCDs (cds);
  15266. if (cds[index] != 0)
  15267. return new AudioCDReader (*cds[index]);
  15268. else
  15269. return 0;
  15270. }
  15271. AudioCDReader::AudioCDReader (const File& volume)
  15272. : AudioFormatReader (0, "CD Audio"),
  15273. volumeDir (volume),
  15274. currentReaderTrack (-1),
  15275. reader (0)
  15276. {
  15277. sampleRate = 44100.0;
  15278. bitsPerSample = 16;
  15279. numChannels = 2;
  15280. usesFloatingPointData = false;
  15281. refreshTrackLengths();
  15282. }
  15283. AudioCDReader::~AudioCDReader()
  15284. {
  15285. if (reader != 0)
  15286. delete reader;
  15287. }
  15288. static int getTrackNumber (const File& file)
  15289. {
  15290. return file.getFileName()
  15291. .initialSectionContainingOnly (T("0123456789"))
  15292. .getIntValue();
  15293. }
  15294. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  15295. {
  15296. const int firstTrack = getTrackNumber (*first);
  15297. const int secondTrack = getTrackNumber (*second);
  15298. jassert (firstTrack > 0 && secondTrack > 0);
  15299. return firstTrack - secondTrack;
  15300. }
  15301. void AudioCDReader::refreshTrackLengths()
  15302. {
  15303. tracks.clear();
  15304. trackStartSamples.clear();
  15305. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  15306. tracks.sort (*this);
  15307. AiffAudioFormat format;
  15308. int sample = 0;
  15309. for (int i = 0; i < tracks.size(); ++i)
  15310. {
  15311. trackStartSamples.add (sample);
  15312. FileInputStream* const in = tracks[i]->createInputStream();
  15313. if (in != 0)
  15314. {
  15315. AudioFormatReader* const r = format.createReaderFor (in, true);
  15316. if (r != 0)
  15317. {
  15318. sample += r->lengthInSamples;
  15319. delete r;
  15320. }
  15321. }
  15322. }
  15323. trackStartSamples.add (sample);
  15324. lengthInSamples = sample;
  15325. }
  15326. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15327. int64 startSampleInFile, int numSamples)
  15328. {
  15329. while (numSamples > 0)
  15330. {
  15331. int track = -1;
  15332. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15333. {
  15334. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15335. {
  15336. track = i;
  15337. break;
  15338. }
  15339. }
  15340. if (track < 0)
  15341. return false;
  15342. if (track != currentReaderTrack)
  15343. {
  15344. deleteAndZero (reader);
  15345. if (tracks [track] != 0)
  15346. {
  15347. FileInputStream* const in = tracks [track]->createInputStream();
  15348. if (in != 0)
  15349. {
  15350. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15351. AiffAudioFormat format;
  15352. reader = format.createReaderFor (bin, true);
  15353. if (reader == 0)
  15354. currentReaderTrack = -1;
  15355. else
  15356. currentReaderTrack = track;
  15357. }
  15358. }
  15359. }
  15360. if (reader == 0)
  15361. return false;
  15362. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15363. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15364. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15365. numSamples -= numAvailable;
  15366. startSampleInFile += numAvailable;
  15367. }
  15368. return true;
  15369. }
  15370. bool AudioCDReader::isCDStillPresent() const
  15371. {
  15372. return volumeDir.exists();
  15373. }
  15374. int AudioCDReader::getNumTracks() const
  15375. {
  15376. return tracks.size();
  15377. }
  15378. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15379. {
  15380. return trackStartSamples [trackNum];
  15381. }
  15382. bool AudioCDReader::isTrackAudio (int trackNum) const
  15383. {
  15384. return tracks [trackNum] != 0;
  15385. }
  15386. void AudioCDReader::enableIndexScanning (bool b)
  15387. {
  15388. // any way to do this on a Mac??
  15389. }
  15390. int AudioCDReader::getLastIndex() const
  15391. {
  15392. return 0;
  15393. }
  15394. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15395. {
  15396. return Array <int>();
  15397. }
  15398. int AudioCDReader::getCDDBId()
  15399. {
  15400. return 0; //xxx
  15401. }
  15402. #endif
  15403. END_JUCE_NAMESPACE
  15404. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  15405. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  15406. BEGIN_JUCE_NAMESPACE
  15407. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15408. const String& formatName_)
  15409. : sampleRate (0),
  15410. bitsPerSample (0),
  15411. lengthInSamples (0),
  15412. numChannels (0),
  15413. usesFloatingPointData (false),
  15414. input (in),
  15415. formatName (formatName_)
  15416. {
  15417. }
  15418. AudioFormatReader::~AudioFormatReader()
  15419. {
  15420. delete input;
  15421. }
  15422. bool AudioFormatReader::read (int** destSamples,
  15423. int numDestChannels,
  15424. int64 startSampleInSource,
  15425. int numSamplesToRead,
  15426. const bool fillLeftoverChannelsWithCopies)
  15427. {
  15428. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15429. int startOffsetInDestBuffer = 0;
  15430. if (startSampleInSource < 0)
  15431. {
  15432. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15433. for (int i = numDestChannels; --i >= 0;)
  15434. if (destSamples[i] != 0)
  15435. zeromem (destSamples[i], sizeof (int) * silence);
  15436. startOffsetInDestBuffer += silence;
  15437. numSamplesToRead -= silence;
  15438. startSampleInSource = 0;
  15439. }
  15440. if (numSamplesToRead <= 0)
  15441. return true;
  15442. if (! readSamples (destSamples, jmin (numChannels, numDestChannels), startOffsetInDestBuffer,
  15443. startSampleInSource, numSamplesToRead))
  15444. return false;
  15445. if (numDestChannels > (int) numChannels)
  15446. {
  15447. if (fillLeftoverChannelsWithCopies)
  15448. {
  15449. int* lastFullChannel = destSamples[0];
  15450. for (int i = numDestChannels; --i > 0;)
  15451. {
  15452. if (destSamples[i] != 0)
  15453. {
  15454. lastFullChannel = destSamples[i];
  15455. break;
  15456. }
  15457. }
  15458. if (lastFullChannel != 0)
  15459. for (int i = numChannels; i < numDestChannels; ++i)
  15460. if (destSamples[i] != 0)
  15461. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15462. }
  15463. else
  15464. {
  15465. for (int i = numChannels; i < numDestChannels; ++i)
  15466. if (destSamples[i] != 0)
  15467. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15468. }
  15469. }
  15470. return true;
  15471. }
  15472. static void findMaxMin (const float* src, const int num,
  15473. float& maxVal, float& minVal)
  15474. {
  15475. float mn = src[0];
  15476. float mx = mn;
  15477. for (int i = 1; i < num; ++i)
  15478. {
  15479. const float s = src[i];
  15480. if (s > mx)
  15481. mx = s;
  15482. if (s < mn)
  15483. mn = s;
  15484. }
  15485. maxVal = mx;
  15486. minVal = mn;
  15487. }
  15488. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15489. int64 numSamples,
  15490. float& lowestLeft, float& highestLeft,
  15491. float& lowestRight, float& highestRight)
  15492. {
  15493. if (numSamples <= 0)
  15494. {
  15495. lowestLeft = 0;
  15496. lowestRight = 0;
  15497. highestLeft = 0;
  15498. highestRight = 0;
  15499. return;
  15500. }
  15501. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  15502. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15503. int* tempBuffer[3];
  15504. tempBuffer[0] = (int*) tempSpace.getData();
  15505. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15506. tempBuffer[2] = 0;
  15507. if (usesFloatingPointData)
  15508. {
  15509. float lmin = 1.0e6;
  15510. float lmax = -lmin;
  15511. float rmin = lmin;
  15512. float rmax = lmax;
  15513. while (numSamples > 0)
  15514. {
  15515. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15516. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15517. numSamples -= numToDo;
  15518. startSampleInFile += numToDo;
  15519. float bufmin, bufmax;
  15520. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  15521. lmin = jmin (lmin, bufmin);
  15522. lmax = jmax (lmax, bufmax);
  15523. if (numChannels > 1)
  15524. {
  15525. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  15526. rmin = jmin (rmin, bufmin);
  15527. rmax = jmax (rmax, bufmax);
  15528. }
  15529. }
  15530. if (numChannels <= 1)
  15531. {
  15532. rmax = lmax;
  15533. rmin = lmin;
  15534. }
  15535. lowestLeft = lmin;
  15536. highestLeft = lmax;
  15537. lowestRight = rmin;
  15538. highestRight = rmax;
  15539. }
  15540. else
  15541. {
  15542. int lmax = INT_MIN;
  15543. int lmin = INT_MAX;
  15544. int rmax = INT_MIN;
  15545. int rmin = INT_MAX;
  15546. while (numSamples > 0)
  15547. {
  15548. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15549. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15550. numSamples -= numToDo;
  15551. startSampleInFile += numToDo;
  15552. for (int j = numChannels; --j >= 0;)
  15553. {
  15554. int bufMax = INT_MIN;
  15555. int bufMin = INT_MAX;
  15556. const int* const b = tempBuffer[j];
  15557. for (int i = 0; i < numToDo; ++i)
  15558. {
  15559. const int samp = b[i];
  15560. if (samp < bufMin)
  15561. bufMin = samp;
  15562. if (samp > bufMax)
  15563. bufMax = samp;
  15564. }
  15565. if (j == 0)
  15566. {
  15567. lmax = jmax (lmax, bufMax);
  15568. lmin = jmin (lmin, bufMin);
  15569. }
  15570. else
  15571. {
  15572. rmax = jmax (rmax, bufMax);
  15573. rmin = jmin (rmin, bufMin);
  15574. }
  15575. }
  15576. }
  15577. if (numChannels <= 1)
  15578. {
  15579. rmax = lmax;
  15580. rmin = lmin;
  15581. }
  15582. lowestLeft = lmin / (float)INT_MAX;
  15583. highestLeft = lmax / (float)INT_MAX;
  15584. lowestRight = rmin / (float)INT_MAX;
  15585. highestRight = rmax / (float)INT_MAX;
  15586. }
  15587. }
  15588. int64 AudioFormatReader::searchForLevel (int64 startSample,
  15589. int64 numSamplesToSearch,
  15590. const double magnitudeRangeMinimum,
  15591. const double magnitudeRangeMaximum,
  15592. const int minimumConsecutiveSamples)
  15593. {
  15594. if (numSamplesToSearch == 0)
  15595. return -1;
  15596. const int bufferSize = 4096;
  15597. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15598. int* tempBuffer[3];
  15599. tempBuffer[0] = (int*) tempSpace.getData();
  15600. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15601. tempBuffer[2] = 0;
  15602. int consecutive = 0;
  15603. int64 firstMatchPos = -1;
  15604. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  15605. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  15606. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  15607. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  15608. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  15609. while (numSamplesToSearch != 0)
  15610. {
  15611. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  15612. int64 bufferStart = startSample;
  15613. if (numSamplesToSearch < 0)
  15614. bufferStart -= numThisTime;
  15615. if (bufferStart >= (int) lengthInSamples)
  15616. break;
  15617. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  15618. int num = numThisTime;
  15619. while (--num >= 0)
  15620. {
  15621. if (numSamplesToSearch < 0)
  15622. --startSample;
  15623. bool matches = false;
  15624. const int index = (int) (startSample - bufferStart);
  15625. if (usesFloatingPointData)
  15626. {
  15627. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  15628. if (sample1 >= magnitudeRangeMinimum
  15629. && sample1 <= magnitudeRangeMaximum)
  15630. {
  15631. matches = true;
  15632. }
  15633. else if (numChannels > 1)
  15634. {
  15635. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  15636. matches = (sample2 >= magnitudeRangeMinimum
  15637. && sample2 <= magnitudeRangeMaximum);
  15638. }
  15639. }
  15640. else
  15641. {
  15642. const int sample1 = abs (tempBuffer[0] [index]);
  15643. if (sample1 >= intMagnitudeRangeMinimum
  15644. && sample1 <= intMagnitudeRangeMaximum)
  15645. {
  15646. matches = true;
  15647. }
  15648. else if (numChannels > 1)
  15649. {
  15650. const int sample2 = abs (tempBuffer[1][index]);
  15651. matches = (sample2 >= intMagnitudeRangeMinimum
  15652. && sample2 <= intMagnitudeRangeMaximum);
  15653. }
  15654. }
  15655. if (matches)
  15656. {
  15657. if (firstMatchPos < 0)
  15658. firstMatchPos = startSample;
  15659. if (++consecutive >= minimumConsecutiveSamples)
  15660. {
  15661. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  15662. return -1;
  15663. return firstMatchPos;
  15664. }
  15665. }
  15666. else
  15667. {
  15668. consecutive = 0;
  15669. firstMatchPos = -1;
  15670. }
  15671. if (numSamplesToSearch > 0)
  15672. ++startSample;
  15673. }
  15674. if (numSamplesToSearch > 0)
  15675. numSamplesToSearch -= numThisTime;
  15676. else
  15677. numSamplesToSearch += numThisTime;
  15678. }
  15679. return -1;
  15680. }
  15681. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  15682. const String& formatName_,
  15683. const double rate,
  15684. const unsigned int numChannels_,
  15685. const unsigned int bitsPerSample_)
  15686. : sampleRate (rate),
  15687. numChannels (numChannels_),
  15688. bitsPerSample (bitsPerSample_),
  15689. usesFloatingPointData (false),
  15690. output (out),
  15691. formatName (formatName_)
  15692. {
  15693. }
  15694. AudioFormatWriter::~AudioFormatWriter()
  15695. {
  15696. delete output;
  15697. }
  15698. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  15699. int64 startSample,
  15700. int64 numSamplesToRead)
  15701. {
  15702. const int bufferSize = 16384;
  15703. const int maxChans = 128;
  15704. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  15705. int* buffers [maxChans];
  15706. for (int i = maxChans; --i >= 0;)
  15707. buffers[i] = 0;
  15708. if (numSamplesToRead < 0)
  15709. numSamplesToRead = reader.lengthInSamples;
  15710. while (numSamplesToRead > 0)
  15711. {
  15712. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  15713. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  15714. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15715. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  15716. return false;
  15717. if (reader.usesFloatingPointData != isFloatingPoint())
  15718. {
  15719. int** bufferChan = buffers;
  15720. while (*bufferChan != 0)
  15721. {
  15722. int* b = *bufferChan++;
  15723. if (isFloatingPoint())
  15724. {
  15725. // int -> float
  15726. const double factor = 1.0 / INT_MAX;
  15727. for (int i = 0; i < numToDo; ++i)
  15728. ((float*)b)[i] = (float) (factor * b[i]);
  15729. }
  15730. else
  15731. {
  15732. // float -> int
  15733. for (int i = 0; i < numToDo; ++i)
  15734. {
  15735. const double samp = *(const float*) b;
  15736. if (samp <= -1.0)
  15737. *b++ = INT_MIN;
  15738. else if (samp >= 1.0)
  15739. *b++ = INT_MAX;
  15740. else
  15741. *b++ = roundDoubleToInt (INT_MAX * samp);
  15742. }
  15743. }
  15744. }
  15745. }
  15746. if (! write ((const int**) buffers, numToDo))
  15747. return false;
  15748. numSamplesToRead -= numToDo;
  15749. startSample += numToDo;
  15750. }
  15751. return true;
  15752. }
  15753. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  15754. int numSamplesToRead,
  15755. const int samplesPerBlock)
  15756. {
  15757. const int maxChans = 128;
  15758. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  15759. int* buffers [maxChans];
  15760. while (numSamplesToRead > 0)
  15761. {
  15762. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  15763. AudioSourceChannelInfo info;
  15764. info.buffer = &tempBuffer;
  15765. info.startSample = 0;
  15766. info.numSamples = numToDo;
  15767. info.clearActiveBufferRegion();
  15768. source.getNextAudioBlock (info);
  15769. int i;
  15770. for (i = maxChans; --i >= 0;)
  15771. buffers[i] = 0;
  15772. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  15773. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15774. if (! isFloatingPoint())
  15775. {
  15776. int** bufferChan = buffers;
  15777. while (*bufferChan != 0)
  15778. {
  15779. int* b = *bufferChan++;
  15780. // float -> int
  15781. for (int j = numToDo; --j >= 0;)
  15782. {
  15783. const double samp = *(const float*) b;
  15784. if (samp <= -1.0)
  15785. *b++ = INT_MIN;
  15786. else if (samp >= 1.0)
  15787. *b++ = INT_MAX;
  15788. else
  15789. *b++ = roundDoubleToInt (INT_MAX * samp);
  15790. }
  15791. }
  15792. }
  15793. if (! write ((const int**) buffers, numToDo))
  15794. return false;
  15795. numSamplesToRead -= numToDo;
  15796. }
  15797. return true;
  15798. }
  15799. AudioFormat::AudioFormat (const String& name,
  15800. const tchar** const extensions)
  15801. : formatName (name),
  15802. fileExtensions (extensions)
  15803. {
  15804. }
  15805. AudioFormat::~AudioFormat()
  15806. {
  15807. }
  15808. const String& AudioFormat::getFormatName() const
  15809. {
  15810. return formatName;
  15811. }
  15812. const StringArray& AudioFormat::getFileExtensions() const
  15813. {
  15814. return fileExtensions;
  15815. }
  15816. bool AudioFormat::canHandleFile (const File& f)
  15817. {
  15818. for (int i = 0; i < fileExtensions.size(); ++i)
  15819. if (f.hasFileExtension (fileExtensions[i]))
  15820. return true;
  15821. return false;
  15822. }
  15823. bool AudioFormat::isCompressed()
  15824. {
  15825. return false;
  15826. }
  15827. const StringArray AudioFormat::getQualityOptions()
  15828. {
  15829. return StringArray();
  15830. }
  15831. END_JUCE_NAMESPACE
  15832. /********* End of inlined file: juce_AudioFormat.cpp *********/
  15833. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  15834. BEGIN_JUCE_NAMESPACE
  15835. AudioFormatManager::AudioFormatManager()
  15836. : knownFormats (4),
  15837. defaultFormatIndex (0)
  15838. {
  15839. }
  15840. AudioFormatManager::~AudioFormatManager()
  15841. {
  15842. clearFormats();
  15843. clearSingletonInstance();
  15844. }
  15845. juce_ImplementSingleton (AudioFormatManager);
  15846. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  15847. const bool makeThisTheDefaultFormat)
  15848. {
  15849. jassert (newFormat != 0);
  15850. if (newFormat != 0)
  15851. {
  15852. #ifdef JUCE_DEBUG
  15853. for (int i = getNumKnownFormats(); --i >= 0;)
  15854. {
  15855. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  15856. {
  15857. jassertfalse // trying to add the same format twice!
  15858. }
  15859. }
  15860. #endif
  15861. if (makeThisTheDefaultFormat)
  15862. defaultFormatIndex = knownFormats.size();
  15863. knownFormats.add (newFormat);
  15864. }
  15865. }
  15866. void AudioFormatManager::registerBasicFormats()
  15867. {
  15868. #if JUCE_MAC
  15869. registerFormat (new AiffAudioFormat(), true);
  15870. registerFormat (new WavAudioFormat(), false);
  15871. #else
  15872. registerFormat (new WavAudioFormat(), true);
  15873. registerFormat (new AiffAudioFormat(), false);
  15874. #endif
  15875. #if JUCE_USE_FLAC
  15876. registerFormat (new FlacAudioFormat(), false);
  15877. #endif
  15878. #if JUCE_USE_OGGVORBIS
  15879. registerFormat (new OggVorbisAudioFormat(), false);
  15880. #endif
  15881. }
  15882. void AudioFormatManager::clearFormats()
  15883. {
  15884. for (int i = getNumKnownFormats(); --i >= 0;)
  15885. {
  15886. AudioFormat* const af = getKnownFormat(i);
  15887. delete af;
  15888. }
  15889. knownFormats.clear();
  15890. defaultFormatIndex = 0;
  15891. }
  15892. int AudioFormatManager::getNumKnownFormats() const
  15893. {
  15894. return knownFormats.size();
  15895. }
  15896. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  15897. {
  15898. return (AudioFormat*) knownFormats [index];
  15899. }
  15900. AudioFormat* AudioFormatManager::getDefaultFormat() const
  15901. {
  15902. return getKnownFormat (defaultFormatIndex);
  15903. }
  15904. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  15905. {
  15906. String e (fileExtension);
  15907. if (! e.startsWithChar (T('.')))
  15908. e = T(".") + e;
  15909. for (int i = 0; i < getNumKnownFormats(); ++i)
  15910. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  15911. return getKnownFormat(i);
  15912. return 0;
  15913. }
  15914. const String AudioFormatManager::getWildcardForAllFormats() const
  15915. {
  15916. StringArray allExtensions;
  15917. int i;
  15918. for (i = 0; i < getNumKnownFormats(); ++i)
  15919. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  15920. allExtensions.trim();
  15921. allExtensions.removeEmptyStrings();
  15922. String s;
  15923. for (i = 0; i < allExtensions.size(); ++i)
  15924. {
  15925. s << T('*');
  15926. if (! allExtensions[i].startsWithChar (T('.')))
  15927. s << T('.');
  15928. s << allExtensions[i];
  15929. if (i < allExtensions.size() - 1)
  15930. s << T(';');
  15931. }
  15932. return s;
  15933. }
  15934. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  15935. {
  15936. // you need to actually register some formats before the manager can
  15937. // use them to open a file!
  15938. jassert (knownFormats.size() > 0);
  15939. for (int i = 0; i < getNumKnownFormats(); ++i)
  15940. {
  15941. AudioFormat* const af = getKnownFormat(i);
  15942. if (af->canHandleFile (file))
  15943. {
  15944. InputStream* const in = file.createInputStream();
  15945. if (in != 0)
  15946. {
  15947. AudioFormatReader* const r = af->createReaderFor (in, true);
  15948. if (r != 0)
  15949. return r;
  15950. }
  15951. }
  15952. }
  15953. return 0;
  15954. }
  15955. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  15956. {
  15957. // you need to actually register some formats before the manager can
  15958. // use them to open a file!
  15959. jassert (knownFormats.size() > 0);
  15960. if (in != 0)
  15961. {
  15962. const int64 originalStreamPos = in->getPosition();
  15963. for (int i = 0; i < getNumKnownFormats(); ++i)
  15964. {
  15965. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  15966. if (r != 0)
  15967. return r;
  15968. in->setPosition (originalStreamPos);
  15969. // the stream that is passed-in must be capable of being repositioned so
  15970. // that all the formats can have a go at opening it.
  15971. jassert (in->getPosition() == originalStreamPos);
  15972. }
  15973. delete in;
  15974. }
  15975. return 0;
  15976. }
  15977. END_JUCE_NAMESPACE
  15978. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  15979. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  15980. BEGIN_JUCE_NAMESPACE
  15981. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  15982. const int64 startSample_,
  15983. const int64 length_,
  15984. const bool deleteSourceWhenDeleted_)
  15985. : AudioFormatReader (0, source_->getFormatName()),
  15986. source (source_),
  15987. startSample (startSample_),
  15988. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  15989. {
  15990. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  15991. sampleRate = source->sampleRate;
  15992. bitsPerSample = source->bitsPerSample;
  15993. lengthInSamples = length;
  15994. numChannels = source->numChannels;
  15995. usesFloatingPointData = source->usesFloatingPointData;
  15996. }
  15997. AudioSubsectionReader::~AudioSubsectionReader()
  15998. {
  15999. if (deleteSourceWhenDeleted)
  16000. delete source;
  16001. }
  16002. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16003. int64 startSampleInFile, int numSamples)
  16004. {
  16005. if (startSampleInFile + numSamples > length)
  16006. {
  16007. for (int i = numDestChannels; --i >= 0;)
  16008. if (destSamples[i] != 0)
  16009. zeromem (destSamples[i], sizeof (int) * numSamples);
  16010. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16011. if (numSamples <= 0)
  16012. return true;
  16013. }
  16014. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16015. startSampleInFile + startSample, numSamples);
  16016. }
  16017. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16018. int64 numSamples,
  16019. float& lowestLeft,
  16020. float& highestLeft,
  16021. float& lowestRight,
  16022. float& highestRight)
  16023. {
  16024. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16025. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16026. source->readMaxLevels (startSampleInFile + startSample,
  16027. numSamples,
  16028. lowestLeft,
  16029. highestLeft,
  16030. lowestRight,
  16031. highestRight);
  16032. }
  16033. END_JUCE_NAMESPACE
  16034. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  16035. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  16036. BEGIN_JUCE_NAMESPACE
  16037. const int timeBeforeDeletingReader = 2000;
  16038. struct AudioThumbnailDataFormat
  16039. {
  16040. char thumbnailMagic[4];
  16041. int samplesPerThumbSample;
  16042. int64 totalSamples; // source samples
  16043. int64 numFinishedSamples; // source samples
  16044. int numThumbnailSamples;
  16045. int numChannels;
  16046. int sampleRate;
  16047. char future[16];
  16048. char data[1];
  16049. };
  16050. #if JUCE_BIG_ENDIAN
  16051. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  16052. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  16053. #endif
  16054. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  16055. {
  16056. (void) d;
  16057. #if JUCE_BIG_ENDIAN
  16058. swap (d->samplesPerThumbSample);
  16059. swap (d->totalSamples);
  16060. swap (d->numFinishedSamples);
  16061. swap (d->numThumbnailSamples);
  16062. swap (d->numChannels);
  16063. swap (d->sampleRate);
  16064. #endif
  16065. }
  16066. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16067. AudioFormatManager& formatManagerToUse_,
  16068. AudioThumbnailCache& cacheToUse)
  16069. : formatManagerToUse (formatManagerToUse_),
  16070. cache (cacheToUse),
  16071. source (0),
  16072. reader (0),
  16073. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16074. {
  16075. clear();
  16076. }
  16077. AudioThumbnail::~AudioThumbnail()
  16078. {
  16079. cache.removeThumbnail (this);
  16080. const ScopedLock sl (readerLock);
  16081. deleteAndZero (reader);
  16082. delete source;
  16083. }
  16084. void AudioThumbnail::setSource (InputSource* const newSource)
  16085. {
  16086. cache.removeThumbnail (this);
  16087. timerCallback(); // stops the timer and deletes the reader
  16088. delete source;
  16089. source = newSource;
  16090. clear();
  16091. if (newSource != 0
  16092. && ! (cache.loadThumb (*this, newSource->hashCode())
  16093. && isFullyLoaded()))
  16094. {
  16095. {
  16096. const ScopedLock sl (readerLock);
  16097. reader = createReader();
  16098. }
  16099. if (reader != 0)
  16100. {
  16101. initialiseFromAudioFile (*reader);
  16102. cache.addThumbnail (this);
  16103. }
  16104. }
  16105. sendChangeMessage (this);
  16106. }
  16107. bool AudioThumbnail::useTimeSlice()
  16108. {
  16109. const ScopedLock sl (readerLock);
  16110. if (isFullyLoaded())
  16111. {
  16112. if (reader != 0)
  16113. startTimer (timeBeforeDeletingReader);
  16114. cache.removeThumbnail (this);
  16115. return false;
  16116. }
  16117. if (reader == 0)
  16118. reader = createReader();
  16119. if (reader != 0)
  16120. {
  16121. readNextBlockFromAudioFile (*reader);
  16122. stopTimer();
  16123. sendChangeMessage (this);
  16124. const bool justFinished = isFullyLoaded();
  16125. if (justFinished)
  16126. cache.storeThumb (*this, source->hashCode());
  16127. return ! justFinished;
  16128. }
  16129. return false;
  16130. }
  16131. AudioFormatReader* AudioThumbnail::createReader() const
  16132. {
  16133. if (source != 0)
  16134. {
  16135. InputStream* const audioFileStream = source->createInputStream();
  16136. if (audioFileStream != 0)
  16137. return formatManagerToUse.createReaderFor (audioFileStream);
  16138. }
  16139. return 0;
  16140. }
  16141. void AudioThumbnail::timerCallback()
  16142. {
  16143. stopTimer();
  16144. const ScopedLock sl (readerLock);
  16145. deleteAndZero (reader);
  16146. }
  16147. void AudioThumbnail::clear()
  16148. {
  16149. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16150. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16151. d->thumbnailMagic[0] = 'j';
  16152. d->thumbnailMagic[1] = 'a';
  16153. d->thumbnailMagic[2] = 't';
  16154. d->thumbnailMagic[3] = 'm';
  16155. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16156. d->totalSamples = 0;
  16157. d->numFinishedSamples = 0;
  16158. d->numThumbnailSamples = 0;
  16159. d->numChannels = 0;
  16160. d->sampleRate = 0;
  16161. numSamplesCached = 0;
  16162. cacheNeedsRefilling = true;
  16163. }
  16164. void AudioThumbnail::loadFrom (InputStream& input)
  16165. {
  16166. data.setSize (0);
  16167. input.readIntoMemoryBlock (data);
  16168. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16169. swapEndiannessIfNeeded (d);
  16170. if (! (d->thumbnailMagic[0] == 'j'
  16171. && d->thumbnailMagic[1] == 'a'
  16172. && d->thumbnailMagic[2] == 't'
  16173. && d->thumbnailMagic[3] == 'm'))
  16174. {
  16175. clear();
  16176. }
  16177. numSamplesCached = 0;
  16178. cacheNeedsRefilling = true;
  16179. }
  16180. void AudioThumbnail::saveTo (OutputStream& output) const
  16181. {
  16182. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16183. swapEndiannessIfNeeded (d);
  16184. output.write (data.getData(), data.getSize());
  16185. swapEndiannessIfNeeded (d);
  16186. }
  16187. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  16188. {
  16189. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16190. d->totalSamples = reader.lengthInSamples;
  16191. d->numChannels = jmin (2, reader.numChannels);
  16192. d->numFinishedSamples = 0;
  16193. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  16194. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16195. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16196. d = (AudioThumbnailDataFormat*) data.getData();
  16197. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16198. return d->totalSamples > 0;
  16199. }
  16200. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  16201. {
  16202. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16203. if (d->numFinishedSamples < d->totalSamples)
  16204. {
  16205. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16206. generateSection (reader,
  16207. d->numFinishedSamples,
  16208. numToDo);
  16209. d->numFinishedSamples += numToDo;
  16210. }
  16211. cacheNeedsRefilling = true;
  16212. return (d->numFinishedSamples < d->totalSamples);
  16213. }
  16214. int AudioThumbnail::getNumChannels() const throw()
  16215. {
  16216. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16217. jassert (d != 0);
  16218. return d->numChannels;
  16219. }
  16220. double AudioThumbnail::getTotalLength() const throw()
  16221. {
  16222. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16223. jassert (d != 0);
  16224. if (d->sampleRate > 0)
  16225. return d->totalSamples / (double)d->sampleRate;
  16226. else
  16227. return 0.0;
  16228. }
  16229. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  16230. int64 startSample,
  16231. int numSamples)
  16232. {
  16233. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16234. jassert (d != 0);
  16235. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16236. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16237. char* l = getChannelData (0);
  16238. char* r = getChannelData (1);
  16239. for (int i = firstDataPos; i < lastDataPos; ++i)
  16240. {
  16241. const int sourceStart = i * d->samplesPerThumbSample;
  16242. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16243. float lowestLeft, highestLeft, lowestRight, highestRight;
  16244. reader.readMaxLevels (sourceStart,
  16245. sourceEnd - sourceStart,
  16246. lowestLeft,
  16247. highestLeft,
  16248. lowestRight,
  16249. highestRight);
  16250. int n = i * 2;
  16251. if (r != 0)
  16252. {
  16253. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16254. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16255. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16256. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16257. }
  16258. else
  16259. {
  16260. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16261. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16262. }
  16263. }
  16264. }
  16265. char* AudioThumbnail::getChannelData (int channel) const
  16266. {
  16267. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16268. jassert (d != 0);
  16269. if (channel >= 0 && channel < d->numChannels)
  16270. return d->data + (channel * 2 * d->numThumbnailSamples);
  16271. return 0;
  16272. }
  16273. bool AudioThumbnail::isFullyLoaded() const throw()
  16274. {
  16275. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16276. jassert (d != 0);
  16277. return d->numFinishedSamples >= d->totalSamples;
  16278. }
  16279. void AudioThumbnail::refillCache (const int numSamples,
  16280. double startTime,
  16281. const double timePerPixel)
  16282. {
  16283. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16284. jassert (d != 0);
  16285. if (numSamples <= 0
  16286. || timePerPixel <= 0.0
  16287. || d->sampleRate <= 0)
  16288. {
  16289. numSamplesCached = 0;
  16290. cacheNeedsRefilling = true;
  16291. return;
  16292. }
  16293. if (numSamples == numSamplesCached
  16294. && numChannelsCached == d->numChannels
  16295. && startTime == cachedStart
  16296. && timePerPixel == cachedTimePerPixel
  16297. && ! cacheNeedsRefilling)
  16298. {
  16299. return;
  16300. }
  16301. numSamplesCached = numSamples;
  16302. numChannelsCached = d->numChannels;
  16303. cachedStart = startTime;
  16304. cachedTimePerPixel = timePerPixel;
  16305. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16306. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16307. const ScopedLock sl (readerLock);
  16308. cacheNeedsRefilling = false;
  16309. if (needExtraDetail && reader == 0)
  16310. reader = createReader();
  16311. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16312. {
  16313. startTimer (timeBeforeDeletingReader);
  16314. char* cacheData = (char*) cachedLevels.getData();
  16315. int sample = roundDoubleToInt (startTime * d->sampleRate);
  16316. for (int i = numSamples; --i >= 0;)
  16317. {
  16318. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  16319. if (sample >= 0)
  16320. {
  16321. if (sample >= reader->lengthInSamples)
  16322. break;
  16323. float lmin, lmax, rmin, rmax;
  16324. reader->readMaxLevels (sample,
  16325. jmax (1, nextSample - sample),
  16326. lmin, lmax, rmin, rmax);
  16327. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16328. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16329. if (numChannelsCached > 1)
  16330. {
  16331. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16332. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16333. }
  16334. cacheData += 2 * numChannelsCached;
  16335. }
  16336. startTime += timePerPixel;
  16337. sample = nextSample;
  16338. }
  16339. }
  16340. else
  16341. {
  16342. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16343. {
  16344. char* const data = getChannelData (channelNum);
  16345. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  16346. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16347. startTime = cachedStart;
  16348. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  16349. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16350. for (int i = numSamples; --i >= 0;)
  16351. {
  16352. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16353. if (sample >= 0 && data != 0)
  16354. {
  16355. char mx = -128;
  16356. char mn = 127;
  16357. while (sample <= nextSample)
  16358. {
  16359. if (sample >= numFinished)
  16360. break;
  16361. const int n = sample << 1;
  16362. const char sampMin = data [n];
  16363. const char sampMax = data [n + 1];
  16364. if (sampMin < mn)
  16365. mn = sampMin;
  16366. if (sampMax > mx)
  16367. mx = sampMax;
  16368. ++sample;
  16369. }
  16370. if (mn <= mx)
  16371. {
  16372. cacheData[0] = mn;
  16373. cacheData[1] = mx;
  16374. }
  16375. else
  16376. {
  16377. cacheData[0] = 1;
  16378. cacheData[1] = 0;
  16379. }
  16380. }
  16381. else
  16382. {
  16383. cacheData[0] = 1;
  16384. cacheData[1] = 0;
  16385. }
  16386. cacheData += numChannelsCached * 2;
  16387. startTime += timePerPixel;
  16388. sample = nextSample;
  16389. }
  16390. }
  16391. }
  16392. }
  16393. void AudioThumbnail::drawChannel (Graphics& g,
  16394. int x, int y, int w, int h,
  16395. double startTime,
  16396. double endTime,
  16397. int channelNum,
  16398. const float verticalZoomFactor)
  16399. {
  16400. refillCache (w, startTime, (endTime - startTime) / w);
  16401. if (numSamplesCached >= w
  16402. && channelNum >= 0
  16403. && channelNum < numChannelsCached)
  16404. {
  16405. const float topY = (float) y;
  16406. const float bottomY = topY + h;
  16407. const float midY = topY + h * 0.5f;
  16408. const float vscale = verticalZoomFactor * h / 256.0f;
  16409. const Rectangle clip (g.getClipBounds());
  16410. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16411. w -= skipLeft;
  16412. x += skipLeft;
  16413. const char* cacheData = ((const char*) cachedLevels.getData())
  16414. + (channelNum << 1)
  16415. + skipLeft * (numChannelsCached << 1);
  16416. while (--w >= 0)
  16417. {
  16418. const char mn = cacheData[0];
  16419. const char mx = cacheData[1];
  16420. cacheData += numChannelsCached << 1;
  16421. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16422. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16423. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16424. ++x;
  16425. if (x >= clip.getRight())
  16426. break;
  16427. }
  16428. }
  16429. }
  16430. END_JUCE_NAMESPACE
  16431. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  16432. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  16433. BEGIN_JUCE_NAMESPACE
  16434. struct ThumbnailCacheEntry
  16435. {
  16436. int64 hash;
  16437. uint32 lastUsed;
  16438. MemoryBlock data;
  16439. juce_UseDebuggingNewOperator
  16440. };
  16441. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16442. : TimeSliceThread (T("thumb cache")),
  16443. maxNumThumbsToStore (maxNumThumbsToStore_)
  16444. {
  16445. startThread (2);
  16446. }
  16447. AudioThumbnailCache::~AudioThumbnailCache()
  16448. {
  16449. }
  16450. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16451. {
  16452. for (int i = thumbs.size(); --i >= 0;)
  16453. {
  16454. if (thumbs[i]->hash == hashCode)
  16455. {
  16456. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  16457. thumbs[i]->data.getSize(),
  16458. false);
  16459. thumb.loadFrom (in);
  16460. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16461. return true;
  16462. }
  16463. }
  16464. return false;
  16465. }
  16466. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16467. const int64 hashCode)
  16468. {
  16469. MemoryOutputStream out;
  16470. thumb.saveTo (out);
  16471. ThumbnailCacheEntry* te = 0;
  16472. for (int i = thumbs.size(); --i >= 0;)
  16473. {
  16474. if (thumbs[i]->hash == hashCode)
  16475. {
  16476. te = thumbs[i];
  16477. break;
  16478. }
  16479. }
  16480. if (te == 0)
  16481. {
  16482. te = new ThumbnailCacheEntry();
  16483. te->hash = hashCode;
  16484. if (thumbs.size() < maxNumThumbsToStore)
  16485. {
  16486. thumbs.add (te);
  16487. }
  16488. else
  16489. {
  16490. int oldest = 0;
  16491. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16492. int i;
  16493. for (i = thumbs.size(); --i >= 0;)
  16494. if (thumbs[i]->lastUsed < oldestTime)
  16495. oldest = i;
  16496. thumbs.set (i, te);
  16497. }
  16498. }
  16499. te->lastUsed = Time::getMillisecondCounter();
  16500. te->data.setSize (0);
  16501. te->data.append (out.getData(), out.getDataSize());
  16502. }
  16503. void AudioThumbnailCache::clear()
  16504. {
  16505. thumbs.clear();
  16506. }
  16507. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  16508. {
  16509. addTimeSliceClient (thumb);
  16510. }
  16511. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  16512. {
  16513. removeTimeSliceClient (thumb);
  16514. }
  16515. END_JUCE_NAMESPACE
  16516. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  16517. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16518. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  16519. #if ! JUCE_WINDOWS
  16520. #include <QuickTime/Movies.h>
  16521. #include <QuickTime/QTML.h>
  16522. #include <QuickTime/QuickTimeComponents.h>
  16523. #include <QuickTime/MediaHandlers.h>
  16524. #include <QuickTime/ImageCodec.h>
  16525. #else
  16526. #if JUCE_MSVC
  16527. #pragma warning (push)
  16528. #pragma warning (disable : 4100)
  16529. #endif
  16530. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  16531. add its header directory to your include path.
  16532. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  16533. flag in juce_Config.h
  16534. */
  16535. #include <Movies.h>
  16536. #include <QTML.h>
  16537. #include <QuickTimeComponents.h>
  16538. #include <MediaHandlers.h>
  16539. #include <ImageCodec.h>
  16540. #if JUCE_MSVC
  16541. #pragma warning (pop)
  16542. #endif
  16543. #endif
  16544. BEGIN_JUCE_NAMESPACE
  16545. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  16546. #define quickTimeFormatName TRANS("QuickTime file")
  16547. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  16548. class QTAudioReader : public AudioFormatReader
  16549. {
  16550. public:
  16551. QTAudioReader (InputStream* const input_, const int trackNum_)
  16552. : AudioFormatReader (input_, quickTimeFormatName),
  16553. ok (false),
  16554. movie (0),
  16555. trackNum (trackNum_),
  16556. extractor (0),
  16557. lastSampleRead (0),
  16558. lastThreadId (0),
  16559. dataHandle (0)
  16560. {
  16561. bufferList = (AudioBufferList*) juce_calloc (256);
  16562. #ifdef WIN32
  16563. if (InitializeQTML (0) != noErr)
  16564. return;
  16565. #endif
  16566. if (EnterMovies() != noErr)
  16567. return;
  16568. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  16569. if (! opened)
  16570. return;
  16571. {
  16572. const int numTracks = GetMovieTrackCount (movie);
  16573. int trackCount = 0;
  16574. for (int i = 1; i <= numTracks; ++i)
  16575. {
  16576. track = GetMovieIndTrack (movie, i);
  16577. media = GetTrackMedia (track);
  16578. OSType mediaType;
  16579. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  16580. if (mediaType == SoundMediaType
  16581. && trackCount++ == trackNum_)
  16582. {
  16583. ok = true;
  16584. break;
  16585. }
  16586. }
  16587. }
  16588. if (! ok)
  16589. return;
  16590. ok = false;
  16591. lengthInSamples = GetMediaDecodeDuration (media);
  16592. usesFloatingPointData = false;
  16593. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  16594. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  16595. / GetMediaTimeScale (media);
  16596. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  16597. unsigned long output_layout_size;
  16598. err = MovieAudioExtractionGetPropertyInfo (extractor,
  16599. kQTPropertyClass_MovieAudioExtraction_Audio,
  16600. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16601. 0, &output_layout_size, 0);
  16602. if (err != noErr)
  16603. return;
  16604. AudioChannelLayout* const qt_audio_channel_layout
  16605. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  16606. err = MovieAudioExtractionGetProperty (extractor,
  16607. kQTPropertyClass_MovieAudioExtraction_Audio,
  16608. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16609. output_layout_size, qt_audio_channel_layout, 0);
  16610. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  16611. err = MovieAudioExtractionSetProperty (extractor,
  16612. kQTPropertyClass_MovieAudioExtraction_Audio,
  16613. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16614. sizeof (qt_audio_channel_layout),
  16615. qt_audio_channel_layout);
  16616. juce_free (qt_audio_channel_layout);
  16617. err = MovieAudioExtractionGetProperty (extractor,
  16618. kQTPropertyClass_MovieAudioExtraction_Audio,
  16619. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16620. sizeof (inputStreamDesc),
  16621. &inputStreamDesc, 0);
  16622. if (err != noErr)
  16623. return;
  16624. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  16625. | kAudioFormatFlagIsPacked
  16626. | kAudioFormatFlagsNativeEndian;
  16627. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  16628. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  16629. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  16630. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  16631. err = MovieAudioExtractionSetProperty (extractor,
  16632. kQTPropertyClass_MovieAudioExtraction_Audio,
  16633. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16634. sizeof (inputStreamDesc),
  16635. &inputStreamDesc);
  16636. if (err != noErr)
  16637. return;
  16638. Boolean allChannelsDiscrete = false;
  16639. err = MovieAudioExtractionSetProperty (extractor,
  16640. kQTPropertyClass_MovieAudioExtraction_Movie,
  16641. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  16642. sizeof (allChannelsDiscrete),
  16643. &allChannelsDiscrete);
  16644. if (err != noErr)
  16645. return;
  16646. bufferList->mNumberBuffers = 1;
  16647. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  16648. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  16649. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  16650. sampleRate = inputStreamDesc.mSampleRate;
  16651. bitsPerSample = 16;
  16652. numChannels = inputStreamDesc.mChannelsPerFrame;
  16653. detachThread();
  16654. ok = true;
  16655. }
  16656. ~QTAudioReader()
  16657. {
  16658. if (dataHandle != 0)
  16659. DisposeHandle (dataHandle);
  16660. if (extractor != 0)
  16661. {
  16662. MovieAudioExtractionEnd (extractor);
  16663. extractor = 0;
  16664. }
  16665. checkThreadIsAttached();
  16666. DisposeMovie (movie);
  16667. juce_free (bufferList->mBuffers[0].mData);
  16668. juce_free (bufferList);
  16669. #if JUCE_MAC
  16670. ExitMoviesOnThread ();
  16671. #endif
  16672. }
  16673. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16674. int64 startSampleInFile, int numSamples)
  16675. {
  16676. checkThreadIsAttached();
  16677. while (numSamples > 0)
  16678. {
  16679. if (! loadFrame ((int) startSampleInFile))
  16680. return false;
  16681. const int numToDo = jmin (numSamples, samplesPerFrame);
  16682. for (int j = numDestChannels; --j >= 0;)
  16683. {
  16684. if (destSamples[j] != 0)
  16685. {
  16686. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  16687. for (int i = 0; i < numToDo; ++i)
  16688. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  16689. }
  16690. }
  16691. startOffsetInDestBuffer += numToDo;
  16692. startSampleInFile += numToDo;
  16693. numSamples -= numToDo;
  16694. }
  16695. detachThread();
  16696. return true;
  16697. }
  16698. bool loadFrame (const int sampleNum)
  16699. {
  16700. if (lastSampleRead != sampleNum)
  16701. {
  16702. TimeRecord time;
  16703. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  16704. time.base = 0;
  16705. time.value.hi = 0;
  16706. time.value.lo = (UInt32) sampleNum;
  16707. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  16708. kQTPropertyClass_MovieAudioExtraction_Movie,
  16709. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  16710. sizeof (time), &time);
  16711. if (err != noErr)
  16712. return false;
  16713. }
  16714. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  16715. UInt32 outFlags = 0;
  16716. UInt32 actualNumSamples = samplesPerFrame;
  16717. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  16718. bufferList, &outFlags);
  16719. lastSampleRead = sampleNum + samplesPerFrame;
  16720. return err == noErr;
  16721. }
  16722. juce_UseDebuggingNewOperator
  16723. bool ok;
  16724. private:
  16725. Movie movie;
  16726. Media media;
  16727. Track track;
  16728. const int trackNum;
  16729. double trackUnitsPerFrame;
  16730. int samplesPerFrame;
  16731. int lastSampleRead;
  16732. Thread::ThreadID lastThreadId;
  16733. MovieAudioExtractionRef extractor;
  16734. AudioStreamBasicDescription inputStreamDesc;
  16735. AudioBufferList* bufferList;
  16736. Handle dataHandle;
  16737. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  16738. {
  16739. input->setPosition (offset);
  16740. input->read (dataPtr, size);
  16741. return noErr;
  16742. }
  16743. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  16744. {
  16745. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  16746. }*/
  16747. void checkThreadIsAttached()
  16748. {
  16749. #if JUCE_MAC
  16750. if (Thread::getCurrentThreadId() != lastThreadId)
  16751. EnterMoviesOnThread (0);
  16752. AttachMovieToCurrentThread (movie);
  16753. #endif
  16754. }
  16755. void detachThread()
  16756. {
  16757. #if JUCE_MAC
  16758. DetachMovieFromCurrentThread (movie);
  16759. #endif
  16760. }
  16761. };
  16762. QuickTimeAudioFormat::QuickTimeAudioFormat()
  16763. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  16764. {
  16765. }
  16766. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  16767. {
  16768. }
  16769. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  16770. {
  16771. return Array<int>();
  16772. }
  16773. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  16774. {
  16775. return Array<int>();
  16776. }
  16777. bool QuickTimeAudioFormat::canDoStereo()
  16778. {
  16779. return true;
  16780. }
  16781. bool QuickTimeAudioFormat::canDoMono()
  16782. {
  16783. return true;
  16784. }
  16785. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  16786. const bool deleteStreamIfOpeningFails)
  16787. {
  16788. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  16789. if (! r->ok)
  16790. {
  16791. if (! deleteStreamIfOpeningFails)
  16792. r->input = 0;
  16793. deleteAndZero (r);
  16794. }
  16795. return r;
  16796. }
  16797. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  16798. double /*sampleRateToUse*/,
  16799. unsigned int /*numberOfChannels*/,
  16800. int /*bitsPerSample*/,
  16801. const StringPairArray& /*metadataValues*/,
  16802. int /*qualityOptionIndex*/)
  16803. {
  16804. jassertfalse // not yet implemented!
  16805. return 0;
  16806. }
  16807. END_JUCE_NAMESPACE
  16808. #endif
  16809. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16810. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  16811. BEGIN_JUCE_NAMESPACE
  16812. #define wavFormatName TRANS("WAV file")
  16813. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  16814. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  16815. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  16816. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  16817. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  16818. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  16819. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  16820. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  16821. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  16822. const String& originator,
  16823. const String& originatorRef,
  16824. const Time& date,
  16825. const int64 timeReferenceSamples,
  16826. const String& codingHistory)
  16827. {
  16828. StringPairArray m;
  16829. m.set (bwavDescription, description);
  16830. m.set (bwavOriginator, originator);
  16831. m.set (bwavOriginatorRef, originatorRef);
  16832. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  16833. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  16834. m.set (bwavTimeReference, String (timeReferenceSamples));
  16835. m.set (bwavCodingHistory, codingHistory);
  16836. return m;
  16837. }
  16838. #if JUCE_MSVC
  16839. #pragma pack (push, 1)
  16840. #define PACKED
  16841. #elif defined (JUCE_GCC)
  16842. #define PACKED __attribute__((packed))
  16843. #else
  16844. #define PACKED
  16845. #endif
  16846. struct BWAVChunk
  16847. {
  16848. uint8 description [256];
  16849. uint8 originator [32];
  16850. uint8 originatorRef [32];
  16851. uint8 originationDate [10];
  16852. uint8 originationTime [8];
  16853. uint32 timeRefLow;
  16854. uint32 timeRefHigh;
  16855. uint16 version;
  16856. uint8 umid[64];
  16857. uint8 reserved[190];
  16858. uint8 codingHistory[1];
  16859. void copyTo (StringPairArray& values) const
  16860. {
  16861. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  16862. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  16863. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  16864. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  16865. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  16866. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  16867. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  16868. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  16869. values.set (WavAudioFormat::bwavTimeReference, String (time));
  16870. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  16871. }
  16872. static MemoryBlock createFrom (const StringPairArray& values)
  16873. {
  16874. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (0) - 1;
  16875. MemoryBlock data ((sizeNeeded + 3) & ~3);
  16876. data.fillWith (0);
  16877. BWAVChunk* b = (BWAVChunk*) data.getData();
  16878. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  16879. // as they get called in the right order..
  16880. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  16881. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  16882. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  16883. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  16884. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  16885. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  16886. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  16887. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  16888. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory);
  16889. if (b->description[0] != 0
  16890. || b->originator[0] != 0
  16891. || b->originationDate[0] != 0
  16892. || b->originationTime[0] != 0
  16893. || b->codingHistory[0] != 0
  16894. || time != 0)
  16895. {
  16896. return data;
  16897. }
  16898. return MemoryBlock();
  16899. }
  16900. } PACKED;
  16901. struct SMPLChunk
  16902. {
  16903. struct SampleLoop
  16904. {
  16905. uint32 identifier;
  16906. uint32 type;
  16907. uint32 start;
  16908. uint32 end;
  16909. uint32 fraction;
  16910. uint32 playCount;
  16911. } PACKED;
  16912. uint32 manufacturer;
  16913. uint32 product;
  16914. uint32 samplePeriod;
  16915. uint32 midiUnityNote;
  16916. uint32 midiPitchFraction;
  16917. uint32 smpteFormat;
  16918. uint32 smpteOffset;
  16919. uint32 numSampleLoops;
  16920. uint32 samplerData;
  16921. SampleLoop loops[1];
  16922. void copyTo (StringPairArray& values, const int totalSize) const
  16923. {
  16924. values.set (T("Manufacturer"), String (swapIfBigEndian (manufacturer)));
  16925. values.set (T("Product"), String (swapIfBigEndian (product)));
  16926. values.set (T("SamplePeriod"), String (swapIfBigEndian (samplePeriod)));
  16927. values.set (T("MidiUnityNote"), String (swapIfBigEndian (midiUnityNote)));
  16928. values.set (T("MidiPitchFraction"), String (swapIfBigEndian (midiPitchFraction)));
  16929. values.set (T("SmpteFormat"), String (swapIfBigEndian (smpteFormat)));
  16930. values.set (T("SmpteOffset"), String (swapIfBigEndian (smpteOffset)));
  16931. values.set (T("NumSampleLoops"), String (swapIfBigEndian (numSampleLoops)));
  16932. values.set (T("SamplerData"), String (swapIfBigEndian (samplerData)));
  16933. for (uint32 i = 0; i < numSampleLoops; ++i)
  16934. {
  16935. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  16936. break;
  16937. values.set (String::formatted (T("Loop%dIdentifier"), i), String (swapIfBigEndian (loops[i].identifier)));
  16938. values.set (String::formatted (T("Loop%dType"), i), String (swapIfBigEndian (loops[i].type)));
  16939. values.set (String::formatted (T("Loop%dStart"), i), String (swapIfBigEndian (loops[i].start)));
  16940. values.set (String::formatted (T("Loop%dEnd"), i), String (swapIfBigEndian (loops[i].end)));
  16941. values.set (String::formatted (T("Loop%dFraction"), i), String (swapIfBigEndian (loops[i].fraction)));
  16942. values.set (String::formatted (T("Loop%dPlayCount"), i), String (swapIfBigEndian (loops[i].playCount)));
  16943. }
  16944. }
  16945. } PACKED;
  16946. #if JUCE_MSVC
  16947. #pragma pack (pop)
  16948. #endif
  16949. #undef PACKED
  16950. #undef chunkName
  16951. #define chunkName(a) ((int) littleEndianInt(a))
  16952. class WavAudioFormatReader : public AudioFormatReader
  16953. {
  16954. int bytesPerFrame;
  16955. int64 dataChunkStart, dataLength;
  16956. WavAudioFormatReader (const WavAudioFormatReader&);
  16957. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  16958. public:
  16959. int64 bwavChunkStart, bwavSize;
  16960. WavAudioFormatReader (InputStream* const in)
  16961. : AudioFormatReader (in, wavFormatName),
  16962. dataLength (0),
  16963. bwavChunkStart (0),
  16964. bwavSize (0)
  16965. {
  16966. if (input->readInt() == chunkName ("RIFF"))
  16967. {
  16968. const uint32 len = (uint32) input->readInt();
  16969. const int64 end = input->getPosition() + len;
  16970. bool hasGotType = false;
  16971. bool hasGotData = false;
  16972. if (input->readInt() == chunkName ("WAVE"))
  16973. {
  16974. while (input->getPosition() < end
  16975. && ! input->isExhausted())
  16976. {
  16977. const int chunkType = input->readInt();
  16978. uint32 length = (uint32) input->readInt();
  16979. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  16980. if (chunkType == chunkName ("fmt "))
  16981. {
  16982. // read the format chunk
  16983. const short format = input->readShort();
  16984. const short numChans = input->readShort();
  16985. sampleRate = input->readInt();
  16986. const int bytesPerSec = input->readInt();
  16987. numChannels = numChans;
  16988. bytesPerFrame = bytesPerSec / (int)sampleRate;
  16989. bitsPerSample = 8 * bytesPerFrame / numChans;
  16990. if (format == 3)
  16991. usesFloatingPointData = true;
  16992. else if (format != 1)
  16993. bytesPerFrame = 0;
  16994. hasGotType = true;
  16995. }
  16996. else if (chunkType == chunkName ("data"))
  16997. {
  16998. // get the data chunk's position
  16999. dataLength = length;
  17000. dataChunkStart = input->getPosition();
  17001. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17002. hasGotData = true;
  17003. }
  17004. else if (chunkType == chunkName ("bext"))
  17005. {
  17006. bwavChunkStart = input->getPosition();
  17007. bwavSize = length;
  17008. // Broadcast-wav extension chunk..
  17009. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  17010. input->read (bwav, length);
  17011. bwav->copyTo (metadataValues);
  17012. juce_free (bwav);
  17013. }
  17014. else if (chunkType == chunkName ("smpl"))
  17015. {
  17016. SMPLChunk* const smpl = (SMPLChunk*) juce_calloc (jmax (length + 1, (int) sizeof (SMPLChunk)));
  17017. input->read (smpl, length);
  17018. smpl->copyTo (metadataValues, length);
  17019. juce_free (smpl);
  17020. }
  17021. else if (chunkEnd <= input->getPosition())
  17022. {
  17023. break;
  17024. }
  17025. input->setPosition (chunkEnd);
  17026. }
  17027. }
  17028. }
  17029. }
  17030. ~WavAudioFormatReader()
  17031. {
  17032. }
  17033. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17034. int64 startSampleInFile, int numSamples)
  17035. {
  17036. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17037. if (samplesAvailable < numSamples)
  17038. {
  17039. for (int i = numDestChannels; --i >= 0;)
  17040. if (destSamples[i] != 0)
  17041. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17042. numSamples = (int) samplesAvailable;
  17043. }
  17044. if (numSamples <= 0)
  17045. return true;
  17046. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17047. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17048. char tempBuffer [tempBufSize];
  17049. while (numSamples > 0)
  17050. {
  17051. int* left = destSamples[0];
  17052. if (left != 0)
  17053. left += startOffsetInDestBuffer;
  17054. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17055. if (right != 0)
  17056. right += startOffsetInDestBuffer;
  17057. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17058. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17059. if (bytesRead < numThisTime * bytesPerFrame)
  17060. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17061. if (bitsPerSample == 16)
  17062. {
  17063. const short* src = (const short*) tempBuffer;
  17064. if (numChannels > 1)
  17065. {
  17066. if (left == 0)
  17067. {
  17068. for (int i = numThisTime; --i >= 0;)
  17069. {
  17070. ++src;
  17071. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17072. }
  17073. }
  17074. else if (right == 0)
  17075. {
  17076. for (int i = numThisTime; --i >= 0;)
  17077. {
  17078. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17079. ++src;
  17080. }
  17081. }
  17082. else
  17083. {
  17084. for (int i = numThisTime; --i >= 0;)
  17085. {
  17086. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17087. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17088. }
  17089. }
  17090. }
  17091. else
  17092. {
  17093. for (int i = numThisTime; --i >= 0;)
  17094. {
  17095. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17096. }
  17097. }
  17098. }
  17099. else if (bitsPerSample == 24)
  17100. {
  17101. const char* src = (const char*) tempBuffer;
  17102. if (numChannels > 1)
  17103. {
  17104. if (left == 0)
  17105. {
  17106. for (int i = numThisTime; --i >= 0;)
  17107. {
  17108. src += 3;
  17109. *right++ = littleEndian24Bit (src) << 8;
  17110. src += 3;
  17111. }
  17112. }
  17113. else if (right == 0)
  17114. {
  17115. for (int i = numThisTime; --i >= 0;)
  17116. {
  17117. *left++ = littleEndian24Bit (src) << 8;
  17118. src += 6;
  17119. }
  17120. }
  17121. else
  17122. {
  17123. for (int i = 0; i < numThisTime; ++i)
  17124. {
  17125. *left++ = littleEndian24Bit (src) << 8;
  17126. src += 3;
  17127. *right++ = littleEndian24Bit (src) << 8;
  17128. src += 3;
  17129. }
  17130. }
  17131. }
  17132. else
  17133. {
  17134. for (int i = 0; i < numThisTime; ++i)
  17135. {
  17136. *left++ = littleEndian24Bit (src) << 8;
  17137. src += 3;
  17138. }
  17139. }
  17140. }
  17141. else if (bitsPerSample == 32)
  17142. {
  17143. const unsigned int* src = (const unsigned int*) tempBuffer;
  17144. unsigned int* l = (unsigned int*) left;
  17145. unsigned int* r = (unsigned int*) right;
  17146. if (numChannels > 1)
  17147. {
  17148. if (l == 0)
  17149. {
  17150. for (int i = numThisTime; --i >= 0;)
  17151. {
  17152. ++src;
  17153. *r++ = swapIfBigEndian (*src++);
  17154. }
  17155. }
  17156. else if (r == 0)
  17157. {
  17158. for (int i = numThisTime; --i >= 0;)
  17159. {
  17160. *l++ = swapIfBigEndian (*src++);
  17161. ++src;
  17162. }
  17163. }
  17164. else
  17165. {
  17166. for (int i = numThisTime; --i >= 0;)
  17167. {
  17168. *l++ = swapIfBigEndian (*src++);
  17169. *r++ = swapIfBigEndian (*src++);
  17170. }
  17171. }
  17172. }
  17173. else
  17174. {
  17175. for (int i = numThisTime; --i >= 0;)
  17176. {
  17177. *l++ = swapIfBigEndian (*src++);
  17178. }
  17179. }
  17180. left = (int*)l;
  17181. right = (int*)r;
  17182. }
  17183. else if (bitsPerSample == 8)
  17184. {
  17185. const unsigned char* src = (const unsigned char*) tempBuffer;
  17186. if (numChannels > 1)
  17187. {
  17188. if (left == 0)
  17189. {
  17190. for (int i = numThisTime; --i >= 0;)
  17191. {
  17192. ++src;
  17193. *right++ = ((int) *src++ - 128) << 24;
  17194. }
  17195. }
  17196. else if (right == 0)
  17197. {
  17198. for (int i = numThisTime; --i >= 0;)
  17199. {
  17200. *left++ = ((int) *src++ - 128) << 24;
  17201. ++src;
  17202. }
  17203. }
  17204. else
  17205. {
  17206. for (int i = numThisTime; --i >= 0;)
  17207. {
  17208. *left++ = ((int) *src++ - 128) << 24;
  17209. *right++ = ((int) *src++ - 128) << 24;
  17210. }
  17211. }
  17212. }
  17213. else
  17214. {
  17215. for (int i = numThisTime; --i >= 0;)
  17216. {
  17217. *left++ = ((int)*src++ - 128) << 24;
  17218. }
  17219. }
  17220. }
  17221. startOffsetInDestBuffer += numThisTime;
  17222. numSamples -= numThisTime;
  17223. }
  17224. if (numSamples > 0)
  17225. {
  17226. for (int i = numDestChannels; --i >= 0;)
  17227. if (destSamples[i] != 0)
  17228. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17229. sizeof (int) * numSamples);
  17230. }
  17231. return true;
  17232. }
  17233. juce_UseDebuggingNewOperator
  17234. };
  17235. class WavAudioFormatWriter : public AudioFormatWriter
  17236. {
  17237. MemoryBlock tempBlock, bwavChunk;
  17238. uint32 lengthInSamples, bytesWritten;
  17239. int64 headerPosition;
  17240. bool writeFailed;
  17241. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17242. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17243. void writeHeader()
  17244. {
  17245. const bool seekedOk = output->setPosition (headerPosition);
  17246. (void) seekedOk;
  17247. // if this fails, you've given it an output stream that can't seek! It needs
  17248. // to be able to seek back to write the header
  17249. jassert (seekedOk);
  17250. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17251. output->writeInt (chunkName ("RIFF"));
  17252. output->writeInt (lengthInSamples * bytesPerFrame
  17253. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  17254. output->writeInt (chunkName ("WAVE"));
  17255. output->writeInt (chunkName ("fmt "));
  17256. output->writeInt (16);
  17257. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17258. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17259. output->writeShort ((short) numChannels);
  17260. output->writeInt ((int) sampleRate);
  17261. output->writeInt (bytesPerFrame * (int) sampleRate);
  17262. output->writeShort ((short) bytesPerFrame);
  17263. output->writeShort ((short) bitsPerSample);
  17264. if (bwavChunk.getSize() > 0)
  17265. {
  17266. output->writeInt (chunkName ("bext"));
  17267. output->writeInt (bwavChunk.getSize());
  17268. output->write (bwavChunk.getData(), bwavChunk.getSize());
  17269. }
  17270. output->writeInt (chunkName ("data"));
  17271. output->writeInt (lengthInSamples * bytesPerFrame);
  17272. usesFloatingPointData = (bitsPerSample == 32);
  17273. }
  17274. public:
  17275. WavAudioFormatWriter (OutputStream* const out,
  17276. const double sampleRate,
  17277. const unsigned int numChannels_,
  17278. const int bits,
  17279. const StringPairArray& metadataValues)
  17280. : AudioFormatWriter (out,
  17281. wavFormatName,
  17282. sampleRate,
  17283. numChannels_,
  17284. bits),
  17285. lengthInSamples (0),
  17286. bytesWritten (0),
  17287. writeFailed (false)
  17288. {
  17289. if (metadataValues.size() > 0)
  17290. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17291. headerPosition = out->getPosition();
  17292. writeHeader();
  17293. }
  17294. ~WavAudioFormatWriter()
  17295. {
  17296. writeHeader();
  17297. }
  17298. bool write (const int** data, int numSamples)
  17299. {
  17300. if (writeFailed)
  17301. return false;
  17302. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17303. tempBlock.ensureSize (bytes, false);
  17304. char* buffer = (char*) tempBlock.getData();
  17305. const int* left = data[0];
  17306. const int* right = data[1];
  17307. if (right == 0)
  17308. right = left;
  17309. if (bitsPerSample == 16)
  17310. {
  17311. short* b = (short*) buffer;
  17312. if (numChannels > 1)
  17313. {
  17314. for (int i = numSamples; --i >= 0;)
  17315. {
  17316. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17317. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17318. }
  17319. }
  17320. else
  17321. {
  17322. for (int i = numSamples; --i >= 0;)
  17323. {
  17324. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17325. }
  17326. }
  17327. }
  17328. else if (bitsPerSample == 24)
  17329. {
  17330. char* b = (char*) buffer;
  17331. if (numChannels > 1)
  17332. {
  17333. for (int i = numSamples; --i >= 0;)
  17334. {
  17335. littleEndian24BitToChars ((*left++) >> 8, b);
  17336. b += 3;
  17337. littleEndian24BitToChars ((*right++) >> 8, b);
  17338. b += 3;
  17339. }
  17340. }
  17341. else
  17342. {
  17343. for (int i = numSamples; --i >= 0;)
  17344. {
  17345. littleEndian24BitToChars ((*left++) >> 8, b);
  17346. b += 3;
  17347. }
  17348. }
  17349. }
  17350. else if (bitsPerSample == 32)
  17351. {
  17352. unsigned int* b = (unsigned int*) buffer;
  17353. if (numChannels > 1)
  17354. {
  17355. for (int i = numSamples; --i >= 0;)
  17356. {
  17357. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17358. *b++ = swapIfBigEndian ((unsigned int) *right++);
  17359. }
  17360. }
  17361. else
  17362. {
  17363. for (int i = numSamples; --i >= 0;)
  17364. {
  17365. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17366. }
  17367. }
  17368. }
  17369. else if (bitsPerSample == 8)
  17370. {
  17371. unsigned char* b = (unsigned char*) buffer;
  17372. if (numChannels > 1)
  17373. {
  17374. for (int i = numSamples; --i >= 0;)
  17375. {
  17376. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17377. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17378. }
  17379. }
  17380. else
  17381. {
  17382. for (int i = numSamples; --i >= 0;)
  17383. {
  17384. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17385. }
  17386. }
  17387. }
  17388. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17389. || ! output->write (buffer, bytes))
  17390. {
  17391. // failed to write to disk, so let's try writing the header.
  17392. // If it's just run out of disk space, then if it does manage
  17393. // to write the header, we'll still have a useable file..
  17394. writeHeader();
  17395. writeFailed = true;
  17396. return false;
  17397. }
  17398. else
  17399. {
  17400. bytesWritten += bytes;
  17401. lengthInSamples += numSamples;
  17402. return true;
  17403. }
  17404. }
  17405. juce_UseDebuggingNewOperator
  17406. };
  17407. WavAudioFormat::WavAudioFormat()
  17408. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  17409. {
  17410. }
  17411. WavAudioFormat::~WavAudioFormat()
  17412. {
  17413. }
  17414. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17415. {
  17416. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17417. return Array <int> (rates);
  17418. }
  17419. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17420. {
  17421. const int depths[] = { 8, 16, 24, 32, 0 };
  17422. return Array <int> (depths);
  17423. }
  17424. bool WavAudioFormat::canDoStereo()
  17425. {
  17426. return true;
  17427. }
  17428. bool WavAudioFormat::canDoMono()
  17429. {
  17430. return true;
  17431. }
  17432. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17433. const bool deleteStreamIfOpeningFails)
  17434. {
  17435. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  17436. if (r->sampleRate == 0)
  17437. {
  17438. if (! deleteStreamIfOpeningFails)
  17439. r->input = 0;
  17440. deleteAndZero (r);
  17441. }
  17442. return r;
  17443. }
  17444. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  17445. double sampleRate,
  17446. unsigned int numChannels,
  17447. int bitsPerSample,
  17448. const StringPairArray& metadataValues,
  17449. int /*qualityOptionIndex*/)
  17450. {
  17451. if (getPossibleBitDepths().contains (bitsPerSample))
  17452. {
  17453. return new WavAudioFormatWriter (out,
  17454. sampleRate,
  17455. numChannels,
  17456. bitsPerSample,
  17457. metadataValues);
  17458. }
  17459. return 0;
  17460. }
  17461. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  17462. {
  17463. bool ok = false;
  17464. WavAudioFormat wav;
  17465. const File dest (file.getNonexistentSibling());
  17466. OutputStream* outStream = dest.createOutputStream();
  17467. if (outStream != 0)
  17468. {
  17469. AudioFormatReader* reader = wav.createReaderFor (file.createInputStream(), true);
  17470. if (reader != 0)
  17471. {
  17472. AudioFormatWriter* writer = wav.createWriterFor (outStream, reader->sampleRate,
  17473. reader->numChannels, reader->bitsPerSample,
  17474. metadata, 0);
  17475. if (writer != 0)
  17476. {
  17477. ok = writer->writeFromAudioReader (*reader, 0, -1);
  17478. outStream = 0;
  17479. delete writer;
  17480. }
  17481. delete reader;
  17482. }
  17483. delete outStream;
  17484. }
  17485. if (ok)
  17486. ok = dest.moveFileTo (file);
  17487. if (! ok)
  17488. dest.deleteFile();
  17489. return ok;
  17490. }
  17491. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  17492. {
  17493. WavAudioFormatReader* reader = (WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true);
  17494. if (reader != 0)
  17495. {
  17496. const int64 bwavPos = reader->bwavChunkStart;
  17497. const int64 bwavSize = reader->bwavSize;
  17498. delete reader;
  17499. if (bwavSize > 0)
  17500. {
  17501. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  17502. if (chunk.getSize() <= bwavSize)
  17503. {
  17504. // the new one will fit in the space available, so write it directly..
  17505. const int64 oldSize = wavFile.getSize();
  17506. FileOutputStream* out = wavFile.createOutputStream();
  17507. out->setPosition (bwavPos);
  17508. out->write (chunk.getData(), chunk.getSize());
  17509. out->setPosition (oldSize);
  17510. delete out;
  17511. jassert (wavFile.getSize() == oldSize);
  17512. return true;
  17513. }
  17514. }
  17515. }
  17516. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  17517. }
  17518. END_JUCE_NAMESPACE
  17519. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  17520. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17521. BEGIN_JUCE_NAMESPACE
  17522. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  17523. const bool deleteReaderWhenThisIsDeleted)
  17524. : reader (reader_),
  17525. deleteReader (deleteReaderWhenThisIsDeleted),
  17526. nextPlayPos (0),
  17527. looping (false)
  17528. {
  17529. jassert (reader != 0);
  17530. }
  17531. AudioFormatReaderSource::~AudioFormatReaderSource()
  17532. {
  17533. releaseResources();
  17534. if (deleteReader)
  17535. delete reader;
  17536. }
  17537. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  17538. {
  17539. nextPlayPos = newPosition;
  17540. }
  17541. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  17542. {
  17543. looping = shouldLoop;
  17544. }
  17545. int AudioFormatReaderSource::getNextReadPosition() const
  17546. {
  17547. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  17548. : nextPlayPos;
  17549. }
  17550. int AudioFormatReaderSource::getTotalLength() const
  17551. {
  17552. return (int) reader->lengthInSamples;
  17553. }
  17554. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17555. double /*sampleRate*/)
  17556. {
  17557. }
  17558. void AudioFormatReaderSource::releaseResources()
  17559. {
  17560. }
  17561. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17562. {
  17563. if (info.numSamples > 0)
  17564. {
  17565. const int start = nextPlayPos;
  17566. if (looping)
  17567. {
  17568. const int newStart = start % (int) reader->lengthInSamples;
  17569. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  17570. if (newEnd > newStart)
  17571. {
  17572. info.buffer->readFromAudioReader (reader,
  17573. info.startSample,
  17574. newEnd - newStart,
  17575. newStart,
  17576. true, true);
  17577. }
  17578. else
  17579. {
  17580. const int endSamps = (int) reader->lengthInSamples - newStart;
  17581. info.buffer->readFromAudioReader (reader,
  17582. info.startSample,
  17583. endSamps,
  17584. newStart,
  17585. true, true);
  17586. info.buffer->readFromAudioReader (reader,
  17587. info.startSample + endSamps,
  17588. newEnd,
  17589. 0,
  17590. true, true);
  17591. }
  17592. nextPlayPos = newEnd;
  17593. }
  17594. else
  17595. {
  17596. info.buffer->readFromAudioReader (reader,
  17597. info.startSample,
  17598. info.numSamples,
  17599. start,
  17600. true, true);
  17601. nextPlayPos += info.numSamples;
  17602. }
  17603. }
  17604. }
  17605. END_JUCE_NAMESPACE
  17606. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17607. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  17608. BEGIN_JUCE_NAMESPACE
  17609. AudioSourcePlayer::AudioSourcePlayer()
  17610. : source (0),
  17611. sampleRate (0),
  17612. bufferSize (0),
  17613. tempBuffer (2, 8),
  17614. lastGain (1.0f),
  17615. gain (1.0f)
  17616. {
  17617. }
  17618. AudioSourcePlayer::~AudioSourcePlayer()
  17619. {
  17620. setSource (0);
  17621. }
  17622. void AudioSourcePlayer::setSource (AudioSource* newSource)
  17623. {
  17624. if (source != newSource)
  17625. {
  17626. AudioSource* const oldSource = source;
  17627. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  17628. newSource->prepareToPlay (bufferSize, sampleRate);
  17629. {
  17630. const ScopedLock sl (readLock);
  17631. source = newSource;
  17632. }
  17633. if (oldSource != 0)
  17634. oldSource->releaseResources();
  17635. }
  17636. }
  17637. void AudioSourcePlayer::setGain (const float newGain) throw()
  17638. {
  17639. gain = newGain;
  17640. }
  17641. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  17642. int totalNumInputChannels,
  17643. float** outputChannelData,
  17644. int totalNumOutputChannels,
  17645. int numSamples)
  17646. {
  17647. // these should have been prepared by audioDeviceAboutToStart()...
  17648. jassert (sampleRate > 0 && bufferSize > 0);
  17649. const ScopedLock sl (readLock);
  17650. if (source != 0)
  17651. {
  17652. AudioSourceChannelInfo info;
  17653. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  17654. // messy stuff needed to compact the channels down into an array
  17655. // of non-zero pointers..
  17656. for (i = 0; i < totalNumInputChannels; ++i)
  17657. {
  17658. if (inputChannelData[i] != 0)
  17659. {
  17660. inputChans [numInputs++] = inputChannelData[i];
  17661. if (numInputs >= numElementsInArray (inputChans))
  17662. break;
  17663. }
  17664. }
  17665. for (i = 0; i < totalNumOutputChannels; ++i)
  17666. {
  17667. if (outputChannelData[i] != 0)
  17668. {
  17669. outputChans [numOutputs++] = outputChannelData[i];
  17670. if (numOutputs >= numElementsInArray (outputChans))
  17671. break;
  17672. }
  17673. }
  17674. if (numInputs > numOutputs)
  17675. {
  17676. // if there aren't enough output channels for the number of
  17677. // inputs, we need to create some temporary extra ones (can't
  17678. // use the input data in case it gets written to)
  17679. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  17680. false, false, true);
  17681. for (i = 0; i < numOutputs; ++i)
  17682. {
  17683. channels[numActiveChans] = outputChans[i];
  17684. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17685. ++numActiveChans;
  17686. }
  17687. for (i = numOutputs; i < numInputs; ++i)
  17688. {
  17689. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  17690. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17691. ++numActiveChans;
  17692. }
  17693. }
  17694. else
  17695. {
  17696. for (i = 0; i < numInputs; ++i)
  17697. {
  17698. channels[numActiveChans] = outputChans[i];
  17699. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17700. ++numActiveChans;
  17701. }
  17702. for (i = numInputs; i < numOutputs; ++i)
  17703. {
  17704. channels[numActiveChans] = outputChans[i];
  17705. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  17706. ++numActiveChans;
  17707. }
  17708. }
  17709. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  17710. info.buffer = &buffer;
  17711. info.startSample = 0;
  17712. info.numSamples = numSamples;
  17713. source->getNextAudioBlock (info);
  17714. for (i = info.buffer->getNumChannels(); --i >= 0;)
  17715. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  17716. lastGain = gain;
  17717. }
  17718. else
  17719. {
  17720. for (int i = 0; i < totalNumOutputChannels; ++i)
  17721. if (outputChannelData[i] != 0)
  17722. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17723. }
  17724. }
  17725. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  17726. {
  17727. sampleRate = device->getCurrentSampleRate();
  17728. bufferSize = device->getCurrentBufferSizeSamples();
  17729. zeromem (channels, sizeof (channels));
  17730. if (source != 0)
  17731. source->prepareToPlay (bufferSize, sampleRate);
  17732. }
  17733. void AudioSourcePlayer::audioDeviceStopped()
  17734. {
  17735. if (source != 0)
  17736. source->releaseResources();
  17737. sampleRate = 0.0;
  17738. bufferSize = 0;
  17739. tempBuffer.setSize (2, 8);
  17740. }
  17741. END_JUCE_NAMESPACE
  17742. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  17743. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  17744. BEGIN_JUCE_NAMESPACE
  17745. AudioTransportSource::AudioTransportSource()
  17746. : source (0),
  17747. resamplerSource (0),
  17748. bufferingSource (0),
  17749. positionableSource (0),
  17750. masterSource (0),
  17751. gain (1.0f),
  17752. lastGain (1.0f),
  17753. playing (false),
  17754. stopped (true),
  17755. sampleRate (44100.0),
  17756. sourceSampleRate (0.0),
  17757. blockSize (128),
  17758. readAheadBufferSize (0),
  17759. isPrepared (false),
  17760. inputStreamEOF (false)
  17761. {
  17762. }
  17763. AudioTransportSource::~AudioTransportSource()
  17764. {
  17765. setSource (0);
  17766. releaseResources();
  17767. }
  17768. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  17769. int readAheadBufferSize_,
  17770. double sourceSampleRateToCorrectFor)
  17771. {
  17772. if (source == newSource)
  17773. {
  17774. if (source == 0)
  17775. return;
  17776. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  17777. }
  17778. readAheadBufferSize = readAheadBufferSize_;
  17779. sourceSampleRate = sourceSampleRateToCorrectFor;
  17780. ResamplingAudioSource* newResamplerSource = 0;
  17781. BufferingAudioSource* newBufferingSource = 0;
  17782. PositionableAudioSource* newPositionableSource = 0;
  17783. AudioSource* newMasterSource = 0;
  17784. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  17785. BufferingAudioSource* oldBufferingSource = bufferingSource;
  17786. AudioSource* oldMasterSource = masterSource;
  17787. if (newSource != 0)
  17788. {
  17789. newPositionableSource = newSource;
  17790. if (readAheadBufferSize_ > 0)
  17791. newPositionableSource = newBufferingSource
  17792. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  17793. newPositionableSource->setNextReadPosition (0);
  17794. if (sourceSampleRateToCorrectFor != 0)
  17795. newMasterSource = newResamplerSource
  17796. = new ResamplingAudioSource (newPositionableSource, false);
  17797. else
  17798. newMasterSource = newPositionableSource;
  17799. if (isPrepared)
  17800. {
  17801. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  17802. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17803. newMasterSource->prepareToPlay (blockSize, sampleRate);
  17804. }
  17805. }
  17806. {
  17807. const ScopedLock sl (callbackLock);
  17808. source = newSource;
  17809. resamplerSource = newResamplerSource;
  17810. bufferingSource = newBufferingSource;
  17811. masterSource = newMasterSource;
  17812. positionableSource = newPositionableSource;
  17813. playing = false;
  17814. }
  17815. if (oldMasterSource != 0)
  17816. oldMasterSource->releaseResources();
  17817. delete oldResamplerSource;
  17818. delete oldBufferingSource;
  17819. }
  17820. void AudioTransportSource::start()
  17821. {
  17822. if ((! playing) && masterSource != 0)
  17823. {
  17824. callbackLock.enter();
  17825. playing = true;
  17826. stopped = false;
  17827. inputStreamEOF = false;
  17828. callbackLock.exit();
  17829. sendChangeMessage (this);
  17830. }
  17831. }
  17832. void AudioTransportSource::stop()
  17833. {
  17834. if (playing)
  17835. {
  17836. callbackLock.enter();
  17837. playing = false;
  17838. callbackLock.exit();
  17839. int n = 500;
  17840. while (--n >= 0 && ! stopped)
  17841. Thread::sleep (2);
  17842. sendChangeMessage (this);
  17843. }
  17844. }
  17845. void AudioTransportSource::setPosition (double newPosition)
  17846. {
  17847. if (sampleRate > 0.0)
  17848. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  17849. }
  17850. double AudioTransportSource::getCurrentPosition() const
  17851. {
  17852. if (sampleRate > 0.0)
  17853. return getNextReadPosition() / sampleRate;
  17854. else
  17855. return 0.0;
  17856. }
  17857. void AudioTransportSource::setNextReadPosition (int newPosition)
  17858. {
  17859. if (positionableSource != 0)
  17860. {
  17861. if (sampleRate > 0 && sourceSampleRate > 0)
  17862. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  17863. positionableSource->setNextReadPosition (newPosition);
  17864. }
  17865. }
  17866. int AudioTransportSource::getNextReadPosition() const
  17867. {
  17868. if (positionableSource != 0)
  17869. {
  17870. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17871. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  17872. }
  17873. return 0;
  17874. }
  17875. int AudioTransportSource::getTotalLength() const
  17876. {
  17877. const ScopedLock sl (callbackLock);
  17878. if (positionableSource != 0)
  17879. {
  17880. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17881. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  17882. }
  17883. return 0;
  17884. }
  17885. bool AudioTransportSource::isLooping() const
  17886. {
  17887. const ScopedLock sl (callbackLock);
  17888. return positionableSource != 0
  17889. && positionableSource->isLooping();
  17890. }
  17891. void AudioTransportSource::setGain (const float newGain) throw()
  17892. {
  17893. gain = newGain;
  17894. }
  17895. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  17896. double sampleRate_)
  17897. {
  17898. const ScopedLock sl (callbackLock);
  17899. sampleRate = sampleRate_;
  17900. blockSize = samplesPerBlockExpected;
  17901. if (masterSource != 0)
  17902. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17903. if (resamplerSource != 0 && sourceSampleRate != 0)
  17904. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17905. isPrepared = true;
  17906. }
  17907. void AudioTransportSource::releaseResources()
  17908. {
  17909. const ScopedLock sl (callbackLock);
  17910. if (masterSource != 0)
  17911. masterSource->releaseResources();
  17912. isPrepared = false;
  17913. }
  17914. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17915. {
  17916. const ScopedLock sl (callbackLock);
  17917. inputStreamEOF = false;
  17918. if (masterSource != 0 && ! stopped)
  17919. {
  17920. masterSource->getNextAudioBlock (info);
  17921. if (! playing)
  17922. {
  17923. // just stopped playing, so fade out the last block..
  17924. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17925. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  17926. if (info.numSamples > 256)
  17927. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  17928. }
  17929. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  17930. && ! positionableSource->isLooping())
  17931. {
  17932. playing = false;
  17933. inputStreamEOF = true;
  17934. sendChangeMessage (this);
  17935. }
  17936. stopped = ! playing;
  17937. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17938. {
  17939. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  17940. lastGain, gain);
  17941. }
  17942. }
  17943. else
  17944. {
  17945. info.clearActiveBufferRegion();
  17946. stopped = true;
  17947. }
  17948. lastGain = gain;
  17949. }
  17950. END_JUCE_NAMESPACE
  17951. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  17952. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  17953. BEGIN_JUCE_NAMESPACE
  17954. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  17955. public Thread,
  17956. private Timer
  17957. {
  17958. public:
  17959. SharedBufferingAudioSourceThread()
  17960. : Thread ("Audio Buffer"),
  17961. sources (8)
  17962. {
  17963. }
  17964. ~SharedBufferingAudioSourceThread()
  17965. {
  17966. stopThread (10000);
  17967. clearSingletonInstance();
  17968. }
  17969. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  17970. void addSource (BufferingAudioSource* source)
  17971. {
  17972. const ScopedLock sl (lock);
  17973. if (! sources.contains ((void*) source))
  17974. {
  17975. sources.add ((void*) source);
  17976. startThread();
  17977. stopTimer();
  17978. }
  17979. notify();
  17980. }
  17981. void removeSource (BufferingAudioSource* source)
  17982. {
  17983. const ScopedLock sl (lock);
  17984. sources.removeValue ((void*) source);
  17985. if (sources.size() == 0)
  17986. startTimer (5000);
  17987. }
  17988. private:
  17989. VoidArray sources;
  17990. CriticalSection lock;
  17991. void run()
  17992. {
  17993. while (! threadShouldExit())
  17994. {
  17995. bool busy = false;
  17996. for (int i = sources.size(); --i >= 0;)
  17997. {
  17998. if (threadShouldExit())
  17999. return;
  18000. const ScopedLock sl (lock);
  18001. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  18002. if (b != 0 && b->readNextBufferChunk())
  18003. busy = true;
  18004. }
  18005. if (! busy)
  18006. wait (500);
  18007. }
  18008. }
  18009. void timerCallback()
  18010. {
  18011. stopTimer();
  18012. if (sources.size() == 0)
  18013. deleteInstance();
  18014. }
  18015. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18016. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18017. };
  18018. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18019. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18020. const bool deleteSourceWhenDeleted_,
  18021. int numberOfSamplesToBuffer_)
  18022. : source (source_),
  18023. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18024. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18025. buffer (2, 0),
  18026. bufferValidStart (0),
  18027. bufferValidEnd (0),
  18028. nextPlayPos (0),
  18029. wasSourceLooping (false)
  18030. {
  18031. jassert (source_ != 0);
  18032. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18033. // not using a larger buffer..
  18034. }
  18035. BufferingAudioSource::~BufferingAudioSource()
  18036. {
  18037. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18038. if (thread != 0)
  18039. thread->removeSource (this);
  18040. if (deleteSourceWhenDeleted)
  18041. delete source;
  18042. }
  18043. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18044. {
  18045. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18046. sampleRate = sampleRate_;
  18047. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18048. buffer.clear();
  18049. bufferValidStart = 0;
  18050. bufferValidEnd = 0;
  18051. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18052. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18053. buffer.getNumSamples() / 2))
  18054. {
  18055. SharedBufferingAudioSourceThread::getInstance()->notify();
  18056. Thread::sleep (5);
  18057. }
  18058. }
  18059. void BufferingAudioSource::releaseResources()
  18060. {
  18061. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18062. if (thread != 0)
  18063. thread->removeSource (this);
  18064. buffer.setSize (2, 0);
  18065. source->releaseResources();
  18066. }
  18067. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18068. {
  18069. const ScopedLock sl (bufferStartPosLock);
  18070. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18071. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18072. if (validStart == validEnd)
  18073. {
  18074. // total cache miss
  18075. info.clearActiveBufferRegion();
  18076. }
  18077. else
  18078. {
  18079. if (validStart > 0)
  18080. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18081. if (validEnd < info.numSamples)
  18082. info.buffer->clear (info.startSample + validEnd,
  18083. info.numSamples - validEnd); // partial cache miss at end
  18084. if (validStart < validEnd)
  18085. {
  18086. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18087. {
  18088. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18089. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18090. if (startBufferIndex < endBufferIndex)
  18091. {
  18092. info.buffer->copyFrom (chan, info.startSample + validStart,
  18093. buffer,
  18094. chan, startBufferIndex,
  18095. validEnd - validStart);
  18096. }
  18097. else
  18098. {
  18099. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18100. info.buffer->copyFrom (chan, info.startSample + validStart,
  18101. buffer,
  18102. chan, startBufferIndex,
  18103. initialSize);
  18104. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18105. buffer,
  18106. chan, 0,
  18107. (validEnd - validStart) - initialSize);
  18108. }
  18109. }
  18110. }
  18111. nextPlayPos += info.numSamples;
  18112. if (source->isLooping() && nextPlayPos > 0)
  18113. nextPlayPos %= source->getTotalLength();
  18114. }
  18115. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18116. if (thread != 0)
  18117. thread->notify();
  18118. }
  18119. int BufferingAudioSource::getNextReadPosition() const
  18120. {
  18121. return (source->isLooping() && nextPlayPos > 0)
  18122. ? nextPlayPos % source->getTotalLength()
  18123. : nextPlayPos;
  18124. }
  18125. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18126. {
  18127. const ScopedLock sl (bufferStartPosLock);
  18128. nextPlayPos = newPosition;
  18129. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18130. if (thread != 0)
  18131. thread->notify();
  18132. }
  18133. bool BufferingAudioSource::readNextBufferChunk()
  18134. {
  18135. bufferStartPosLock.enter();
  18136. if (wasSourceLooping != isLooping())
  18137. {
  18138. wasSourceLooping = isLooping();
  18139. bufferValidStart = 0;
  18140. bufferValidEnd = 0;
  18141. }
  18142. int newBVS = jmax (0, nextPlayPos);
  18143. int newBVE = newBVS + buffer.getNumSamples() - 4;
  18144. int sectionToReadStart = 0;
  18145. int sectionToReadEnd = 0;
  18146. const int maxChunkSize = 2048;
  18147. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18148. {
  18149. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18150. sectionToReadStart = newBVS;
  18151. sectionToReadEnd = newBVE;
  18152. bufferValidStart = 0;
  18153. bufferValidEnd = 0;
  18154. }
  18155. else if (abs (newBVS - bufferValidStart) > 512
  18156. || abs (newBVE - bufferValidEnd) > 512)
  18157. {
  18158. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18159. sectionToReadStart = bufferValidEnd;
  18160. sectionToReadEnd = newBVE;
  18161. bufferValidStart = newBVS;
  18162. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18163. }
  18164. bufferStartPosLock.exit();
  18165. if (sectionToReadStart != sectionToReadEnd)
  18166. {
  18167. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18168. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18169. if (bufferIndexStart < bufferIndexEnd)
  18170. {
  18171. readBufferSection (sectionToReadStart,
  18172. sectionToReadEnd - sectionToReadStart,
  18173. bufferIndexStart);
  18174. }
  18175. else
  18176. {
  18177. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18178. readBufferSection (sectionToReadStart,
  18179. initialSize,
  18180. bufferIndexStart);
  18181. readBufferSection (sectionToReadStart + initialSize,
  18182. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18183. 0);
  18184. }
  18185. const ScopedLock sl2 (bufferStartPosLock);
  18186. bufferValidStart = newBVS;
  18187. bufferValidEnd = newBVE;
  18188. return true;
  18189. }
  18190. else
  18191. {
  18192. return false;
  18193. }
  18194. }
  18195. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18196. {
  18197. if (source->getNextReadPosition() != start)
  18198. source->setNextReadPosition (start);
  18199. AudioSourceChannelInfo info;
  18200. info.buffer = &buffer;
  18201. info.startSample = bufferOffset;
  18202. info.numSamples = length;
  18203. source->getNextAudioBlock (info);
  18204. }
  18205. END_JUCE_NAMESPACE
  18206. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  18207. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18208. BEGIN_JUCE_NAMESPACE
  18209. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18210. const bool deleteSourceWhenDeleted_)
  18211. : requiredNumberOfChannels (2),
  18212. source (source_),
  18213. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18214. buffer (2, 16)
  18215. {
  18216. remappedInfo.buffer = &buffer;
  18217. remappedInfo.startSample = 0;
  18218. }
  18219. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18220. {
  18221. if (deleteSourceWhenDeleted)
  18222. delete source;
  18223. }
  18224. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18225. {
  18226. const ScopedLock sl (lock);
  18227. requiredNumberOfChannels = requiredNumberOfChannels_;
  18228. }
  18229. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18230. {
  18231. const ScopedLock sl (lock);
  18232. remappedInputs.clear();
  18233. remappedOutputs.clear();
  18234. }
  18235. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18236. {
  18237. const ScopedLock sl (lock);
  18238. while (remappedInputs.size() < destIndex)
  18239. remappedInputs.add (-1);
  18240. remappedInputs.set (destIndex, sourceIndex);
  18241. }
  18242. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18243. {
  18244. const ScopedLock sl (lock);
  18245. while (remappedOutputs.size() < sourceIndex)
  18246. remappedOutputs.add (-1);
  18247. remappedOutputs.set (sourceIndex, destIndex);
  18248. }
  18249. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18250. {
  18251. const ScopedLock sl (lock);
  18252. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18253. return remappedInputs.getUnchecked (inputChannelIndex);
  18254. return -1;
  18255. }
  18256. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18257. {
  18258. const ScopedLock sl (lock);
  18259. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18260. return remappedOutputs .getUnchecked (outputChannelIndex);
  18261. return -1;
  18262. }
  18263. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18264. {
  18265. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18266. }
  18267. void ChannelRemappingAudioSource::releaseResources()
  18268. {
  18269. source->releaseResources();
  18270. }
  18271. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18272. {
  18273. const ScopedLock sl (lock);
  18274. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18275. const int numChans = bufferToFill.buffer->getNumChannels();
  18276. int i;
  18277. for (i = 0; i < buffer.getNumChannels(); ++i)
  18278. {
  18279. const int remappedChan = getRemappedInputChannel (i);
  18280. if (remappedChan >= 0 && remappedChan < numChans)
  18281. {
  18282. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18283. remappedChan,
  18284. bufferToFill.startSample,
  18285. bufferToFill.numSamples);
  18286. }
  18287. else
  18288. {
  18289. buffer.clear (i, 0, bufferToFill.numSamples);
  18290. }
  18291. }
  18292. remappedInfo.numSamples = bufferToFill.numSamples;
  18293. source->getNextAudioBlock (remappedInfo);
  18294. bufferToFill.clearActiveBufferRegion();
  18295. for (i = 0; i < requiredNumberOfChannels; ++i)
  18296. {
  18297. const int remappedChan = getRemappedOutputChannel (i);
  18298. if (remappedChan >= 0 && remappedChan < numChans)
  18299. {
  18300. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18301. buffer, i, 0, bufferToFill.numSamples);
  18302. }
  18303. }
  18304. }
  18305. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18306. {
  18307. XmlElement* e = new XmlElement (T("MAPPINGS"));
  18308. String ins, outs;
  18309. int i;
  18310. const ScopedLock sl (lock);
  18311. for (i = 0; i < remappedInputs.size(); ++i)
  18312. ins << remappedInputs.getUnchecked(i) << T(' ');
  18313. for (i = 0; i < remappedOutputs.size(); ++i)
  18314. outs << remappedOutputs.getUnchecked(i) << T(' ');
  18315. e->setAttribute (T("inputs"), ins.trimEnd());
  18316. e->setAttribute (T("outputs"), outs.trimEnd());
  18317. return e;
  18318. }
  18319. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18320. {
  18321. if (e.hasTagName (T("MAPPINGS")))
  18322. {
  18323. const ScopedLock sl (lock);
  18324. clearAllMappings();
  18325. StringArray ins, outs;
  18326. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  18327. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  18328. int i;
  18329. for (i = 0; i < ins.size(); ++i)
  18330. remappedInputs.add (ins[i].getIntValue());
  18331. for (i = 0; i < outs.size(); ++i)
  18332. remappedOutputs.add (outs[i].getIntValue());
  18333. }
  18334. }
  18335. END_JUCE_NAMESPACE
  18336. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18337. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18338. BEGIN_JUCE_NAMESPACE
  18339. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18340. const bool deleteInputWhenDeleted_)
  18341. : input (inputSource),
  18342. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18343. {
  18344. jassert (inputSource != 0);
  18345. for (int i = 2; --i >= 0;)
  18346. iirFilters.add (new IIRFilter());
  18347. }
  18348. IIRFilterAudioSource::~IIRFilterAudioSource()
  18349. {
  18350. if (deleteInputWhenDeleted)
  18351. delete input;
  18352. }
  18353. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18354. {
  18355. for (int i = iirFilters.size(); --i >= 0;)
  18356. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18357. }
  18358. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18359. {
  18360. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18361. for (int i = iirFilters.size(); --i >= 0;)
  18362. iirFilters.getUnchecked(i)->reset();
  18363. }
  18364. void IIRFilterAudioSource::releaseResources()
  18365. {
  18366. input->releaseResources();
  18367. }
  18368. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18369. {
  18370. input->getNextAudioBlock (bufferToFill);
  18371. const int numChannels = bufferToFill.buffer->getNumChannels();
  18372. while (numChannels > iirFilters.size())
  18373. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18374. for (int i = 0; i < numChannels; ++i)
  18375. iirFilters.getUnchecked(i)
  18376. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18377. bufferToFill.numSamples);
  18378. }
  18379. END_JUCE_NAMESPACE
  18380. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18381. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  18382. BEGIN_JUCE_NAMESPACE
  18383. MixerAudioSource::MixerAudioSource()
  18384. : tempBuffer (2, 0),
  18385. currentSampleRate (0.0),
  18386. bufferSizeExpected (0)
  18387. {
  18388. }
  18389. MixerAudioSource::~MixerAudioSource()
  18390. {
  18391. removeAllInputs();
  18392. }
  18393. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18394. {
  18395. if (input != 0 && ! inputs.contains (input))
  18396. {
  18397. lock.enter();
  18398. double localRate = currentSampleRate;
  18399. int localBufferSize = bufferSizeExpected;
  18400. lock.exit();
  18401. if (localRate != 0.0)
  18402. input->prepareToPlay (localBufferSize, localRate);
  18403. const ScopedLock sl (lock);
  18404. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18405. inputs.add (input);
  18406. }
  18407. }
  18408. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18409. {
  18410. if (input != 0)
  18411. {
  18412. lock.enter();
  18413. const int index = inputs.indexOf ((void*) input);
  18414. if (index >= 0)
  18415. {
  18416. inputsToDelete.shiftBits (index, 1);
  18417. inputs.remove (index);
  18418. }
  18419. lock.exit();
  18420. if (index >= 0)
  18421. {
  18422. input->releaseResources();
  18423. if (deleteInput)
  18424. delete input;
  18425. }
  18426. }
  18427. }
  18428. void MixerAudioSource::removeAllInputs()
  18429. {
  18430. lock.enter();
  18431. VoidArray inputsCopy (inputs);
  18432. BitArray inputsToDeleteCopy (inputsToDelete);
  18433. inputs.clear();
  18434. lock.exit();
  18435. for (int i = inputsCopy.size(); --i >= 0;)
  18436. if (inputsToDeleteCopy[i])
  18437. delete (AudioSource*) inputsCopy[i];
  18438. }
  18439. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18440. {
  18441. tempBuffer.setSize (2, samplesPerBlockExpected);
  18442. const ScopedLock sl (lock);
  18443. currentSampleRate = sampleRate;
  18444. bufferSizeExpected = samplesPerBlockExpected;
  18445. for (int i = inputs.size(); --i >= 0;)
  18446. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  18447. sampleRate);
  18448. }
  18449. void MixerAudioSource::releaseResources()
  18450. {
  18451. const ScopedLock sl (lock);
  18452. for (int i = inputs.size(); --i >= 0;)
  18453. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  18454. tempBuffer.setSize (2, 0);
  18455. currentSampleRate = 0;
  18456. bufferSizeExpected = 0;
  18457. }
  18458. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18459. {
  18460. const ScopedLock sl (lock);
  18461. if (inputs.size() > 0)
  18462. {
  18463. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  18464. if (inputs.size() > 1)
  18465. {
  18466. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  18467. info.buffer->getNumSamples());
  18468. AudioSourceChannelInfo info2;
  18469. info2.buffer = &tempBuffer;
  18470. info2.numSamples = info.numSamples;
  18471. info2.startSample = 0;
  18472. for (int i = 1; i < inputs.size(); ++i)
  18473. {
  18474. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  18475. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  18476. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  18477. }
  18478. }
  18479. }
  18480. else
  18481. {
  18482. info.clearActiveBufferRegion();
  18483. }
  18484. }
  18485. END_JUCE_NAMESPACE
  18486. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  18487. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  18488. BEGIN_JUCE_NAMESPACE
  18489. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  18490. const bool deleteInputWhenDeleted_)
  18491. : input (inputSource),
  18492. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  18493. ratio (1.0),
  18494. lastRatio (1.0),
  18495. buffer (2, 0),
  18496. sampsInBuffer (0)
  18497. {
  18498. jassert (input != 0);
  18499. }
  18500. ResamplingAudioSource::~ResamplingAudioSource()
  18501. {
  18502. if (deleteInputWhenDeleted)
  18503. delete input;
  18504. }
  18505. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  18506. {
  18507. jassert (samplesInPerOutputSample > 0);
  18508. const ScopedLock sl (ratioLock);
  18509. ratio = jmax (0.0, samplesInPerOutputSample);
  18510. }
  18511. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  18512. double sampleRate)
  18513. {
  18514. const ScopedLock sl (ratioLock);
  18515. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18516. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  18517. buffer.clear();
  18518. sampsInBuffer = 0;
  18519. bufferPos = 0;
  18520. subSampleOffset = 0.0;
  18521. createLowPass (ratio);
  18522. resetFilters();
  18523. }
  18524. void ResamplingAudioSource::releaseResources()
  18525. {
  18526. input->releaseResources();
  18527. buffer.setSize (2, 0);
  18528. }
  18529. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18530. {
  18531. const ScopedLock sl (ratioLock);
  18532. if (lastRatio != ratio)
  18533. {
  18534. createLowPass (ratio);
  18535. lastRatio = ratio;
  18536. }
  18537. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  18538. int bufferSize = buffer.getNumSamples();
  18539. if (bufferSize < sampsNeeded + 8)
  18540. {
  18541. bufferPos %= bufferSize;
  18542. bufferSize = sampsNeeded + 32;
  18543. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  18544. }
  18545. bufferPos %= bufferSize;
  18546. int endOfBufferPos = bufferPos + sampsInBuffer;
  18547. while (sampsNeeded > sampsInBuffer)
  18548. {
  18549. endOfBufferPos %= bufferSize;
  18550. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  18551. bufferSize - endOfBufferPos);
  18552. AudioSourceChannelInfo readInfo;
  18553. readInfo.buffer = &buffer;
  18554. readInfo.numSamples = numToDo;
  18555. readInfo.startSample = endOfBufferPos;
  18556. input->getNextAudioBlock (readInfo);
  18557. if (ratio > 1.0001)
  18558. {
  18559. // for down-sampling, pre-apply the filter..
  18560. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18561. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  18562. }
  18563. sampsInBuffer += numToDo;
  18564. endOfBufferPos += numToDo;
  18565. }
  18566. float* dl = info.buffer->getSampleData (0, info.startSample);
  18567. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  18568. const float* const bl = buffer.getSampleData (0, 0);
  18569. const float* const br = buffer.getSampleData (1, 0);
  18570. int nextPos = (bufferPos + 1) % bufferSize;
  18571. for (int m = info.numSamples; --m >= 0;)
  18572. {
  18573. const float alpha = (float) subSampleOffset;
  18574. const float invAlpha = 1.0f - alpha;
  18575. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  18576. if (dr != 0)
  18577. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  18578. subSampleOffset += ratio;
  18579. jassert (sampsInBuffer > 0);
  18580. while (subSampleOffset >= 1.0)
  18581. {
  18582. if (++bufferPos >= bufferSize)
  18583. bufferPos = 0;
  18584. --sampsInBuffer;
  18585. nextPos = (bufferPos + 1) % bufferSize;
  18586. subSampleOffset -= 1.0;
  18587. }
  18588. }
  18589. if (ratio < 0.9999)
  18590. {
  18591. // for up-sampling, apply the filter after transposing..
  18592. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18593. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  18594. }
  18595. else if (ratio <= 1.0001)
  18596. {
  18597. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  18598. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18599. {
  18600. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  18601. FilterState& fs = filterStates[i];
  18602. if (info.numSamples > 1)
  18603. {
  18604. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  18605. }
  18606. else
  18607. {
  18608. fs.y2 = fs.y1;
  18609. fs.x2 = fs.x1;
  18610. }
  18611. fs.y1 = fs.x1 = *endOfBuffer;
  18612. }
  18613. }
  18614. jassert (sampsInBuffer >= 0);
  18615. }
  18616. void ResamplingAudioSource::createLowPass (const double ratio)
  18617. {
  18618. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  18619. : 0.5 * ratio;
  18620. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  18621. const double nSquared = n * n;
  18622. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18623. setFilterCoefficients (c1,
  18624. c1 * 2.0f,
  18625. c1,
  18626. 1.0,
  18627. c1 * 2.0 * (1.0 - nSquared),
  18628. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18629. }
  18630. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  18631. {
  18632. const double a = 1.0 / c4;
  18633. c1 *= a;
  18634. c2 *= a;
  18635. c3 *= a;
  18636. c5 *= a;
  18637. c6 *= a;
  18638. coefficients[0] = c1;
  18639. coefficients[1] = c2;
  18640. coefficients[2] = c3;
  18641. coefficients[3] = c4;
  18642. coefficients[4] = c5;
  18643. coefficients[5] = c6;
  18644. }
  18645. void ResamplingAudioSource::resetFilters()
  18646. {
  18647. zeromem (filterStates, sizeof (filterStates));
  18648. }
  18649. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  18650. {
  18651. while (--num >= 0)
  18652. {
  18653. const double in = *samples;
  18654. double out = coefficients[0] * in
  18655. + coefficients[1] * fs.x1
  18656. + coefficients[2] * fs.x2
  18657. - coefficients[4] * fs.y1
  18658. - coefficients[5] * fs.y2;
  18659. #if JUCE_INTEL
  18660. if (! (out < -1.0e-8 || out > 1.0e-8))
  18661. out = 0;
  18662. #endif
  18663. fs.x2 = fs.x1;
  18664. fs.x1 = in;
  18665. fs.y2 = fs.y1;
  18666. fs.y1 = out;
  18667. *samples++ = (float) out;
  18668. }
  18669. }
  18670. END_JUCE_NAMESPACE
  18671. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  18672. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18673. BEGIN_JUCE_NAMESPACE
  18674. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  18675. : frequency (1000.0),
  18676. sampleRate (44100.0),
  18677. currentPhase (0.0),
  18678. phasePerSample (0.0),
  18679. amplitude (0.5f)
  18680. {
  18681. }
  18682. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  18683. {
  18684. }
  18685. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  18686. {
  18687. amplitude = newAmplitude;
  18688. }
  18689. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  18690. {
  18691. frequency = newFrequencyHz;
  18692. phasePerSample = 0.0;
  18693. }
  18694. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18695. double sampleRate_)
  18696. {
  18697. currentPhase = 0.0;
  18698. phasePerSample = 0.0;
  18699. sampleRate = sampleRate_;
  18700. }
  18701. void ToneGeneratorAudioSource::releaseResources()
  18702. {
  18703. }
  18704. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18705. {
  18706. if (phasePerSample == 0.0)
  18707. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18708. for (int i = 0; i < info.numSamples; ++i)
  18709. {
  18710. const float sample = amplitude * (float) sin (currentPhase);
  18711. currentPhase += phasePerSample;
  18712. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  18713. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  18714. }
  18715. }
  18716. END_JUCE_NAMESPACE
  18717. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18718. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  18719. BEGIN_JUCE_NAMESPACE
  18720. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18721. : sampleRate (0),
  18722. bufferSize (0),
  18723. useDefaultInputChannels (true),
  18724. useDefaultOutputChannels (true)
  18725. {
  18726. }
  18727. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  18728. {
  18729. return outputDeviceName == other.outputDeviceName
  18730. && inputDeviceName == other.inputDeviceName
  18731. && sampleRate == other.sampleRate
  18732. && bufferSize == other.bufferSize
  18733. && inputChannels == other.inputChannels
  18734. && useDefaultInputChannels == other.useDefaultInputChannels
  18735. && outputChannels == other.outputChannels
  18736. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  18737. }
  18738. AudioDeviceManager::AudioDeviceManager()
  18739. : currentAudioDevice (0),
  18740. numInputChansNeeded (0),
  18741. numOutputChansNeeded (2),
  18742. lastExplicitSettings (0),
  18743. listNeedsScanning (true),
  18744. useInputNames (false),
  18745. inputLevelMeasurementEnabledCount (0),
  18746. inputLevel (0),
  18747. testSound (0),
  18748. tempBuffer (2, 2),
  18749. enabledMidiInputs (4),
  18750. midiCallbacks (4),
  18751. midiCallbackDevices (4),
  18752. defaultMidiOutput (0),
  18753. cpuUsageMs (0),
  18754. timeToCpuScale (0)
  18755. {
  18756. callbackHandler.owner = this;
  18757. }
  18758. AudioDeviceManager::~AudioDeviceManager()
  18759. {
  18760. deleteAndZero (currentAudioDevice);
  18761. deleteAndZero (defaultMidiOutput);
  18762. delete lastExplicitSettings;
  18763. delete testSound;
  18764. }
  18765. void AudioDeviceManager::createDeviceTypesIfNeeded()
  18766. {
  18767. if (availableDeviceTypes.size() == 0)
  18768. {
  18769. createAudioDeviceTypes (availableDeviceTypes);
  18770. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  18771. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  18772. if (availableDeviceTypes.size() > 0)
  18773. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  18774. }
  18775. }
  18776. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  18777. {
  18778. scanDevicesIfNeeded();
  18779. return availableDeviceTypes;
  18780. }
  18781. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  18782. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  18783. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  18784. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  18785. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  18786. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  18787. {
  18788. #if JUCE_WINDOWS
  18789. #if JUCE_WASAPI
  18790. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  18791. list.add (juce_createAudioIODeviceType_WASAPI());
  18792. #endif
  18793. #if JUCE_DIRECTSOUND
  18794. list.add (juce_createAudioIODeviceType_DirectSound());
  18795. #endif
  18796. #if JUCE_ASIO
  18797. list.add (juce_createAudioIODeviceType_ASIO());
  18798. #endif
  18799. #endif
  18800. #if JUCE_MAC
  18801. list.add (juce_createAudioIODeviceType_CoreAudio());
  18802. #endif
  18803. #if JUCE_LINUX && JUCE_ALSA
  18804. list.add (juce_createAudioIODeviceType_ALSA());
  18805. #endif
  18806. }
  18807. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  18808. const int numOutputChannelsNeeded,
  18809. const XmlElement* const e,
  18810. const bool selectDefaultDeviceOnFailure,
  18811. const String& preferredDefaultDeviceName,
  18812. const AudioDeviceSetup* preferredSetupOptions)
  18813. {
  18814. scanDevicesIfNeeded();
  18815. numInputChansNeeded = numInputChannelsNeeded;
  18816. numOutputChansNeeded = numOutputChannelsNeeded;
  18817. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  18818. {
  18819. delete lastExplicitSettings;
  18820. lastExplicitSettings = new XmlElement (*e);
  18821. String error;
  18822. AudioDeviceSetup setup;
  18823. if (preferredSetupOptions != 0)
  18824. setup = *preferredSetupOptions;
  18825. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  18826. {
  18827. setup.inputDeviceName = setup.outputDeviceName
  18828. = e->getStringAttribute (T("audioDeviceName"));
  18829. }
  18830. else
  18831. {
  18832. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  18833. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  18834. }
  18835. currentDeviceType = e->getStringAttribute (T("deviceType"));
  18836. if (currentDeviceType.isEmpty())
  18837. {
  18838. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  18839. if (type != 0)
  18840. currentDeviceType = type->getTypeName();
  18841. else if (availableDeviceTypes.size() > 0)
  18842. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  18843. }
  18844. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  18845. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  18846. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  18847. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  18848. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  18849. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  18850. error = setAudioDeviceSetup (setup, true);
  18851. midiInsFromXml.clear();
  18852. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  18853. midiInsFromXml.add (c->getStringAttribute (T("name")));
  18854. const StringArray allMidiIns (MidiInput::getDevices());
  18855. for (int i = allMidiIns.size(); --i >= 0;)
  18856. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  18857. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  18858. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  18859. false, preferredDefaultDeviceName);
  18860. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  18861. return error;
  18862. }
  18863. else
  18864. {
  18865. AudioDeviceSetup setup;
  18866. if (preferredSetupOptions != 0)
  18867. {
  18868. setup = *preferredSetupOptions;
  18869. }
  18870. else if (preferredDefaultDeviceName.isNotEmpty())
  18871. {
  18872. for (int j = availableDeviceTypes.size(); --j >= 0;)
  18873. {
  18874. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  18875. StringArray outs (type->getDeviceNames (false));
  18876. int i;
  18877. for (i = 0; i < outs.size(); ++i)
  18878. {
  18879. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  18880. {
  18881. setup.outputDeviceName = outs[i];
  18882. break;
  18883. }
  18884. }
  18885. StringArray ins (type->getDeviceNames (true));
  18886. for (i = 0; i < ins.size(); ++i)
  18887. {
  18888. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  18889. {
  18890. setup.inputDeviceName = ins[i];
  18891. break;
  18892. }
  18893. }
  18894. }
  18895. }
  18896. insertDefaultDeviceNames (setup);
  18897. return setAudioDeviceSetup (setup, false);
  18898. }
  18899. }
  18900. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  18901. {
  18902. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18903. if (type != 0)
  18904. {
  18905. if (setup.outputDeviceName.isEmpty())
  18906. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  18907. if (setup.inputDeviceName.isEmpty())
  18908. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  18909. }
  18910. }
  18911. XmlElement* AudioDeviceManager::createStateXml() const
  18912. {
  18913. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  18914. }
  18915. void AudioDeviceManager::scanDevicesIfNeeded()
  18916. {
  18917. if (listNeedsScanning)
  18918. {
  18919. listNeedsScanning = false;
  18920. createDeviceTypesIfNeeded();
  18921. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18922. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  18923. }
  18924. }
  18925. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  18926. {
  18927. scanDevicesIfNeeded();
  18928. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18929. {
  18930. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  18931. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  18932. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  18933. {
  18934. return type;
  18935. }
  18936. }
  18937. return 0;
  18938. }
  18939. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  18940. {
  18941. setup = currentSetup;
  18942. }
  18943. void AudioDeviceManager::deleteCurrentDevice()
  18944. {
  18945. deleteAndZero (currentAudioDevice);
  18946. currentSetup.inputDeviceName = String::empty;
  18947. currentSetup.outputDeviceName = String::empty;
  18948. }
  18949. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  18950. const bool treatAsChosenDevice)
  18951. {
  18952. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18953. {
  18954. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  18955. && currentDeviceType != type)
  18956. {
  18957. currentDeviceType = type;
  18958. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  18959. insertDefaultDeviceNames (s);
  18960. setAudioDeviceSetup (s, treatAsChosenDevice);
  18961. sendChangeMessage (this);
  18962. break;
  18963. }
  18964. }
  18965. }
  18966. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  18967. {
  18968. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18969. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  18970. return availableDeviceTypes[i];
  18971. return availableDeviceTypes[0];
  18972. }
  18973. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  18974. const bool treatAsChosenDevice)
  18975. {
  18976. jassert (&newSetup != &currentSetup); // this will have no effect
  18977. if (newSetup == currentSetup && currentAudioDevice != 0)
  18978. return String::empty;
  18979. if (! (newSetup == currentSetup))
  18980. sendChangeMessage (this);
  18981. stopDevice();
  18982. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  18983. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  18984. String error;
  18985. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18986. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  18987. {
  18988. deleteCurrentDevice();
  18989. if (treatAsChosenDevice)
  18990. updateXml();
  18991. return String::empty;
  18992. }
  18993. if (currentSetup.inputDeviceName != newInputDeviceName
  18994. || currentSetup.outputDeviceName != newOutputDeviceName
  18995. || currentAudioDevice == 0)
  18996. {
  18997. deleteCurrentDevice();
  18998. scanDevicesIfNeeded();
  18999. if (newOutputDeviceName.isNotEmpty()
  19000. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19001. {
  19002. return "No such device: " + newOutputDeviceName;
  19003. }
  19004. if (newInputDeviceName.isNotEmpty()
  19005. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19006. {
  19007. return "No such device: " + newInputDeviceName;
  19008. }
  19009. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19010. if (currentAudioDevice == 0)
  19011. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  19012. else
  19013. error = currentAudioDevice->getLastError();
  19014. if (error.isNotEmpty())
  19015. {
  19016. deleteCurrentDevice();
  19017. return error;
  19018. }
  19019. if (newSetup.useDefaultInputChannels)
  19020. {
  19021. inputChannels.clear();
  19022. inputChannels.setRange (0, numInputChansNeeded, true);
  19023. }
  19024. if (newSetup.useDefaultOutputChannels)
  19025. {
  19026. outputChannels.clear();
  19027. outputChannels.setRange (0, numOutputChansNeeded, true);
  19028. }
  19029. if (newInputDeviceName.isEmpty())
  19030. inputChannels.clear();
  19031. if (newOutputDeviceName.isEmpty())
  19032. outputChannels.clear();
  19033. }
  19034. if (! newSetup.useDefaultInputChannels)
  19035. inputChannels = newSetup.inputChannels;
  19036. if (! newSetup.useDefaultOutputChannels)
  19037. outputChannels = newSetup.outputChannels;
  19038. currentSetup = newSetup;
  19039. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19040. error = currentAudioDevice->open (inputChannels,
  19041. outputChannels,
  19042. currentSetup.sampleRate,
  19043. currentSetup.bufferSize);
  19044. if (error.isEmpty())
  19045. {
  19046. currentDeviceType = currentAudioDevice->getTypeName();
  19047. currentAudioDevice->start (&callbackHandler);
  19048. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19049. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19050. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19051. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19052. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19053. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19054. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19055. if (treatAsChosenDevice)
  19056. updateXml();
  19057. }
  19058. else
  19059. {
  19060. deleteCurrentDevice();
  19061. }
  19062. return error;
  19063. }
  19064. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19065. {
  19066. jassert (currentAudioDevice != 0);
  19067. if (rate > 0)
  19068. {
  19069. bool ok = false;
  19070. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19071. {
  19072. const double sr = currentAudioDevice->getSampleRate (i);
  19073. if (sr == rate)
  19074. ok = true;
  19075. }
  19076. if (! ok)
  19077. rate = 0;
  19078. }
  19079. if (rate == 0)
  19080. {
  19081. double lowestAbove44 = 0.0;
  19082. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19083. {
  19084. const double sr = currentAudioDevice->getSampleRate (i);
  19085. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19086. lowestAbove44 = sr;
  19087. }
  19088. if (lowestAbove44 == 0.0)
  19089. rate = currentAudioDevice->getSampleRate (0);
  19090. else
  19091. rate = lowestAbove44;
  19092. }
  19093. return rate;
  19094. }
  19095. void AudioDeviceManager::stopDevice()
  19096. {
  19097. if (currentAudioDevice != 0)
  19098. currentAudioDevice->stop();
  19099. deleteAndZero (testSound);
  19100. }
  19101. void AudioDeviceManager::closeAudioDevice()
  19102. {
  19103. stopDevice();
  19104. deleteAndZero (currentAudioDevice);
  19105. }
  19106. void AudioDeviceManager::restartLastAudioDevice()
  19107. {
  19108. if (currentAudioDevice == 0)
  19109. {
  19110. if (currentSetup.inputDeviceName.isEmpty()
  19111. && currentSetup.outputDeviceName.isEmpty())
  19112. {
  19113. // This method will only reload the last device that was running
  19114. // before closeAudioDevice() was called - you need to actually open
  19115. // one first, with setAudioDevice().
  19116. jassertfalse
  19117. return;
  19118. }
  19119. AudioDeviceSetup s (currentSetup);
  19120. setAudioDeviceSetup (s, false);
  19121. }
  19122. }
  19123. void AudioDeviceManager::updateXml()
  19124. {
  19125. delete lastExplicitSettings;
  19126. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  19127. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  19128. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  19129. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  19130. if (currentAudioDevice != 0)
  19131. {
  19132. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  19133. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19134. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  19135. if (! currentSetup.useDefaultInputChannels)
  19136. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  19137. if (! currentSetup.useDefaultOutputChannels)
  19138. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  19139. }
  19140. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19141. {
  19142. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19143. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  19144. lastExplicitSettings->addChildElement (m);
  19145. }
  19146. if (midiInsFromXml.size() > 0)
  19147. {
  19148. // Add any midi devices that have been enabled before, but which aren't currently
  19149. // open because the device has been disconnected.
  19150. const StringArray availableMidiDevices (MidiInput::getDevices());
  19151. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19152. {
  19153. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19154. {
  19155. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19156. m->setAttribute (T("name"), midiInsFromXml[i]);
  19157. lastExplicitSettings->addChildElement (m);
  19158. }
  19159. }
  19160. }
  19161. if (defaultMidiOutputName.isNotEmpty())
  19162. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  19163. }
  19164. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19165. {
  19166. {
  19167. const ScopedLock sl (audioCallbackLock);
  19168. if (callbacks.contains (newCallback))
  19169. return;
  19170. }
  19171. if (currentAudioDevice != 0 && newCallback != 0)
  19172. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19173. const ScopedLock sl (audioCallbackLock);
  19174. callbacks.add (newCallback);
  19175. }
  19176. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19177. {
  19178. if (callback != 0)
  19179. {
  19180. bool needsDeinitialising = currentAudioDevice != 0;
  19181. {
  19182. const ScopedLock sl (audioCallbackLock);
  19183. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19184. callbacks.removeValue (callback);
  19185. }
  19186. if (needsDeinitialising)
  19187. callback->audioDeviceStopped();
  19188. }
  19189. }
  19190. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19191. int numInputChannels,
  19192. float** outputChannelData,
  19193. int numOutputChannels,
  19194. int numSamples)
  19195. {
  19196. const ScopedLock sl (audioCallbackLock);
  19197. if (inputLevelMeasurementEnabledCount > 0)
  19198. {
  19199. for (int j = 0; j < numSamples; ++j)
  19200. {
  19201. float s = 0;
  19202. for (int i = 0; i < numInputChannels; ++i)
  19203. s += fabsf (inputChannelData[i][j]);
  19204. s /= numInputChannels;
  19205. const double decayFactor = 0.99992;
  19206. if (s > inputLevel)
  19207. inputLevel = s;
  19208. else if (inputLevel > 0.001f)
  19209. inputLevel *= decayFactor;
  19210. else
  19211. inputLevel = 0;
  19212. }
  19213. }
  19214. if (callbacks.size() > 0)
  19215. {
  19216. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19217. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19218. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19219. outputChannelData, numOutputChannels, numSamples);
  19220. float** const tempChans = tempBuffer.getArrayOfChannels();
  19221. for (int i = callbacks.size(); --i > 0;)
  19222. {
  19223. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19224. tempChans, numOutputChannels, numSamples);
  19225. for (int chan = 0; chan < numOutputChannels; ++chan)
  19226. {
  19227. const float* const src = tempChans [chan];
  19228. float* const dst = outputChannelData [chan];
  19229. if (src != 0 && dst != 0)
  19230. for (int j = 0; j < numSamples; ++j)
  19231. dst[j] += src[j];
  19232. }
  19233. }
  19234. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19235. const double filterAmount = 0.2;
  19236. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19237. }
  19238. else
  19239. {
  19240. for (int i = 0; i < numOutputChannels; ++i)
  19241. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19242. }
  19243. if (testSound != 0)
  19244. {
  19245. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19246. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19247. for (int i = 0; i < numOutputChannels; ++i)
  19248. for (int j = 0; j < numSamps; ++j)
  19249. outputChannelData [i][j] += src[j];
  19250. testSoundPosition += numSamps;
  19251. if (testSoundPosition >= testSound->getNumSamples())
  19252. {
  19253. delete testSound;
  19254. testSound = 0;
  19255. }
  19256. }
  19257. }
  19258. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19259. {
  19260. cpuUsageMs = 0;
  19261. const double sampleRate = device->getCurrentSampleRate();
  19262. const int blockSize = device->getCurrentBufferSizeSamples();
  19263. if (sampleRate > 0.0 && blockSize > 0)
  19264. {
  19265. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19266. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19267. }
  19268. {
  19269. const ScopedLock sl (audioCallbackLock);
  19270. for (int i = callbacks.size(); --i >= 0;)
  19271. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19272. }
  19273. sendChangeMessage (this);
  19274. }
  19275. void AudioDeviceManager::audioDeviceStoppedInt()
  19276. {
  19277. cpuUsageMs = 0;
  19278. timeToCpuScale = 0;
  19279. sendChangeMessage (this);
  19280. const ScopedLock sl (audioCallbackLock);
  19281. for (int i = callbacks.size(); --i >= 0;)
  19282. callbacks.getUnchecked(i)->audioDeviceStopped();
  19283. }
  19284. double AudioDeviceManager::getCpuUsage() const
  19285. {
  19286. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19287. }
  19288. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19289. const bool enabled)
  19290. {
  19291. if (enabled != isMidiInputEnabled (name))
  19292. {
  19293. if (enabled)
  19294. {
  19295. const int index = MidiInput::getDevices().indexOf (name);
  19296. if (index >= 0)
  19297. {
  19298. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19299. if (min != 0)
  19300. {
  19301. enabledMidiInputs.add (min);
  19302. min->start();
  19303. }
  19304. }
  19305. }
  19306. else
  19307. {
  19308. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19309. if (enabledMidiInputs[i]->getName() == name)
  19310. enabledMidiInputs.remove (i);
  19311. }
  19312. updateXml();
  19313. sendChangeMessage (this);
  19314. }
  19315. }
  19316. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19317. {
  19318. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19319. if (enabledMidiInputs[i]->getName() == name)
  19320. return true;
  19321. return false;
  19322. }
  19323. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19324. MidiInputCallback* callback)
  19325. {
  19326. removeMidiInputCallback (name, callback);
  19327. if (name.isEmpty())
  19328. {
  19329. midiCallbacks.add (callback);
  19330. midiCallbackDevices.add (0);
  19331. }
  19332. else
  19333. {
  19334. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19335. {
  19336. if (enabledMidiInputs[i]->getName() == name)
  19337. {
  19338. const ScopedLock sl (midiCallbackLock);
  19339. midiCallbacks.add (callback);
  19340. midiCallbackDevices.add (enabledMidiInputs[i]);
  19341. break;
  19342. }
  19343. }
  19344. }
  19345. }
  19346. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19347. MidiInputCallback* /*callback*/)
  19348. {
  19349. const ScopedLock sl (midiCallbackLock);
  19350. for (int i = midiCallbacks.size(); --i >= 0;)
  19351. {
  19352. String devName;
  19353. if (midiCallbackDevices.getUnchecked(i) != 0)
  19354. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19355. if (devName == name)
  19356. {
  19357. midiCallbacks.remove (i);
  19358. midiCallbackDevices.remove (i);
  19359. }
  19360. }
  19361. }
  19362. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19363. const MidiMessage& message)
  19364. {
  19365. if (! message.isActiveSense())
  19366. {
  19367. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19368. const ScopedLock sl (midiCallbackLock);
  19369. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19370. {
  19371. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19372. if (md == source || (md == 0 && isDefaultSource))
  19373. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19374. }
  19375. }
  19376. }
  19377. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19378. {
  19379. if (defaultMidiOutputName != deviceName)
  19380. {
  19381. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19382. {
  19383. const ScopedLock sl (audioCallbackLock);
  19384. oldCallbacks = callbacks;
  19385. callbacks.clear();
  19386. }
  19387. if (currentAudioDevice != 0)
  19388. for (int i = oldCallbacks.size(); --i >= 0;)
  19389. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19390. deleteAndZero (defaultMidiOutput);
  19391. defaultMidiOutputName = deviceName;
  19392. if (deviceName.isNotEmpty())
  19393. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19394. if (currentAudioDevice != 0)
  19395. for (int i = oldCallbacks.size(); --i >= 0;)
  19396. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19397. {
  19398. const ScopedLock sl (audioCallbackLock);
  19399. callbacks = oldCallbacks;
  19400. }
  19401. updateXml();
  19402. sendChangeMessage (this);
  19403. }
  19404. }
  19405. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19406. int numInputChannels,
  19407. float** outputChannelData,
  19408. int numOutputChannels,
  19409. int numSamples)
  19410. {
  19411. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19412. }
  19413. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19414. {
  19415. owner->audioDeviceAboutToStartInt (device);
  19416. }
  19417. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19418. {
  19419. owner->audioDeviceStoppedInt();
  19420. }
  19421. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19422. {
  19423. owner->handleIncomingMidiMessageInt (source, message);
  19424. }
  19425. void AudioDeviceManager::playTestSound()
  19426. {
  19427. audioCallbackLock.enter();
  19428. AudioSampleBuffer* oldSound = testSound;
  19429. testSound = 0;
  19430. audioCallbackLock.exit();
  19431. delete oldSound;
  19432. testSoundPosition = 0;
  19433. if (currentAudioDevice != 0)
  19434. {
  19435. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  19436. const int soundLength = (int) sampleRate;
  19437. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  19438. float* samples = newSound->getSampleData (0);
  19439. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  19440. const float amplitude = 0.5f;
  19441. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19442. for (int i = 0; i < soundLength; ++i)
  19443. samples[i] = amplitude * (float) sin (i * phasePerSample);
  19444. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  19445. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  19446. const ScopedLock sl (audioCallbackLock);
  19447. testSound = newSound;
  19448. }
  19449. }
  19450. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  19451. {
  19452. const ScopedLock sl (audioCallbackLock);
  19453. if (enableMeasurement)
  19454. ++inputLevelMeasurementEnabledCount;
  19455. else
  19456. --inputLevelMeasurementEnabledCount;
  19457. inputLevel = 0;
  19458. }
  19459. double AudioDeviceManager::getCurrentInputLevel() const
  19460. {
  19461. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  19462. return inputLevel;
  19463. }
  19464. END_JUCE_NAMESPACE
  19465. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  19466. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  19467. BEGIN_JUCE_NAMESPACE
  19468. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  19469. : name (deviceName),
  19470. typeName (typeName_)
  19471. {
  19472. }
  19473. AudioIODevice::~AudioIODevice()
  19474. {
  19475. }
  19476. bool AudioIODevice::hasControlPanel() const
  19477. {
  19478. return false;
  19479. }
  19480. bool AudioIODevice::showControlPanel()
  19481. {
  19482. jassertfalse // this should only be called for devices which return true from
  19483. // their hasControlPanel() method.
  19484. return false;
  19485. }
  19486. END_JUCE_NAMESPACE
  19487. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  19488. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  19489. BEGIN_JUCE_NAMESPACE
  19490. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  19491. : typeName (name)
  19492. {
  19493. }
  19494. AudioIODeviceType::~AudioIODeviceType()
  19495. {
  19496. }
  19497. END_JUCE_NAMESPACE
  19498. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  19499. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  19500. BEGIN_JUCE_NAMESPACE
  19501. MidiOutput::MidiOutput() throw()
  19502. : Thread ("midi out"),
  19503. internal (0),
  19504. firstMessage (0)
  19505. {
  19506. }
  19507. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  19508. const int len,
  19509. const double sampleNumber) throw()
  19510. : message (data, len, sampleNumber)
  19511. {
  19512. }
  19513. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  19514. const double millisecondCounterToStartAt,
  19515. double samplesPerSecondForBuffer) throw()
  19516. {
  19517. // You've got to call startBackgroundThread() for this to actually work..
  19518. jassert (isThreadRunning());
  19519. // this needs to be a value in the future - RTFM for this method!
  19520. jassert (millisecondCounterToStartAt > 0);
  19521. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  19522. MidiBuffer::Iterator i (buffer);
  19523. const uint8* data;
  19524. int len, time;
  19525. while (i.getNextEvent (data, len, time))
  19526. {
  19527. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  19528. PendingMessage* const m
  19529. = new PendingMessage (data, len, eventTime);
  19530. const ScopedLock sl (lock);
  19531. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  19532. {
  19533. m->next = firstMessage;
  19534. firstMessage = m;
  19535. }
  19536. else
  19537. {
  19538. PendingMessage* mm = firstMessage;
  19539. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  19540. mm = mm->next;
  19541. m->next = mm->next;
  19542. mm->next = m;
  19543. }
  19544. }
  19545. notify();
  19546. }
  19547. void MidiOutput::clearAllPendingMessages() throw()
  19548. {
  19549. const ScopedLock sl (lock);
  19550. while (firstMessage != 0)
  19551. {
  19552. PendingMessage* const m = firstMessage;
  19553. firstMessage = firstMessage->next;
  19554. delete m;
  19555. }
  19556. }
  19557. void MidiOutput::startBackgroundThread() throw()
  19558. {
  19559. startThread (9);
  19560. }
  19561. void MidiOutput::stopBackgroundThread() throw()
  19562. {
  19563. stopThread (5000);
  19564. }
  19565. void MidiOutput::run()
  19566. {
  19567. while (! threadShouldExit())
  19568. {
  19569. uint32 now = Time::getMillisecondCounter();
  19570. uint32 eventTime = 0;
  19571. uint32 timeToWait = 500;
  19572. lock.enter();
  19573. PendingMessage* message = firstMessage;
  19574. if (message != 0)
  19575. {
  19576. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  19577. if (eventTime > now + 20)
  19578. {
  19579. timeToWait = jmax (10, eventTime - now - 100);
  19580. message = 0;
  19581. }
  19582. else
  19583. {
  19584. firstMessage = message->next;
  19585. }
  19586. }
  19587. lock.exit();
  19588. if (message != 0)
  19589. {
  19590. if (eventTime > now)
  19591. {
  19592. Time::waitForMillisecondCounter (eventTime);
  19593. if (threadShouldExit())
  19594. break;
  19595. }
  19596. if (eventTime > now - 200)
  19597. sendMessageNow (message->message);
  19598. delete message;
  19599. }
  19600. else
  19601. {
  19602. jassert (timeToWait < 1000 * 30);
  19603. wait (timeToWait);
  19604. }
  19605. }
  19606. clearAllPendingMessages();
  19607. }
  19608. END_JUCE_NAMESPACE
  19609. /********* End of inlined file: juce_MidiOutput.cpp *********/
  19610. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  19611. BEGIN_JUCE_NAMESPACE
  19612. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19613. {
  19614. const double maxVal = (double) 0x7fff;
  19615. char* intData = (char*) dest;
  19616. if (dest != (void*) source || destBytesPerSample <= 4)
  19617. {
  19618. for (int i = 0; i < numSamples; ++i)
  19619. {
  19620. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19621. intData += destBytesPerSample;
  19622. }
  19623. }
  19624. else
  19625. {
  19626. intData += destBytesPerSample * numSamples;
  19627. for (int i = numSamples; --i >= 0;)
  19628. {
  19629. intData -= destBytesPerSample;
  19630. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19631. }
  19632. }
  19633. }
  19634. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19635. {
  19636. const double maxVal = (double) 0x7fff;
  19637. char* intData = (char*) dest;
  19638. if (dest != (void*) source || destBytesPerSample <= 4)
  19639. {
  19640. for (int i = 0; i < numSamples; ++i)
  19641. {
  19642. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19643. intData += destBytesPerSample;
  19644. }
  19645. }
  19646. else
  19647. {
  19648. intData += destBytesPerSample * numSamples;
  19649. for (int i = numSamples; --i >= 0;)
  19650. {
  19651. intData -= destBytesPerSample;
  19652. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19653. }
  19654. }
  19655. }
  19656. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19657. {
  19658. const double maxVal = (double) 0x7fffff;
  19659. char* intData = (char*) dest;
  19660. if (dest != (void*) source || destBytesPerSample <= 4)
  19661. {
  19662. for (int i = 0; i < numSamples; ++i)
  19663. {
  19664. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19665. intData += destBytesPerSample;
  19666. }
  19667. }
  19668. else
  19669. {
  19670. intData += destBytesPerSample * numSamples;
  19671. for (int i = numSamples; --i >= 0;)
  19672. {
  19673. intData -= destBytesPerSample;
  19674. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19675. }
  19676. }
  19677. }
  19678. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19679. {
  19680. const double maxVal = (double) 0x7fffff;
  19681. char* intData = (char*) dest;
  19682. if (dest != (void*) source || destBytesPerSample <= 4)
  19683. {
  19684. for (int i = 0; i < numSamples; ++i)
  19685. {
  19686. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19687. intData += destBytesPerSample;
  19688. }
  19689. }
  19690. else
  19691. {
  19692. intData += destBytesPerSample * numSamples;
  19693. for (int i = numSamples; --i >= 0;)
  19694. {
  19695. intData -= destBytesPerSample;
  19696. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19697. }
  19698. }
  19699. }
  19700. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19701. {
  19702. const double maxVal = (double) 0x7fffffff;
  19703. char* intData = (char*) dest;
  19704. if (dest != (void*) source || destBytesPerSample <= 4)
  19705. {
  19706. for (int i = 0; i < numSamples; ++i)
  19707. {
  19708. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19709. intData += destBytesPerSample;
  19710. }
  19711. }
  19712. else
  19713. {
  19714. intData += destBytesPerSample * numSamples;
  19715. for (int i = numSamples; --i >= 0;)
  19716. {
  19717. intData -= destBytesPerSample;
  19718. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19719. }
  19720. }
  19721. }
  19722. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19723. {
  19724. const double maxVal = (double) 0x7fffffff;
  19725. char* intData = (char*) dest;
  19726. if (dest != (void*) source || destBytesPerSample <= 4)
  19727. {
  19728. for (int i = 0; i < numSamples; ++i)
  19729. {
  19730. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19731. intData += destBytesPerSample;
  19732. }
  19733. }
  19734. else
  19735. {
  19736. intData += destBytesPerSample * numSamples;
  19737. for (int i = numSamples; --i >= 0;)
  19738. {
  19739. intData -= destBytesPerSample;
  19740. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19741. }
  19742. }
  19743. }
  19744. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19745. {
  19746. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19747. char* d = (char*) dest;
  19748. for (int i = 0; i < numSamples; ++i)
  19749. {
  19750. *(float*)d = source[i];
  19751. #if JUCE_BIG_ENDIAN
  19752. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19753. #endif
  19754. d += destBytesPerSample;
  19755. }
  19756. }
  19757. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19758. {
  19759. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19760. char* d = (char*) dest;
  19761. for (int i = 0; i < numSamples; ++i)
  19762. {
  19763. *(float*)d = source[i];
  19764. #if JUCE_LITTLE_ENDIAN
  19765. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19766. #endif
  19767. d += destBytesPerSample;
  19768. }
  19769. }
  19770. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19771. {
  19772. const float scale = 1.0f / 0x7fff;
  19773. const char* intData = (const char*) source;
  19774. if (source != (void*) dest || srcBytesPerSample >= 4)
  19775. {
  19776. for (int i = 0; i < numSamples; ++i)
  19777. {
  19778. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19779. intData += srcBytesPerSample;
  19780. }
  19781. }
  19782. else
  19783. {
  19784. intData += srcBytesPerSample * numSamples;
  19785. for (int i = numSamples; --i >= 0;)
  19786. {
  19787. intData -= srcBytesPerSample;
  19788. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19789. }
  19790. }
  19791. }
  19792. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19793. {
  19794. const float scale = 1.0f / 0x7fff;
  19795. const char* intData = (const char*) source;
  19796. if (source != (void*) dest || srcBytesPerSample >= 4)
  19797. {
  19798. for (int i = 0; i < numSamples; ++i)
  19799. {
  19800. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19801. intData += srcBytesPerSample;
  19802. }
  19803. }
  19804. else
  19805. {
  19806. intData += srcBytesPerSample * numSamples;
  19807. for (int i = numSamples; --i >= 0;)
  19808. {
  19809. intData -= srcBytesPerSample;
  19810. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19811. }
  19812. }
  19813. }
  19814. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19815. {
  19816. const float scale = 1.0f / 0x7fffff;
  19817. const char* intData = (const char*) source;
  19818. if (source != (void*) dest || srcBytesPerSample >= 4)
  19819. {
  19820. for (int i = 0; i < numSamples; ++i)
  19821. {
  19822. dest[i] = scale * (short) littleEndian24Bit (intData);
  19823. intData += srcBytesPerSample;
  19824. }
  19825. }
  19826. else
  19827. {
  19828. intData += srcBytesPerSample * numSamples;
  19829. for (int i = numSamples; --i >= 0;)
  19830. {
  19831. intData -= srcBytesPerSample;
  19832. dest[i] = scale * (short) littleEndian24Bit (intData);
  19833. }
  19834. }
  19835. }
  19836. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19837. {
  19838. const float scale = 1.0f / 0x7fffff;
  19839. const char* intData = (const char*) source;
  19840. if (source != (void*) dest || srcBytesPerSample >= 4)
  19841. {
  19842. for (int i = 0; i < numSamples; ++i)
  19843. {
  19844. dest[i] = scale * (short) bigEndian24Bit (intData);
  19845. intData += srcBytesPerSample;
  19846. }
  19847. }
  19848. else
  19849. {
  19850. intData += srcBytesPerSample * numSamples;
  19851. for (int i = numSamples; --i >= 0;)
  19852. {
  19853. intData -= srcBytesPerSample;
  19854. dest[i] = scale * (short) bigEndian24Bit (intData);
  19855. }
  19856. }
  19857. }
  19858. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19859. {
  19860. const float scale = 1.0f / 0x7fffffff;
  19861. const char* intData = (const char*) source;
  19862. if (source != (void*) dest || srcBytesPerSample >= 4)
  19863. {
  19864. for (int i = 0; i < numSamples; ++i)
  19865. {
  19866. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19867. intData += srcBytesPerSample;
  19868. }
  19869. }
  19870. else
  19871. {
  19872. intData += srcBytesPerSample * numSamples;
  19873. for (int i = numSamples; --i >= 0;)
  19874. {
  19875. intData -= srcBytesPerSample;
  19876. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19877. }
  19878. }
  19879. }
  19880. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19881. {
  19882. const float scale = 1.0f / 0x7fffffff;
  19883. const char* intData = (const char*) source;
  19884. if (source != (void*) dest || srcBytesPerSample >= 4)
  19885. {
  19886. for (int i = 0; i < numSamples; ++i)
  19887. {
  19888. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19889. intData += srcBytesPerSample;
  19890. }
  19891. }
  19892. else
  19893. {
  19894. intData += srcBytesPerSample * numSamples;
  19895. for (int i = numSamples; --i >= 0;)
  19896. {
  19897. intData -= srcBytesPerSample;
  19898. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19899. }
  19900. }
  19901. }
  19902. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19903. {
  19904. const char* s = (const char*) source;
  19905. for (int i = 0; i < numSamples; ++i)
  19906. {
  19907. dest[i] = *(float*)s;
  19908. #if JUCE_BIG_ENDIAN
  19909. uint32* const d = (uint32*) (dest + i);
  19910. *d = swapByteOrder (*d);
  19911. #endif
  19912. s += srcBytesPerSample;
  19913. }
  19914. }
  19915. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19916. {
  19917. const char* s = (const char*) source;
  19918. for (int i = 0; i < numSamples; ++i)
  19919. {
  19920. dest[i] = *(float*)s;
  19921. #if JUCE_LITTLE_ENDIAN
  19922. uint32* const d = (uint32*) (dest + i);
  19923. *d = swapByteOrder (*d);
  19924. #endif
  19925. s += srcBytesPerSample;
  19926. }
  19927. }
  19928. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  19929. const float* const source,
  19930. void* const dest,
  19931. const int numSamples)
  19932. {
  19933. switch (destFormat)
  19934. {
  19935. case int16LE:
  19936. convertFloatToInt16LE (source, dest, numSamples);
  19937. break;
  19938. case int16BE:
  19939. convertFloatToInt16BE (source, dest, numSamples);
  19940. break;
  19941. case int24LE:
  19942. convertFloatToInt24LE (source, dest, numSamples);
  19943. break;
  19944. case int24BE:
  19945. convertFloatToInt24BE (source, dest, numSamples);
  19946. break;
  19947. case int32LE:
  19948. convertFloatToInt32LE (source, dest, numSamples);
  19949. break;
  19950. case int32BE:
  19951. convertFloatToInt32BE (source, dest, numSamples);
  19952. break;
  19953. case float32LE:
  19954. convertFloatToFloat32LE (source, dest, numSamples);
  19955. break;
  19956. case float32BE:
  19957. convertFloatToFloat32BE (source, dest, numSamples);
  19958. break;
  19959. default:
  19960. jassertfalse
  19961. break;
  19962. }
  19963. }
  19964. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  19965. const void* const source,
  19966. float* const dest,
  19967. const int numSamples)
  19968. {
  19969. switch (sourceFormat)
  19970. {
  19971. case int16LE:
  19972. convertInt16LEToFloat (source, dest, numSamples);
  19973. break;
  19974. case int16BE:
  19975. convertInt16BEToFloat (source, dest, numSamples);
  19976. break;
  19977. case int24LE:
  19978. convertInt24LEToFloat (source, dest, numSamples);
  19979. break;
  19980. case int24BE:
  19981. convertInt24BEToFloat (source, dest, numSamples);
  19982. break;
  19983. case int32LE:
  19984. convertInt32LEToFloat (source, dest, numSamples);
  19985. break;
  19986. case int32BE:
  19987. convertInt32BEToFloat (source, dest, numSamples);
  19988. break;
  19989. case float32LE:
  19990. convertFloat32LEToFloat (source, dest, numSamples);
  19991. break;
  19992. case float32BE:
  19993. convertFloat32BEToFloat (source, dest, numSamples);
  19994. break;
  19995. default:
  19996. jassertfalse
  19997. break;
  19998. }
  19999. }
  20000. void AudioDataConverters::interleaveSamples (const float** const source,
  20001. float* const dest,
  20002. const int numSamples,
  20003. const int numChannels)
  20004. {
  20005. for (int chan = 0; chan < numChannels; ++chan)
  20006. {
  20007. int i = chan;
  20008. const float* src = source [chan];
  20009. for (int j = 0; j < numSamples; ++j)
  20010. {
  20011. dest [i] = src [j];
  20012. i += numChannels;
  20013. }
  20014. }
  20015. }
  20016. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20017. float** const dest,
  20018. const int numSamples,
  20019. const int numChannels)
  20020. {
  20021. for (int chan = 0; chan < numChannels; ++chan)
  20022. {
  20023. int i = chan;
  20024. float* dst = dest [chan];
  20025. for (int j = 0; j < numSamples; ++j)
  20026. {
  20027. dst [j] = source [i];
  20028. i += numChannels;
  20029. }
  20030. }
  20031. }
  20032. END_JUCE_NAMESPACE
  20033. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  20034. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  20035. BEGIN_JUCE_NAMESPACE
  20036. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20037. const int numSamples) throw()
  20038. : numChannels (numChannels_),
  20039. size (numSamples)
  20040. {
  20041. jassert (numSamples >= 0);
  20042. jassert (numChannels_ > 0);
  20043. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  20044. allocatedData = (float*) juce_malloc (allocatedBytes);
  20045. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  20046. float* chan = allocatedData;
  20047. for (int i = 0; i < numChannels_; ++i)
  20048. {
  20049. channels[i] = chan;
  20050. chan += numSamples;
  20051. }
  20052. channels [numChannels_] = 0;
  20053. }
  20054. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20055. const int numChannels_,
  20056. const int numSamples) throw()
  20057. : numChannels (numChannels_),
  20058. size (numSamples),
  20059. allocatedBytes (0),
  20060. allocatedData (0)
  20061. {
  20062. jassert (numChannels_ > 0);
  20063. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20064. if (numChannels_ < numElementsInArray (preallocatedChannelSpace))
  20065. channels = (float**) preallocatedChannelSpace;
  20066. else
  20067. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  20068. for (int i = 0; i < numChannels_; ++i)
  20069. {
  20070. // you have to pass in the same number of valid pointers as numChannels
  20071. jassert (dataToReferTo[i] != 0);
  20072. channels[i] = dataToReferTo[i];
  20073. }
  20074. channels [numChannels_] = 0;
  20075. }
  20076. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20077. const int numChannels_,
  20078. const int numSamples) throw()
  20079. {
  20080. jassert (numChannels_ > 0);
  20081. juce_free (allocatedData);
  20082. allocatedData = 0;
  20083. allocatedBytes = 0;
  20084. if (numChannels_ > numChannels)
  20085. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  20086. numChannels = numChannels_;
  20087. size = numSamples;
  20088. for (int i = 0; i < numChannels_; ++i)
  20089. {
  20090. // you have to pass in the same number of valid pointers as numChannels
  20091. jassert (dataToReferTo[i] != 0);
  20092. channels[i] = dataToReferTo[i];
  20093. }
  20094. channels [numChannels_] = 0;
  20095. }
  20096. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20097. : numChannels (other.numChannels),
  20098. size (other.size)
  20099. {
  20100. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  20101. if (other.allocatedData != 0)
  20102. {
  20103. allocatedBytes = numChannels * size * sizeof (float) + 32;
  20104. allocatedData = (float*) juce_malloc (allocatedBytes);
  20105. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  20106. float* chan = allocatedData;
  20107. for (int i = 0; i < numChannels; ++i)
  20108. {
  20109. channels[i] = chan;
  20110. chan += size;
  20111. }
  20112. channels [numChannels] = 0;
  20113. }
  20114. else
  20115. {
  20116. allocatedData = 0;
  20117. allocatedBytes = 0;
  20118. memcpy (channels, other.channels, sizeof (channels));
  20119. }
  20120. }
  20121. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20122. {
  20123. if (this != &other)
  20124. {
  20125. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20126. const int numBytes = size * sizeof (float);
  20127. for (int i = 0; i < numChannels; ++i)
  20128. memcpy (channels[i], other.channels[i], numBytes);
  20129. }
  20130. return *this;
  20131. }
  20132. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20133. {
  20134. juce_free (allocatedData);
  20135. if (channels != (float**) preallocatedChannelSpace)
  20136. juce_free (channels);
  20137. }
  20138. void AudioSampleBuffer::setSize (const int newNumChannels,
  20139. const int newNumSamples,
  20140. const bool keepExistingContent,
  20141. const bool clearExtraSpace,
  20142. const bool avoidReallocating) throw()
  20143. {
  20144. jassert (newNumChannels > 0);
  20145. if (newNumSamples != size || newNumChannels != numChannels)
  20146. {
  20147. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  20148. if (keepExistingContent)
  20149. {
  20150. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20151. : (float*) juce_malloc (newTotalBytes);
  20152. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  20153. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  20154. {
  20155. memcpy (newData + i * newNumSamples,
  20156. channels[i],
  20157. sizeToCopy);
  20158. }
  20159. juce_free (allocatedData);
  20160. allocatedData = newData;
  20161. allocatedBytes = newTotalBytes;
  20162. }
  20163. else
  20164. {
  20165. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20166. {
  20167. if (clearExtraSpace)
  20168. zeromem (allocatedData, newTotalBytes);
  20169. }
  20170. else
  20171. {
  20172. juce_free (allocatedData);
  20173. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20174. : (float*) juce_malloc (newTotalBytes);
  20175. allocatedBytes = newTotalBytes;
  20176. }
  20177. }
  20178. size = newNumSamples;
  20179. if (newNumChannels > numChannels)
  20180. channels = (float**) juce_realloc (channels, (newNumChannels + 1) * sizeof (float*));
  20181. numChannels = newNumChannels;
  20182. float* chan = allocatedData;
  20183. for (int i = 0; i < newNumChannels; ++i)
  20184. {
  20185. channels[i] = chan;
  20186. chan += size;
  20187. }
  20188. channels [newNumChannels] = 0;
  20189. }
  20190. }
  20191. void AudioSampleBuffer::clear() throw()
  20192. {
  20193. for (int i = 0; i < numChannels; ++i)
  20194. zeromem (channels[i], size * sizeof (float));
  20195. }
  20196. void AudioSampleBuffer::clear (const int startSample,
  20197. const int numSamples) throw()
  20198. {
  20199. jassert (startSample >= 0 && startSample + numSamples <= size);
  20200. for (int i = 0; i < numChannels; ++i)
  20201. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20202. }
  20203. void AudioSampleBuffer::clear (const int channel,
  20204. const int startSample,
  20205. const int numSamples) throw()
  20206. {
  20207. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20208. jassert (startSample >= 0 && startSample + numSamples <= size);
  20209. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20210. }
  20211. void AudioSampleBuffer::applyGain (const int channel,
  20212. const int startSample,
  20213. int numSamples,
  20214. const float gain) throw()
  20215. {
  20216. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20217. jassert (startSample >= 0 && startSample + numSamples <= size);
  20218. if (gain != 1.0f)
  20219. {
  20220. float* d = channels [channel] + startSample;
  20221. if (gain == 0.0f)
  20222. {
  20223. zeromem (d, sizeof (float) * numSamples);
  20224. }
  20225. else
  20226. {
  20227. while (--numSamples >= 0)
  20228. *d++ *= gain;
  20229. }
  20230. }
  20231. }
  20232. void AudioSampleBuffer::applyGainRamp (const int channel,
  20233. const int startSample,
  20234. int numSamples,
  20235. float startGain,
  20236. float endGain) throw()
  20237. {
  20238. if (startGain == endGain)
  20239. {
  20240. applyGain (channel, startSample, numSamples, startGain);
  20241. }
  20242. else
  20243. {
  20244. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20245. jassert (startSample >= 0 && startSample + numSamples <= size);
  20246. const float increment = (endGain - startGain) / numSamples;
  20247. float* d = channels [channel] + startSample;
  20248. while (--numSamples >= 0)
  20249. {
  20250. *d++ *= startGain;
  20251. startGain += increment;
  20252. }
  20253. }
  20254. }
  20255. void AudioSampleBuffer::applyGain (const int startSample,
  20256. const int numSamples,
  20257. const float gain) throw()
  20258. {
  20259. for (int i = 0; i < numChannels; ++i)
  20260. applyGain (i, startSample, numSamples, gain);
  20261. }
  20262. void AudioSampleBuffer::addFrom (const int destChannel,
  20263. const int destStartSample,
  20264. const AudioSampleBuffer& source,
  20265. const int sourceChannel,
  20266. const int sourceStartSample,
  20267. int numSamples,
  20268. const float gain) throw()
  20269. {
  20270. jassert (&source != this || sourceChannel != destChannel);
  20271. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20272. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20273. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20274. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20275. if (gain != 0.0f && numSamples > 0)
  20276. {
  20277. float* d = channels [destChannel] + destStartSample;
  20278. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20279. if (gain != 1.0f)
  20280. {
  20281. while (--numSamples >= 0)
  20282. *d++ += gain * *s++;
  20283. }
  20284. else
  20285. {
  20286. while (--numSamples >= 0)
  20287. *d++ += *s++;
  20288. }
  20289. }
  20290. }
  20291. void AudioSampleBuffer::addFrom (const int destChannel,
  20292. const int destStartSample,
  20293. const float* source,
  20294. int numSamples,
  20295. const float gain) throw()
  20296. {
  20297. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20298. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20299. jassert (source != 0);
  20300. if (gain != 0.0f && numSamples > 0)
  20301. {
  20302. float* d = channels [destChannel] + destStartSample;
  20303. if (gain != 1.0f)
  20304. {
  20305. while (--numSamples >= 0)
  20306. *d++ += gain * *source++;
  20307. }
  20308. else
  20309. {
  20310. while (--numSamples >= 0)
  20311. *d++ += *source++;
  20312. }
  20313. }
  20314. }
  20315. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20316. const int destStartSample,
  20317. const float* source,
  20318. int numSamples,
  20319. float startGain,
  20320. const float endGain) throw()
  20321. {
  20322. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20323. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20324. jassert (source != 0);
  20325. if (startGain == endGain)
  20326. {
  20327. addFrom (destChannel,
  20328. destStartSample,
  20329. source,
  20330. numSamples,
  20331. startGain);
  20332. }
  20333. else
  20334. {
  20335. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20336. {
  20337. const float increment = (endGain - startGain) / numSamples;
  20338. float* d = channels [destChannel] + destStartSample;
  20339. while (--numSamples >= 0)
  20340. {
  20341. *d++ += startGain * *source++;
  20342. startGain += increment;
  20343. }
  20344. }
  20345. }
  20346. }
  20347. void AudioSampleBuffer::copyFrom (const int destChannel,
  20348. const int destStartSample,
  20349. const AudioSampleBuffer& source,
  20350. const int sourceChannel,
  20351. const int sourceStartSample,
  20352. int numSamples) throw()
  20353. {
  20354. jassert (&source != this || sourceChannel != destChannel);
  20355. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20356. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20357. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20358. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20359. if (numSamples > 0)
  20360. {
  20361. memcpy (channels [destChannel] + destStartSample,
  20362. source.channels [sourceChannel] + sourceStartSample,
  20363. sizeof (float) * numSamples);
  20364. }
  20365. }
  20366. void AudioSampleBuffer::copyFrom (const int destChannel,
  20367. const int destStartSample,
  20368. const float* source,
  20369. int numSamples) throw()
  20370. {
  20371. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20372. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20373. jassert (source != 0);
  20374. if (numSamples > 0)
  20375. {
  20376. memcpy (channels [destChannel] + destStartSample,
  20377. source,
  20378. sizeof (float) * numSamples);
  20379. }
  20380. }
  20381. void AudioSampleBuffer::copyFrom (const int destChannel,
  20382. const int destStartSample,
  20383. const float* source,
  20384. int numSamples,
  20385. const float gain) throw()
  20386. {
  20387. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20388. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20389. jassert (source != 0);
  20390. if (numSamples > 0 && gain != 0)
  20391. {
  20392. float* d = channels [destChannel] + destStartSample;
  20393. if (gain != 1.0f)
  20394. {
  20395. while (--numSamples >= 0)
  20396. *d++ = gain * *source++;
  20397. }
  20398. else
  20399. {
  20400. memcpy (d, source, sizeof (float) * numSamples);
  20401. }
  20402. }
  20403. }
  20404. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20405. const int destStartSample,
  20406. const float* source,
  20407. int numSamples,
  20408. float startGain,
  20409. float endGain) throw()
  20410. {
  20411. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20412. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20413. jassert (source != 0);
  20414. if (startGain == endGain)
  20415. {
  20416. copyFrom (destChannel,
  20417. destStartSample,
  20418. source,
  20419. numSamples,
  20420. startGain);
  20421. }
  20422. else
  20423. {
  20424. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20425. {
  20426. const float increment = (endGain - startGain) / numSamples;
  20427. float* d = channels [destChannel] + destStartSample;
  20428. while (--numSamples >= 0)
  20429. {
  20430. *d++ = startGain * *source++;
  20431. startGain += increment;
  20432. }
  20433. }
  20434. }
  20435. }
  20436. void AudioSampleBuffer::findMinMax (const int channel,
  20437. const int startSample,
  20438. int numSamples,
  20439. float& minVal,
  20440. float& maxVal) const throw()
  20441. {
  20442. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20443. jassert (startSample >= 0 && startSample + numSamples <= size);
  20444. if (numSamples <= 0)
  20445. {
  20446. minVal = 0.0f;
  20447. maxVal = 0.0f;
  20448. }
  20449. else
  20450. {
  20451. const float* d = channels [channel] + startSample;
  20452. float mn = *d++;
  20453. float mx = mn;
  20454. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  20455. {
  20456. const float samp = *d++;
  20457. if (samp > mx)
  20458. mx = samp;
  20459. if (samp < mn)
  20460. mn = samp;
  20461. }
  20462. maxVal = mx;
  20463. minVal = mn;
  20464. }
  20465. }
  20466. float AudioSampleBuffer::getMagnitude (const int channel,
  20467. const int startSample,
  20468. const int numSamples) const throw()
  20469. {
  20470. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20471. jassert (startSample >= 0 && startSample + numSamples <= size);
  20472. float mn, mx;
  20473. findMinMax (channel, startSample, numSamples, mn, mx);
  20474. return jmax (mn, -mn, mx, -mx);
  20475. }
  20476. float AudioSampleBuffer::getMagnitude (const int startSample,
  20477. const int numSamples) const throw()
  20478. {
  20479. float mag = 0.0f;
  20480. for (int i = 0; i < numChannels; ++i)
  20481. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  20482. return mag;
  20483. }
  20484. float AudioSampleBuffer::getRMSLevel (const int channel,
  20485. const int startSample,
  20486. const int numSamples) const throw()
  20487. {
  20488. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20489. jassert (startSample >= 0 && startSample + numSamples <= size);
  20490. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  20491. return 0.0f;
  20492. const float* const data = channels [channel] + startSample;
  20493. double sum = 0.0;
  20494. for (int i = 0; i < numSamples; ++i)
  20495. {
  20496. const float sample = data [i];
  20497. sum += sample * sample;
  20498. }
  20499. return (float) sqrt (sum / numSamples);
  20500. }
  20501. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  20502. const int startSample,
  20503. const int numSamples,
  20504. const int readerStartSample,
  20505. const bool useLeftChan,
  20506. const bool useRightChan) throw()
  20507. {
  20508. jassert (reader != 0);
  20509. jassert (startSample >= 0 && startSample + numSamples <= size);
  20510. if (numSamples > 0)
  20511. {
  20512. int* chans[3];
  20513. if (useLeftChan == useRightChan)
  20514. {
  20515. chans[0] = (int*) getSampleData (0, startSample);
  20516. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  20517. }
  20518. else if (useLeftChan || (reader->numChannels == 1))
  20519. {
  20520. chans[0] = (int*) getSampleData (0, startSample);
  20521. chans[1] = 0;
  20522. }
  20523. else if (useRightChan)
  20524. {
  20525. chans[0] = 0;
  20526. chans[1] = (int*) getSampleData (0, startSample);
  20527. }
  20528. chans[2] = 0;
  20529. reader->read (chans, 2, readerStartSample, numSamples, true);
  20530. if (! reader->usesFloatingPointData)
  20531. {
  20532. for (int j = 0; j < 2; ++j)
  20533. {
  20534. float* const d = (float*) (chans[j]);
  20535. if (d != 0)
  20536. {
  20537. const float multiplier = 1.0f / 0x7fffffff;
  20538. for (int i = 0; i < numSamples; ++i)
  20539. d[i] = *(int*)(d + i) * multiplier;
  20540. }
  20541. }
  20542. }
  20543. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  20544. {
  20545. // if this is a stereo buffer and the source was mono, dupe the first channel..
  20546. memcpy (getSampleData (1, startSample),
  20547. getSampleData (0, startSample),
  20548. sizeof (float) * numSamples);
  20549. }
  20550. }
  20551. }
  20552. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  20553. const int startSample,
  20554. const int numSamples) const throw()
  20555. {
  20556. jassert (startSample >= 0 && startSample + numSamples <= size);
  20557. if (numSamples > 0)
  20558. {
  20559. int* chans [3];
  20560. if (writer->isFloatingPoint())
  20561. {
  20562. chans[0] = (int*) getSampleData (0, startSample);
  20563. if (numChannels > 1)
  20564. chans[1] = (int*) getSampleData (1, startSample);
  20565. else
  20566. chans[1] = 0;
  20567. chans[2] = 0;
  20568. writer->write ((const int**) chans, numSamples);
  20569. }
  20570. else
  20571. {
  20572. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  20573. if (numChannels > 1)
  20574. chans[1] = chans[0] + numSamples;
  20575. else
  20576. chans[1] = 0;
  20577. chans[2] = 0;
  20578. for (int j = 0; j < 2; ++j)
  20579. {
  20580. int* const dest = chans[j];
  20581. if (dest != 0)
  20582. {
  20583. const float* const src = channels [j] + startSample;
  20584. for (int i = 0; i < numSamples; ++i)
  20585. {
  20586. const double samp = src[i];
  20587. if (samp <= -1.0)
  20588. dest[i] = INT_MIN;
  20589. else if (samp >= 1.0)
  20590. dest[i] = INT_MAX;
  20591. else
  20592. dest[i] = roundDoubleToInt (INT_MAX * samp);
  20593. }
  20594. }
  20595. }
  20596. writer->write ((const int**) chans, numSamples);
  20597. juce_free (chans[0]);
  20598. }
  20599. }
  20600. }
  20601. END_JUCE_NAMESPACE
  20602. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  20603. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  20604. BEGIN_JUCE_NAMESPACE
  20605. IIRFilter::IIRFilter() throw()
  20606. : active (false)
  20607. {
  20608. reset();
  20609. }
  20610. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  20611. : active (other.active)
  20612. {
  20613. const ScopedLock sl (other.processLock);
  20614. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20615. reset();
  20616. }
  20617. IIRFilter::~IIRFilter() throw()
  20618. {
  20619. }
  20620. void IIRFilter::reset() throw()
  20621. {
  20622. const ScopedLock sl (processLock);
  20623. x1 = 0;
  20624. x2 = 0;
  20625. y1 = 0;
  20626. y2 = 0;
  20627. }
  20628. float IIRFilter::processSingleSampleRaw (const float in) throw()
  20629. {
  20630. float out = coefficients[0] * in
  20631. + coefficients[1] * x1
  20632. + coefficients[2] * x2
  20633. - coefficients[4] * y1
  20634. - coefficients[5] * y2;
  20635. #if JUCE_INTEL
  20636. if (! (out < -1.0e-8 || out > 1.0e-8))
  20637. out = 0;
  20638. #endif
  20639. x2 = x1;
  20640. x1 = in;
  20641. y2 = y1;
  20642. y1 = out;
  20643. return out;
  20644. }
  20645. void IIRFilter::processSamples (float* const samples,
  20646. const int numSamples) throw()
  20647. {
  20648. const ScopedLock sl (processLock);
  20649. if (active)
  20650. {
  20651. for (int i = 0; i < numSamples; ++i)
  20652. {
  20653. const float in = samples[i];
  20654. float out = coefficients[0] * in
  20655. + coefficients[1] * x1
  20656. + coefficients[2] * x2
  20657. - coefficients[4] * y1
  20658. - coefficients[5] * y2;
  20659. #if JUCE_INTEL
  20660. if (! (out < -1.0e-8 || out > 1.0e-8))
  20661. out = 0;
  20662. #endif
  20663. x2 = x1;
  20664. x1 = in;
  20665. y2 = y1;
  20666. y1 = out;
  20667. samples[i] = out;
  20668. }
  20669. }
  20670. }
  20671. void IIRFilter::makeLowPass (const double sampleRate,
  20672. const double frequency) throw()
  20673. {
  20674. jassert (sampleRate > 0);
  20675. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  20676. const double nSquared = n * n;
  20677. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20678. setCoefficients (c1,
  20679. c1 * 2.0f,
  20680. c1,
  20681. 1.0,
  20682. c1 * 2.0 * (1.0 - nSquared),
  20683. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20684. }
  20685. void IIRFilter::makeHighPass (const double sampleRate,
  20686. const double frequency) throw()
  20687. {
  20688. const double n = tan (double_Pi * frequency / sampleRate);
  20689. const double nSquared = n * n;
  20690. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20691. setCoefficients (c1,
  20692. c1 * -2.0f,
  20693. c1,
  20694. 1.0,
  20695. c1 * 2.0 * (nSquared - 1.0),
  20696. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20697. }
  20698. void IIRFilter::makeLowShelf (const double sampleRate,
  20699. const double cutOffFrequency,
  20700. const double Q,
  20701. const float gainFactor) throw()
  20702. {
  20703. jassert (sampleRate > 0);
  20704. jassert (Q > 0);
  20705. const double A = jmax (0.0f, gainFactor);
  20706. const double aminus1 = A - 1.0;
  20707. const double aplus1 = A + 1.0;
  20708. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20709. const double coso = cos (omega);
  20710. const double beta = sin (omega) * sqrt (A) / Q;
  20711. const double aminus1TimesCoso = aminus1 * coso;
  20712. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  20713. A * 2.0 * (aminus1 - aplus1 * coso),
  20714. A * (aplus1 - aminus1TimesCoso - beta),
  20715. aplus1 + aminus1TimesCoso + beta,
  20716. -2.0 * (aminus1 + aplus1 * coso),
  20717. aplus1 + aminus1TimesCoso - beta);
  20718. }
  20719. void IIRFilter::makeHighShelf (const double sampleRate,
  20720. const double cutOffFrequency,
  20721. const double Q,
  20722. const float gainFactor) throw()
  20723. {
  20724. jassert (sampleRate > 0);
  20725. jassert (Q > 0);
  20726. const double A = jmax (0.0f, gainFactor);
  20727. const double aminus1 = A - 1.0;
  20728. const double aplus1 = A + 1.0;
  20729. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20730. const double coso = cos (omega);
  20731. const double beta = sin (omega) * sqrt (A) / Q;
  20732. const double aminus1TimesCoso = aminus1 * coso;
  20733. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  20734. A * -2.0 * (aminus1 + aplus1 * coso),
  20735. A * (aplus1 + aminus1TimesCoso - beta),
  20736. aplus1 - aminus1TimesCoso + beta,
  20737. 2.0 * (aminus1 - aplus1 * coso),
  20738. aplus1 - aminus1TimesCoso - beta);
  20739. }
  20740. void IIRFilter::makeBandPass (const double sampleRate,
  20741. const double centreFrequency,
  20742. const double Q,
  20743. const float gainFactor) throw()
  20744. {
  20745. jassert (sampleRate > 0);
  20746. jassert (Q > 0);
  20747. const double A = jmax (0.0f, gainFactor);
  20748. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  20749. const double alpha = 0.5 * sin (omega) / Q;
  20750. const double c2 = -2.0 * cos (omega);
  20751. const double alphaTimesA = alpha * A;
  20752. const double alphaOverA = alpha / A;
  20753. setCoefficients (1.0 + alphaTimesA,
  20754. c2,
  20755. 1.0 - alphaTimesA,
  20756. 1.0 + alphaOverA,
  20757. c2,
  20758. 1.0 - alphaOverA);
  20759. }
  20760. void IIRFilter::makeInactive() throw()
  20761. {
  20762. const ScopedLock sl (processLock);
  20763. active = false;
  20764. }
  20765. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  20766. {
  20767. const ScopedLock sl (processLock);
  20768. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20769. active = other.active;
  20770. }
  20771. void IIRFilter::setCoefficients (double c1,
  20772. double c2,
  20773. double c3,
  20774. double c4,
  20775. double c5,
  20776. double c6) throw()
  20777. {
  20778. const double a = 1.0 / c4;
  20779. c1 *= a;
  20780. c2 *= a;
  20781. c3 *= a;
  20782. c5 *= a;
  20783. c6 *= a;
  20784. const ScopedLock sl (processLock);
  20785. coefficients[0] = (float) c1;
  20786. coefficients[1] = (float) c2;
  20787. coefficients[2] = (float) c3;
  20788. coefficients[3] = (float) c4;
  20789. coefficients[4] = (float) c5;
  20790. coefficients[5] = (float) c6;
  20791. active = true;
  20792. }
  20793. END_JUCE_NAMESPACE
  20794. /********* End of inlined file: juce_IIRFilter.cpp *********/
  20795. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  20796. BEGIN_JUCE_NAMESPACE
  20797. MidiBuffer::MidiBuffer() throw()
  20798. : ArrayAllocationBase <uint8> (32),
  20799. bytesUsed (0)
  20800. {
  20801. }
  20802. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  20803. : ArrayAllocationBase <uint8> (32),
  20804. bytesUsed (0)
  20805. {
  20806. addEvent (message, 0);
  20807. }
  20808. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  20809. : ArrayAllocationBase <uint8> (32),
  20810. bytesUsed (other.bytesUsed)
  20811. {
  20812. ensureAllocatedSize (bytesUsed);
  20813. memcpy (elements, other.elements, bytesUsed);
  20814. }
  20815. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  20816. {
  20817. if (this != &other)
  20818. {
  20819. bytesUsed = other.bytesUsed;
  20820. ensureAllocatedSize (bytesUsed);
  20821. if (bytesUsed > 0)
  20822. memcpy (elements, other.elements, bytesUsed);
  20823. }
  20824. return *this;
  20825. }
  20826. void MidiBuffer::swap (MidiBuffer& other)
  20827. {
  20828. swapVariables <uint8*> (this->elements, other.elements);
  20829. swapVariables <int> (this->numAllocated, other.numAllocated);
  20830. swapVariables <int> (this->bytesUsed, other.bytesUsed);
  20831. }
  20832. MidiBuffer::~MidiBuffer() throw()
  20833. {
  20834. }
  20835. void MidiBuffer::clear() throw()
  20836. {
  20837. bytesUsed = 0;
  20838. }
  20839. void MidiBuffer::clear (const int startSample,
  20840. const int numSamples) throw()
  20841. {
  20842. uint8* const start = findEventAfter (elements, startSample - 1);
  20843. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  20844. if (end > start)
  20845. {
  20846. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  20847. if (bytesToMove > 0)
  20848. memmove (start, end, bytesToMove);
  20849. bytesUsed -= (int) (end - start);
  20850. }
  20851. }
  20852. void MidiBuffer::addEvent (const MidiMessage& m,
  20853. const int sampleNumber) throw()
  20854. {
  20855. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  20856. }
  20857. static int findActualEventLength (const uint8* const data,
  20858. const int maxBytes) throw()
  20859. {
  20860. unsigned int byte = (unsigned int) *data;
  20861. int size = 0;
  20862. if (byte == 0xf0 || byte == 0xf7)
  20863. {
  20864. const uint8* d = data + 1;
  20865. while (d < data + maxBytes)
  20866. if (*d++ == 0xf7)
  20867. break;
  20868. size = (int) (d - data);
  20869. }
  20870. else if (byte == 0xff)
  20871. {
  20872. int n;
  20873. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  20874. size = jmin (maxBytes, n + 2 + bytesLeft);
  20875. }
  20876. else if (byte >= 0x80)
  20877. {
  20878. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  20879. }
  20880. return size;
  20881. }
  20882. void MidiBuffer::addEvent (const uint8* const newData,
  20883. const int maxBytes,
  20884. const int sampleNumber) throw()
  20885. {
  20886. const int numBytes = findActualEventLength (newData, maxBytes);
  20887. if (numBytes > 0)
  20888. {
  20889. ensureAllocatedSize (bytesUsed + numBytes + 6);
  20890. uint8* d = findEventAfter (elements, sampleNumber);
  20891. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  20892. if (bytesToMove > 0)
  20893. memmove (d + numBytes + 6,
  20894. d,
  20895. bytesToMove);
  20896. *(int*) d = sampleNumber;
  20897. d += 4;
  20898. *(uint16*) d = (uint16) numBytes;
  20899. d += 2;
  20900. memcpy (d, newData, numBytes);
  20901. bytesUsed += numBytes + 6;
  20902. }
  20903. }
  20904. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  20905. const int startSample,
  20906. const int numSamples,
  20907. const int sampleDeltaToAdd) throw()
  20908. {
  20909. Iterator i (otherBuffer);
  20910. i.setNextSamplePosition (startSample);
  20911. const uint8* data;
  20912. int size, position;
  20913. while (i.getNextEvent (data, size, position)
  20914. && (position < startSample + numSamples || numSamples < 0))
  20915. {
  20916. addEvent (data, size, position + sampleDeltaToAdd);
  20917. }
  20918. }
  20919. bool MidiBuffer::isEmpty() const throw()
  20920. {
  20921. return bytesUsed == 0;
  20922. }
  20923. int MidiBuffer::getNumEvents() const throw()
  20924. {
  20925. int n = 0;
  20926. const uint8* d = elements;
  20927. const uint8* const end = elements + bytesUsed;
  20928. while (d < end)
  20929. {
  20930. d += 4;
  20931. d += 2 + *(const uint16*) d;
  20932. ++n;
  20933. }
  20934. return n;
  20935. }
  20936. int MidiBuffer::getFirstEventTime() const throw()
  20937. {
  20938. return (bytesUsed > 0) ? *(const int*) elements : 0;
  20939. }
  20940. int MidiBuffer::getLastEventTime() const throw()
  20941. {
  20942. if (bytesUsed == 0)
  20943. return 0;
  20944. const uint8* d = elements;
  20945. const uint8* const endData = d + bytesUsed;
  20946. for (;;)
  20947. {
  20948. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  20949. if (nextOne >= endData)
  20950. return *(const int*) d;
  20951. d = nextOne;
  20952. }
  20953. }
  20954. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  20955. {
  20956. const uint8* const endData = elements + bytesUsed;
  20957. while (d < endData && *(int*) d <= samplePosition)
  20958. {
  20959. d += 4;
  20960. d += 2 + *(uint16*) d;
  20961. }
  20962. return d;
  20963. }
  20964. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  20965. : buffer (buffer),
  20966. data (buffer.elements)
  20967. {
  20968. }
  20969. MidiBuffer::Iterator::~Iterator() throw()
  20970. {
  20971. }
  20972. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  20973. {
  20974. data = buffer.elements;
  20975. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  20976. while (data < dataEnd && *(int*) data < samplePosition)
  20977. {
  20978. data += 4;
  20979. data += 2 + *(uint16*) data;
  20980. }
  20981. }
  20982. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  20983. int& numBytes,
  20984. int& samplePosition) throw()
  20985. {
  20986. if (data >= buffer.elements + buffer.bytesUsed)
  20987. return false;
  20988. samplePosition = *(int*) data;
  20989. data += 4;
  20990. numBytes = *(uint16*) data;
  20991. data += 2;
  20992. midiData = data;
  20993. data += numBytes;
  20994. return true;
  20995. }
  20996. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  20997. int& samplePosition) throw()
  20998. {
  20999. if (data >= buffer.elements + buffer.bytesUsed)
  21000. return false;
  21001. samplePosition = *(int*) data;
  21002. data += 4;
  21003. const int numBytes = *(uint16*) data;
  21004. data += 2;
  21005. result = MidiMessage (data, numBytes, samplePosition);
  21006. data += numBytes;
  21007. return true;
  21008. }
  21009. END_JUCE_NAMESPACE
  21010. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  21011. /********* Start of inlined file: juce_MidiFile.cpp *********/
  21012. BEGIN_JUCE_NAMESPACE
  21013. struct TempoInfo
  21014. {
  21015. double bpm, timestamp;
  21016. };
  21017. struct TimeSigInfo
  21018. {
  21019. int numerator, denominator;
  21020. double timestamp;
  21021. };
  21022. MidiFile::MidiFile() throw()
  21023. : numTracks (0),
  21024. timeFormat ((short)(unsigned short)0xe728)
  21025. {
  21026. }
  21027. MidiFile::~MidiFile() throw()
  21028. {
  21029. clear();
  21030. }
  21031. void MidiFile::clear() throw()
  21032. {
  21033. while (numTracks > 0)
  21034. delete tracks [--numTracks];
  21035. }
  21036. int MidiFile::getNumTracks() const throw()
  21037. {
  21038. return numTracks;
  21039. }
  21040. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21041. {
  21042. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  21043. }
  21044. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  21045. {
  21046. jassert (numTracks < numElementsInArray (tracks));
  21047. if (numTracks < numElementsInArray (tracks))
  21048. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  21049. }
  21050. short MidiFile::getTimeFormat() const throw()
  21051. {
  21052. return timeFormat;
  21053. }
  21054. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21055. {
  21056. timeFormat = (short)ticks;
  21057. }
  21058. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21059. const int subframeResolution) throw()
  21060. {
  21061. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21062. }
  21063. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21064. {
  21065. for (int i = numTracks; --i >= 0;)
  21066. {
  21067. const int numEvents = tracks[i]->getNumEvents();
  21068. for (int j = 0; j < numEvents; ++j)
  21069. {
  21070. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  21071. if (m.isTempoMetaEvent())
  21072. tempoChangeEvents.addEvent (m);
  21073. }
  21074. }
  21075. }
  21076. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21077. {
  21078. for (int i = numTracks; --i >= 0;)
  21079. {
  21080. const int numEvents = tracks[i]->getNumEvents();
  21081. for (int j = 0; j < numEvents; ++j)
  21082. {
  21083. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  21084. if (m.isTimeSignatureMetaEvent())
  21085. timeSigEvents.addEvent (m);
  21086. }
  21087. }
  21088. }
  21089. double MidiFile::getLastTimestamp() const
  21090. {
  21091. double t = 0.0;
  21092. for (int i = numTracks; --i >= 0;)
  21093. t = jmax (t, tracks[i]->getEndTime());
  21094. return t;
  21095. }
  21096. static bool parseMidiHeader (const char* &data,
  21097. short& timeFormat,
  21098. short& fileType,
  21099. short& numberOfTracks)
  21100. {
  21101. unsigned int ch = (int) bigEndianInt (data);
  21102. data += 4;
  21103. if (ch != bigEndianInt ("MThd"))
  21104. {
  21105. bool ok = false;
  21106. if (ch == bigEndianInt ("RIFF"))
  21107. {
  21108. for (int i = 0; i < 8; ++i)
  21109. {
  21110. ch = bigEndianInt (data);
  21111. data += 4;
  21112. if (ch == bigEndianInt ("MThd"))
  21113. {
  21114. ok = true;
  21115. break;
  21116. }
  21117. }
  21118. }
  21119. if (! ok)
  21120. return false;
  21121. }
  21122. unsigned int bytesRemaining = bigEndianInt (data);
  21123. data += 4;
  21124. fileType = (short)bigEndianShort (data);
  21125. data += 2;
  21126. numberOfTracks = (short)bigEndianShort (data);
  21127. data += 2;
  21128. timeFormat = (short)bigEndianShort (data);
  21129. data += 2;
  21130. bytesRemaining -= 6;
  21131. data += bytesRemaining;
  21132. return true;
  21133. }
  21134. bool MidiFile::readFrom (InputStream& sourceStream)
  21135. {
  21136. clear();
  21137. MemoryBlock data;
  21138. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21139. // (put a sanity-check on the file size, as midi files are generally small)
  21140. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21141. {
  21142. int size = data.getSize();
  21143. const char* d = (char*) data.getData();
  21144. short fileType, expectedTracks;
  21145. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21146. {
  21147. size -= (int) (d - (char*) data.getData());
  21148. int track = 0;
  21149. while (size > 0 && track < expectedTracks)
  21150. {
  21151. const int chunkType = (int)bigEndianInt (d);
  21152. d += 4;
  21153. const int chunkSize = (int)bigEndianInt (d);
  21154. d += 4;
  21155. if (chunkSize <= 0)
  21156. break;
  21157. if (size < 0)
  21158. return false;
  21159. if (chunkType == (int)bigEndianInt ("MTrk"))
  21160. {
  21161. readNextTrack (d, chunkSize);
  21162. }
  21163. size -= chunkSize + 8;
  21164. d += chunkSize;
  21165. ++track;
  21166. }
  21167. return true;
  21168. }
  21169. }
  21170. return false;
  21171. }
  21172. // a comparator that puts all the note-offs before note-ons that have the same time
  21173. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21174. const MidiMessageSequence::MidiEventHolder* const second) throw()
  21175. {
  21176. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21177. if (diff == 0)
  21178. {
  21179. if (first->message.isNoteOff() && second->message.isNoteOn())
  21180. return -1;
  21181. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21182. return 1;
  21183. else
  21184. return 0;
  21185. }
  21186. else
  21187. {
  21188. return (diff > 0) ? 1 : -1;
  21189. }
  21190. }
  21191. void MidiFile::readNextTrack (const char* data, int size)
  21192. {
  21193. double time = 0;
  21194. char lastStatusByte = 0;
  21195. MidiMessageSequence result;
  21196. while (size > 0)
  21197. {
  21198. int bytesUsed;
  21199. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  21200. data += bytesUsed;
  21201. size -= bytesUsed;
  21202. time += delay;
  21203. int messSize = 0;
  21204. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  21205. if (messSize <= 0)
  21206. break;
  21207. size -= messSize;
  21208. data += messSize;
  21209. result.addEvent (mm);
  21210. const char firstByte = *(mm.getRawData());
  21211. if ((firstByte & 0xf0) != 0xf0)
  21212. lastStatusByte = firstByte;
  21213. }
  21214. // use a sort that puts all the note-offs before note-ons that have the same time
  21215. result.list.sort (*this, true);
  21216. result.updateMatchedPairs();
  21217. addTrack (result);
  21218. }
  21219. static double convertTicksToSeconds (const double time,
  21220. const MidiMessageSequence& tempoEvents,
  21221. const int timeFormat)
  21222. {
  21223. if (timeFormat > 0)
  21224. {
  21225. int numer = 4, denom = 4;
  21226. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21227. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21228. double secsPerTick = 0.5 * tickLen;
  21229. const int numEvents = tempoEvents.getNumEvents();
  21230. for (int i = 0; i < numEvents; ++i)
  21231. {
  21232. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21233. if (time <= m.getTimeStamp())
  21234. break;
  21235. if (timeFormat > 0)
  21236. {
  21237. correctedTempoTime = correctedTempoTime
  21238. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21239. }
  21240. else
  21241. {
  21242. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21243. }
  21244. tempoTime = m.getTimeStamp();
  21245. if (m.isTempoMetaEvent())
  21246. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21247. else if (m.isTimeSignatureMetaEvent())
  21248. m.getTimeSignatureInfo (numer, denom);
  21249. while (i + 1 < numEvents)
  21250. {
  21251. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21252. if (m2.getTimeStamp() == tempoTime)
  21253. {
  21254. ++i;
  21255. if (m2.isTempoMetaEvent())
  21256. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21257. else if (m2.isTimeSignatureMetaEvent())
  21258. m2.getTimeSignatureInfo (numer, denom);
  21259. }
  21260. else
  21261. {
  21262. break;
  21263. }
  21264. }
  21265. }
  21266. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21267. }
  21268. else
  21269. {
  21270. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21271. }
  21272. }
  21273. void MidiFile::convertTimestampTicksToSeconds()
  21274. {
  21275. MidiMessageSequence tempoEvents;
  21276. findAllTempoEvents (tempoEvents);
  21277. findAllTimeSigEvents (tempoEvents);
  21278. for (int i = 0; i < numTracks; ++i)
  21279. {
  21280. MidiMessageSequence& ms = *tracks[i];
  21281. for (int j = ms.getNumEvents(); --j >= 0;)
  21282. {
  21283. MidiMessage& m = ms.getEventPointer(j)->message;
  21284. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  21285. tempoEvents,
  21286. timeFormat));
  21287. }
  21288. }
  21289. }
  21290. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21291. {
  21292. unsigned int buffer = v & 0x7F;
  21293. while ((v >>= 7) != 0)
  21294. {
  21295. buffer <<= 8;
  21296. buffer |= ((v & 0x7F) | 0x80);
  21297. }
  21298. for (;;)
  21299. {
  21300. out.writeByte ((char) buffer);
  21301. if (buffer & 0x80)
  21302. buffer >>= 8;
  21303. else
  21304. break;
  21305. }
  21306. }
  21307. bool MidiFile::writeTo (OutputStream& out)
  21308. {
  21309. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  21310. out.writeIntBigEndian (6);
  21311. out.writeShortBigEndian (1); // type
  21312. out.writeShortBigEndian (numTracks);
  21313. out.writeShortBigEndian (timeFormat);
  21314. for (int i = 0; i < numTracks; ++i)
  21315. writeTrack (out, i);
  21316. out.flush();
  21317. return true;
  21318. }
  21319. void MidiFile::writeTrack (OutputStream& mainOut,
  21320. const int trackNum)
  21321. {
  21322. MemoryOutputStream out;
  21323. const MidiMessageSequence& ms = *tracks[trackNum];
  21324. int lastTick = 0;
  21325. char lastStatusByte = 0;
  21326. for (int i = 0; i < ms.getNumEvents(); ++i)
  21327. {
  21328. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21329. const int tick = roundDoubleToInt (mm.getTimeStamp());
  21330. const int delta = jmax (0, tick - lastTick);
  21331. writeVariableLengthInt (out, delta);
  21332. lastTick = tick;
  21333. const char statusByte = *(mm.getRawData());
  21334. if ((statusByte == lastStatusByte)
  21335. && ((statusByte & 0xf0) != 0xf0)
  21336. && i > 0
  21337. && mm.getRawDataSize() > 1)
  21338. {
  21339. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21340. }
  21341. else
  21342. {
  21343. out.write (mm.getRawData(), mm.getRawDataSize());
  21344. }
  21345. lastStatusByte = statusByte;
  21346. }
  21347. out.writeByte (0);
  21348. const MidiMessage m (MidiMessage::endOfTrack());
  21349. out.write (m.getRawData(),
  21350. m.getRawDataSize());
  21351. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  21352. mainOut.writeIntBigEndian (out.getDataSize());
  21353. mainOut.write (out.getData(), out.getDataSize());
  21354. }
  21355. END_JUCE_NAMESPACE
  21356. /********* End of inlined file: juce_MidiFile.cpp *********/
  21357. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  21358. BEGIN_JUCE_NAMESPACE
  21359. MidiKeyboardState::MidiKeyboardState()
  21360. : listeners (2)
  21361. {
  21362. zeromem (noteStates, sizeof (noteStates));
  21363. }
  21364. MidiKeyboardState::~MidiKeyboardState()
  21365. {
  21366. }
  21367. void MidiKeyboardState::reset()
  21368. {
  21369. const ScopedLock sl (lock);
  21370. zeromem (noteStates, sizeof (noteStates));
  21371. eventsToAdd.clear();
  21372. }
  21373. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21374. {
  21375. jassert (midiChannel >= 0 && midiChannel <= 16);
  21376. return ((unsigned int) n) < 128
  21377. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21378. }
  21379. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21380. {
  21381. return ((unsigned int) n) < 128
  21382. && (noteStates[n] & midiChannelMask) != 0;
  21383. }
  21384. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21385. {
  21386. jassert (midiChannel >= 0 && midiChannel <= 16);
  21387. jassert (((unsigned int) midiNoteNumber) < 128);
  21388. const ScopedLock sl (lock);
  21389. if (((unsigned int) midiNoteNumber) < 128)
  21390. {
  21391. const int timeNow = (int) Time::getMillisecondCounter();
  21392. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21393. eventsToAdd.clear (0, timeNow - 500);
  21394. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21395. }
  21396. }
  21397. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21398. {
  21399. if (((unsigned int) midiNoteNumber) < 128)
  21400. {
  21401. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21402. for (int i = listeners.size(); --i >= 0;)
  21403. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21404. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21405. }
  21406. }
  21407. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21408. {
  21409. const ScopedLock sl (lock);
  21410. if (isNoteOn (midiChannel, midiNoteNumber))
  21411. {
  21412. const int timeNow = (int) Time::getMillisecondCounter();
  21413. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21414. eventsToAdd.clear (0, timeNow - 500);
  21415. noteOffInternal (midiChannel, midiNoteNumber);
  21416. }
  21417. }
  21418. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21419. {
  21420. if (isNoteOn (midiChannel, midiNoteNumber))
  21421. {
  21422. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21423. for (int i = listeners.size(); --i >= 0;)
  21424. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21425. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  21426. }
  21427. }
  21428. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21429. {
  21430. const ScopedLock sl (lock);
  21431. if (midiChannel <= 0)
  21432. {
  21433. for (int i = 1; i <= 16; ++i)
  21434. allNotesOff (i);
  21435. }
  21436. else
  21437. {
  21438. for (int i = 0; i < 128; ++i)
  21439. noteOff (midiChannel, i);
  21440. }
  21441. }
  21442. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21443. {
  21444. if (message.isNoteOn())
  21445. {
  21446. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21447. }
  21448. else if (message.isNoteOff())
  21449. {
  21450. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21451. }
  21452. else if (message.isAllNotesOff())
  21453. {
  21454. for (int i = 0; i < 128; ++i)
  21455. noteOffInternal (message.getChannel(), i);
  21456. }
  21457. }
  21458. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21459. const int startSample,
  21460. const int numSamples,
  21461. const bool injectIndirectEvents)
  21462. {
  21463. MidiBuffer::Iterator i (buffer);
  21464. MidiMessage message (0xf4, 0.0);
  21465. int time;
  21466. const ScopedLock sl (lock);
  21467. while (i.getNextEvent (message, time))
  21468. processNextMidiEvent (message);
  21469. if (injectIndirectEvents)
  21470. {
  21471. MidiBuffer::Iterator i2 (eventsToAdd);
  21472. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  21473. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  21474. while (i2.getNextEvent (message, time))
  21475. {
  21476. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  21477. buffer.addEvent (message, startSample + pos);
  21478. }
  21479. }
  21480. eventsToAdd.clear();
  21481. }
  21482. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  21483. {
  21484. const ScopedLock sl (lock);
  21485. listeners.addIfNotAlreadyThere (listener);
  21486. }
  21487. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  21488. {
  21489. const ScopedLock sl (lock);
  21490. listeners.removeValue (listener);
  21491. }
  21492. END_JUCE_NAMESPACE
  21493. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  21494. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  21495. BEGIN_JUCE_NAMESPACE
  21496. int MidiMessage::readVariableLengthVal (const uint8* data,
  21497. int& numBytesUsed) throw()
  21498. {
  21499. numBytesUsed = 0;
  21500. int v = 0;
  21501. int i;
  21502. do
  21503. {
  21504. i = (int) *data++;
  21505. if (++numBytesUsed > 6)
  21506. break;
  21507. v = (v << 7) + (i & 0x7f);
  21508. } while (i & 0x80);
  21509. return v;
  21510. }
  21511. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  21512. {
  21513. // this method only works for valid starting bytes of a short midi message
  21514. jassert (firstByte >= 0x80
  21515. && firstByte != 0xf0
  21516. && firstByte != 0xf7);
  21517. static const char messageLengths[] =
  21518. {
  21519. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21520. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21521. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21522. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21523. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21524. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21525. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21526. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  21527. };
  21528. return messageLengths [firstByte & 0x7f];
  21529. }
  21530. MidiMessage::MidiMessage (const uint8* const d,
  21531. const int dataSize,
  21532. const double t) throw()
  21533. : timeStamp (t),
  21534. message (0),
  21535. size (dataSize)
  21536. {
  21537. jassert (dataSize > 0);
  21538. if (dataSize <= 4)
  21539. data = (uint8*) &message;
  21540. else
  21541. data = (uint8*) juce_malloc (dataSize);
  21542. memcpy (data, d, dataSize);
  21543. // check that the length matches the data..
  21544. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  21545. }
  21546. MidiMessage::MidiMessage (const int byte1,
  21547. const double t) throw()
  21548. : timeStamp (t),
  21549. data ((uint8*) &message),
  21550. size (1)
  21551. {
  21552. data[0] = (uint8) byte1;
  21553. // check that the length matches the data..
  21554. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  21555. }
  21556. MidiMessage::MidiMessage (const int byte1,
  21557. const int byte2,
  21558. const double t) throw()
  21559. : timeStamp (t),
  21560. data ((uint8*) &message),
  21561. size (2)
  21562. {
  21563. data[0] = (uint8) byte1;
  21564. data[1] = (uint8) byte2;
  21565. // check that the length matches the data..
  21566. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  21567. }
  21568. MidiMessage::MidiMessage (const int byte1,
  21569. const int byte2,
  21570. const int byte3,
  21571. const double t) throw()
  21572. : timeStamp (t),
  21573. data ((uint8*) &message),
  21574. size (3)
  21575. {
  21576. data[0] = (uint8) byte1;
  21577. data[1] = (uint8) byte2;
  21578. data[2] = (uint8) byte3;
  21579. // check that the length matches the data..
  21580. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  21581. }
  21582. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  21583. : timeStamp (other.timeStamp),
  21584. message (other.message),
  21585. size (other.size)
  21586. {
  21587. if (other.data != (uint8*) &other.message)
  21588. {
  21589. data = (uint8*) juce_malloc (size);
  21590. memcpy (data, other.data, size);
  21591. }
  21592. else
  21593. {
  21594. data = (uint8*) &message;
  21595. }
  21596. }
  21597. MidiMessage::MidiMessage (const MidiMessage& other,
  21598. const double newTimeStamp) throw()
  21599. : timeStamp (newTimeStamp),
  21600. message (other.message),
  21601. size (other.size)
  21602. {
  21603. if (other.data != (uint8*) &other.message)
  21604. {
  21605. data = (uint8*) juce_malloc (size);
  21606. memcpy (data, other.data, size);
  21607. }
  21608. else
  21609. {
  21610. data = (uint8*) &message;
  21611. }
  21612. }
  21613. MidiMessage::MidiMessage (const uint8* src,
  21614. int sz,
  21615. int& numBytesUsed,
  21616. const uint8 lastStatusByte,
  21617. double t) throw()
  21618. : timeStamp (t),
  21619. data ((uint8*) &message),
  21620. message (0)
  21621. {
  21622. unsigned int byte = (unsigned int) *src;
  21623. if (byte < 0x80)
  21624. {
  21625. byte = (unsigned int) (uint8) lastStatusByte;
  21626. numBytesUsed = -1;
  21627. }
  21628. else
  21629. {
  21630. numBytesUsed = 0;
  21631. --sz;
  21632. ++src;
  21633. }
  21634. if (byte >= 0x80)
  21635. {
  21636. if (byte == 0xf0)
  21637. {
  21638. const uint8* d = (const uint8*) src;
  21639. while (d < src + sz)
  21640. {
  21641. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  21642. {
  21643. if (*d == 0xf7) // include an 0xf7 if we hit one
  21644. ++d;
  21645. break;
  21646. }
  21647. ++d;
  21648. }
  21649. size = 1 + (int) (d - src);
  21650. data = (uint8*) juce_malloc (size);
  21651. *data = (uint8) byte;
  21652. memcpy (data + 1, src, size - 1);
  21653. }
  21654. else if (byte == 0xff)
  21655. {
  21656. int n;
  21657. const int bytesLeft = readVariableLengthVal (src + 1, n);
  21658. size = jmin (sz + 1, n + 2 + bytesLeft);
  21659. data = (uint8*) juce_malloc (size);
  21660. *data = (uint8) byte;
  21661. memcpy (data + 1, src, size - 1);
  21662. }
  21663. else
  21664. {
  21665. size = getMessageLengthFromFirstByte ((uint8) byte);
  21666. *data = (uint8) byte;
  21667. if (size > 1)
  21668. {
  21669. data[1] = src[0];
  21670. if (size > 2)
  21671. data[2] = src[1];
  21672. }
  21673. }
  21674. numBytesUsed += size;
  21675. }
  21676. else
  21677. {
  21678. message = 0;
  21679. size = 0;
  21680. }
  21681. }
  21682. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  21683. {
  21684. if (this == &other)
  21685. return *this;
  21686. timeStamp = other.timeStamp;
  21687. size = other.size;
  21688. message = other.message;
  21689. if (data != (uint8*) &message)
  21690. juce_free (data);
  21691. if (other.data != (uint8*) &other.message)
  21692. {
  21693. data = (uint8*) juce_malloc (size);
  21694. memcpy (data, other.data, size);
  21695. }
  21696. else
  21697. {
  21698. data = (uint8*) &message;
  21699. }
  21700. return *this;
  21701. }
  21702. MidiMessage::~MidiMessage() throw()
  21703. {
  21704. if (data != (uint8*) &message)
  21705. juce_free (data);
  21706. }
  21707. int MidiMessage::getChannel() const throw()
  21708. {
  21709. if ((data[0] & 0xf0) != 0xf0)
  21710. return (data[0] & 0xf) + 1;
  21711. else
  21712. return 0;
  21713. }
  21714. bool MidiMessage::isForChannel (const int channel) const throw()
  21715. {
  21716. return ((data[0] & 0xf) == channel - 1)
  21717. && ((data[0] & 0xf0) != 0xf0);
  21718. }
  21719. void MidiMessage::setChannel (const int channel) throw()
  21720. {
  21721. if ((data[0] & 0xf0) != (uint8) 0xf0)
  21722. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  21723. | (uint8)(channel - 1));
  21724. }
  21725. bool MidiMessage::isNoteOn() const throw()
  21726. {
  21727. return ((data[0] & 0xf0) == 0x90)
  21728. && (data[2] != 0);
  21729. }
  21730. bool MidiMessage::isNoteOff() const throw()
  21731. {
  21732. return ((data[0] & 0xf0) == 0x80)
  21733. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  21734. }
  21735. bool MidiMessage::isNoteOnOrOff() const throw()
  21736. {
  21737. const int d = data[0] & 0xf0;
  21738. return (d == 0x90) || (d == 0x80);
  21739. }
  21740. int MidiMessage::getNoteNumber() const throw()
  21741. {
  21742. return data[1];
  21743. }
  21744. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  21745. {
  21746. if (isNoteOnOrOff())
  21747. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  21748. }
  21749. uint8 MidiMessage::getVelocity() const throw()
  21750. {
  21751. if (isNoteOnOrOff())
  21752. return data[2];
  21753. else
  21754. return 0;
  21755. }
  21756. float MidiMessage::getFloatVelocity() const throw()
  21757. {
  21758. return getVelocity() * (1.0f / 127.0f);
  21759. }
  21760. void MidiMessage::setVelocity (const float newVelocity) throw()
  21761. {
  21762. if (isNoteOnOrOff())
  21763. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  21764. }
  21765. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  21766. {
  21767. if (isNoteOnOrOff())
  21768. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  21769. }
  21770. bool MidiMessage::isAftertouch() const throw()
  21771. {
  21772. return (data[0] & 0xf0) == 0xa0;
  21773. }
  21774. int MidiMessage::getAfterTouchValue() const throw()
  21775. {
  21776. return data[2];
  21777. }
  21778. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  21779. const int noteNum,
  21780. const int aftertouchValue) throw()
  21781. {
  21782. jassert (channel > 0 && channel <= 16);
  21783. jassert (((unsigned int) noteNum) <= 127);
  21784. jassert (((unsigned int) aftertouchValue) <= 127);
  21785. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  21786. noteNum & 0x7f,
  21787. aftertouchValue & 0x7f);
  21788. }
  21789. bool MidiMessage::isChannelPressure() const throw()
  21790. {
  21791. return (data[0] & 0xf0) == 0xd0;
  21792. }
  21793. int MidiMessage::getChannelPressureValue() const throw()
  21794. {
  21795. jassert (isChannelPressure());
  21796. return data[1];
  21797. }
  21798. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  21799. const int pressure) throw()
  21800. {
  21801. jassert (channel > 0 && channel <= 16);
  21802. jassert (((unsigned int) pressure) <= 127);
  21803. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  21804. pressure & 0x7f);
  21805. }
  21806. bool MidiMessage::isProgramChange() const throw()
  21807. {
  21808. return (data[0] & 0xf0) == 0xc0;
  21809. }
  21810. int MidiMessage::getProgramChangeNumber() const throw()
  21811. {
  21812. return data[1];
  21813. }
  21814. const MidiMessage MidiMessage::programChange (const int channel,
  21815. const int programNumber) throw()
  21816. {
  21817. jassert (channel > 0 && channel <= 16);
  21818. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  21819. programNumber & 0x7f);
  21820. }
  21821. bool MidiMessage::isPitchWheel() const throw()
  21822. {
  21823. return (data[0] & 0xf0) == 0xe0;
  21824. }
  21825. int MidiMessage::getPitchWheelValue() const throw()
  21826. {
  21827. return data[1] | (data[2] << 7);
  21828. }
  21829. const MidiMessage MidiMessage::pitchWheel (const int channel,
  21830. const int position) throw()
  21831. {
  21832. jassert (channel > 0 && channel <= 16);
  21833. jassert (((unsigned int) position) <= 0x3fff);
  21834. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  21835. position & 127,
  21836. (position >> 7) & 127);
  21837. }
  21838. bool MidiMessage::isController() const throw()
  21839. {
  21840. return (data[0] & 0xf0) == 0xb0;
  21841. }
  21842. int MidiMessage::getControllerNumber() const throw()
  21843. {
  21844. jassert (isController());
  21845. return data[1];
  21846. }
  21847. int MidiMessage::getControllerValue() const throw()
  21848. {
  21849. jassert (isController());
  21850. return data[2];
  21851. }
  21852. const MidiMessage MidiMessage::controllerEvent (const int channel,
  21853. const int controllerType,
  21854. const int value) throw()
  21855. {
  21856. // the channel must be between 1 and 16 inclusive
  21857. jassert (channel > 0 && channel <= 16);
  21858. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  21859. controllerType & 127,
  21860. value & 127);
  21861. }
  21862. const MidiMessage MidiMessage::noteOn (const int channel,
  21863. const int noteNumber,
  21864. const float velocity) throw()
  21865. {
  21866. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  21867. }
  21868. const MidiMessage MidiMessage::noteOn (const int channel,
  21869. const int noteNumber,
  21870. const uint8 velocity) throw()
  21871. {
  21872. jassert (channel > 0 && channel <= 16);
  21873. jassert (((unsigned int) noteNumber) <= 127);
  21874. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  21875. noteNumber & 127,
  21876. jlimit (0, 127, roundFloatToInt (velocity)));
  21877. }
  21878. const MidiMessage MidiMessage::noteOff (const int channel,
  21879. const int noteNumber) throw()
  21880. {
  21881. jassert (channel > 0 && channel <= 16);
  21882. jassert (((unsigned int) noteNumber) <= 127);
  21883. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  21884. }
  21885. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  21886. {
  21887. jassert (channel > 0 && channel <= 16);
  21888. return controllerEvent (channel, 123, 0);
  21889. }
  21890. bool MidiMessage::isAllNotesOff() const throw()
  21891. {
  21892. return (data[0] & 0xf0) == 0xb0
  21893. && data[1] == 123;
  21894. }
  21895. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  21896. {
  21897. return controllerEvent (channel, 120, 0);
  21898. }
  21899. bool MidiMessage::isAllSoundOff() const throw()
  21900. {
  21901. return (data[0] & 0xf0) == 0xb0
  21902. && data[1] == 120;
  21903. }
  21904. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  21905. {
  21906. return controllerEvent (channel, 121, 0);
  21907. }
  21908. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  21909. {
  21910. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  21911. uint8 buf[8];
  21912. buf[0] = 0xf0;
  21913. buf[1] = 0x7f;
  21914. buf[2] = 0x7f;
  21915. buf[3] = 0x04;
  21916. buf[4] = 0x01;
  21917. buf[5] = (uint8) (vol & 0x7f);
  21918. buf[6] = (uint8) (vol >> 7);
  21919. buf[7] = 0xf7;
  21920. return MidiMessage (buf, 8);
  21921. }
  21922. bool MidiMessage::isSysEx() const throw()
  21923. {
  21924. return *data == 0xf0;
  21925. }
  21926. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  21927. const int dataSize) throw()
  21928. {
  21929. MemoryBlock mm (dataSize + 2);
  21930. uint8* const m = (uint8*) mm.getData();
  21931. m[0] = 0xf0;
  21932. memcpy (m + 1, sysexData, dataSize);
  21933. m[dataSize + 1] = 0xf7;
  21934. return MidiMessage (m, dataSize + 2);
  21935. }
  21936. const uint8* MidiMessage::getSysExData() const throw()
  21937. {
  21938. return (isSysEx()) ? getRawData() + 1
  21939. : 0;
  21940. }
  21941. int MidiMessage::getSysExDataSize() const throw()
  21942. {
  21943. return (isSysEx()) ? size - 2
  21944. : 0;
  21945. }
  21946. bool MidiMessage::isMetaEvent() const throw()
  21947. {
  21948. return *data == 0xff;
  21949. }
  21950. bool MidiMessage::isActiveSense() const throw()
  21951. {
  21952. return *data == 0xfe;
  21953. }
  21954. int MidiMessage::getMetaEventType() const throw()
  21955. {
  21956. if (*data != 0xff)
  21957. return -1;
  21958. else
  21959. return data[1];
  21960. }
  21961. int MidiMessage::getMetaEventLength() const throw()
  21962. {
  21963. if (*data == 0xff)
  21964. {
  21965. int n;
  21966. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  21967. }
  21968. return 0;
  21969. }
  21970. const uint8* MidiMessage::getMetaEventData() const throw()
  21971. {
  21972. int n;
  21973. const uint8* d = data + 2;
  21974. readVariableLengthVal (d, n);
  21975. return d + n;
  21976. }
  21977. bool MidiMessage::isTrackMetaEvent() const throw()
  21978. {
  21979. return getMetaEventType() == 0;
  21980. }
  21981. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  21982. {
  21983. return getMetaEventType() == 47;
  21984. }
  21985. bool MidiMessage::isTextMetaEvent() const throw()
  21986. {
  21987. const int t = getMetaEventType();
  21988. return t > 0 && t < 16;
  21989. }
  21990. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  21991. {
  21992. return String ((const char*) getMetaEventData(),
  21993. getMetaEventLength());
  21994. }
  21995. bool MidiMessage::isTrackNameEvent() const throw()
  21996. {
  21997. return (data[1] == 3)
  21998. && (*data == 0xff);
  21999. }
  22000. bool MidiMessage::isTempoMetaEvent() const throw()
  22001. {
  22002. return (data[1] == 81)
  22003. && (*data == 0xff);
  22004. }
  22005. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22006. {
  22007. return (data[1] == 0x20)
  22008. && (*data == 0xff)
  22009. && (data[2] == 1);
  22010. }
  22011. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22012. {
  22013. return data[3] + 1;
  22014. }
  22015. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22016. {
  22017. if (! isTempoMetaEvent())
  22018. return 0.0;
  22019. const uint8* const d = getMetaEventData();
  22020. return (((unsigned int) d[0] << 16)
  22021. | ((unsigned int) d[1] << 8)
  22022. | d[2])
  22023. / 1000000.0;
  22024. }
  22025. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22026. {
  22027. if (timeFormat > 0)
  22028. {
  22029. if (! isTempoMetaEvent())
  22030. return 0.5 / timeFormat;
  22031. return getTempoSecondsPerQuarterNote() / timeFormat;
  22032. }
  22033. else
  22034. {
  22035. const int frameCode = (-timeFormat) >> 8;
  22036. double framesPerSecond;
  22037. switch (frameCode)
  22038. {
  22039. case 24: framesPerSecond = 24.0; break;
  22040. case 25: framesPerSecond = 25.0; break;
  22041. case 29: framesPerSecond = 29.97; break;
  22042. case 30: framesPerSecond = 30.0; break;
  22043. default: framesPerSecond = 30.0; break;
  22044. }
  22045. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22046. }
  22047. }
  22048. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22049. {
  22050. uint8 d[8];
  22051. d[0] = 0xff;
  22052. d[1] = 81;
  22053. d[2] = 3;
  22054. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22055. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22056. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22057. return MidiMessage (d, 6, 0.0);
  22058. }
  22059. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22060. {
  22061. return (data[1] == 0x58)
  22062. && (*data == (uint8) 0xff);
  22063. }
  22064. void MidiMessage::getTimeSignatureInfo (int& numerator,
  22065. int& denominator) const throw()
  22066. {
  22067. if (isTimeSignatureMetaEvent())
  22068. {
  22069. const uint8* const d = getMetaEventData();
  22070. numerator = d[0];
  22071. denominator = 1 << d[1];
  22072. }
  22073. else
  22074. {
  22075. numerator = 4;
  22076. denominator = 4;
  22077. }
  22078. }
  22079. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  22080. const int denominator) throw()
  22081. {
  22082. uint8 d[8];
  22083. d[0] = 0xff;
  22084. d[1] = 0x58;
  22085. d[2] = 0x04;
  22086. d[3] = (uint8) numerator;
  22087. int n = 1;
  22088. int powerOfTwo = 0;
  22089. while (n < denominator)
  22090. {
  22091. n <<= 1;
  22092. ++powerOfTwo;
  22093. }
  22094. d[4] = (uint8) powerOfTwo;
  22095. d[5] = 0x01;
  22096. d[6] = 96;
  22097. return MidiMessage (d, 7, 0.0);
  22098. }
  22099. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22100. {
  22101. uint8 d[8];
  22102. d[0] = 0xff;
  22103. d[1] = 0x20;
  22104. d[2] = 0x01;
  22105. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22106. return MidiMessage (d, 4, 0.0);
  22107. }
  22108. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22109. {
  22110. return getMetaEventType() == 89;
  22111. }
  22112. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22113. {
  22114. return (int) *getMetaEventData();
  22115. }
  22116. const MidiMessage MidiMessage::endOfTrack() throw()
  22117. {
  22118. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22119. }
  22120. bool MidiMessage::isSongPositionPointer() const throw()
  22121. {
  22122. return *data == 0xf2;
  22123. }
  22124. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22125. {
  22126. return data[1] | (data[2] << 7);
  22127. }
  22128. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22129. {
  22130. return MidiMessage (0xf2,
  22131. positionInMidiBeats & 127,
  22132. (positionInMidiBeats >> 7) & 127);
  22133. }
  22134. bool MidiMessage::isMidiStart() const throw()
  22135. {
  22136. return *data == 0xfa;
  22137. }
  22138. const MidiMessage MidiMessage::midiStart() throw()
  22139. {
  22140. return MidiMessage (0xfa);
  22141. }
  22142. bool MidiMessage::isMidiContinue() const throw()
  22143. {
  22144. return *data == 0xfb;
  22145. }
  22146. const MidiMessage MidiMessage::midiContinue() throw()
  22147. {
  22148. return MidiMessage (0xfb);
  22149. }
  22150. bool MidiMessage::isMidiStop() const throw()
  22151. {
  22152. return *data == 0xfc;
  22153. }
  22154. const MidiMessage MidiMessage::midiStop() throw()
  22155. {
  22156. return MidiMessage (0xfc);
  22157. }
  22158. bool MidiMessage::isMidiClock() const throw()
  22159. {
  22160. return *data == 0xf8;
  22161. }
  22162. const MidiMessage MidiMessage::midiClock() throw()
  22163. {
  22164. return MidiMessage (0xf8);
  22165. }
  22166. bool MidiMessage::isQuarterFrame() const throw()
  22167. {
  22168. return *data == 0xf1;
  22169. }
  22170. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22171. {
  22172. return ((int) data[1]) >> 4;
  22173. }
  22174. int MidiMessage::getQuarterFrameValue() const throw()
  22175. {
  22176. return ((int) data[1]) & 0x0f;
  22177. }
  22178. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22179. const int value) throw()
  22180. {
  22181. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22182. }
  22183. bool MidiMessage::isFullFrame() const throw()
  22184. {
  22185. return data[0] == 0xf0
  22186. && data[1] == 0x7f
  22187. && size >= 10
  22188. && data[3] == 0x01
  22189. && data[4] == 0x01;
  22190. }
  22191. void MidiMessage::getFullFrameParameters (int& hours,
  22192. int& minutes,
  22193. int& seconds,
  22194. int& frames,
  22195. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22196. {
  22197. jassert (isFullFrame());
  22198. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22199. hours = data[5] & 0x1f;
  22200. minutes = data[6];
  22201. seconds = data[7];
  22202. frames = data[8];
  22203. }
  22204. const MidiMessage MidiMessage::fullFrame (const int hours,
  22205. const int minutes,
  22206. const int seconds,
  22207. const int frames,
  22208. MidiMessage::SmpteTimecodeType timecodeType)
  22209. {
  22210. uint8 d[10];
  22211. d[0] = 0xf0;
  22212. d[1] = 0x7f;
  22213. d[2] = 0x7f;
  22214. d[3] = 0x01;
  22215. d[4] = 0x01;
  22216. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22217. d[6] = (uint8) minutes;
  22218. d[7] = (uint8) seconds;
  22219. d[8] = (uint8) frames;
  22220. d[9] = 0xf7;
  22221. return MidiMessage (d, 10, 0.0);
  22222. }
  22223. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22224. {
  22225. return data[0] == 0xf0
  22226. && data[1] == 0x7f
  22227. && data[3] == 0x06
  22228. && size > 5;
  22229. }
  22230. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22231. {
  22232. jassert (isMidiMachineControlMessage());
  22233. return (MidiMachineControlCommand) data[4];
  22234. }
  22235. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22236. {
  22237. uint8 d[6];
  22238. d[0] = 0xf0;
  22239. d[1] = 0x7f;
  22240. d[2] = 0x00;
  22241. d[3] = 0x06;
  22242. d[4] = (uint8) command;
  22243. d[5] = 0xf7;
  22244. return MidiMessage (d, 6, 0.0);
  22245. }
  22246. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22247. int& minutes,
  22248. int& seconds,
  22249. int& frames) const throw()
  22250. {
  22251. if (size >= 12
  22252. && data[0] == 0xf0
  22253. && data[1] == 0x7f
  22254. && data[3] == 0x06
  22255. && data[4] == 0x44
  22256. && data[5] == 0x06
  22257. && data[6] == 0x01)
  22258. {
  22259. hours = data[7] % 24; // (that some machines send out hours > 24)
  22260. minutes = data[8];
  22261. seconds = data[9];
  22262. frames = data[10];
  22263. return true;
  22264. }
  22265. return false;
  22266. }
  22267. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22268. int minutes,
  22269. int seconds,
  22270. int frames)
  22271. {
  22272. uint8 d[12];
  22273. d[0] = 0xf0;
  22274. d[1] = 0x7f;
  22275. d[2] = 0x00;
  22276. d[3] = 0x06;
  22277. d[4] = 0x44;
  22278. d[5] = 0x06;
  22279. d[6] = 0x01;
  22280. d[7] = (uint8) hours;
  22281. d[8] = (uint8) minutes;
  22282. d[9] = (uint8) seconds;
  22283. d[10] = (uint8) frames;
  22284. d[11] = 0xf7;
  22285. return MidiMessage (d, 12, 0.0);
  22286. }
  22287. const String MidiMessage::getMidiNoteName (int note,
  22288. bool useSharps,
  22289. bool includeOctaveNumber,
  22290. int octaveNumForMiddleC) throw()
  22291. {
  22292. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22293. "F", "F#", "G", "G#", "A",
  22294. "A#", "B" };
  22295. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22296. "F", "Gb", "G", "Ab", "A",
  22297. "Bb", "B" };
  22298. if (((unsigned int) note) < 128)
  22299. {
  22300. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22301. : flatNoteNames [note % 12]);
  22302. if (includeOctaveNumber)
  22303. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22304. else
  22305. return s;
  22306. }
  22307. return String::empty;
  22308. }
  22309. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22310. {
  22311. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22312. return 440.0 * pow (2.0, noteNumber / 12.0);
  22313. }
  22314. const String MidiMessage::getGMInstrumentName (int n) throw()
  22315. {
  22316. const char *names[] =
  22317. {
  22318. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22319. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22320. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22321. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22322. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22323. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22324. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22325. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22326. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22327. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22328. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22329. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22330. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22331. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22332. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22333. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22334. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22335. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22336. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22337. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22338. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22339. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22340. "Applause", "Gunshot"
  22341. };
  22342. return (((unsigned int) n) < 128) ? names[n]
  22343. : (const char*)0;
  22344. }
  22345. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22346. {
  22347. const char* names[] =
  22348. {
  22349. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22350. "Bass", "Strings", "Ensemble", "Brass",
  22351. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22352. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22353. };
  22354. return (((unsigned int) n) <= 15) ? names[n]
  22355. : (const char*)0;
  22356. }
  22357. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22358. {
  22359. const char* names[] =
  22360. {
  22361. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22362. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22363. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22364. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22365. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22366. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22367. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22368. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22369. "Mute Triangle", "Open Triangle"
  22370. };
  22371. return (n >= 35 && n <= 81) ? names [n - 35]
  22372. : (const char*)0;
  22373. }
  22374. const String MidiMessage::getControllerName (int n) throw()
  22375. {
  22376. const char* names[] =
  22377. {
  22378. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22379. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22380. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22381. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22382. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22383. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22384. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22385. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22386. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22387. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22388. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22389. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22390. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22391. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22392. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22393. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22394. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22395. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22396. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22398. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22399. "Poly Operation"
  22400. };
  22401. return (((unsigned int) n) < 128) ? names[n]
  22402. : (const char*)0;
  22403. }
  22404. END_JUCE_NAMESPACE
  22405. /********* End of inlined file: juce_MidiMessage.cpp *********/
  22406. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  22407. BEGIN_JUCE_NAMESPACE
  22408. MidiMessageCollector::MidiMessageCollector()
  22409. : lastCallbackTime (0),
  22410. sampleRate (44100.0001)
  22411. {
  22412. }
  22413. MidiMessageCollector::~MidiMessageCollector()
  22414. {
  22415. }
  22416. void MidiMessageCollector::reset (const double sampleRate_)
  22417. {
  22418. jassert (sampleRate_ > 0);
  22419. const ScopedLock sl (midiCallbackLock);
  22420. sampleRate = sampleRate_;
  22421. incomingMessages.clear();
  22422. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22423. }
  22424. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22425. {
  22426. // you need to call reset() to set the correct sample rate before using this object
  22427. jassert (sampleRate != 44100.0001);
  22428. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22429. // for details of what the number should be.
  22430. jassert (message.getTimeStamp() != 0);
  22431. const ScopedLock sl (midiCallbackLock);
  22432. const int sampleNumber
  22433. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22434. incomingMessages.addEvent (message, sampleNumber);
  22435. // if the messages don't get used for over a second, we'd better
  22436. // get rid of any old ones to avoid the queue getting too big
  22437. if (sampleNumber > sampleRate)
  22438. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22439. }
  22440. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22441. const int numSamples)
  22442. {
  22443. // you need to call reset() to set the correct sample rate before using this object
  22444. jassert (sampleRate != 44100.0001);
  22445. const double timeNow = Time::getMillisecondCounterHiRes();
  22446. const double msElapsed = timeNow - lastCallbackTime;
  22447. const ScopedLock sl (midiCallbackLock);
  22448. lastCallbackTime = timeNow;
  22449. if (! incomingMessages.isEmpty())
  22450. {
  22451. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  22452. int startSample = 0;
  22453. int scale = 1 << 16;
  22454. const uint8* midiData;
  22455. int numBytes, samplePosition;
  22456. MidiBuffer::Iterator iter (incomingMessages);
  22457. if (numSourceSamples > numSamples)
  22458. {
  22459. // if our list of events is longer than the buffer we're being
  22460. // asked for, scale them down to squeeze them all in..
  22461. const int maxBlockLengthToUse = numSamples << 5;
  22462. if (numSourceSamples > maxBlockLengthToUse)
  22463. {
  22464. startSample = numSourceSamples - maxBlockLengthToUse;
  22465. numSourceSamples = maxBlockLengthToUse;
  22466. iter.setNextSamplePosition (startSample);
  22467. }
  22468. scale = (numSamples << 10) / numSourceSamples;
  22469. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22470. {
  22471. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22472. destBuffer.addEvent (midiData, numBytes,
  22473. jlimit (0, numSamples - 1, samplePosition));
  22474. }
  22475. }
  22476. else
  22477. {
  22478. // if our event list is shorter than the number we need, put them
  22479. // towards the end of the buffer
  22480. startSample = numSamples - numSourceSamples;
  22481. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22482. {
  22483. destBuffer.addEvent (midiData, numBytes,
  22484. jlimit (0, numSamples - 1, samplePosition + startSample));
  22485. }
  22486. }
  22487. incomingMessages.clear();
  22488. }
  22489. }
  22490. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  22491. {
  22492. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  22493. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22494. addMessageToQueue (m);
  22495. }
  22496. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  22497. {
  22498. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  22499. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22500. addMessageToQueue (m);
  22501. }
  22502. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  22503. {
  22504. addMessageToQueue (message);
  22505. }
  22506. END_JUCE_NAMESPACE
  22507. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  22508. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  22509. BEGIN_JUCE_NAMESPACE
  22510. MidiMessageSequence::MidiMessageSequence()
  22511. {
  22512. }
  22513. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  22514. {
  22515. list.ensureStorageAllocated (other.list.size());
  22516. for (int i = 0; i < other.list.size(); ++i)
  22517. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22518. }
  22519. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  22520. {
  22521. if (this != &other)
  22522. {
  22523. clear();
  22524. for (int i = 0; i < other.list.size(); ++i)
  22525. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22526. }
  22527. return *this;
  22528. }
  22529. MidiMessageSequence::~MidiMessageSequence()
  22530. {
  22531. }
  22532. void MidiMessageSequence::clear()
  22533. {
  22534. list.clear();
  22535. }
  22536. int MidiMessageSequence::getNumEvents() const
  22537. {
  22538. return list.size();
  22539. }
  22540. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  22541. {
  22542. return list [index];
  22543. }
  22544. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  22545. {
  22546. const MidiEventHolder* const meh = list [index];
  22547. if (meh != 0 && meh->noteOffObject != 0)
  22548. return meh->noteOffObject->message.getTimeStamp();
  22549. else
  22550. return 0.0;
  22551. }
  22552. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  22553. {
  22554. const MidiEventHolder* const meh = list [index];
  22555. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  22556. }
  22557. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  22558. {
  22559. return list.indexOf (event);
  22560. }
  22561. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  22562. {
  22563. const int numEvents = list.size();
  22564. int i;
  22565. for (i = 0; i < numEvents; ++i)
  22566. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  22567. break;
  22568. return i;
  22569. }
  22570. double MidiMessageSequence::getStartTime() const
  22571. {
  22572. if (list.size() > 0)
  22573. return list.getUnchecked(0)->message.getTimeStamp();
  22574. else
  22575. return 0;
  22576. }
  22577. double MidiMessageSequence::getEndTime() const
  22578. {
  22579. if (list.size() > 0)
  22580. return list.getLast()->message.getTimeStamp();
  22581. else
  22582. return 0;
  22583. }
  22584. double MidiMessageSequence::getEventTime (const int index) const
  22585. {
  22586. if (((unsigned int) index) < (unsigned int) list.size())
  22587. return list.getUnchecked (index)->message.getTimeStamp();
  22588. return 0.0;
  22589. }
  22590. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  22591. double timeAdjustment)
  22592. {
  22593. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  22594. timeAdjustment += newMessage.getTimeStamp();
  22595. newOne->message.setTimeStamp (timeAdjustment);
  22596. int i;
  22597. for (i = list.size(); --i >= 0;)
  22598. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  22599. break;
  22600. list.insert (i + 1, newOne);
  22601. }
  22602. void MidiMessageSequence::deleteEvent (const int index,
  22603. const bool deleteMatchingNoteUp)
  22604. {
  22605. if (((unsigned int) index) < (unsigned int) list.size())
  22606. {
  22607. if (deleteMatchingNoteUp)
  22608. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  22609. list.remove (index);
  22610. }
  22611. }
  22612. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  22613. double timeAdjustment,
  22614. double firstAllowableTime,
  22615. double endOfAllowableDestTimes)
  22616. {
  22617. firstAllowableTime -= timeAdjustment;
  22618. endOfAllowableDestTimes -= timeAdjustment;
  22619. for (int i = 0; i < other.list.size(); ++i)
  22620. {
  22621. const MidiMessage& m = other.list.getUnchecked(i)->message;
  22622. const double t = m.getTimeStamp();
  22623. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  22624. {
  22625. MidiEventHolder* const newOne = new MidiEventHolder (m);
  22626. newOne->message.setTimeStamp (timeAdjustment + t);
  22627. list.add (newOne);
  22628. }
  22629. }
  22630. sort();
  22631. }
  22632. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22633. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22634. {
  22635. const double diff = first->message.getTimeStamp()
  22636. - second->message.getTimeStamp();
  22637. return (diff > 0) - (diff < 0);
  22638. }
  22639. void MidiMessageSequence::sort()
  22640. {
  22641. list.sort (*this, true);
  22642. }
  22643. void MidiMessageSequence::updateMatchedPairs()
  22644. {
  22645. for (int i = 0; i < list.size(); ++i)
  22646. {
  22647. const MidiMessage& m1 = list.getUnchecked(i)->message;
  22648. if (m1.isNoteOn())
  22649. {
  22650. list.getUnchecked(i)->noteOffObject = 0;
  22651. const int note = m1.getNoteNumber();
  22652. const int chan = m1.getChannel();
  22653. const int len = list.size();
  22654. for (int j = i + 1; j < len; ++j)
  22655. {
  22656. const MidiMessage& m = list.getUnchecked(j)->message;
  22657. if (m.getNoteNumber() == note && m.getChannel() == chan)
  22658. {
  22659. if (m.isNoteOff())
  22660. {
  22661. list.getUnchecked(i)->noteOffObject = list[j];
  22662. break;
  22663. }
  22664. else if (m.isNoteOn())
  22665. {
  22666. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  22667. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  22668. list.getUnchecked(i)->noteOffObject = list[j];
  22669. break;
  22670. }
  22671. }
  22672. }
  22673. }
  22674. }
  22675. }
  22676. void MidiMessageSequence::addTimeToMessages (const double delta)
  22677. {
  22678. for (int i = list.size(); --i >= 0;)
  22679. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  22680. + delta);
  22681. }
  22682. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  22683. MidiMessageSequence& destSequence,
  22684. const bool alsoIncludeMetaEvents) const
  22685. {
  22686. for (int i = 0; i < list.size(); ++i)
  22687. {
  22688. const MidiMessage& mm = list.getUnchecked(i)->message;
  22689. if (mm.isForChannel (channelNumberToExtract)
  22690. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  22691. {
  22692. destSequence.addEvent (mm);
  22693. }
  22694. }
  22695. }
  22696. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  22697. {
  22698. for (int i = 0; i < list.size(); ++i)
  22699. {
  22700. const MidiMessage& mm = list.getUnchecked(i)->message;
  22701. if (mm.isSysEx())
  22702. destSequence.addEvent (mm);
  22703. }
  22704. }
  22705. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  22706. {
  22707. for (int i = list.size(); --i >= 0;)
  22708. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  22709. list.remove(i);
  22710. }
  22711. void MidiMessageSequence::deleteSysExMessages()
  22712. {
  22713. for (int i = list.size(); --i >= 0;)
  22714. if (list.getUnchecked(i)->message.isSysEx())
  22715. list.remove(i);
  22716. }
  22717. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  22718. const double time,
  22719. OwnedArray<MidiMessage>& dest)
  22720. {
  22721. bool doneProg = false;
  22722. bool donePitchWheel = false;
  22723. Array <int> doneControllers (32);
  22724. for (int i = list.size(); --i >= 0;)
  22725. {
  22726. const MidiMessage& mm = list.getUnchecked(i)->message;
  22727. if (mm.isForChannel (channelNumber)
  22728. && mm.getTimeStamp() <= time)
  22729. {
  22730. if (mm.isProgramChange())
  22731. {
  22732. if (! doneProg)
  22733. {
  22734. dest.add (new MidiMessage (mm, 0.0));
  22735. doneProg = true;
  22736. }
  22737. }
  22738. else if (mm.isController())
  22739. {
  22740. if (! doneControllers.contains (mm.getControllerNumber()))
  22741. {
  22742. dest.add (new MidiMessage (mm, 0.0));
  22743. doneControllers.add (mm.getControllerNumber());
  22744. }
  22745. }
  22746. else if (mm.isPitchWheel())
  22747. {
  22748. if (! donePitchWheel)
  22749. {
  22750. dest.add (new MidiMessage (mm, 0.0));
  22751. donePitchWheel = true;
  22752. }
  22753. }
  22754. }
  22755. }
  22756. }
  22757. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  22758. : message (message_),
  22759. noteOffObject (0)
  22760. {
  22761. }
  22762. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  22763. {
  22764. }
  22765. END_JUCE_NAMESPACE
  22766. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  22767. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  22768. BEGIN_JUCE_NAMESPACE
  22769. AudioPluginFormat::AudioPluginFormat() throw()
  22770. {
  22771. }
  22772. AudioPluginFormat::~AudioPluginFormat()
  22773. {
  22774. }
  22775. END_JUCE_NAMESPACE
  22776. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  22777. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22778. BEGIN_JUCE_NAMESPACE
  22779. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  22780. {
  22781. }
  22782. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  22783. {
  22784. clearSingletonInstance();
  22785. }
  22786. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  22787. void AudioPluginFormatManager::addDefaultFormats()
  22788. {
  22789. #ifdef JUCE_DEBUG
  22790. // you should only call this method once!
  22791. for (int i = formats.size(); --i >= 0;)
  22792. {
  22793. #if JUCE_PLUGINHOST_VST
  22794. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  22795. #endif
  22796. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22797. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  22798. #endif
  22799. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22800. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  22801. #endif
  22802. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22803. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  22804. #endif
  22805. }
  22806. #endif
  22807. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22808. formats.add (new AudioUnitPluginFormat());
  22809. #endif
  22810. #if JUCE_PLUGINHOST_VST
  22811. formats.add (new VSTPluginFormat());
  22812. #endif
  22813. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22814. formats.add (new DirectXPluginFormat());
  22815. #endif
  22816. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22817. formats.add (new LADSPAPluginFormat());
  22818. #endif
  22819. }
  22820. int AudioPluginFormatManager::getNumFormats() throw()
  22821. {
  22822. return formats.size();
  22823. }
  22824. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  22825. {
  22826. return formats [index];
  22827. }
  22828. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  22829. {
  22830. formats.add (format);
  22831. }
  22832. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  22833. String& errorMessage) const
  22834. {
  22835. AudioPluginInstance* result = 0;
  22836. for (int i = 0; i < formats.size(); ++i)
  22837. {
  22838. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  22839. if (result != 0)
  22840. break;
  22841. }
  22842. if (result == 0)
  22843. {
  22844. if (! doesPluginStillExist (description))
  22845. errorMessage = TRANS ("This plug-in file no longer exists");
  22846. else
  22847. errorMessage = TRANS ("This plug-in failed to load correctly");
  22848. }
  22849. return result;
  22850. }
  22851. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  22852. {
  22853. for (int i = 0; i < formats.size(); ++i)
  22854. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  22855. return formats.getUnchecked(i)->doesPluginStillExist (description);
  22856. return false;
  22857. }
  22858. END_JUCE_NAMESPACE
  22859. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22860. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  22861. #define JUCE_PLUGIN_HOST 1
  22862. BEGIN_JUCE_NAMESPACE
  22863. AudioPluginInstance::AudioPluginInstance()
  22864. {
  22865. }
  22866. AudioPluginInstance::~AudioPluginInstance()
  22867. {
  22868. }
  22869. END_JUCE_NAMESPACE
  22870. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  22871. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  22872. BEGIN_JUCE_NAMESPACE
  22873. KnownPluginList::KnownPluginList()
  22874. {
  22875. }
  22876. KnownPluginList::~KnownPluginList()
  22877. {
  22878. }
  22879. void KnownPluginList::clear()
  22880. {
  22881. if (types.size() > 0)
  22882. {
  22883. types.clear();
  22884. sendChangeMessage (this);
  22885. }
  22886. }
  22887. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  22888. {
  22889. for (int i = 0; i < types.size(); ++i)
  22890. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  22891. return types.getUnchecked(i);
  22892. return 0;
  22893. }
  22894. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  22895. {
  22896. for (int i = 0; i < types.size(); ++i)
  22897. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  22898. return types.getUnchecked(i);
  22899. return 0;
  22900. }
  22901. bool KnownPluginList::addType (const PluginDescription& type)
  22902. {
  22903. for (int i = types.size(); --i >= 0;)
  22904. {
  22905. if (types.getUnchecked(i)->isDuplicateOf (type))
  22906. {
  22907. // strange - found a duplicate plugin with different info..
  22908. jassert (types.getUnchecked(i)->name == type.name);
  22909. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  22910. *types.getUnchecked(i) = type;
  22911. return false;
  22912. }
  22913. }
  22914. types.add (new PluginDescription (type));
  22915. sendChangeMessage (this);
  22916. return true;
  22917. }
  22918. void KnownPluginList::removeType (const int index) throw()
  22919. {
  22920. types.remove (index);
  22921. sendChangeMessage (this);
  22922. }
  22923. static Time getFileModTime (const String& fileOrIdentifier) throw()
  22924. {
  22925. if (fileOrIdentifier.startsWithChar (T('/'))
  22926. || fileOrIdentifier[1] == T(':'))
  22927. {
  22928. return File (fileOrIdentifier).getLastModificationTime();
  22929. }
  22930. return Time (0);
  22931. }
  22932. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  22933. {
  22934. return t1 != t2 || t1 == Time (0);
  22935. }
  22936. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  22937. {
  22938. if (getTypeForFile (fileOrIdentifier) == 0)
  22939. return false;
  22940. for (int i = types.size(); --i >= 0;)
  22941. {
  22942. const PluginDescription* const d = types.getUnchecked(i);
  22943. if (d->fileOrIdentifier == fileOrIdentifier
  22944. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22945. {
  22946. return false;
  22947. }
  22948. }
  22949. return true;
  22950. }
  22951. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  22952. const bool dontRescanIfAlreadyInList,
  22953. OwnedArray <PluginDescription>& typesFound,
  22954. AudioPluginFormat& format)
  22955. {
  22956. bool addedOne = false;
  22957. if (dontRescanIfAlreadyInList
  22958. && getTypeForFile (fileOrIdentifier) != 0)
  22959. {
  22960. bool needsRescanning = false;
  22961. for (int i = types.size(); --i >= 0;)
  22962. {
  22963. const PluginDescription* const d = types.getUnchecked(i);
  22964. if (d->fileOrIdentifier == fileOrIdentifier)
  22965. {
  22966. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22967. needsRescanning = true;
  22968. else
  22969. typesFound.add (new PluginDescription (*d));
  22970. }
  22971. }
  22972. if (! needsRescanning)
  22973. return false;
  22974. }
  22975. OwnedArray <PluginDescription> found;
  22976. format.findAllTypesForFile (found, fileOrIdentifier);
  22977. for (int i = 0; i < found.size(); ++i)
  22978. {
  22979. PluginDescription* const desc = found.getUnchecked(i);
  22980. jassert (desc != 0);
  22981. if (addType (*desc))
  22982. addedOne = true;
  22983. typesFound.add (new PluginDescription (*desc));
  22984. }
  22985. return addedOne;
  22986. }
  22987. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  22988. OwnedArray <PluginDescription>& typesFound)
  22989. {
  22990. for (int i = 0; i < files.size(); ++i)
  22991. {
  22992. bool loaded = false;
  22993. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  22994. {
  22995. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  22996. if (scanAndAddFile (files[i], true, typesFound, *format))
  22997. loaded = true;
  22998. }
  22999. if (! loaded)
  23000. {
  23001. const File f (files[i]);
  23002. if (f.isDirectory())
  23003. {
  23004. StringArray s;
  23005. {
  23006. OwnedArray <File> subFiles;
  23007. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23008. for (int j = 0; j < subFiles.size(); ++j)
  23009. s.add (subFiles.getUnchecked (j)->getFullPathName());
  23010. }
  23011. scanAndAddDragAndDroppedFiles (s, typesFound);
  23012. }
  23013. }
  23014. }
  23015. }
  23016. class PluginSorter
  23017. {
  23018. public:
  23019. KnownPluginList::SortMethod method;
  23020. PluginSorter() throw() {}
  23021. int compareElements (const PluginDescription* const first,
  23022. const PluginDescription* const second) const throw()
  23023. {
  23024. int diff = 0;
  23025. if (method == KnownPluginList::sortByCategory)
  23026. diff = first->category.compareLexicographically (second->category);
  23027. else if (method == KnownPluginList::sortByManufacturer)
  23028. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23029. else if (method == KnownPluginList::sortByFileSystemLocation)
  23030. diff = first->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  23031. .upToLastOccurrenceOf (T("/"), false, false)
  23032. .compare (second->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  23033. .upToLastOccurrenceOf (T("/"), false, false));
  23034. if (diff == 0)
  23035. diff = first->name.compareLexicographically (second->name);
  23036. return diff;
  23037. }
  23038. };
  23039. void KnownPluginList::sort (const SortMethod method)
  23040. {
  23041. if (method != defaultOrder)
  23042. {
  23043. PluginSorter sorter;
  23044. sorter.method = method;
  23045. types.sort (sorter, true);
  23046. sendChangeMessage (this);
  23047. }
  23048. }
  23049. XmlElement* KnownPluginList::createXml() const
  23050. {
  23051. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  23052. for (int i = 0; i < types.size(); ++i)
  23053. e->addChildElement (types.getUnchecked(i)->createXml());
  23054. return e;
  23055. }
  23056. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23057. {
  23058. clear();
  23059. if (xml.hasTagName (T("KNOWNPLUGINS")))
  23060. {
  23061. forEachXmlChildElement (xml, e)
  23062. {
  23063. PluginDescription info;
  23064. if (info.loadFromXml (*e))
  23065. addType (info);
  23066. }
  23067. }
  23068. }
  23069. const int menuIdBase = 0x324503f4;
  23070. // This is used to turn a bunch of paths into a nested menu structure.
  23071. struct PluginFilesystemTree
  23072. {
  23073. private:
  23074. String folder;
  23075. OwnedArray <PluginFilesystemTree> subFolders;
  23076. Array <PluginDescription*> plugins;
  23077. void addPlugin (PluginDescription* const pd, const String& path)
  23078. {
  23079. if (path.isEmpty())
  23080. {
  23081. plugins.add (pd);
  23082. }
  23083. else
  23084. {
  23085. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  23086. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  23087. for (int i = subFolders.size(); --i >= 0;)
  23088. {
  23089. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23090. {
  23091. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23092. return;
  23093. }
  23094. }
  23095. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23096. newFolder->folder = firstSubFolder;
  23097. subFolders.add (newFolder);
  23098. newFolder->addPlugin (pd, remainingPath);
  23099. }
  23100. }
  23101. // removes any deeply nested folders that don't contain any actual plugins
  23102. void optimise()
  23103. {
  23104. for (int i = subFolders.size(); --i >= 0;)
  23105. {
  23106. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23107. sub->optimise();
  23108. if (sub->plugins.size() == 0)
  23109. {
  23110. for (int j = 0; j < sub->subFolders.size(); ++j)
  23111. subFolders.add (sub->subFolders.getUnchecked(j));
  23112. sub->subFolders.clear (false);
  23113. subFolders.remove (i);
  23114. }
  23115. }
  23116. }
  23117. public:
  23118. void buildTree (const Array <PluginDescription*>& allPlugins)
  23119. {
  23120. for (int i = 0; i < allPlugins.size(); ++i)
  23121. {
  23122. String path (allPlugins.getUnchecked(i)
  23123. ->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  23124. .upToLastOccurrenceOf (T("/"), false, false));
  23125. if (path.substring (1, 2) == T(":"))
  23126. path = path.substring (2);
  23127. addPlugin (allPlugins.getUnchecked(i), path);
  23128. }
  23129. optimise();
  23130. }
  23131. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23132. {
  23133. int i;
  23134. for (i = 0; i < subFolders.size(); ++i)
  23135. {
  23136. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23137. PopupMenu subMenu;
  23138. sub->addToMenu (subMenu, allPlugins);
  23139. #if JUCE_MAC
  23140. // avoid the special AU formatting nonsense on Mac..
  23141. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (T(":"), false, false), subMenu);
  23142. #else
  23143. m.addSubMenu (sub->folder, subMenu);
  23144. #endif
  23145. }
  23146. for (i = 0; i < plugins.size(); ++i)
  23147. {
  23148. PluginDescription* const plugin = plugins.getUnchecked(i);
  23149. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23150. plugin->name, true, false);
  23151. }
  23152. }
  23153. };
  23154. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23155. {
  23156. Array <PluginDescription*> sorted;
  23157. {
  23158. PluginSorter sorter;
  23159. sorter.method = sortMethod;
  23160. for (int i = 0; i < types.size(); ++i)
  23161. sorted.addSorted (sorter, types.getUnchecked(i));
  23162. }
  23163. if (sortMethod == sortByCategory
  23164. || sortMethod == sortByManufacturer)
  23165. {
  23166. String lastSubMenuName;
  23167. PopupMenu sub;
  23168. for (int i = 0; i < sorted.size(); ++i)
  23169. {
  23170. const PluginDescription* const pd = sorted.getUnchecked(i);
  23171. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23172. : pd->manufacturerName);
  23173. if (! thisSubMenuName.containsNonWhitespaceChars())
  23174. thisSubMenuName = T("Other");
  23175. if (thisSubMenuName != lastSubMenuName)
  23176. {
  23177. if (sub.getNumItems() > 0)
  23178. {
  23179. menu.addSubMenu (lastSubMenuName, sub);
  23180. sub.clear();
  23181. }
  23182. lastSubMenuName = thisSubMenuName;
  23183. }
  23184. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23185. }
  23186. if (sub.getNumItems() > 0)
  23187. menu.addSubMenu (lastSubMenuName, sub);
  23188. }
  23189. else if (sortMethod == sortByFileSystemLocation)
  23190. {
  23191. PluginFilesystemTree root;
  23192. root.buildTree (sorted);
  23193. root.addToMenu (menu, types);
  23194. }
  23195. else
  23196. {
  23197. for (int i = 0; i < sorted.size(); ++i)
  23198. {
  23199. const PluginDescription* const pd = sorted.getUnchecked(i);
  23200. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23201. }
  23202. }
  23203. }
  23204. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23205. {
  23206. const int i = menuResultCode - menuIdBase;
  23207. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23208. }
  23209. END_JUCE_NAMESPACE
  23210. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  23211. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  23212. BEGIN_JUCE_NAMESPACE
  23213. PluginDescription::PluginDescription() throw()
  23214. : uid (0),
  23215. isInstrument (false),
  23216. numInputChannels (0),
  23217. numOutputChannels (0)
  23218. {
  23219. }
  23220. PluginDescription::~PluginDescription() throw()
  23221. {
  23222. }
  23223. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23224. : name (other.name),
  23225. pluginFormatName (other.pluginFormatName),
  23226. category (other.category),
  23227. manufacturerName (other.manufacturerName),
  23228. version (other.version),
  23229. fileOrIdentifier (other.fileOrIdentifier),
  23230. lastFileModTime (other.lastFileModTime),
  23231. uid (other.uid),
  23232. isInstrument (other.isInstrument),
  23233. numInputChannels (other.numInputChannels),
  23234. numOutputChannels (other.numOutputChannels)
  23235. {
  23236. }
  23237. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23238. {
  23239. name = other.name;
  23240. pluginFormatName = other.pluginFormatName;
  23241. category = other.category;
  23242. manufacturerName = other.manufacturerName;
  23243. version = other.version;
  23244. fileOrIdentifier = other.fileOrIdentifier;
  23245. uid = other.uid;
  23246. isInstrument = other.isInstrument;
  23247. lastFileModTime = other.lastFileModTime;
  23248. numInputChannels = other.numInputChannels;
  23249. numOutputChannels = other.numOutputChannels;
  23250. return *this;
  23251. }
  23252. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23253. {
  23254. return fileOrIdentifier == other.fileOrIdentifier
  23255. && uid == other.uid;
  23256. }
  23257. const String PluginDescription::createIdentifierString() const throw()
  23258. {
  23259. return pluginFormatName
  23260. + T("-") + name
  23261. + T("-") + String::toHexString (fileOrIdentifier.hashCode())
  23262. + T("-") + String::toHexString (uid);
  23263. }
  23264. XmlElement* PluginDescription::createXml() const
  23265. {
  23266. XmlElement* const e = new XmlElement (T("PLUGIN"));
  23267. e->setAttribute (T("name"), name);
  23268. e->setAttribute (T("format"), pluginFormatName);
  23269. e->setAttribute (T("category"), category);
  23270. e->setAttribute (T("manufacturer"), manufacturerName);
  23271. e->setAttribute (T("version"), version);
  23272. e->setAttribute (T("file"), fileOrIdentifier);
  23273. e->setAttribute (T("uid"), String::toHexString (uid));
  23274. e->setAttribute (T("isInstrument"), isInstrument);
  23275. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  23276. e->setAttribute (T("numInputs"), numInputChannels);
  23277. e->setAttribute (T("numOutputs"), numOutputChannels);
  23278. return e;
  23279. }
  23280. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23281. {
  23282. if (xml.hasTagName (T("PLUGIN")))
  23283. {
  23284. name = xml.getStringAttribute (T("name"));
  23285. pluginFormatName = xml.getStringAttribute (T("format"));
  23286. category = xml.getStringAttribute (T("category"));
  23287. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  23288. version = xml.getStringAttribute (T("version"));
  23289. fileOrIdentifier = xml.getStringAttribute (T("file"));
  23290. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  23291. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  23292. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  23293. numInputChannels = xml.getIntAttribute (T("numInputs"));
  23294. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  23295. return true;
  23296. }
  23297. return false;
  23298. }
  23299. END_JUCE_NAMESPACE
  23300. /********* End of inlined file: juce_PluginDescription.cpp *********/
  23301. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23302. BEGIN_JUCE_NAMESPACE
  23303. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23304. AudioPluginFormat& formatToLookFor,
  23305. FileSearchPath directoriesToSearch,
  23306. const bool recursive,
  23307. const File& deadMansPedalFile_)
  23308. : list (listToAddTo),
  23309. format (formatToLookFor),
  23310. deadMansPedalFile (deadMansPedalFile_),
  23311. nextIndex (0),
  23312. progress (0)
  23313. {
  23314. directoriesToSearch.removeRedundantPaths();
  23315. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23316. // If any plugins have crashed recently when being loaded, move them to the
  23317. // end of the list to give the others a chance to load correctly..
  23318. const StringArray crashedPlugins (getDeadMansPedalFile());
  23319. for (int i = 0; i < crashedPlugins.size(); ++i)
  23320. {
  23321. const String f = crashedPlugins[i];
  23322. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23323. if (f == filesOrIdentifiersToScan[j])
  23324. filesOrIdentifiersToScan.move (j, -1);
  23325. }
  23326. }
  23327. PluginDirectoryScanner::~PluginDirectoryScanner()
  23328. {
  23329. }
  23330. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23331. {
  23332. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23333. }
  23334. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23335. {
  23336. String file (filesOrIdentifiersToScan [nextIndex]);
  23337. if (file.isNotEmpty())
  23338. {
  23339. if (! list.isListingUpToDate (file))
  23340. {
  23341. OwnedArray <PluginDescription> typesFound;
  23342. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23343. StringArray crashedPlugins (getDeadMansPedalFile());
  23344. crashedPlugins.removeString (file);
  23345. crashedPlugins.add (file);
  23346. setDeadMansPedalFile (crashedPlugins);
  23347. list.scanAndAddFile (file,
  23348. dontRescanIfAlreadyInList,
  23349. typesFound,
  23350. format);
  23351. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23352. crashedPlugins.removeString (file);
  23353. setDeadMansPedalFile (crashedPlugins);
  23354. if (typesFound.size() == 0)
  23355. failedFiles.add (file);
  23356. }
  23357. ++nextIndex;
  23358. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23359. }
  23360. return nextIndex < filesOrIdentifiersToScan.size();
  23361. }
  23362. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23363. {
  23364. StringArray lines;
  23365. if (deadMansPedalFile != File::nonexistent)
  23366. {
  23367. lines.addLines (deadMansPedalFile.loadFileAsString());
  23368. lines.removeEmptyStrings();
  23369. }
  23370. return lines;
  23371. }
  23372. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23373. {
  23374. if (deadMansPedalFile != File::nonexistent)
  23375. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23376. }
  23377. END_JUCE_NAMESPACE
  23378. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23379. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  23380. BEGIN_JUCE_NAMESPACE
  23381. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23382. const File& deadMansPedalFile_,
  23383. PropertiesFile* const propertiesToUse_)
  23384. : list (listToEdit),
  23385. deadMansPedalFile (deadMansPedalFile_),
  23386. propertiesToUse (propertiesToUse_)
  23387. {
  23388. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23389. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23390. optionsButton->addButtonListener (this);
  23391. optionsButton->setTriggeredOnMouseDown (true);
  23392. setSize (400, 600);
  23393. list.addChangeListener (this);
  23394. }
  23395. PluginListComponent::~PluginListComponent()
  23396. {
  23397. list.removeChangeListener (this);
  23398. deleteAllChildren();
  23399. }
  23400. void PluginListComponent::resized()
  23401. {
  23402. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23403. optionsButton->changeWidthToFitText (24);
  23404. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23405. }
  23406. void PluginListComponent::changeListenerCallback (void*)
  23407. {
  23408. listBox->updateContent();
  23409. listBox->repaint();
  23410. }
  23411. int PluginListComponent::getNumRows()
  23412. {
  23413. return list.getNumTypes();
  23414. }
  23415. void PluginListComponent::paintListBoxItem (int row,
  23416. Graphics& g,
  23417. int width, int height,
  23418. bool rowIsSelected)
  23419. {
  23420. if (rowIsSelected)
  23421. g.fillAll (findColour (TextEditor::highlightColourId));
  23422. const PluginDescription* const pd = list.getType (row);
  23423. if (pd != 0)
  23424. {
  23425. GlyphArrangement ga;
  23426. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23427. g.setColour (Colours::black);
  23428. ga.draw (g);
  23429. float x, y, r, b;
  23430. ga.getBoundingBox (0, -1, x, y, r, b, false);
  23431. String desc;
  23432. desc << pd->pluginFormatName
  23433. << (pd->isInstrument ? " instrument" : " effect")
  23434. << " - "
  23435. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23436. << " / "
  23437. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23438. if (pd->manufacturerName.isNotEmpty())
  23439. desc << " - " << pd->manufacturerName;
  23440. if (pd->version.isNotEmpty())
  23441. desc << " - " << pd->version;
  23442. if (pd->category.isNotEmpty())
  23443. desc << " - category: '" << pd->category << '\'';
  23444. g.setColour (Colours::grey);
  23445. ga.clear();
  23446. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  23447. ga.draw (g);
  23448. }
  23449. }
  23450. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23451. {
  23452. list.removeType (lastRowSelected);
  23453. }
  23454. void PluginListComponent::buttonClicked (Button* b)
  23455. {
  23456. if (optionsButton == b)
  23457. {
  23458. PopupMenu menu;
  23459. menu.addItem (1, TRANS("Clear list"));
  23460. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23461. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23462. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23463. menu.addSeparator();
  23464. menu.addItem (2, TRANS("Sort alphabetically"));
  23465. menu.addItem (3, TRANS("Sort by category"));
  23466. menu.addItem (4, TRANS("Sort by manufacturer"));
  23467. menu.addSeparator();
  23468. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23469. {
  23470. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23471. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23472. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23473. }
  23474. const int r = menu.showAt (optionsButton);
  23475. if (r == 1)
  23476. {
  23477. list.clear();
  23478. }
  23479. else if (r == 2)
  23480. {
  23481. list.sort (KnownPluginList::sortAlphabetically);
  23482. }
  23483. else if (r == 3)
  23484. {
  23485. list.sort (KnownPluginList::sortByCategory);
  23486. }
  23487. else if (r == 4)
  23488. {
  23489. list.sort (KnownPluginList::sortByManufacturer);
  23490. }
  23491. else if (r == 5)
  23492. {
  23493. const SparseSet <int> selected (listBox->getSelectedRows());
  23494. for (int i = list.getNumTypes(); --i >= 0;)
  23495. if (selected.contains (i))
  23496. list.removeType (i);
  23497. }
  23498. else if (r == 6)
  23499. {
  23500. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  23501. if (desc != 0)
  23502. {
  23503. if (File (desc->fileOrIdentifier).existsAsFile())
  23504. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  23505. }
  23506. }
  23507. else if (r == 7)
  23508. {
  23509. for (int i = list.getNumTypes(); --i >= 0;)
  23510. {
  23511. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  23512. {
  23513. list.removeType (i);
  23514. }
  23515. }
  23516. }
  23517. else if (r != 0)
  23518. {
  23519. typeToScan = r - 10;
  23520. startTimer (1);
  23521. }
  23522. }
  23523. }
  23524. void PluginListComponent::timerCallback()
  23525. {
  23526. stopTimer();
  23527. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  23528. }
  23529. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  23530. {
  23531. return true;
  23532. }
  23533. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  23534. {
  23535. OwnedArray <PluginDescription> typesFound;
  23536. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  23537. }
  23538. void PluginListComponent::scanFor (AudioPluginFormat* format)
  23539. {
  23540. if (format == 0)
  23541. return;
  23542. FileSearchPath path (format->getDefaultLocationsToSearch());
  23543. if (propertiesToUse != 0)
  23544. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23545. {
  23546. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  23547. FileSearchPathListComponent pathList;
  23548. pathList.setSize (500, 300);
  23549. pathList.setPath (path);
  23550. aw.addCustomComponent (&pathList);
  23551. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  23552. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23553. if (aw.runModalLoop() == 0)
  23554. return;
  23555. path = pathList.getPath();
  23556. }
  23557. if (propertiesToUse != 0)
  23558. {
  23559. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23560. propertiesToUse->saveIfNeeded();
  23561. }
  23562. double progress = 0.0;
  23563. AlertWindow aw (TRANS("Scanning for plugins..."),
  23564. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  23565. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23566. aw.addProgressBarComponent (progress);
  23567. aw.enterModalState();
  23568. MessageManager::getInstance()->runDispatchLoopUntil (300);
  23569. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  23570. for (;;)
  23571. {
  23572. aw.setMessage (TRANS("Testing:\n\n")
  23573. + scanner.getNextPluginFileThatWillBeScanned());
  23574. MessageManager::getInstance()->runDispatchLoopUntil (20);
  23575. if (! scanner.scanNextFile (true))
  23576. break;
  23577. if (! aw.isCurrentlyModal())
  23578. break;
  23579. progress = scanner.getProgress();
  23580. }
  23581. if (scanner.getFailedFiles().size() > 0)
  23582. {
  23583. StringArray shortNames;
  23584. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  23585. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  23586. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  23587. TRANS("Scan complete"),
  23588. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  23589. + shortNames.joinIntoString (", "));
  23590. }
  23591. }
  23592. END_JUCE_NAMESPACE
  23593. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  23594. /********* Start of inlined file: juce_AudioUnitPluginFormat.mm *********/
  23595. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  23596. #include <AudioUnit/AudioUnit.h>
  23597. #include <AudioUnit/AUCocoaUIView.h>
  23598. #include <CoreAudioKit/AUGenericView.h>
  23599. #if JUCE_SUPPORT_CARBON
  23600. #include <AudioToolbox/AudioUnitUtilities.h>
  23601. #include <AudioUnit/AudioUnitCarbonView.h>
  23602. #endif
  23603. BEGIN_JUCE_NAMESPACE
  23604. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  23605. #endif
  23606. #if JUCE_MAC
  23607. #if MACOS_10_3_OR_EARLIER
  23608. #define kAudioUnitType_Generator 'augn'
  23609. #endif
  23610. // Change this to disable logging of various activities
  23611. #ifndef AU_LOGGING
  23612. #define AU_LOGGING 1
  23613. #endif
  23614. #if AU_LOGGING
  23615. #define log(a) Logger::writeToLog(a);
  23616. #else
  23617. #define log(a)
  23618. #endif
  23619. static int insideCallback = 0;
  23620. static const String osTypeToString (OSType type) throw()
  23621. {
  23622. char s[4];
  23623. s[0] = (char) (((uint32) type) >> 24);
  23624. s[1] = (char) (((uint32) type) >> 16);
  23625. s[2] = (char) (((uint32) type) >> 8);
  23626. s[3] = (char) ((uint32) type);
  23627. return String (s, 4);
  23628. }
  23629. static OSType stringToOSType (const String& s1) throw()
  23630. {
  23631. const String s (s1 + " ");
  23632. return (((OSType) (unsigned char) s[0]) << 24)
  23633. | (((OSType) (unsigned char) s[1]) << 16)
  23634. | (((OSType) (unsigned char) s[2]) << 8)
  23635. | ((OSType) (unsigned char) s[3]);
  23636. }
  23637. static const tchar* auIdentifierPrefix = T("AudioUnit:");
  23638. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  23639. {
  23640. jassert (osTypeToString ('abcd') == T("abcd")); // agh, must have got the endianness wrong..
  23641. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  23642. String s (auIdentifierPrefix);
  23643. if (desc.componentType == kAudioUnitType_MusicDevice)
  23644. s << "Synths/";
  23645. else if (desc.componentType == kAudioUnitType_MusicEffect
  23646. || desc.componentType == kAudioUnitType_Effect)
  23647. s << "Effects/";
  23648. else if (desc.componentType == kAudioUnitType_Generator)
  23649. s << "Generators/";
  23650. else if (desc.componentType == kAudioUnitType_Panner)
  23651. s << "Panners/";
  23652. s << osTypeToString (desc.componentType)
  23653. << T(",")
  23654. << osTypeToString (desc.componentSubType)
  23655. << T(",")
  23656. << osTypeToString (desc.componentManufacturer);
  23657. return s;
  23658. }
  23659. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  23660. {
  23661. Handle componentNameHandle = NewHandle (sizeof (void*));
  23662. Handle componentInfoHandle = NewHandle (sizeof (void*));
  23663. if (componentNameHandle != 0 && componentInfoHandle != 0)
  23664. {
  23665. ComponentDescription desc;
  23666. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  23667. {
  23668. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  23669. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  23670. if (nameString != 0 && nameString[0] != 0)
  23671. {
  23672. const String all ((const char*) nameString + 1, nameString[0]);
  23673. DBG ("name: "+ all);
  23674. manufacturer = all.upToFirstOccurrenceOf (T(":"), false, false).trim();
  23675. name = all.fromFirstOccurrenceOf (T(":"), false, false).trim();
  23676. }
  23677. if (infoString != 0 && infoString[0] != 0)
  23678. {
  23679. const String all ((const char*) infoString + 1, infoString[0]);
  23680. DBG ("info: " + all);
  23681. }
  23682. if (name.isEmpty())
  23683. name = "<Unknown>";
  23684. }
  23685. DisposeHandle (componentNameHandle);
  23686. DisposeHandle (componentInfoHandle);
  23687. }
  23688. }
  23689. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  23690. String& name, String& version, String& manufacturer)
  23691. {
  23692. zerostruct (desc);
  23693. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  23694. {
  23695. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (T(':')),
  23696. fileOrIdentifier.lastIndexOfChar (T('/'))) + 1));
  23697. StringArray tokens;
  23698. tokens.addTokens (s, T(","), 0);
  23699. tokens.trim();
  23700. tokens.removeEmptyStrings();
  23701. if (tokens.size() == 3)
  23702. {
  23703. desc.componentType = stringToOSType (tokens[0]);
  23704. desc.componentSubType = stringToOSType (tokens[1]);
  23705. desc.componentManufacturer = stringToOSType (tokens[2]);
  23706. ComponentRecord* comp = FindNextComponent (0, &desc);
  23707. if (comp != 0)
  23708. {
  23709. getAUDetails (comp, name, manufacturer);
  23710. return true;
  23711. }
  23712. }
  23713. }
  23714. return false;
  23715. }
  23716. class AudioUnitPluginWindowCarbon;
  23717. class AudioUnitPluginWindowCocoa;
  23718. class AudioUnitPluginInstance : public AudioPluginInstance
  23719. {
  23720. public:
  23721. ~AudioUnitPluginInstance();
  23722. // AudioPluginInstance methods:
  23723. void fillInPluginDescription (PluginDescription& desc) const
  23724. {
  23725. desc.name = pluginName;
  23726. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  23727. desc.uid = ((int) componentDesc.componentType)
  23728. ^ ((int) componentDesc.componentSubType)
  23729. ^ ((int) componentDesc.componentManufacturer);
  23730. desc.lastFileModTime = 0;
  23731. desc.pluginFormatName = "AudioUnit";
  23732. desc.category = getCategory();
  23733. desc.manufacturerName = manufacturer;
  23734. desc.version = version;
  23735. desc.numInputChannels = getNumInputChannels();
  23736. desc.numOutputChannels = getNumOutputChannels();
  23737. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  23738. }
  23739. const String getName() const { return pluginName; }
  23740. bool acceptsMidi() const { return wantsMidiMessages; }
  23741. bool producesMidi() const { return false; }
  23742. // AudioProcessor methods:
  23743. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23744. void releaseResources();
  23745. void processBlock (AudioSampleBuffer& buffer,
  23746. MidiBuffer& midiMessages);
  23747. AudioProcessorEditor* createEditor();
  23748. const String getInputChannelName (const int index) const;
  23749. bool isInputChannelStereoPair (int index) const;
  23750. const String getOutputChannelName (const int index) const;
  23751. bool isOutputChannelStereoPair (int index) const;
  23752. int getNumParameters();
  23753. float getParameter (int index);
  23754. void setParameter (int index, float newValue);
  23755. const String getParameterName (int index);
  23756. const String getParameterText (int index);
  23757. bool isParameterAutomatable (int index) const;
  23758. int getNumPrograms();
  23759. int getCurrentProgram();
  23760. void setCurrentProgram (int index);
  23761. const String getProgramName (int index);
  23762. void changeProgramName (int index, const String& newName);
  23763. void getStateInformation (MemoryBlock& destData);
  23764. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23765. void setStateInformation (const void* data, int sizeInBytes);
  23766. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23767. juce_UseDebuggingNewOperator
  23768. private:
  23769. friend class AudioUnitPluginWindowCarbon;
  23770. friend class AudioUnitPluginWindowCocoa;
  23771. friend class AudioUnitPluginFormat;
  23772. ComponentDescription componentDesc;
  23773. String pluginName, manufacturer, version;
  23774. String fileOrIdentifier;
  23775. CriticalSection lock;
  23776. bool initialised, wantsMidiMessages, wasPlaying;
  23777. AudioBufferList* outputBufferList;
  23778. AudioTimeStamp timeStamp;
  23779. AudioSampleBuffer* currentBuffer;
  23780. AudioUnit audioUnit;
  23781. Array <int> parameterIds;
  23782. bool getComponentDescFromFile (const String& fileOrIdentifier);
  23783. void initialise();
  23784. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23785. const AudioTimeStamp* inTimeStamp,
  23786. UInt32 inBusNumber,
  23787. UInt32 inNumberFrames,
  23788. AudioBufferList* ioData) const;
  23789. static OSStatus renderGetInputCallback (void* inRefCon,
  23790. AudioUnitRenderActionFlags* ioActionFlags,
  23791. const AudioTimeStamp* inTimeStamp,
  23792. UInt32 inBusNumber,
  23793. UInt32 inNumberFrames,
  23794. AudioBufferList* ioData)
  23795. {
  23796. return ((AudioUnitPluginInstance*) inRefCon)
  23797. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  23798. }
  23799. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  23800. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  23801. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  23802. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23803. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23804. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  23805. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  23806. {
  23807. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  23808. }
  23809. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  23810. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  23811. Float64* outCurrentMeasureDownBeat)
  23812. {
  23813. return ((AudioUnitPluginInstance*) inHostUserData)
  23814. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  23815. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  23816. }
  23817. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23818. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23819. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  23820. {
  23821. return ((AudioUnitPluginInstance*) inHostUserData)
  23822. ->getTransportState (outIsPlaying, outTransportStateChanged,
  23823. outCurrentSampleInTimeLine, outIsCycling,
  23824. outCycleStartBeat, outCycleEndBeat);
  23825. }
  23826. void getNumChannels (int& numIns, int& numOuts)
  23827. {
  23828. numIns = 0;
  23829. numOuts = 0;
  23830. AUChannelInfo supportedChannels [128];
  23831. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  23832. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  23833. 0, supportedChannels, &supportedChannelsSize) == noErr
  23834. && supportedChannelsSize > 0)
  23835. {
  23836. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  23837. {
  23838. numIns = jmax (numIns, supportedChannels[i].inChannels);
  23839. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  23840. }
  23841. }
  23842. else
  23843. {
  23844. // (this really means the plugin will take any number of ins/outs as long
  23845. // as they are the same)
  23846. numIns = numOuts = 2;
  23847. }
  23848. }
  23849. const String getCategory() const;
  23850. AudioUnitPluginInstance (const String& fileOrIdentifier);
  23851. };
  23852. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  23853. : fileOrIdentifier (fileOrIdentifier),
  23854. initialised (false),
  23855. wantsMidiMessages (false),
  23856. audioUnit (0),
  23857. outputBufferList (0),
  23858. currentBuffer (0)
  23859. {
  23860. try
  23861. {
  23862. ++insideCallback;
  23863. log (T("Opening AU: ") + fileOrIdentifier);
  23864. if (getComponentDescFromFile (fileOrIdentifier))
  23865. {
  23866. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  23867. if (comp != 0)
  23868. {
  23869. audioUnit = (AudioUnit) OpenComponent (comp);
  23870. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  23871. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  23872. }
  23873. }
  23874. --insideCallback;
  23875. }
  23876. catch (...)
  23877. {
  23878. --insideCallback;
  23879. }
  23880. }
  23881. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  23882. {
  23883. {
  23884. const ScopedLock sl (lock);
  23885. jassert (insideCallback == 0);
  23886. if (audioUnit != 0)
  23887. {
  23888. AudioUnitUninitialize (audioUnit);
  23889. CloseComponent (audioUnit);
  23890. audioUnit = 0;
  23891. }
  23892. }
  23893. juce_free (outputBufferList);
  23894. }
  23895. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  23896. {
  23897. zerostruct (componentDesc);
  23898. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  23899. return true;
  23900. const File file (fileOrIdentifier);
  23901. if (! file.hasFileExtension (T(".component")))
  23902. return false;
  23903. const char* const utf8 = fileOrIdentifier.toUTF8();
  23904. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23905. strlen (utf8), file.isDirectory());
  23906. if (url != 0)
  23907. {
  23908. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23909. CFRelease (url);
  23910. if (bundleRef != 0)
  23911. {
  23912. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23913. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  23914. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  23915. if (pluginName.isEmpty())
  23916. pluginName = file.getFileNameWithoutExtension();
  23917. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  23918. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  23919. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  23920. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  23921. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  23922. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  23923. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23924. UseResFile (resFileId);
  23925. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  23926. {
  23927. Handle h = Get1IndResource ('thng', i);
  23928. if (h != 0)
  23929. {
  23930. HLock (h);
  23931. const uint32* const types = (const uint32*) *h;
  23932. if (types[0] == kAudioUnitType_MusicDevice
  23933. || types[0] == kAudioUnitType_MusicEffect
  23934. || types[0] == kAudioUnitType_Effect
  23935. || types[0] == kAudioUnitType_Generator
  23936. || types[0] == kAudioUnitType_Panner)
  23937. {
  23938. componentDesc.componentType = types[0];
  23939. componentDesc.componentSubType = types[1];
  23940. componentDesc.componentManufacturer = types[2];
  23941. break;
  23942. }
  23943. HUnlock (h);
  23944. ReleaseResource (h);
  23945. }
  23946. }
  23947. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23948. CFRelease (bundleRef);
  23949. }
  23950. }
  23951. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  23952. }
  23953. void AudioUnitPluginInstance::initialise()
  23954. {
  23955. if (initialised || audioUnit == 0)
  23956. return;
  23957. log (T("Initialising AU: ") + pluginName);
  23958. parameterIds.clear();
  23959. {
  23960. UInt32 paramListSize = 0;
  23961. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23962. 0, 0, &paramListSize);
  23963. if (paramListSize > 0)
  23964. {
  23965. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  23966. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23967. 0, &parameterIds.getReference(0), &paramListSize);
  23968. }
  23969. }
  23970. {
  23971. AURenderCallbackStruct info;
  23972. zerostruct (info);
  23973. info.inputProcRefCon = this;
  23974. info.inputProc = renderGetInputCallback;
  23975. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  23976. 0, &info, sizeof (info));
  23977. }
  23978. {
  23979. HostCallbackInfo info;
  23980. zerostruct (info);
  23981. info.hostUserData = this;
  23982. info.beatAndTempoProc = getBeatAndTempoCallback;
  23983. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  23984. info.transportStateProc = getTransportStateCallback;
  23985. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  23986. 0, &info, sizeof (info));
  23987. }
  23988. int numIns, numOuts;
  23989. getNumChannels (numIns, numOuts);
  23990. setPlayConfigDetails (numIns, numOuts, 0, 0);
  23991. initialised = AudioUnitInitialize (audioUnit) == noErr;
  23992. setLatencySamples (0);
  23993. }
  23994. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  23995. int samplesPerBlockExpected)
  23996. {
  23997. initialise();
  23998. if (initialised)
  23999. {
  24000. int numIns, numOuts;
  24001. getNumChannels (numIns, numOuts);
  24002. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24003. Float64 latencySecs = 0.0;
  24004. UInt32 latencySize = sizeof (latencySecs);
  24005. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24006. 0, &latencySecs, &latencySize);
  24007. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  24008. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24009. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24010. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24011. AudioStreamBasicDescription stream;
  24012. zerostruct (stream);
  24013. stream.mSampleRate = sampleRate_;
  24014. stream.mFormatID = kAudioFormatLinearPCM;
  24015. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24016. stream.mFramesPerPacket = 1;
  24017. stream.mBytesPerPacket = 4;
  24018. stream.mBytesPerFrame = 4;
  24019. stream.mBitsPerChannel = 32;
  24020. stream.mChannelsPerFrame = numIns;
  24021. OSStatus err = AudioUnitSetProperty (audioUnit,
  24022. kAudioUnitProperty_StreamFormat,
  24023. kAudioUnitScope_Input,
  24024. 0, &stream, sizeof (stream));
  24025. stream.mChannelsPerFrame = numOuts;
  24026. err = AudioUnitSetProperty (audioUnit,
  24027. kAudioUnitProperty_StreamFormat,
  24028. kAudioUnitScope_Output,
  24029. 0, &stream, sizeof (stream));
  24030. juce_free (outputBufferList);
  24031. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  24032. outputBufferList->mNumberBuffers = numOuts;
  24033. for (int i = numOuts; --i >= 0;)
  24034. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24035. zerostruct (timeStamp);
  24036. timeStamp.mSampleTime = 0;
  24037. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24038. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24039. currentBuffer = 0;
  24040. wasPlaying = false;
  24041. }
  24042. }
  24043. void AudioUnitPluginInstance::releaseResources()
  24044. {
  24045. if (initialised)
  24046. {
  24047. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24048. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24049. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24050. juce_free (outputBufferList);
  24051. outputBufferList = 0;
  24052. currentBuffer = 0;
  24053. }
  24054. }
  24055. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24056. const AudioTimeStamp* inTimeStamp,
  24057. UInt32 inBusNumber,
  24058. UInt32 inNumberFrames,
  24059. AudioBufferList* ioData) const
  24060. {
  24061. if (inBusNumber == 0
  24062. && currentBuffer != 0)
  24063. {
  24064. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24065. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24066. {
  24067. if (i < currentBuffer->getNumChannels())
  24068. {
  24069. memcpy (ioData->mBuffers[i].mData,
  24070. currentBuffer->getSampleData (i, 0),
  24071. sizeof (float) * inNumberFrames);
  24072. }
  24073. else
  24074. {
  24075. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24076. }
  24077. }
  24078. }
  24079. return noErr;
  24080. }
  24081. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24082. MidiBuffer& midiMessages)
  24083. {
  24084. const int numSamples = buffer.getNumSamples();
  24085. if (initialised)
  24086. {
  24087. AudioUnitRenderActionFlags flags = 0;
  24088. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24089. for (int i = getNumOutputChannels(); --i >= 0;)
  24090. {
  24091. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24092. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24093. }
  24094. currentBuffer = &buffer;
  24095. if (wantsMidiMessages)
  24096. {
  24097. const uint8* midiEventData;
  24098. int midiEventSize, midiEventPosition;
  24099. MidiBuffer::Iterator i (midiMessages);
  24100. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24101. {
  24102. if (midiEventSize <= 3)
  24103. MusicDeviceMIDIEvent (audioUnit,
  24104. midiEventData[0], midiEventData[1], midiEventData[2],
  24105. midiEventPosition);
  24106. else
  24107. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24108. }
  24109. midiMessages.clear();
  24110. }
  24111. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24112. 0, numSamples, outputBufferList);
  24113. timeStamp.mSampleTime += numSamples;
  24114. }
  24115. else
  24116. {
  24117. // Not initialised, so just bypass..
  24118. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24119. buffer.clear (i, 0, buffer.getNumSamples());
  24120. }
  24121. }
  24122. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24123. {
  24124. AudioPlayHead* const ph = getPlayHead();
  24125. AudioPlayHead::CurrentPositionInfo result;
  24126. if (ph != 0 && ph->getCurrentPosition (result))
  24127. {
  24128. if (outCurrentBeat != 0)
  24129. *outCurrentBeat = result.ppqPosition;
  24130. if (outCurrentTempo != 0)
  24131. *outCurrentTempo = result.bpm;
  24132. }
  24133. else
  24134. {
  24135. if (outCurrentBeat != 0)
  24136. *outCurrentBeat = 0;
  24137. if (outCurrentTempo != 0)
  24138. *outCurrentTempo = 120.0;
  24139. }
  24140. return noErr;
  24141. }
  24142. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24143. Float32* outTimeSig_Numerator,
  24144. UInt32* outTimeSig_Denominator,
  24145. Float64* outCurrentMeasureDownBeat) const
  24146. {
  24147. AudioPlayHead* const ph = getPlayHead();
  24148. AudioPlayHead::CurrentPositionInfo result;
  24149. if (ph != 0 && ph->getCurrentPosition (result))
  24150. {
  24151. if (outTimeSig_Numerator != 0)
  24152. *outTimeSig_Numerator = result.timeSigNumerator;
  24153. if (outTimeSig_Denominator != 0)
  24154. *outTimeSig_Denominator = result.timeSigDenominator;
  24155. if (outDeltaSampleOffsetToNextBeat != 0)
  24156. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24157. if (outCurrentMeasureDownBeat != 0)
  24158. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24159. }
  24160. else
  24161. {
  24162. if (outDeltaSampleOffsetToNextBeat != 0)
  24163. *outDeltaSampleOffsetToNextBeat = 0;
  24164. if (outTimeSig_Numerator != 0)
  24165. *outTimeSig_Numerator = 4;
  24166. if (outTimeSig_Denominator != 0)
  24167. *outTimeSig_Denominator = 4;
  24168. if (outCurrentMeasureDownBeat != 0)
  24169. *outCurrentMeasureDownBeat = 0;
  24170. }
  24171. return noErr;
  24172. }
  24173. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24174. Boolean* outTransportStateChanged,
  24175. Float64* outCurrentSampleInTimeLine,
  24176. Boolean* outIsCycling,
  24177. Float64* outCycleStartBeat,
  24178. Float64* outCycleEndBeat)
  24179. {
  24180. AudioPlayHead* const ph = getPlayHead();
  24181. AudioPlayHead::CurrentPositionInfo result;
  24182. if (ph != 0 && ph->getCurrentPosition (result))
  24183. {
  24184. if (outIsPlaying != 0)
  24185. *outIsPlaying = result.isPlaying;
  24186. if (outTransportStateChanged != 0)
  24187. {
  24188. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24189. wasPlaying = result.isPlaying;
  24190. }
  24191. if (outCurrentSampleInTimeLine != 0)
  24192. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  24193. if (outIsCycling != 0)
  24194. *outIsCycling = false;
  24195. if (outCycleStartBeat != 0)
  24196. *outCycleStartBeat = 0;
  24197. if (outCycleEndBeat != 0)
  24198. *outCycleEndBeat = 0;
  24199. }
  24200. else
  24201. {
  24202. if (outIsPlaying != 0)
  24203. *outIsPlaying = false;
  24204. if (outTransportStateChanged != 0)
  24205. *outTransportStateChanged = false;
  24206. if (outCurrentSampleInTimeLine != 0)
  24207. *outCurrentSampleInTimeLine = 0;
  24208. if (outIsCycling != 0)
  24209. *outIsCycling = false;
  24210. if (outCycleStartBeat != 0)
  24211. *outCycleStartBeat = 0;
  24212. if (outCycleEndBeat != 0)
  24213. *outCycleEndBeat = 0;
  24214. }
  24215. return noErr;
  24216. }
  24217. static VoidArray activeWindows;
  24218. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24219. {
  24220. public:
  24221. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24222. : AudioProcessorEditor (&plugin_),
  24223. plugin (plugin_),
  24224. wrapper (0)
  24225. {
  24226. addAndMakeVisible (wrapper = new NSViewComponent());
  24227. activeWindows.add (this);
  24228. setOpaque (true);
  24229. setVisible (true);
  24230. setSize (100, 100);
  24231. createView (createGenericViewIfNeeded);
  24232. }
  24233. ~AudioUnitPluginWindowCocoa()
  24234. {
  24235. const bool wasValid = isValid();
  24236. wrapper->setView (0);
  24237. activeWindows.removeValue (this);
  24238. if (wasValid)
  24239. plugin.editorBeingDeleted (this);
  24240. delete wrapper;
  24241. }
  24242. bool isValid() const { return wrapper->getView() != 0; }
  24243. void paint (Graphics& g)
  24244. {
  24245. g.fillAll (Colours::white);
  24246. }
  24247. void resized()
  24248. {
  24249. wrapper->setSize (getWidth(), getHeight());
  24250. }
  24251. private:
  24252. AudioUnitPluginInstance& plugin;
  24253. NSViewComponent* wrapper;
  24254. bool createView (const bool createGenericViewIfNeeded)
  24255. {
  24256. NSView* pluginView = 0;
  24257. UInt32 dataSize = 0;
  24258. Boolean isWritable = false;
  24259. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24260. 0, &dataSize, &isWritable) == noErr
  24261. && dataSize != 0
  24262. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24263. 0, &dataSize, &isWritable) == noErr)
  24264. {
  24265. AudioUnitCocoaViewInfo* info = (AudioUnitCocoaViewInfo*) juce_calloc (dataSize);
  24266. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24267. 0, info, &dataSize) == noErr)
  24268. {
  24269. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24270. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24271. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24272. Class viewClass = [viewBundle classNamed: viewClassName];
  24273. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24274. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24275. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24276. {
  24277. id factory = [[[viewClass alloc] init] autorelease];
  24278. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24279. withSize: NSMakeSize (getWidth(), getHeight())];
  24280. }
  24281. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24282. {
  24283. CFRelease (info->mCocoaAUViewClass[i]);
  24284. CFRelease (info->mCocoaAUViewBundleLocation);
  24285. }
  24286. }
  24287. juce_free (info);
  24288. }
  24289. if (createGenericViewIfNeeded && (pluginView == 0))
  24290. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24291. wrapper->setView (pluginView);
  24292. if (pluginView != 0)
  24293. setSize ([pluginView frame].size.width,
  24294. [pluginView frame].size.height);
  24295. return pluginView != 0;
  24296. }
  24297. };
  24298. #if JUCE_SUPPORT_CARBON
  24299. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24300. {
  24301. public:
  24302. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24303. : AudioProcessorEditor (&plugin_),
  24304. plugin (plugin_),
  24305. viewComponent (0)
  24306. {
  24307. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24308. activeWindows.add (this);
  24309. setOpaque (true);
  24310. setVisible (true);
  24311. setSize (400, 300);
  24312. ComponentDescription viewList [16];
  24313. UInt32 viewListSize = sizeof (viewList);
  24314. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24315. 0, &viewList, &viewListSize);
  24316. componentRecord = FindNextComponent (0, &viewList[0]);
  24317. }
  24318. ~AudioUnitPluginWindowCarbon()
  24319. {
  24320. deleteAndZero (innerWrapper);
  24321. activeWindows.removeValue (this);
  24322. if (isValid())
  24323. plugin.editorBeingDeleted (this);
  24324. }
  24325. bool isValid() const throw() { return componentRecord != 0; }
  24326. void paint (Graphics& g)
  24327. {
  24328. g.fillAll (Colours::black);
  24329. }
  24330. void resized()
  24331. {
  24332. innerWrapper->setSize (getWidth(), getHeight());
  24333. }
  24334. bool keyStateChanged (const bool)
  24335. {
  24336. return false;
  24337. }
  24338. bool keyPressed (const KeyPress&)
  24339. {
  24340. return false;
  24341. }
  24342. void broughtToFront()
  24343. {
  24344. activeWindows.removeValue (this);
  24345. activeWindows.add (this);
  24346. }
  24347. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24348. AudioUnitCarbonView getViewComponent()
  24349. {
  24350. if (viewComponent == 0 && componentRecord != 0)
  24351. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24352. return viewComponent;
  24353. }
  24354. void closeViewComponent()
  24355. {
  24356. if (viewComponent != 0)
  24357. {
  24358. CloseComponent (viewComponent);
  24359. viewComponent = 0;
  24360. }
  24361. }
  24362. juce_UseDebuggingNewOperator
  24363. private:
  24364. AudioUnitPluginInstance& plugin;
  24365. ComponentRecord* componentRecord;
  24366. AudioUnitCarbonView viewComponent;
  24367. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24368. {
  24369. public:
  24370. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24371. : owner (owner_)
  24372. {
  24373. }
  24374. ~InnerWrapperComponent()
  24375. {
  24376. deleteWindow();
  24377. }
  24378. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24379. {
  24380. log (T("Opening AU GUI: ") + owner->plugin.getName());
  24381. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24382. if (viewComponent == 0)
  24383. return 0;
  24384. Float32Point pos = { 0, 0 };
  24385. Float32Point size = { 250, 200 };
  24386. HIViewRef pluginView = 0;
  24387. AudioUnitCarbonViewCreate (viewComponent,
  24388. owner->getAudioUnit(),
  24389. windowRef,
  24390. rootView,
  24391. &pos,
  24392. &size,
  24393. (ControlRef*) &pluginView);
  24394. return pluginView;
  24395. }
  24396. void removeView (HIViewRef)
  24397. {
  24398. log (T("Closing AU GUI: ") + owner->plugin.getName());
  24399. owner->closeViewComponent();
  24400. }
  24401. private:
  24402. AudioUnitPluginWindowCarbon* const owner;
  24403. };
  24404. friend class InnerWrapperComponent;
  24405. InnerWrapperComponent* innerWrapper;
  24406. };
  24407. #endif
  24408. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24409. {
  24410. AudioProcessorEditor* w = new AudioUnitPluginWindowCocoa (*this, false);
  24411. if (! ((AudioUnitPluginWindowCocoa*) w)->isValid())
  24412. deleteAndZero (w);
  24413. #if JUCE_SUPPORT_CARBON
  24414. if (w == 0)
  24415. {
  24416. w = new AudioUnitPluginWindowCarbon (*this);
  24417. if (! ((AudioUnitPluginWindowCarbon*) w)->isValid())
  24418. deleteAndZero (w);
  24419. }
  24420. #endif
  24421. if (w == 0)
  24422. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24423. return w;
  24424. }
  24425. const String AudioUnitPluginInstance::getCategory() const
  24426. {
  24427. const char* result = 0;
  24428. switch (componentDesc.componentType)
  24429. {
  24430. case kAudioUnitType_Effect:
  24431. case kAudioUnitType_MusicEffect:
  24432. result = "Effect";
  24433. break;
  24434. case kAudioUnitType_MusicDevice:
  24435. result = "Synth";
  24436. break;
  24437. case kAudioUnitType_Generator:
  24438. result = "Generator";
  24439. break;
  24440. case kAudioUnitType_Panner:
  24441. result = "Panner";
  24442. break;
  24443. default:
  24444. break;
  24445. }
  24446. return result;
  24447. }
  24448. int AudioUnitPluginInstance::getNumParameters()
  24449. {
  24450. return parameterIds.size();
  24451. }
  24452. float AudioUnitPluginInstance::getParameter (int index)
  24453. {
  24454. const ScopedLock sl (lock);
  24455. Float32 value = 0.0f;
  24456. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24457. {
  24458. AudioUnitGetParameter (audioUnit,
  24459. (UInt32) parameterIds.getUnchecked (index),
  24460. kAudioUnitScope_Global, 0,
  24461. &value);
  24462. }
  24463. return value;
  24464. }
  24465. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24466. {
  24467. const ScopedLock sl (lock);
  24468. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24469. {
  24470. AudioUnitSetParameter (audioUnit,
  24471. (UInt32) parameterIds.getUnchecked (index),
  24472. kAudioUnitScope_Global, 0,
  24473. newValue, 0);
  24474. }
  24475. }
  24476. const String AudioUnitPluginInstance::getParameterName (int index)
  24477. {
  24478. AudioUnitParameterInfo info;
  24479. zerostruct (info);
  24480. UInt32 sz = sizeof (info);
  24481. String name;
  24482. if (AudioUnitGetProperty (audioUnit,
  24483. kAudioUnitProperty_ParameterInfo,
  24484. kAudioUnitScope_Global,
  24485. parameterIds [index], &info, &sz) == noErr)
  24486. {
  24487. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  24488. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  24489. else
  24490. name = String (info.name, sizeof (info.name));
  24491. }
  24492. return name;
  24493. }
  24494. const String AudioUnitPluginInstance::getParameterText (int index)
  24495. {
  24496. return String (getParameter (index));
  24497. }
  24498. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  24499. {
  24500. AudioUnitParameterInfo info;
  24501. UInt32 sz = sizeof (info);
  24502. if (AudioUnitGetProperty (audioUnit,
  24503. kAudioUnitProperty_ParameterInfo,
  24504. kAudioUnitScope_Global,
  24505. parameterIds [index], &info, &sz) == noErr)
  24506. {
  24507. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  24508. }
  24509. return true;
  24510. }
  24511. int AudioUnitPluginInstance::getNumPrograms()
  24512. {
  24513. CFArrayRef presets;
  24514. UInt32 sz = sizeof (CFArrayRef);
  24515. int num = 0;
  24516. if (AudioUnitGetProperty (audioUnit,
  24517. kAudioUnitProperty_FactoryPresets,
  24518. kAudioUnitScope_Global,
  24519. 0, &presets, &sz) == noErr)
  24520. {
  24521. num = (int) CFArrayGetCount (presets);
  24522. CFRelease (presets);
  24523. }
  24524. return num;
  24525. }
  24526. int AudioUnitPluginInstance::getCurrentProgram()
  24527. {
  24528. AUPreset current;
  24529. current.presetNumber = 0;
  24530. UInt32 sz = sizeof (AUPreset);
  24531. AudioUnitGetProperty (audioUnit,
  24532. kAudioUnitProperty_FactoryPresets,
  24533. kAudioUnitScope_Global,
  24534. 0, &current, &sz);
  24535. return current.presetNumber;
  24536. }
  24537. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  24538. {
  24539. AUPreset current;
  24540. current.presetNumber = newIndex;
  24541. current.presetName = 0;
  24542. AudioUnitSetProperty (audioUnit,
  24543. kAudioUnitProperty_FactoryPresets,
  24544. kAudioUnitScope_Global,
  24545. 0, &current, sizeof (AUPreset));
  24546. }
  24547. const String AudioUnitPluginInstance::getProgramName (int index)
  24548. {
  24549. String s;
  24550. CFArrayRef presets;
  24551. UInt32 sz = sizeof (CFArrayRef);
  24552. if (AudioUnitGetProperty (audioUnit,
  24553. kAudioUnitProperty_FactoryPresets,
  24554. kAudioUnitScope_Global,
  24555. 0, &presets, &sz) == noErr)
  24556. {
  24557. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  24558. {
  24559. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  24560. if (p != 0 && p->presetNumber == index)
  24561. {
  24562. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  24563. break;
  24564. }
  24565. }
  24566. CFRelease (presets);
  24567. }
  24568. return s;
  24569. }
  24570. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  24571. {
  24572. jassertfalse // xxx not implemented!
  24573. }
  24574. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  24575. {
  24576. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  24577. return T("Input ") + String (index + 1);
  24578. return String::empty;
  24579. }
  24580. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  24581. {
  24582. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  24583. return false;
  24584. return true;
  24585. }
  24586. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  24587. {
  24588. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  24589. return T("Output ") + String (index + 1);
  24590. return String::empty;
  24591. }
  24592. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  24593. {
  24594. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  24595. return false;
  24596. return true;
  24597. }
  24598. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  24599. {
  24600. getCurrentProgramStateInformation (destData);
  24601. }
  24602. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24603. {
  24604. CFPropertyListRef propertyList = 0;
  24605. UInt32 sz = sizeof (CFPropertyListRef);
  24606. if (AudioUnitGetProperty (audioUnit,
  24607. kAudioUnitProperty_ClassInfo,
  24608. kAudioUnitScope_Global,
  24609. 0, &propertyList, &sz) == noErr)
  24610. {
  24611. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  24612. CFWriteStreamOpen (stream);
  24613. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  24614. CFWriteStreamClose (stream);
  24615. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  24616. destData.setSize (bytesWritten);
  24617. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  24618. CFRelease (data);
  24619. CFRelease (stream);
  24620. CFRelease (propertyList);
  24621. }
  24622. }
  24623. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24624. {
  24625. setCurrentProgramStateInformation (data, sizeInBytes);
  24626. }
  24627. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24628. {
  24629. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  24630. (const UInt8*) data,
  24631. sizeInBytes,
  24632. kCFAllocatorNull);
  24633. CFReadStreamOpen (stream);
  24634. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  24635. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  24636. stream,
  24637. 0,
  24638. kCFPropertyListImmutable,
  24639. &format,
  24640. 0);
  24641. CFRelease (stream);
  24642. if (propertyList != 0)
  24643. AudioUnitSetProperty (audioUnit,
  24644. kAudioUnitProperty_ClassInfo,
  24645. kAudioUnitScope_Global,
  24646. 0, &propertyList, sizeof (propertyList));
  24647. }
  24648. AudioUnitPluginFormat::AudioUnitPluginFormat()
  24649. {
  24650. }
  24651. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  24652. {
  24653. }
  24654. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24655. const String& fileOrIdentifier)
  24656. {
  24657. if (! fileMightContainThisPluginType (fileOrIdentifier))
  24658. return;
  24659. PluginDescription desc;
  24660. desc.fileOrIdentifier = fileOrIdentifier;
  24661. desc.uid = 0;
  24662. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  24663. if (instance == 0)
  24664. return;
  24665. try
  24666. {
  24667. instance->fillInPluginDescription (desc);
  24668. results.add (new PluginDescription (desc));
  24669. }
  24670. catch (...)
  24671. {
  24672. // crashed while loading...
  24673. }
  24674. deleteAndZero (instance);
  24675. }
  24676. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24677. {
  24678. AudioUnitPluginInstance* result = 0;
  24679. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  24680. {
  24681. result = new AudioUnitPluginInstance (desc.fileOrIdentifier);
  24682. if (result->audioUnit != 0)
  24683. {
  24684. result->initialise();
  24685. }
  24686. else
  24687. {
  24688. deleteAndZero (result);
  24689. }
  24690. }
  24691. return result;
  24692. }
  24693. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  24694. const bool /*recursive*/)
  24695. {
  24696. StringArray result;
  24697. ComponentRecord* comp = 0;
  24698. ComponentDescription desc;
  24699. zerostruct (desc);
  24700. for (;;)
  24701. {
  24702. zerostruct (desc);
  24703. comp = FindNextComponent (comp, &desc);
  24704. if (comp == 0)
  24705. break;
  24706. GetComponentInfo (comp, &desc, 0, 0, 0);
  24707. if (desc.componentType == kAudioUnitType_MusicDevice
  24708. || desc.componentType == kAudioUnitType_MusicEffect
  24709. || desc.componentType == kAudioUnitType_Effect
  24710. || desc.componentType == kAudioUnitType_Generator
  24711. || desc.componentType == kAudioUnitType_Panner)
  24712. {
  24713. const String s (createAUPluginIdentifier (desc));
  24714. DBG (s);
  24715. result.add (s);
  24716. }
  24717. }
  24718. return result;
  24719. }
  24720. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  24721. {
  24722. ComponentDescription desc;
  24723. String name, version, manufacturer;
  24724. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  24725. return FindNextComponent (0, &desc) != 0;
  24726. const File f (fileOrIdentifier);
  24727. return f.hasFileExtension (T(".component"))
  24728. && f.isDirectory();
  24729. }
  24730. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  24731. {
  24732. ComponentDescription desc;
  24733. String name, version, manufacturer;
  24734. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  24735. if (name.isEmpty())
  24736. name = fileOrIdentifier;
  24737. return name;
  24738. }
  24739. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  24740. {
  24741. return File (desc.fileOrIdentifier).exists();
  24742. }
  24743. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  24744. {
  24745. return FileSearchPath ("/(Default AudioUnit locations)");
  24746. }
  24747. #endif
  24748. END_JUCE_NAMESPACE
  24749. #undef log
  24750. #endif
  24751. /********* End of inlined file: juce_AudioUnitPluginFormat.mm *********/
  24752. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  24753. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  24754. #define JUCE_MAC_VST_INCLUDED 1
  24755. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  24756. #if JUCE_PLUGINHOST_VST
  24757. #if (defined (_WIN32) || defined (_WIN64))
  24758. #undef _WIN32_WINNT
  24759. #define _WIN32_WINNT 0x500
  24760. #undef STRICT
  24761. #define STRICT
  24762. #include <windows.h>
  24763. #include <float.h>
  24764. #pragma warning (disable : 4312 4355)
  24765. #elif defined (LINUX) || defined (__linux__)
  24766. #include <float.h>
  24767. #include <sys/time.h>
  24768. #include <X11/Xlib.h>
  24769. #include <X11/Xutil.h>
  24770. #include <X11/Xatom.h>
  24771. #undef Font
  24772. #undef KeyPress
  24773. #undef Drawable
  24774. #undef Time
  24775. #else
  24776. #ifndef JUCE_MAC_VST_INCLUDED
  24777. // On the mac, this file needs to be compiled indirectly, by using
  24778. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  24779. #error
  24780. #endif
  24781. #include <Cocoa/Cocoa.h>
  24782. #include <Carbon/Carbon.h>
  24783. #endif
  24784. #if ! (JUCE_MAC && JUCE_64BIT)
  24785. BEGIN_JUCE_NAMESPACE
  24786. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24787. #endif
  24788. #undef PRAGMA_ALIGN_SUPPORTED
  24789. #define VST_FORCE_DEPRECATED 0
  24790. #ifdef _MSC_VER
  24791. #pragma warning (push)
  24792. #pragma warning (disable: 4996)
  24793. #endif
  24794. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  24795. your include path if you want to add VST support.
  24796. If you're not interested in VSTs, you can disable them by changing the
  24797. JUCE_PLUGINHOST_VST flag in juce_Config.h
  24798. */
  24799. #include "pluginterfaces/vst2.x/aeffectx.h"
  24800. #ifdef _MSC_VER
  24801. #pragma warning (pop)
  24802. #endif
  24803. #if JUCE_LINUX
  24804. #define Font JUCE_NAMESPACE::Font
  24805. #define KeyPress JUCE_NAMESPACE::KeyPress
  24806. #define Drawable JUCE_NAMESPACE::Drawable
  24807. #define Time JUCE_NAMESPACE::Time
  24808. #endif
  24809. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  24810. #ifdef __aeffect__
  24811. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24812. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24813. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  24814. events to the list.
  24815. This is used by both the VST hosting code and the plugin wrapper.
  24816. */
  24817. class VSTMidiEventList
  24818. {
  24819. public:
  24820. VSTMidiEventList()
  24821. : events (0), numEventsUsed (0), numEventsAllocated (0)
  24822. {
  24823. }
  24824. ~VSTMidiEventList()
  24825. {
  24826. freeEvents();
  24827. }
  24828. void clear()
  24829. {
  24830. numEventsUsed = 0;
  24831. if (events != 0)
  24832. events->numEvents = 0;
  24833. }
  24834. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  24835. {
  24836. ensureSize (numEventsUsed + 1);
  24837. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  24838. events->numEvents = ++numEventsUsed;
  24839. if (numBytes <= 4)
  24840. {
  24841. if (e->type == kVstSysExType)
  24842. {
  24843. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24844. e->type = kVstMidiType;
  24845. e->byteSize = sizeof (VstMidiEvent);
  24846. e->noteLength = 0;
  24847. e->noteOffset = 0;
  24848. e->detune = 0;
  24849. e->noteOffVelocity = 0;
  24850. }
  24851. e->deltaFrames = frameOffset;
  24852. memcpy (e->midiData, midiData, numBytes);
  24853. }
  24854. else
  24855. {
  24856. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  24857. if (se->type == kVstSysExType)
  24858. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  24859. else
  24860. se->sysexDump = (char*) juce_malloc (numBytes);
  24861. memcpy (se->sysexDump, midiData, numBytes);
  24862. se->type = kVstSysExType;
  24863. se->byteSize = sizeof (VstMidiSysexEvent);
  24864. se->deltaFrames = frameOffset;
  24865. se->flags = 0;
  24866. se->dumpBytes = numBytes;
  24867. se->resvd1 = 0;
  24868. se->resvd2 = 0;
  24869. }
  24870. }
  24871. // Handy method to pull the events out of an event buffer supplied by the host
  24872. // or plugin.
  24873. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  24874. {
  24875. for (int i = 0; i < events->numEvents; ++i)
  24876. {
  24877. const VstEvent* const e = events->events[i];
  24878. if (e != 0)
  24879. {
  24880. if (e->type == kVstMidiType)
  24881. {
  24882. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  24883. 4, e->deltaFrames);
  24884. }
  24885. else if (e->type == kVstSysExType)
  24886. {
  24887. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  24888. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  24889. e->deltaFrames);
  24890. }
  24891. }
  24892. }
  24893. }
  24894. void ensureSize (int numEventsNeeded)
  24895. {
  24896. if (numEventsNeeded > numEventsAllocated)
  24897. {
  24898. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24899. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24900. if (events == 0)
  24901. events = (VstEvents*) juce_calloc (size);
  24902. else
  24903. events = (VstEvents*) juce_realloc (events, size);
  24904. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  24905. {
  24906. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  24907. (int) sizeof (VstMidiSysexEvent)));
  24908. e->type = kVstMidiType;
  24909. e->byteSize = sizeof (VstMidiEvent);
  24910. events->events[i] = (VstEvent*) e;
  24911. }
  24912. numEventsAllocated = numEventsNeeded;
  24913. }
  24914. }
  24915. void freeEvents()
  24916. {
  24917. if (events != 0)
  24918. {
  24919. for (int i = numEventsAllocated; --i >= 0;)
  24920. {
  24921. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  24922. if (e->type == kVstSysExType)
  24923. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24924. juce_free (e);
  24925. }
  24926. juce_free (events);
  24927. events = 0;
  24928. numEventsUsed = 0;
  24929. numEventsAllocated = 0;
  24930. }
  24931. }
  24932. VstEvents* events;
  24933. private:
  24934. int numEventsUsed, numEventsAllocated;
  24935. };
  24936. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24937. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24938. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  24939. #if ! JUCE_WIN32
  24940. #define _fpreset()
  24941. #define _clearfp()
  24942. #endif
  24943. extern void juce_callAnyTimersSynchronously();
  24944. const int fxbVersionNum = 1;
  24945. struct fxProgram
  24946. {
  24947. long chunkMagic; // 'CcnK'
  24948. long byteSize; // of this chunk, excl. magic + byteSize
  24949. long fxMagic; // 'FxCk'
  24950. long version;
  24951. long fxID; // fx unique id
  24952. long fxVersion;
  24953. long numParams;
  24954. char prgName[28];
  24955. float params[1]; // variable no. of parameters
  24956. };
  24957. struct fxSet
  24958. {
  24959. long chunkMagic; // 'CcnK'
  24960. long byteSize; // of this chunk, excl. magic + byteSize
  24961. long fxMagic; // 'FxBk'
  24962. long version;
  24963. long fxID; // fx unique id
  24964. long fxVersion;
  24965. long numPrograms;
  24966. char future[128];
  24967. fxProgram programs[1]; // variable no. of programs
  24968. };
  24969. struct fxChunkSet
  24970. {
  24971. long chunkMagic; // 'CcnK'
  24972. long byteSize; // of this chunk, excl. magic + byteSize
  24973. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24974. long version;
  24975. long fxID; // fx unique id
  24976. long fxVersion;
  24977. long numPrograms;
  24978. char future[128];
  24979. long chunkSize;
  24980. char chunk[8]; // variable
  24981. };
  24982. struct fxProgramSet
  24983. {
  24984. long chunkMagic; // 'CcnK'
  24985. long byteSize; // of this chunk, excl. magic + byteSize
  24986. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24987. long version;
  24988. long fxID; // fx unique id
  24989. long fxVersion;
  24990. long numPrograms;
  24991. char name[28];
  24992. long chunkSize;
  24993. char chunk[8]; // variable
  24994. };
  24995. #ifdef JUCE_LITTLE_ENDIAN
  24996. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  24997. static float vst_swapFloat (const float x) throw()
  24998. {
  24999. union { uint32 asInt; float asFloat; } n;
  25000. n.asFloat = x;
  25001. n.asInt = swapByteOrder (n.asInt);
  25002. return n.asFloat;
  25003. }
  25004. #else
  25005. #define vst_swap(x) (x)
  25006. #define vst_swapFloat(x) (x)
  25007. #endif
  25008. typedef AEffect* (*MainCall) (audioMasterCallback);
  25009. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25010. static int shellUIDToCreate = 0;
  25011. static int insideVSTCallback = 0;
  25012. class VSTPluginWindow;
  25013. // Change this to disable logging of various VST activities
  25014. #ifndef VST_LOGGING
  25015. #define VST_LOGGING 1
  25016. #endif
  25017. #if VST_LOGGING
  25018. #define log(a) Logger::writeToLog(a);
  25019. #else
  25020. #define log(a)
  25021. #endif
  25022. #if JUCE_MAC && JUCE_PPC
  25023. static void* NewCFMFromMachO (void* const machofp) throw()
  25024. {
  25025. void* result = juce_malloc (8);
  25026. ((void**) result)[0] = machofp;
  25027. ((void**) result)[1] = result;
  25028. return result;
  25029. }
  25030. #endif
  25031. #if JUCE_LINUX
  25032. extern Display* display;
  25033. extern XContext improbableNumber;
  25034. typedef void (*EventProcPtr) (XEvent* ev);
  25035. static bool xErrorTriggered;
  25036. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25037. {
  25038. xErrorTriggered = true;
  25039. return 0;
  25040. }
  25041. static int getPropertyFromXWindow (Window handle, Atom atom)
  25042. {
  25043. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25044. xErrorTriggered = false;
  25045. int userSize;
  25046. unsigned long bytes, userCount;
  25047. unsigned char* data;
  25048. Atom userType;
  25049. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25050. &userType, &userSize, &userCount, &bytes, &data);
  25051. XSetErrorHandler (oldErrorHandler);
  25052. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25053. : 0;
  25054. }
  25055. static Window getChildWindow (Window windowToCheck)
  25056. {
  25057. Window rootWindow, parentWindow;
  25058. Window* childWindows;
  25059. unsigned int numChildren;
  25060. XQueryTree (display,
  25061. windowToCheck,
  25062. &rootWindow,
  25063. &parentWindow,
  25064. &childWindows,
  25065. &numChildren);
  25066. if (numChildren > 0)
  25067. return childWindows [0];
  25068. return 0;
  25069. }
  25070. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25071. {
  25072. if (e.mods.isLeftButtonDown())
  25073. {
  25074. ev.xbutton.button = Button1;
  25075. ev.xbutton.state |= Button1Mask;
  25076. }
  25077. else if (e.mods.isRightButtonDown())
  25078. {
  25079. ev.xbutton.button = Button3;
  25080. ev.xbutton.state |= Button3Mask;
  25081. }
  25082. else if (e.mods.isMiddleButtonDown())
  25083. {
  25084. ev.xbutton.button = Button2;
  25085. ev.xbutton.state |= Button2Mask;
  25086. }
  25087. }
  25088. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25089. {
  25090. if (e.mods.isLeftButtonDown())
  25091. ev.xmotion.state |= Button1Mask;
  25092. else if (e.mods.isRightButtonDown())
  25093. ev.xmotion.state |= Button3Mask;
  25094. else if (e.mods.isMiddleButtonDown())
  25095. ev.xmotion.state |= Button2Mask;
  25096. }
  25097. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25098. {
  25099. if (e.mods.isLeftButtonDown())
  25100. ev.xcrossing.state |= Button1Mask;
  25101. else if (e.mods.isRightButtonDown())
  25102. ev.xcrossing.state |= Button3Mask;
  25103. else if (e.mods.isMiddleButtonDown())
  25104. ev.xcrossing.state |= Button2Mask;
  25105. }
  25106. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25107. {
  25108. if (increment < 0)
  25109. {
  25110. ev.xbutton.button = Button5;
  25111. ev.xbutton.state |= Button5Mask;
  25112. }
  25113. else if (increment > 0)
  25114. {
  25115. ev.xbutton.button = Button4;
  25116. ev.xbutton.state |= Button4Mask;
  25117. }
  25118. }
  25119. #endif
  25120. static VoidArray activeModules;
  25121. class ModuleHandle : public ReferenceCountedObject
  25122. {
  25123. public:
  25124. File file;
  25125. MainCall moduleMain;
  25126. String pluginName;
  25127. static ModuleHandle* findOrCreateModule (const File& file)
  25128. {
  25129. for (int i = activeModules.size(); --i >= 0;)
  25130. {
  25131. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  25132. if (module->file == file)
  25133. return module;
  25134. }
  25135. _fpreset(); // (doesn't do any harm)
  25136. ++insideVSTCallback;
  25137. shellUIDToCreate = 0;
  25138. log ("Attempting to load VST: " + file.getFullPathName());
  25139. ModuleHandle* m = new ModuleHandle (file);
  25140. if (! m->open())
  25141. deleteAndZero (m);
  25142. --insideVSTCallback;
  25143. _fpreset(); // (doesn't do any harm)
  25144. return m;
  25145. }
  25146. ModuleHandle (const File& file_)
  25147. : file (file_),
  25148. moduleMain (0),
  25149. #if JUCE_WIN32 || JUCE_LINUX
  25150. hModule (0)
  25151. #elif JUCE_MAC
  25152. fragId (0),
  25153. resHandle (0),
  25154. bundleRef (0),
  25155. resFileId (0)
  25156. #endif
  25157. {
  25158. activeModules.add (this);
  25159. #if JUCE_WIN32 || JUCE_LINUX
  25160. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25161. #elif JUCE_MAC
  25162. FSRef ref;
  25163. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25164. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25165. #endif
  25166. }
  25167. ~ModuleHandle()
  25168. {
  25169. activeModules.removeValue (this);
  25170. close();
  25171. }
  25172. juce_UseDebuggingNewOperator
  25173. #if JUCE_WIN32 || JUCE_LINUX
  25174. void* hModule;
  25175. String fullParentDirectoryPathName;
  25176. bool open()
  25177. {
  25178. #if JUCE_WIN32
  25179. static bool timePeriodSet = false;
  25180. if (! timePeriodSet)
  25181. {
  25182. timePeriodSet = true;
  25183. timeBeginPeriod (2);
  25184. }
  25185. #endif
  25186. pluginName = file.getFileNameWithoutExtension();
  25187. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25188. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25189. if (moduleMain == 0)
  25190. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25191. return moduleMain != 0;
  25192. }
  25193. void close()
  25194. {
  25195. _fpreset(); // (doesn't do any harm)
  25196. PlatformUtilities::freeDynamicLibrary (hModule);
  25197. }
  25198. void closeEffect (AEffect* eff)
  25199. {
  25200. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25201. }
  25202. #else
  25203. CFragConnectionID fragId;
  25204. Handle resHandle;
  25205. CFBundleRef bundleRef;
  25206. FSSpec parentDirFSSpec;
  25207. short resFileId;
  25208. bool open()
  25209. {
  25210. bool ok = false;
  25211. const String filename (file.getFullPathName());
  25212. if (file.hasFileExtension (T(".vst")))
  25213. {
  25214. const char* const utf8 = filename.toUTF8();
  25215. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25216. strlen (utf8), file.isDirectory());
  25217. if (url != 0)
  25218. {
  25219. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25220. CFRelease (url);
  25221. if (bundleRef != 0)
  25222. {
  25223. if (CFBundleLoadExecutable (bundleRef))
  25224. {
  25225. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25226. if (moduleMain == 0)
  25227. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25228. if (moduleMain != 0)
  25229. {
  25230. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25231. if (name != 0)
  25232. {
  25233. if (CFGetTypeID (name) == CFStringGetTypeID())
  25234. {
  25235. char buffer[1024];
  25236. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25237. pluginName = buffer;
  25238. }
  25239. }
  25240. if (pluginName.isEmpty())
  25241. pluginName = file.getFileNameWithoutExtension();
  25242. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25243. ok = true;
  25244. }
  25245. }
  25246. if (! ok)
  25247. {
  25248. CFBundleUnloadExecutable (bundleRef);
  25249. CFRelease (bundleRef);
  25250. bundleRef = 0;
  25251. }
  25252. }
  25253. }
  25254. }
  25255. #if JUCE_PPC
  25256. else
  25257. {
  25258. FSRef fn;
  25259. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  25260. {
  25261. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25262. if (resFileId != -1)
  25263. {
  25264. const int numEffs = Count1Resources ('aEff');
  25265. for (int i = 0; i < numEffs; ++i)
  25266. {
  25267. resHandle = Get1IndResource ('aEff', i + 1);
  25268. if (resHandle != 0)
  25269. {
  25270. OSType type;
  25271. Str255 name;
  25272. SInt16 id;
  25273. GetResInfo (resHandle, &id, &type, name);
  25274. pluginName = String ((const char*) name + 1, name[0]);
  25275. DetachResource (resHandle);
  25276. HLock (resHandle);
  25277. Ptr ptr;
  25278. Str255 errorText;
  25279. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25280. name, kPrivateCFragCopy,
  25281. &fragId, &ptr, errorText);
  25282. if (err == noErr)
  25283. {
  25284. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25285. ok = true;
  25286. }
  25287. else
  25288. {
  25289. HUnlock (resHandle);
  25290. }
  25291. break;
  25292. }
  25293. }
  25294. if (! ok)
  25295. CloseResFile (resFileId);
  25296. }
  25297. }
  25298. }
  25299. #endif
  25300. return ok;
  25301. }
  25302. void close()
  25303. {
  25304. #if JUCE_PPC
  25305. if (fragId != 0)
  25306. {
  25307. if (moduleMain != 0)
  25308. disposeMachOFromCFM ((void*) moduleMain);
  25309. CloseConnection (&fragId);
  25310. HUnlock (resHandle);
  25311. if (resFileId != 0)
  25312. CloseResFile (resFileId);
  25313. }
  25314. else
  25315. #endif
  25316. if (bundleRef != 0)
  25317. {
  25318. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25319. if (CFGetRetainCount (bundleRef) == 1)
  25320. CFBundleUnloadExecutable (bundleRef);
  25321. if (CFGetRetainCount (bundleRef) > 0)
  25322. CFRelease (bundleRef);
  25323. }
  25324. }
  25325. void closeEffect (AEffect* eff)
  25326. {
  25327. #if JUCE_PPC
  25328. if (fragId != 0)
  25329. {
  25330. VoidArray thingsToDelete;
  25331. thingsToDelete.add ((void*) eff->dispatcher);
  25332. thingsToDelete.add ((void*) eff->process);
  25333. thingsToDelete.add ((void*) eff->setParameter);
  25334. thingsToDelete.add ((void*) eff->getParameter);
  25335. thingsToDelete.add ((void*) eff->processReplacing);
  25336. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25337. for (int i = thingsToDelete.size(); --i >= 0;)
  25338. disposeMachOFromCFM (thingsToDelete[i]);
  25339. }
  25340. else
  25341. #endif
  25342. {
  25343. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25344. }
  25345. }
  25346. #if JUCE_PPC
  25347. static void* newMachOFromCFM (void* cfmfp)
  25348. {
  25349. if (cfmfp == 0)
  25350. return 0;
  25351. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  25352. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25353. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25354. mfp[2] = 0x800c0000;
  25355. mfp[3] = 0x804c0004;
  25356. mfp[4] = 0x7c0903a6;
  25357. mfp[5] = 0x4e800420;
  25358. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25359. return mfp;
  25360. }
  25361. static void disposeMachOFromCFM (void* ptr)
  25362. {
  25363. juce_free (ptr);
  25364. }
  25365. void coerceAEffectFunctionCalls (AEffect* eff)
  25366. {
  25367. if (fragId != 0)
  25368. {
  25369. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25370. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25371. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25372. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25373. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25374. }
  25375. }
  25376. #endif
  25377. #endif
  25378. };
  25379. /**
  25380. An instance of a plugin, created by a VSTPluginFormat.
  25381. */
  25382. class VSTPluginInstance : public AudioPluginInstance,
  25383. private Timer,
  25384. private AsyncUpdater
  25385. {
  25386. public:
  25387. ~VSTPluginInstance();
  25388. // AudioPluginInstance methods:
  25389. void fillInPluginDescription (PluginDescription& desc) const
  25390. {
  25391. desc.name = name;
  25392. desc.fileOrIdentifier = module->file.getFullPathName();
  25393. desc.uid = getUID();
  25394. desc.lastFileModTime = module->file.getLastModificationTime();
  25395. desc.pluginFormatName = "VST";
  25396. desc.category = getCategory();
  25397. {
  25398. char buffer [kVstMaxVendorStrLen + 8];
  25399. zerostruct (buffer);
  25400. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25401. desc.manufacturerName = buffer;
  25402. }
  25403. desc.version = getVersion();
  25404. desc.numInputChannels = getNumInputChannels();
  25405. desc.numOutputChannels = getNumOutputChannels();
  25406. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25407. }
  25408. const String getName() const { return name; }
  25409. int getUID() const throw();
  25410. bool acceptsMidi() const { return wantsMidiMessages; }
  25411. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25412. // AudioProcessor methods:
  25413. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25414. void releaseResources();
  25415. void processBlock (AudioSampleBuffer& buffer,
  25416. MidiBuffer& midiMessages);
  25417. AudioProcessorEditor* createEditor();
  25418. const String getInputChannelName (const int index) const;
  25419. bool isInputChannelStereoPair (int index) const;
  25420. const String getOutputChannelName (const int index) const;
  25421. bool isOutputChannelStereoPair (int index) const;
  25422. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25423. float getParameter (int index);
  25424. void setParameter (int index, float newValue);
  25425. const String getParameterName (int index);
  25426. const String getParameterText (int index);
  25427. bool isParameterAutomatable (int index) const;
  25428. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25429. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25430. void setCurrentProgram (int index);
  25431. const String getProgramName (int index);
  25432. void changeProgramName (int index, const String& newName);
  25433. void getStateInformation (MemoryBlock& destData);
  25434. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25435. void setStateInformation (const void* data, int sizeInBytes);
  25436. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25437. void timerCallback();
  25438. void handleAsyncUpdate();
  25439. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25440. juce_UseDebuggingNewOperator
  25441. private:
  25442. friend class VSTPluginWindow;
  25443. friend class VSTPluginFormat;
  25444. AEffect* effect;
  25445. String name;
  25446. CriticalSection lock;
  25447. bool wantsMidiMessages, initialised, isPowerOn;
  25448. mutable StringArray programNames;
  25449. AudioSampleBuffer tempBuffer;
  25450. CriticalSection midiInLock;
  25451. MidiBuffer incomingMidi;
  25452. VSTMidiEventList midiEventsToSend;
  25453. VstTimeInfo vstHostTime;
  25454. float** channels;
  25455. ReferenceCountedObjectPtr <ModuleHandle> module;
  25456. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25457. bool restoreProgramSettings (const fxProgram* const prog);
  25458. const String getCurrentProgramName();
  25459. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25460. void updateStoredProgramNames();
  25461. void initialise();
  25462. void handleMidiFromPlugin (const VstEvents* const events);
  25463. void createTempParameterStore (MemoryBlock& dest);
  25464. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25465. const String getParameterLabel (int index) const;
  25466. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25467. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25468. void setChunkData (const char* data, int size, bool isPreset);
  25469. bool loadFromFXBFile (const void* data, int numBytes);
  25470. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25471. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25472. const String getVersion() const throw();
  25473. const String getCategory() const throw();
  25474. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25475. void setPower (const bool on);
  25476. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25477. };
  25478. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25479. : effect (0),
  25480. wantsMidiMessages (false),
  25481. initialised (false),
  25482. isPowerOn (false),
  25483. tempBuffer (1, 1),
  25484. channels (0),
  25485. module (module_)
  25486. {
  25487. try
  25488. {
  25489. _fpreset();
  25490. ++insideVSTCallback;
  25491. name = module->pluginName;
  25492. log (T("Creating VST instance: ") + name);
  25493. #if JUCE_MAC
  25494. if (module->resFileId != 0)
  25495. UseResFile (module->resFileId);
  25496. #if JUCE_PPC
  25497. if (module->fragId != 0)
  25498. {
  25499. static void* audioMasterCoerced = 0;
  25500. if (audioMasterCoerced == 0)
  25501. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  25502. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  25503. }
  25504. else
  25505. #endif
  25506. #endif
  25507. {
  25508. effect = module->moduleMain (&audioMaster);
  25509. }
  25510. --insideVSTCallback;
  25511. if (effect != 0 && effect->magic == kEffectMagic)
  25512. {
  25513. #if JUCE_PPC
  25514. module->coerceAEffectFunctionCalls (effect);
  25515. #endif
  25516. jassert (effect->resvd2 == 0);
  25517. jassert (effect->object != 0);
  25518. _fpreset(); // some dodgy plugs fuck around with this
  25519. }
  25520. else
  25521. {
  25522. effect = 0;
  25523. }
  25524. }
  25525. catch (...)
  25526. {
  25527. --insideVSTCallback;
  25528. }
  25529. }
  25530. VSTPluginInstance::~VSTPluginInstance()
  25531. {
  25532. {
  25533. const ScopedLock sl (lock);
  25534. jassert (insideVSTCallback == 0);
  25535. if (effect != 0 && effect->magic == kEffectMagic)
  25536. {
  25537. try
  25538. {
  25539. #if JUCE_MAC
  25540. if (module->resFileId != 0)
  25541. UseResFile (module->resFileId);
  25542. #endif
  25543. // Must delete any editors before deleting the plugin instance!
  25544. jassert (getActiveEditor() == 0);
  25545. _fpreset(); // some dodgy plugs fuck around with this
  25546. module->closeEffect (effect);
  25547. }
  25548. catch (...)
  25549. {}
  25550. }
  25551. module = 0;
  25552. effect = 0;
  25553. }
  25554. juce_free (channels);
  25555. channels = 0;
  25556. }
  25557. void VSTPluginInstance::initialise()
  25558. {
  25559. if (initialised || effect == 0)
  25560. return;
  25561. log (T("Initialising VST: ") + module->pluginName);
  25562. initialised = true;
  25563. dispatch (effIdentify, 0, 0, 0, 0);
  25564. // this code would ask the plugin for its name, but so few plugins
  25565. // actually bother implementing this correctly, that it's better to
  25566. // just ignore it and use the file name instead.
  25567. /* {
  25568. char buffer [256];
  25569. zerostruct (buffer);
  25570. dispatch (effGetEffectName, 0, 0, buffer, 0);
  25571. name = String (buffer).trim();
  25572. if (name.isEmpty())
  25573. name = module->pluginName;
  25574. }
  25575. */
  25576. if (getSampleRate() > 0)
  25577. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  25578. if (getBlockSize() > 0)
  25579. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  25580. dispatch (effOpen, 0, 0, 0, 0);
  25581. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25582. getSampleRate(), getBlockSize());
  25583. if (getNumPrograms() > 1)
  25584. setCurrentProgram (0);
  25585. else
  25586. dispatch (effSetProgram, 0, 0, 0, 0);
  25587. int i;
  25588. for (i = effect->numInputs; --i >= 0;)
  25589. dispatch (effConnectInput, i, 1, 0, 0);
  25590. for (i = effect->numOutputs; --i >= 0;)
  25591. dispatch (effConnectOutput, i, 1, 0, 0);
  25592. updateStoredProgramNames();
  25593. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  25594. setLatencySamples (effect->initialDelay);
  25595. }
  25596. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  25597. int samplesPerBlockExpected)
  25598. {
  25599. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25600. sampleRate_, samplesPerBlockExpected);
  25601. setLatencySamples (effect->initialDelay);
  25602. juce_free (channels);
  25603. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  25604. vstHostTime.tempo = 120.0;
  25605. vstHostTime.timeSigNumerator = 4;
  25606. vstHostTime.timeSigDenominator = 4;
  25607. vstHostTime.sampleRate = sampleRate_;
  25608. vstHostTime.samplePos = 0;
  25609. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  25610. initialise();
  25611. if (initialised)
  25612. {
  25613. wantsMidiMessages = wantsMidiMessages
  25614. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  25615. if (wantsMidiMessages)
  25616. midiEventsToSend.ensureSize (256);
  25617. else
  25618. midiEventsToSend.freeEvents();
  25619. incomingMidi.clear();
  25620. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  25621. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  25622. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  25623. if (! isPowerOn)
  25624. setPower (true);
  25625. // dodgy hack to force some plugins to initialise the sample rate..
  25626. if ((! hasEditor()) && getNumParameters() > 0)
  25627. {
  25628. const float old = getParameter (0);
  25629. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  25630. setParameter (0, old);
  25631. }
  25632. dispatch (effStartProcess, 0, 0, 0, 0);
  25633. }
  25634. }
  25635. void VSTPluginInstance::releaseResources()
  25636. {
  25637. if (initialised)
  25638. {
  25639. dispatch (effStopProcess, 0, 0, 0, 0);
  25640. setPower (false);
  25641. }
  25642. tempBuffer.setSize (1, 1);
  25643. incomingMidi.clear();
  25644. midiEventsToSend.freeEvents();
  25645. juce_free (channels);
  25646. channels = 0;
  25647. }
  25648. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25649. MidiBuffer& midiMessages)
  25650. {
  25651. const int numSamples = buffer.getNumSamples();
  25652. if (initialised)
  25653. {
  25654. AudioPlayHead* playHead = getPlayHead();
  25655. if (playHead != 0)
  25656. {
  25657. AudioPlayHead::CurrentPositionInfo position;
  25658. playHead->getCurrentPosition (position);
  25659. vstHostTime.tempo = position.bpm;
  25660. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  25661. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  25662. vstHostTime.ppqPos = position.ppqPosition;
  25663. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  25664. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  25665. if (position.isPlaying)
  25666. vstHostTime.flags |= kVstTransportPlaying;
  25667. else
  25668. vstHostTime.flags &= ~kVstTransportPlaying;
  25669. }
  25670. #if JUCE_WIN32
  25671. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  25672. #elif JUCE_LINUX
  25673. timeval micro;
  25674. gettimeofday (&micro, 0);
  25675. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  25676. #elif JUCE_MAC
  25677. UnsignedWide micro;
  25678. Microseconds (&micro);
  25679. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  25680. #endif
  25681. if (wantsMidiMessages)
  25682. {
  25683. midiEventsToSend.clear();
  25684. midiEventsToSend.ensureSize (1);
  25685. MidiBuffer::Iterator iter (midiMessages);
  25686. const uint8* midiData;
  25687. int numBytesOfMidiData, samplePosition;
  25688. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  25689. {
  25690. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  25691. jlimit (0, numSamples - 1, samplePosition));
  25692. }
  25693. try
  25694. {
  25695. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  25696. }
  25697. catch (...)
  25698. {}
  25699. }
  25700. int i;
  25701. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  25702. for (i = 0; i < maxChans; ++i)
  25703. channels[i] = buffer.getSampleData (i);
  25704. channels [maxChans] = 0;
  25705. _clearfp();
  25706. if ((effect->flags & effFlagsCanReplacing) != 0)
  25707. {
  25708. try
  25709. {
  25710. effect->processReplacing (effect, channels, channels, numSamples);
  25711. }
  25712. catch (...)
  25713. {}
  25714. }
  25715. else
  25716. {
  25717. tempBuffer.setSize (effect->numOutputs, numSamples);
  25718. tempBuffer.clear();
  25719. float* outs [64];
  25720. for (i = effect->numOutputs; --i >= 0;)
  25721. outs[i] = tempBuffer.getSampleData (i);
  25722. outs [effect->numOutputs] = 0;
  25723. try
  25724. {
  25725. effect->process (effect, channels, outs, numSamples);
  25726. }
  25727. catch (...)
  25728. {}
  25729. for (i = effect->numOutputs; --i >= 0;)
  25730. buffer.copyFrom (i, 0, outs[i], numSamples);
  25731. }
  25732. }
  25733. else
  25734. {
  25735. // Not initialised, so just bypass..
  25736. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25737. buffer.clear (i, 0, buffer.getNumSamples());
  25738. }
  25739. {
  25740. // copy any incoming midi..
  25741. const ScopedLock sl (midiInLock);
  25742. midiMessages = incomingMidi;
  25743. incomingMidi.clear();
  25744. }
  25745. }
  25746. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  25747. {
  25748. if (events != 0)
  25749. {
  25750. const ScopedLock sl (midiInLock);
  25751. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  25752. }
  25753. }
  25754. static Array <VSTPluginWindow*> activeVSTWindows;
  25755. class VSTPluginWindow : public AudioProcessorEditor,
  25756. #if ! JUCE_MAC
  25757. public ComponentMovementWatcher,
  25758. #endif
  25759. public Timer
  25760. {
  25761. public:
  25762. VSTPluginWindow (VSTPluginInstance& plugin_)
  25763. : AudioProcessorEditor (&plugin_),
  25764. #if ! JUCE_MAC
  25765. ComponentMovementWatcher (this),
  25766. #endif
  25767. plugin (plugin_),
  25768. isOpen (false),
  25769. wasShowing (false),
  25770. pluginRefusesToResize (false),
  25771. pluginWantsKeys (false),
  25772. alreadyInside (false),
  25773. recursiveResize (false)
  25774. {
  25775. #if JUCE_WIN32
  25776. sizeCheckCount = 0;
  25777. pluginHWND = 0;
  25778. #elif JUCE_LINUX
  25779. pluginWindow = None;
  25780. pluginProc = None;
  25781. #else
  25782. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25783. #endif
  25784. activeVSTWindows.add (this);
  25785. setSize (1, 1);
  25786. setOpaque (true);
  25787. setVisible (true);
  25788. }
  25789. ~VSTPluginWindow()
  25790. {
  25791. #if JUCE_MAC
  25792. deleteAndZero (innerWrapper);
  25793. #else
  25794. closePluginWindow();
  25795. #endif
  25796. activeVSTWindows.removeValue (this);
  25797. plugin.editorBeingDeleted (this);
  25798. }
  25799. #if ! JUCE_MAC
  25800. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  25801. {
  25802. if (recursiveResize)
  25803. return;
  25804. Component* const topComp = getTopLevelComponent();
  25805. if (topComp->getPeer() != 0)
  25806. {
  25807. int x = 0, y = 0;
  25808. relativePositionToOtherComponent (topComp, x, y);
  25809. recursiveResize = true;
  25810. #if JUCE_WIN32
  25811. if (pluginHWND != 0)
  25812. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  25813. #elif JUCE_LINUX
  25814. if (pluginWindow != 0)
  25815. {
  25816. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  25817. XMoveWindow (display, pluginWindow, x, y);
  25818. XMapRaised (display, pluginWindow);
  25819. }
  25820. #endif
  25821. recursiveResize = false;
  25822. }
  25823. }
  25824. void componentVisibilityChanged (Component&)
  25825. {
  25826. const bool isShowingNow = isShowing();
  25827. if (wasShowing != isShowingNow)
  25828. {
  25829. wasShowing = isShowingNow;
  25830. if (isShowingNow)
  25831. openPluginWindow();
  25832. else
  25833. closePluginWindow();
  25834. }
  25835. componentMovedOrResized (true, true);
  25836. }
  25837. void componentPeerChanged()
  25838. {
  25839. closePluginWindow();
  25840. openPluginWindow();
  25841. }
  25842. #endif
  25843. bool keyStateChanged (const bool)
  25844. {
  25845. return pluginWantsKeys;
  25846. }
  25847. bool keyPressed (const KeyPress&)
  25848. {
  25849. return pluginWantsKeys;
  25850. }
  25851. #if JUCE_MAC
  25852. void paint (Graphics& g)
  25853. {
  25854. g.fillAll (Colours::black);
  25855. }
  25856. #else
  25857. void paint (Graphics& g)
  25858. {
  25859. if (isOpen)
  25860. {
  25861. ComponentPeer* const peer = getPeer();
  25862. if (peer != 0)
  25863. {
  25864. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  25865. getScreenY() - peer->getScreenY(),
  25866. getWidth(), getHeight());
  25867. #if JUCE_LINUX
  25868. if (pluginWindow != 0)
  25869. {
  25870. const Rectangle clip (g.getClipBounds());
  25871. XEvent ev;
  25872. zerostruct (ev);
  25873. ev.xexpose.type = Expose;
  25874. ev.xexpose.display = display;
  25875. ev.xexpose.window = pluginWindow;
  25876. ev.xexpose.x = clip.getX();
  25877. ev.xexpose.y = clip.getY();
  25878. ev.xexpose.width = clip.getWidth();
  25879. ev.xexpose.height = clip.getHeight();
  25880. sendEventToChild (&ev);
  25881. }
  25882. #endif
  25883. }
  25884. }
  25885. else
  25886. {
  25887. g.fillAll (Colours::black);
  25888. }
  25889. }
  25890. #endif
  25891. void timerCallback()
  25892. {
  25893. #if JUCE_WIN32
  25894. if (--sizeCheckCount <= 0)
  25895. {
  25896. sizeCheckCount = 10;
  25897. checkPluginWindowSize();
  25898. }
  25899. #endif
  25900. try
  25901. {
  25902. static bool reentrant = false;
  25903. if (! reentrant)
  25904. {
  25905. reentrant = true;
  25906. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  25907. reentrant = false;
  25908. }
  25909. }
  25910. catch (...)
  25911. {}
  25912. }
  25913. void mouseDown (const MouseEvent& e)
  25914. {
  25915. #if JUCE_LINUX
  25916. if (pluginWindow == 0)
  25917. return;
  25918. toFront (true);
  25919. XEvent ev;
  25920. zerostruct (ev);
  25921. ev.xbutton.display = display;
  25922. ev.xbutton.type = ButtonPress;
  25923. ev.xbutton.window = pluginWindow;
  25924. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25925. ev.xbutton.time = CurrentTime;
  25926. ev.xbutton.x = e.x;
  25927. ev.xbutton.y = e.y;
  25928. ev.xbutton.x_root = e.getScreenX();
  25929. ev.xbutton.y_root = e.getScreenY();
  25930. translateJuceToXButtonModifiers (e, ev);
  25931. sendEventToChild (&ev);
  25932. #elif JUCE_WIN32
  25933. (void) e;
  25934. toFront (true);
  25935. #endif
  25936. }
  25937. void broughtToFront()
  25938. {
  25939. activeVSTWindows.removeValue (this);
  25940. activeVSTWindows.add (this);
  25941. #if JUCE_MAC
  25942. dispatch (effEditTop, 0, 0, 0, 0);
  25943. #endif
  25944. }
  25945. juce_UseDebuggingNewOperator
  25946. private:
  25947. VSTPluginInstance& plugin;
  25948. bool isOpen, wasShowing, recursiveResize;
  25949. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  25950. #if JUCE_WIN32
  25951. HWND pluginHWND;
  25952. void* originalWndProc;
  25953. int sizeCheckCount;
  25954. #elif JUCE_LINUX
  25955. Window pluginWindow;
  25956. EventProcPtr pluginProc;
  25957. #endif
  25958. #if JUCE_MAC
  25959. void openPluginWindow (WindowRef parentWindow)
  25960. {
  25961. if (isOpen || parentWindow == 0)
  25962. return;
  25963. isOpen = true;
  25964. ERect* rect = 0;
  25965. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25966. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  25967. // do this before and after like in the steinberg example
  25968. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25969. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25970. // Install keyboard hooks
  25971. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25972. // double-check it's not too tiny
  25973. int w = 250, h = 150;
  25974. if (rect != 0)
  25975. {
  25976. w = rect->right - rect->left;
  25977. h = rect->bottom - rect->top;
  25978. if (w == 0 || h == 0)
  25979. {
  25980. w = 250;
  25981. h = 150;
  25982. }
  25983. }
  25984. w = jmax (w, 32);
  25985. h = jmax (h, 32);
  25986. setSize (w, h);
  25987. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25988. repaint();
  25989. }
  25990. #else
  25991. void openPluginWindow()
  25992. {
  25993. if (isOpen || getWindowHandle() == 0)
  25994. return;
  25995. log (T("Opening VST UI: ") + plugin.name);
  25996. isOpen = true;
  25997. ERect* rect = 0;
  25998. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25999. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26000. // do this before and after like in the steinberg example
  26001. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26002. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26003. // Install keyboard hooks
  26004. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26005. #if JUCE_WIN32
  26006. originalWndProc = 0;
  26007. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26008. if (pluginHWND == 0)
  26009. {
  26010. isOpen = false;
  26011. setSize (300, 150);
  26012. return;
  26013. }
  26014. #pragma warning (push)
  26015. #pragma warning (disable: 4244)
  26016. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26017. if (! pluginWantsKeys)
  26018. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  26019. #pragma warning (pop)
  26020. int w, h;
  26021. RECT r;
  26022. GetWindowRect (pluginHWND, &r);
  26023. w = r.right - r.left;
  26024. h = r.bottom - r.top;
  26025. if (rect != 0)
  26026. {
  26027. const int rw = rect->right - rect->left;
  26028. const int rh = rect->bottom - rect->top;
  26029. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26030. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26031. {
  26032. // very dodgy logic to decide which size is right.
  26033. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26034. {
  26035. SetWindowPos (pluginHWND, 0,
  26036. 0, 0, rw, rh,
  26037. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26038. GetWindowRect (pluginHWND, &r);
  26039. w = r.right - r.left;
  26040. h = r.bottom - r.top;
  26041. pluginRefusesToResize = (w != rw) || (h != rh);
  26042. w = rw;
  26043. h = rh;
  26044. }
  26045. }
  26046. }
  26047. #elif JUCE_LINUX
  26048. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26049. if (pluginWindow != 0)
  26050. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26051. XInternAtom (display, "_XEventProc", False));
  26052. int w = 250, h = 150;
  26053. if (rect != 0)
  26054. {
  26055. w = rect->right - rect->left;
  26056. h = rect->bottom - rect->top;
  26057. if (w == 0 || h == 0)
  26058. {
  26059. w = 250;
  26060. h = 150;
  26061. }
  26062. }
  26063. if (pluginWindow != 0)
  26064. XMapRaised (display, pluginWindow);
  26065. #endif
  26066. // double-check it's not too tiny
  26067. w = jmax (w, 32);
  26068. h = jmax (h, 32);
  26069. setSize (w, h);
  26070. #if JUCE_WIN32
  26071. checkPluginWindowSize();
  26072. #endif
  26073. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26074. repaint();
  26075. }
  26076. #endif
  26077. #if ! JUCE_MAC
  26078. void closePluginWindow()
  26079. {
  26080. if (isOpen)
  26081. {
  26082. log (T("Closing VST UI: ") + plugin.getName());
  26083. isOpen = false;
  26084. dispatch (effEditClose, 0, 0, 0, 0);
  26085. #if JUCE_WIN32
  26086. #pragma warning (push)
  26087. #pragma warning (disable: 4244)
  26088. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26089. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  26090. #pragma warning (pop)
  26091. stopTimer();
  26092. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26093. DestroyWindow (pluginHWND);
  26094. pluginHWND = 0;
  26095. #elif JUCE_LINUX
  26096. stopTimer();
  26097. pluginWindow = 0;
  26098. pluginProc = 0;
  26099. #endif
  26100. }
  26101. }
  26102. #endif
  26103. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26104. {
  26105. return plugin.dispatch (opcode, index, value, ptr, opt);
  26106. }
  26107. #if JUCE_WIN32
  26108. void checkPluginWindowSize() throw()
  26109. {
  26110. RECT r;
  26111. GetWindowRect (pluginHWND, &r);
  26112. const int w = r.right - r.left;
  26113. const int h = r.bottom - r.top;
  26114. if (isShowing() && w > 0 && h > 0
  26115. && (w != getWidth() || h != getHeight())
  26116. && ! pluginRefusesToResize)
  26117. {
  26118. setSize (w, h);
  26119. sizeCheckCount = 0;
  26120. }
  26121. }
  26122. // hooks to get keyboard events from VST windows..
  26123. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26124. {
  26125. for (int i = activeVSTWindows.size(); --i >= 0;)
  26126. {
  26127. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26128. if (w->pluginHWND == hW)
  26129. {
  26130. if (message == WM_CHAR
  26131. || message == WM_KEYDOWN
  26132. || message == WM_SYSKEYDOWN
  26133. || message == WM_KEYUP
  26134. || message == WM_SYSKEYUP
  26135. || message == WM_APPCOMMAND)
  26136. {
  26137. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26138. message, wParam, lParam);
  26139. }
  26140. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26141. (HWND) w->pluginHWND,
  26142. message,
  26143. wParam,
  26144. lParam);
  26145. }
  26146. }
  26147. return DefWindowProc (hW, message, wParam, lParam);
  26148. }
  26149. #endif
  26150. #if JUCE_LINUX
  26151. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26152. void sendEventToChild (XEvent* event)
  26153. {
  26154. if (pluginProc != 0)
  26155. {
  26156. // if the plugin publishes an event procedure, pass the event directly..
  26157. pluginProc (event);
  26158. }
  26159. else if (pluginWindow != 0)
  26160. {
  26161. // if the plugin has a window, then send the event to the window so that
  26162. // its message thread will pick it up..
  26163. XSendEvent (display, pluginWindow, False, 0L, event);
  26164. XFlush (display);
  26165. }
  26166. }
  26167. void mouseEnter (const MouseEvent& e)
  26168. {
  26169. if (pluginWindow != 0)
  26170. {
  26171. XEvent ev;
  26172. zerostruct (ev);
  26173. ev.xcrossing.display = display;
  26174. ev.xcrossing.type = EnterNotify;
  26175. ev.xcrossing.window = pluginWindow;
  26176. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26177. ev.xcrossing.time = CurrentTime;
  26178. ev.xcrossing.x = e.x;
  26179. ev.xcrossing.y = e.y;
  26180. ev.xcrossing.x_root = e.getScreenX();
  26181. ev.xcrossing.y_root = e.getScreenY();
  26182. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26183. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26184. translateJuceToXCrossingModifiers (e, ev);
  26185. sendEventToChild (&ev);
  26186. }
  26187. }
  26188. void mouseExit (const MouseEvent& e)
  26189. {
  26190. if (pluginWindow != 0)
  26191. {
  26192. XEvent ev;
  26193. zerostruct (ev);
  26194. ev.xcrossing.display = display;
  26195. ev.xcrossing.type = LeaveNotify;
  26196. ev.xcrossing.window = pluginWindow;
  26197. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26198. ev.xcrossing.time = CurrentTime;
  26199. ev.xcrossing.x = e.x;
  26200. ev.xcrossing.y = e.y;
  26201. ev.xcrossing.x_root = e.getScreenX();
  26202. ev.xcrossing.y_root = e.getScreenY();
  26203. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26204. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26205. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26206. translateJuceToXCrossingModifiers (e, ev);
  26207. sendEventToChild (&ev);
  26208. }
  26209. }
  26210. void mouseMove (const MouseEvent& e)
  26211. {
  26212. if (pluginWindow != 0)
  26213. {
  26214. XEvent ev;
  26215. zerostruct (ev);
  26216. ev.xmotion.display = display;
  26217. ev.xmotion.type = MotionNotify;
  26218. ev.xmotion.window = pluginWindow;
  26219. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26220. ev.xmotion.time = CurrentTime;
  26221. ev.xmotion.is_hint = NotifyNormal;
  26222. ev.xmotion.x = e.x;
  26223. ev.xmotion.y = e.y;
  26224. ev.xmotion.x_root = e.getScreenX();
  26225. ev.xmotion.y_root = e.getScreenY();
  26226. sendEventToChild (&ev);
  26227. }
  26228. }
  26229. void mouseDrag (const MouseEvent& e)
  26230. {
  26231. if (pluginWindow != 0)
  26232. {
  26233. XEvent ev;
  26234. zerostruct (ev);
  26235. ev.xmotion.display = display;
  26236. ev.xmotion.type = MotionNotify;
  26237. ev.xmotion.window = pluginWindow;
  26238. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26239. ev.xmotion.time = CurrentTime;
  26240. ev.xmotion.x = e.x ;
  26241. ev.xmotion.y = e.y;
  26242. ev.xmotion.x_root = e.getScreenX();
  26243. ev.xmotion.y_root = e.getScreenY();
  26244. ev.xmotion.is_hint = NotifyNormal;
  26245. translateJuceToXMotionModifiers (e, ev);
  26246. sendEventToChild (&ev);
  26247. }
  26248. }
  26249. void mouseUp (const MouseEvent& e)
  26250. {
  26251. if (pluginWindow != 0)
  26252. {
  26253. XEvent ev;
  26254. zerostruct (ev);
  26255. ev.xbutton.display = display;
  26256. ev.xbutton.type = ButtonRelease;
  26257. ev.xbutton.window = pluginWindow;
  26258. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26259. ev.xbutton.time = CurrentTime;
  26260. ev.xbutton.x = e.x;
  26261. ev.xbutton.y = e.y;
  26262. ev.xbutton.x_root = e.getScreenX();
  26263. ev.xbutton.y_root = e.getScreenY();
  26264. translateJuceToXButtonModifiers (e, ev);
  26265. sendEventToChild (&ev);
  26266. }
  26267. }
  26268. void mouseWheelMove (const MouseEvent& e,
  26269. float incrementX,
  26270. float incrementY)
  26271. {
  26272. if (pluginWindow != 0)
  26273. {
  26274. XEvent ev;
  26275. zerostruct (ev);
  26276. ev.xbutton.display = display;
  26277. ev.xbutton.type = ButtonPress;
  26278. ev.xbutton.window = pluginWindow;
  26279. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26280. ev.xbutton.time = CurrentTime;
  26281. ev.xbutton.x = e.x;
  26282. ev.xbutton.y = e.y;
  26283. ev.xbutton.x_root = e.getScreenX();
  26284. ev.xbutton.y_root = e.getScreenY();
  26285. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26286. sendEventToChild (&ev);
  26287. // TODO - put a usleep here ?
  26288. ev.xbutton.type = ButtonRelease;
  26289. sendEventToChild (&ev);
  26290. }
  26291. }
  26292. #endif
  26293. #if JUCE_MAC
  26294. #if ! JUCE_SUPPORT_CARBON
  26295. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26296. #endif
  26297. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26298. {
  26299. public:
  26300. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26301. : owner (owner_),
  26302. alreadyInside (false)
  26303. {
  26304. }
  26305. ~InnerWrapperComponent()
  26306. {
  26307. deleteWindow();
  26308. }
  26309. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26310. {
  26311. owner->openPluginWindow (windowRef);
  26312. return 0;
  26313. }
  26314. void removeView (HIViewRef)
  26315. {
  26316. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26317. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26318. }
  26319. bool getEmbeddedViewSize (int& w, int& h)
  26320. {
  26321. ERect* rect = 0;
  26322. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26323. w = rect->right - rect->left;
  26324. h = rect->bottom - rect->top;
  26325. return true;
  26326. }
  26327. void mouseDown (int x, int y)
  26328. {
  26329. if (! alreadyInside)
  26330. {
  26331. alreadyInside = true;
  26332. getTopLevelComponent()->toFront (true);
  26333. owner->dispatch (effEditMouse, x, y, 0, 0);
  26334. alreadyInside = false;
  26335. }
  26336. else
  26337. {
  26338. PostEvent (::mouseDown, 0);
  26339. }
  26340. }
  26341. void paint()
  26342. {
  26343. ComponentPeer* const peer = getPeer();
  26344. if (peer != 0)
  26345. {
  26346. ERect r;
  26347. r.left = getScreenX() - peer->getScreenX();
  26348. r.right = r.left + getWidth();
  26349. r.top = getScreenY() - peer->getScreenY();
  26350. r.bottom = r.top + getHeight();
  26351. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26352. }
  26353. }
  26354. private:
  26355. VSTPluginWindow* const owner;
  26356. bool alreadyInside;
  26357. };
  26358. friend class InnerWrapperComponent;
  26359. InnerWrapperComponent* innerWrapper;
  26360. void resized()
  26361. {
  26362. innerWrapper->setSize (getWidth(), getHeight());
  26363. }
  26364. #endif
  26365. };
  26366. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26367. {
  26368. if (hasEditor())
  26369. return new VSTPluginWindow (*this);
  26370. return 0;
  26371. }
  26372. void VSTPluginInstance::handleAsyncUpdate()
  26373. {
  26374. // indicates that something about the plugin has changed..
  26375. updateHostDisplay();
  26376. }
  26377. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26378. {
  26379. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26380. {
  26381. changeProgramName (getCurrentProgram(), prog->prgName);
  26382. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26383. setParameter (i, vst_swapFloat (prog->params[i]));
  26384. return true;
  26385. }
  26386. return false;
  26387. }
  26388. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26389. const int dataSize)
  26390. {
  26391. if (dataSize < 28)
  26392. return false;
  26393. const fxSet* const set = (const fxSet*) data;
  26394. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26395. || vst_swap (set->version) > fxbVersionNum)
  26396. return false;
  26397. if (vst_swap (set->fxMagic) == 'FxBk')
  26398. {
  26399. // bank of programs
  26400. if (vst_swap (set->numPrograms) >= 0)
  26401. {
  26402. const int oldProg = getCurrentProgram();
  26403. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26404. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26405. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26406. {
  26407. if (i != oldProg)
  26408. {
  26409. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26410. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26411. return false;
  26412. if (vst_swap (set->numPrograms) > 0)
  26413. setCurrentProgram (i);
  26414. if (! restoreProgramSettings (prog))
  26415. return false;
  26416. }
  26417. }
  26418. if (vst_swap (set->numPrograms) > 0)
  26419. setCurrentProgram (oldProg);
  26420. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26421. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26422. return false;
  26423. if (! restoreProgramSettings (prog))
  26424. return false;
  26425. }
  26426. }
  26427. else if (vst_swap (set->fxMagic) == 'FxCk')
  26428. {
  26429. // single program
  26430. const fxProgram* const prog = (const fxProgram*) data;
  26431. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26432. return false;
  26433. changeProgramName (getCurrentProgram(), prog->prgName);
  26434. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26435. setParameter (i, vst_swapFloat (prog->params[i]));
  26436. }
  26437. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26438. {
  26439. // non-preset chunk
  26440. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26441. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26442. return false;
  26443. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26444. }
  26445. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26446. {
  26447. // preset chunk
  26448. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26449. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26450. return false;
  26451. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26452. changeProgramName (getCurrentProgram(), cset->name);
  26453. }
  26454. else
  26455. {
  26456. return false;
  26457. }
  26458. return true;
  26459. }
  26460. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26461. {
  26462. const int numParams = getNumParameters();
  26463. prog->chunkMagic = vst_swap ('CcnK');
  26464. prog->byteSize = 0;
  26465. prog->fxMagic = vst_swap ('FxCk');
  26466. prog->version = vst_swap (fxbVersionNum);
  26467. prog->fxID = vst_swap (getUID());
  26468. prog->fxVersion = vst_swap (getVersionNumber());
  26469. prog->numParams = vst_swap (numParams);
  26470. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  26471. for (int i = 0; i < numParams; ++i)
  26472. prog->params[i] = vst_swapFloat (getParameter (i));
  26473. }
  26474. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26475. {
  26476. const int numPrograms = getNumPrograms();
  26477. const int numParams = getNumParameters();
  26478. if (usesChunks())
  26479. {
  26480. if (isFXB)
  26481. {
  26482. MemoryBlock chunk;
  26483. getChunkData (chunk, false, maxSizeMB);
  26484. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26485. dest.setSize (totalLen, true);
  26486. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26487. set->chunkMagic = vst_swap ('CcnK');
  26488. set->byteSize = 0;
  26489. set->fxMagic = vst_swap ('FBCh');
  26490. set->version = vst_swap (fxbVersionNum);
  26491. set->fxID = vst_swap (getUID());
  26492. set->fxVersion = vst_swap (getVersionNumber());
  26493. set->numPrograms = vst_swap (numPrograms);
  26494. set->chunkSize = vst_swap (chunk.getSize());
  26495. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26496. }
  26497. else
  26498. {
  26499. MemoryBlock chunk;
  26500. getChunkData (chunk, true, maxSizeMB);
  26501. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  26502. dest.setSize (totalLen, true);
  26503. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  26504. set->chunkMagic = vst_swap ('CcnK');
  26505. set->byteSize = 0;
  26506. set->fxMagic = vst_swap ('FPCh');
  26507. set->version = vst_swap (fxbVersionNum);
  26508. set->fxID = vst_swap (getUID());
  26509. set->fxVersion = vst_swap (getVersionNumber());
  26510. set->numPrograms = vst_swap (numPrograms);
  26511. set->chunkSize = vst_swap (chunk.getSize());
  26512. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  26513. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26514. }
  26515. }
  26516. else
  26517. {
  26518. if (isFXB)
  26519. {
  26520. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26521. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  26522. dest.setSize (len, true);
  26523. fxSet* const set = (fxSet*) dest.getData();
  26524. set->chunkMagic = vst_swap ('CcnK');
  26525. set->byteSize = 0;
  26526. set->fxMagic = vst_swap ('FxBk');
  26527. set->version = vst_swap (fxbVersionNum);
  26528. set->fxID = vst_swap (getUID());
  26529. set->fxVersion = vst_swap (getVersionNumber());
  26530. set->numPrograms = vst_swap (numPrograms);
  26531. const int oldProgram = getCurrentProgram();
  26532. MemoryBlock oldSettings;
  26533. createTempParameterStore (oldSettings);
  26534. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  26535. for (int i = 0; i < numPrograms; ++i)
  26536. {
  26537. if (i != oldProgram)
  26538. {
  26539. setCurrentProgram (i);
  26540. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  26541. }
  26542. }
  26543. setCurrentProgram (oldProgram);
  26544. restoreFromTempParameterStore (oldSettings);
  26545. }
  26546. else
  26547. {
  26548. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26549. dest.setSize (totalLen, true);
  26550. setParamsInProgramBlock ((fxProgram*) dest.getData());
  26551. }
  26552. }
  26553. return true;
  26554. }
  26555. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  26556. {
  26557. if (usesChunks())
  26558. {
  26559. void* data = 0;
  26560. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  26561. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  26562. {
  26563. mb.setSize (bytes);
  26564. mb.copyFrom (data, 0, bytes);
  26565. }
  26566. }
  26567. }
  26568. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  26569. {
  26570. if (size > 0 && usesChunks())
  26571. {
  26572. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  26573. if (! isPreset)
  26574. updateStoredProgramNames();
  26575. }
  26576. }
  26577. void VSTPluginInstance::timerCallback()
  26578. {
  26579. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  26580. stopTimer();
  26581. }
  26582. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  26583. {
  26584. const ScopedLock sl (lock);
  26585. ++insideVSTCallback;
  26586. int result = 0;
  26587. try
  26588. {
  26589. if (effect != 0)
  26590. {
  26591. #if JUCE_MAC
  26592. if (module->resFileId != 0)
  26593. UseResFile (module->resFileId);
  26594. CGrafPtr oldPort;
  26595. if (getActiveEditor() != 0)
  26596. {
  26597. int x = 0, y = 0;
  26598. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  26599. GetPort (&oldPort);
  26600. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  26601. SetOrigin (-x, -y);
  26602. }
  26603. #endif
  26604. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  26605. #if JUCE_MAC
  26606. if (getActiveEditor() != 0)
  26607. SetPort (oldPort);
  26608. module->resFileId = CurResFile();
  26609. #endif
  26610. --insideVSTCallback;
  26611. return result;
  26612. }
  26613. }
  26614. catch (...)
  26615. {
  26616. //char s[512];
  26617. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  26618. }
  26619. --insideVSTCallback;
  26620. return result;
  26621. }
  26622. // handles non plugin-specific callbacks..
  26623. static const int defaultVSTSampleRateValue = 16384;
  26624. static const int defaultVSTBlockSizeValue = 512;
  26625. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26626. {
  26627. (void) index;
  26628. (void) value;
  26629. (void) opt;
  26630. switch (opcode)
  26631. {
  26632. case audioMasterCanDo:
  26633. {
  26634. static const char* canDos[] = { "supplyIdle",
  26635. "sendVstEvents",
  26636. "sendVstMidiEvent",
  26637. "sendVstTimeInfo",
  26638. "receiveVstEvents",
  26639. "receiveVstMidiEvent",
  26640. "supportShell",
  26641. "shellCategory" };
  26642. for (int i = 0; i < numElementsInArray (canDos); ++i)
  26643. if (strcmp (canDos[i], (const char*) ptr) == 0)
  26644. return 1;
  26645. return 0;
  26646. }
  26647. case audioMasterVersion:
  26648. return 0x2400;
  26649. case audioMasterCurrentId:
  26650. return shellUIDToCreate;
  26651. case audioMasterGetNumAutomatableParameters:
  26652. return 0;
  26653. case audioMasterGetAutomationState:
  26654. return 1;
  26655. case audioMasterGetVendorVersion:
  26656. return 0x0101;
  26657. case audioMasterGetVendorString:
  26658. case audioMasterGetProductString:
  26659. {
  26660. String hostName ("Juce VST Host");
  26661. if (JUCEApplication::getInstance() != 0)
  26662. hostName = JUCEApplication::getInstance()->getApplicationName();
  26663. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  26664. }
  26665. break;
  26666. case audioMasterGetSampleRate:
  26667. return (VstIntPtr) defaultVSTSampleRateValue;
  26668. case audioMasterGetBlockSize:
  26669. return (VstIntPtr) defaultVSTBlockSizeValue;
  26670. case audioMasterSetOutputSampleRate:
  26671. return 0;
  26672. default:
  26673. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  26674. break;
  26675. }
  26676. return 0;
  26677. }
  26678. // handles callbacks for a specific plugin
  26679. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26680. {
  26681. switch (opcode)
  26682. {
  26683. case audioMasterAutomate:
  26684. sendParamChangeMessageToListeners (index, opt);
  26685. break;
  26686. case audioMasterProcessEvents:
  26687. handleMidiFromPlugin ((const VstEvents*) ptr);
  26688. break;
  26689. case audioMasterGetTime:
  26690. #ifdef _MSC_VER
  26691. #pragma warning (push)
  26692. #pragma warning (disable: 4311)
  26693. #endif
  26694. return (VstIntPtr) &vstHostTime;
  26695. #ifdef _MSC_VER
  26696. #pragma warning (pop)
  26697. #endif
  26698. break;
  26699. case audioMasterIdle:
  26700. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  26701. {
  26702. ++insideVSTCallback;
  26703. #if JUCE_MAC
  26704. if (getActiveEditor() != 0)
  26705. dispatch (effEditIdle, 0, 0, 0, 0);
  26706. #endif
  26707. juce_callAnyTimersSynchronously();
  26708. handleUpdateNowIfNeeded();
  26709. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  26710. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  26711. --insideVSTCallback;
  26712. }
  26713. break;
  26714. case audioMasterUpdateDisplay:
  26715. triggerAsyncUpdate();
  26716. break;
  26717. case audioMasterTempoAt:
  26718. // returns (10000 * bpm)
  26719. break;
  26720. case audioMasterNeedIdle:
  26721. startTimer (50);
  26722. break;
  26723. case audioMasterSizeWindow:
  26724. if (getActiveEditor() != 0)
  26725. getActiveEditor()->setSize (index, value);
  26726. return 1;
  26727. case audioMasterGetSampleRate:
  26728. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  26729. case audioMasterGetBlockSize:
  26730. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  26731. case audioMasterWantMidi:
  26732. wantsMidiMessages = true;
  26733. break;
  26734. case audioMasterGetDirectory:
  26735. #if JUCE_MAC
  26736. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  26737. #else
  26738. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  26739. #endif
  26740. case audioMasterGetAutomationState:
  26741. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  26742. break;
  26743. // none of these are handled (yet)..
  26744. case audioMasterBeginEdit:
  26745. case audioMasterEndEdit:
  26746. case audioMasterSetTime:
  26747. case audioMasterPinConnected:
  26748. case audioMasterGetParameterQuantization:
  26749. case audioMasterIOChanged:
  26750. case audioMasterGetInputLatency:
  26751. case audioMasterGetOutputLatency:
  26752. case audioMasterGetPreviousPlug:
  26753. case audioMasterGetNextPlug:
  26754. case audioMasterWillReplaceOrAccumulate:
  26755. case audioMasterGetCurrentProcessLevel:
  26756. case audioMasterOfflineStart:
  26757. case audioMasterOfflineRead:
  26758. case audioMasterOfflineWrite:
  26759. case audioMasterOfflineGetCurrentPass:
  26760. case audioMasterOfflineGetCurrentMetaPass:
  26761. case audioMasterVendorSpecific:
  26762. case audioMasterSetIcon:
  26763. case audioMasterGetLanguage:
  26764. case audioMasterOpenWindow:
  26765. case audioMasterCloseWindow:
  26766. break;
  26767. default:
  26768. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26769. }
  26770. return 0;
  26771. }
  26772. // entry point for all callbacks from the plugin
  26773. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  26774. {
  26775. try
  26776. {
  26777. if (effect != 0 && effect->resvd2 != 0)
  26778. {
  26779. return ((VSTPluginInstance*)(effect->resvd2))
  26780. ->handleCallback (opcode, index, value, ptr, opt);
  26781. }
  26782. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26783. }
  26784. catch (...)
  26785. {
  26786. return 0;
  26787. }
  26788. }
  26789. const String VSTPluginInstance::getVersion() const throw()
  26790. {
  26791. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  26792. String s;
  26793. if (v == 0 || v == -1)
  26794. v = getVersionNumber();
  26795. if (v != 0)
  26796. {
  26797. int versionBits[4];
  26798. int n = 0;
  26799. while (v != 0)
  26800. {
  26801. versionBits [n++] = (v & 0xff);
  26802. v >>= 8;
  26803. }
  26804. s << 'V';
  26805. while (n > 0)
  26806. {
  26807. s << versionBits [--n];
  26808. if (n > 0)
  26809. s << '.';
  26810. }
  26811. }
  26812. return s;
  26813. }
  26814. int VSTPluginInstance::getUID() const throw()
  26815. {
  26816. int uid = effect != 0 ? effect->uniqueID : 0;
  26817. if (uid == 0)
  26818. uid = module->file.hashCode();
  26819. return uid;
  26820. }
  26821. const String VSTPluginInstance::getCategory() const throw()
  26822. {
  26823. const char* result = 0;
  26824. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  26825. {
  26826. case kPlugCategEffect:
  26827. result = "Effect";
  26828. break;
  26829. case kPlugCategSynth:
  26830. result = "Synth";
  26831. break;
  26832. case kPlugCategAnalysis:
  26833. result = "Anaylsis";
  26834. break;
  26835. case kPlugCategMastering:
  26836. result = "Mastering";
  26837. break;
  26838. case kPlugCategSpacializer:
  26839. result = "Spacial";
  26840. break;
  26841. case kPlugCategRoomFx:
  26842. result = "Reverb";
  26843. break;
  26844. case kPlugSurroundFx:
  26845. result = "Surround";
  26846. break;
  26847. case kPlugCategRestoration:
  26848. result = "Restoration";
  26849. break;
  26850. case kPlugCategGenerator:
  26851. result = "Tone generation";
  26852. break;
  26853. default:
  26854. break;
  26855. }
  26856. return result;
  26857. }
  26858. float VSTPluginInstance::getParameter (int index)
  26859. {
  26860. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26861. {
  26862. try
  26863. {
  26864. const ScopedLock sl (lock);
  26865. return effect->getParameter (effect, index);
  26866. }
  26867. catch (...)
  26868. {
  26869. }
  26870. }
  26871. return 0.0f;
  26872. }
  26873. void VSTPluginInstance::setParameter (int index, float newValue)
  26874. {
  26875. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26876. {
  26877. try
  26878. {
  26879. const ScopedLock sl (lock);
  26880. if (effect->getParameter (effect, index) != newValue)
  26881. effect->setParameter (effect, index, newValue);
  26882. }
  26883. catch (...)
  26884. {
  26885. }
  26886. }
  26887. }
  26888. const String VSTPluginInstance::getParameterName (int index)
  26889. {
  26890. if (effect != 0)
  26891. {
  26892. jassert (index >= 0 && index < effect->numParams);
  26893. char nm [256];
  26894. zerostruct (nm);
  26895. dispatch (effGetParamName, index, 0, nm, 0);
  26896. return String (nm).trim();
  26897. }
  26898. return String::empty;
  26899. }
  26900. const String VSTPluginInstance::getParameterLabel (int index) const
  26901. {
  26902. if (effect != 0)
  26903. {
  26904. jassert (index >= 0 && index < effect->numParams);
  26905. char nm [256];
  26906. zerostruct (nm);
  26907. dispatch (effGetParamLabel, index, 0, nm, 0);
  26908. return String (nm).trim();
  26909. }
  26910. return String::empty;
  26911. }
  26912. const String VSTPluginInstance::getParameterText (int index)
  26913. {
  26914. if (effect != 0)
  26915. {
  26916. jassert (index >= 0 && index < effect->numParams);
  26917. char nm [256];
  26918. zerostruct (nm);
  26919. dispatch (effGetParamDisplay, index, 0, nm, 0);
  26920. return String (nm).trim();
  26921. }
  26922. return String::empty;
  26923. }
  26924. bool VSTPluginInstance::isParameterAutomatable (int index) const
  26925. {
  26926. if (effect != 0)
  26927. {
  26928. jassert (index >= 0 && index < effect->numParams);
  26929. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  26930. }
  26931. return false;
  26932. }
  26933. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  26934. {
  26935. dest.setSize (64 + 4 * getNumParameters());
  26936. dest.fillWith (0);
  26937. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  26938. float* const p = (float*) (((char*) dest.getData()) + 64);
  26939. for (int i = 0; i < getNumParameters(); ++i)
  26940. p[i] = getParameter(i);
  26941. }
  26942. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  26943. {
  26944. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  26945. float* p = (float*) (((char*) m.getData()) + 64);
  26946. for (int i = 0; i < getNumParameters(); ++i)
  26947. setParameter (i, p[i]);
  26948. }
  26949. void VSTPluginInstance::setCurrentProgram (int newIndex)
  26950. {
  26951. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  26952. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  26953. }
  26954. const String VSTPluginInstance::getProgramName (int index)
  26955. {
  26956. if (index == getCurrentProgram())
  26957. {
  26958. return getCurrentProgramName();
  26959. }
  26960. else if (effect != 0)
  26961. {
  26962. char nm [256];
  26963. zerostruct (nm);
  26964. if (dispatch (effGetProgramNameIndexed,
  26965. jlimit (0, getNumPrograms(), index),
  26966. -1, nm, 0) != 0)
  26967. {
  26968. return String (nm).trim();
  26969. }
  26970. }
  26971. return programNames [index];
  26972. }
  26973. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  26974. {
  26975. if (index == getCurrentProgram())
  26976. {
  26977. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  26978. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  26979. }
  26980. else
  26981. {
  26982. jassertfalse // xxx not implemented!
  26983. }
  26984. }
  26985. void VSTPluginInstance::updateStoredProgramNames()
  26986. {
  26987. if (effect != 0 && getNumPrograms() > 0)
  26988. {
  26989. char nm [256];
  26990. zerostruct (nm);
  26991. // only do this if the plugin can't use indexed names..
  26992. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  26993. {
  26994. const int oldProgram = getCurrentProgram();
  26995. MemoryBlock oldSettings;
  26996. createTempParameterStore (oldSettings);
  26997. for (int i = 0; i < getNumPrograms(); ++i)
  26998. {
  26999. setCurrentProgram (i);
  27000. getCurrentProgramName(); // (this updates the list)
  27001. }
  27002. setCurrentProgram (oldProgram);
  27003. restoreFromTempParameterStore (oldSettings);
  27004. }
  27005. }
  27006. }
  27007. const String VSTPluginInstance::getCurrentProgramName()
  27008. {
  27009. if (effect != 0)
  27010. {
  27011. char nm [256];
  27012. zerostruct (nm);
  27013. dispatch (effGetProgramName, 0, 0, nm, 0);
  27014. const int index = getCurrentProgram();
  27015. if (programNames[index].isEmpty())
  27016. {
  27017. while (programNames.size() < index)
  27018. programNames.add (String::empty);
  27019. programNames.set (index, String (nm).trim());
  27020. }
  27021. return String (nm).trim();
  27022. }
  27023. return String::empty;
  27024. }
  27025. const String VSTPluginInstance::getInputChannelName (const int index) const
  27026. {
  27027. if (index >= 0 && index < getNumInputChannels())
  27028. {
  27029. VstPinProperties pinProps;
  27030. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27031. return String (pinProps.label, sizeof (pinProps.label));
  27032. }
  27033. return String::empty;
  27034. }
  27035. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27036. {
  27037. if (index < 0 || index >= getNumInputChannels())
  27038. return false;
  27039. VstPinProperties pinProps;
  27040. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27041. return (pinProps.flags & kVstPinIsStereo) != 0;
  27042. return true;
  27043. }
  27044. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27045. {
  27046. if (index >= 0 && index < getNumOutputChannels())
  27047. {
  27048. VstPinProperties pinProps;
  27049. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27050. return String (pinProps.label, sizeof (pinProps.label));
  27051. }
  27052. return String::empty;
  27053. }
  27054. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27055. {
  27056. if (index < 0 || index >= getNumOutputChannels())
  27057. return false;
  27058. VstPinProperties pinProps;
  27059. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27060. return (pinProps.flags & kVstPinIsStereo) != 0;
  27061. return true;
  27062. }
  27063. void VSTPluginInstance::setPower (const bool on)
  27064. {
  27065. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27066. isPowerOn = on;
  27067. }
  27068. const int defaultMaxSizeMB = 64;
  27069. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27070. {
  27071. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27072. }
  27073. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27074. {
  27075. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27076. }
  27077. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27078. {
  27079. loadFromFXBFile (data, sizeInBytes);
  27080. }
  27081. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27082. {
  27083. loadFromFXBFile (data, sizeInBytes);
  27084. }
  27085. VSTPluginFormat::VSTPluginFormat()
  27086. {
  27087. }
  27088. VSTPluginFormat::~VSTPluginFormat()
  27089. {
  27090. }
  27091. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27092. const String& fileOrIdentifier)
  27093. {
  27094. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27095. return;
  27096. PluginDescription desc;
  27097. desc.fileOrIdentifier = fileOrIdentifier;
  27098. desc.uid = 0;
  27099. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  27100. if (instance == 0)
  27101. return;
  27102. try
  27103. {
  27104. #if JUCE_MAC
  27105. if (instance->module->resFileId != 0)
  27106. UseResFile (instance->module->resFileId);
  27107. #endif
  27108. instance->fillInPluginDescription (desc);
  27109. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27110. if (category != kPlugCategShell)
  27111. {
  27112. // Normal plugin...
  27113. results.add (new PluginDescription (desc));
  27114. ++insideVSTCallback;
  27115. instance->dispatch (effOpen, 0, 0, 0, 0);
  27116. --insideVSTCallback;
  27117. }
  27118. else
  27119. {
  27120. // It's a shell plugin, so iterate all the subtypes...
  27121. char shellEffectName [64];
  27122. for (;;)
  27123. {
  27124. zerostruct (shellEffectName);
  27125. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27126. if (uid == 0)
  27127. {
  27128. break;
  27129. }
  27130. else
  27131. {
  27132. desc.uid = uid;
  27133. desc.name = shellEffectName;
  27134. bool alreadyThere = false;
  27135. for (int i = results.size(); --i >= 0;)
  27136. {
  27137. PluginDescription* const d = results.getUnchecked(i);
  27138. if (d->isDuplicateOf (desc))
  27139. {
  27140. alreadyThere = true;
  27141. break;
  27142. }
  27143. }
  27144. if (! alreadyThere)
  27145. results.add (new PluginDescription (desc));
  27146. }
  27147. }
  27148. }
  27149. }
  27150. catch (...)
  27151. {
  27152. // crashed while loading...
  27153. }
  27154. deleteAndZero (instance);
  27155. }
  27156. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27157. {
  27158. VSTPluginInstance* result = 0;
  27159. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27160. {
  27161. File file (desc.fileOrIdentifier);
  27162. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27163. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27164. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27165. if (module != 0)
  27166. {
  27167. shellUIDToCreate = desc.uid;
  27168. result = new VSTPluginInstance (module);
  27169. if (result->effect != 0)
  27170. {
  27171. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  27172. result->initialise();
  27173. }
  27174. else
  27175. {
  27176. deleteAndZero (result);
  27177. }
  27178. }
  27179. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27180. }
  27181. return result;
  27182. }
  27183. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27184. {
  27185. const File f (fileOrIdentifier);
  27186. #if JUCE_MAC
  27187. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  27188. return true;
  27189. #if JUCE_PPC
  27190. FSRef fileRef;
  27191. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27192. {
  27193. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27194. if (resFileId != -1)
  27195. {
  27196. const int numEffects = Count1Resources ('aEff');
  27197. CloseResFile (resFileId);
  27198. if (numEffects > 0)
  27199. return true;
  27200. }
  27201. }
  27202. #endif
  27203. return false;
  27204. #elif JUCE_WIN32
  27205. return f.existsAsFile()
  27206. && f.hasFileExtension (T(".dll"));
  27207. #elif JUCE_LINUX
  27208. return f.existsAsFile()
  27209. && f.hasFileExtension (T(".so"));
  27210. #endif
  27211. }
  27212. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27213. {
  27214. return fileOrIdentifier;
  27215. }
  27216. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27217. {
  27218. return File (desc.fileOrIdentifier).exists();
  27219. }
  27220. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27221. {
  27222. StringArray results;
  27223. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27224. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27225. return results;
  27226. }
  27227. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27228. {
  27229. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27230. // .component or .vst directories.
  27231. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27232. while (iter.next())
  27233. {
  27234. const File f (iter.getFile());
  27235. bool isPlugin = false;
  27236. if (fileMightContainThisPluginType (f.getFullPathName()))
  27237. {
  27238. isPlugin = true;
  27239. results.add (f.getFullPathName());
  27240. }
  27241. if (recursive && (! isPlugin) && f.isDirectory())
  27242. recursiveFileSearch (results, f, true);
  27243. }
  27244. }
  27245. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27246. {
  27247. #if JUCE_MAC
  27248. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27249. #elif JUCE_WIN32
  27250. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27251. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27252. #elif JUCE_LINUX
  27253. return FileSearchPath ("/usr/lib/vst");
  27254. #endif
  27255. }
  27256. END_JUCE_NAMESPACE
  27257. #endif
  27258. #undef log
  27259. #endif
  27260. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  27261. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  27262. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  27263. BEGIN_JUCE_NAMESPACE
  27264. AudioProcessor::AudioProcessor()
  27265. : playHead (0),
  27266. activeEditor (0),
  27267. sampleRate (0),
  27268. blockSize (0),
  27269. numInputChannels (0),
  27270. numOutputChannels (0),
  27271. latencySamples (0),
  27272. suspended (false),
  27273. nonRealtime (false)
  27274. {
  27275. }
  27276. AudioProcessor::~AudioProcessor()
  27277. {
  27278. // ooh, nasty - the editor should have been deleted before the filter
  27279. // that it refers to is deleted..
  27280. jassert (activeEditor == 0);
  27281. #ifdef JUCE_DEBUG
  27282. // This will fail if you've called beginParameterChangeGesture() for one
  27283. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27284. jassert (changingParams.countNumberOfSetBits() == 0);
  27285. #endif
  27286. }
  27287. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27288. {
  27289. playHead = newPlayHead;
  27290. }
  27291. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27292. {
  27293. const ScopedLock sl (listenerLock);
  27294. listeners.addIfNotAlreadyThere (newListener);
  27295. }
  27296. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27297. {
  27298. const ScopedLock sl (listenerLock);
  27299. listeners.removeValue (listenerToRemove);
  27300. }
  27301. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27302. const int numOuts,
  27303. const double sampleRate_,
  27304. const int blockSize_) throw()
  27305. {
  27306. numInputChannels = numIns;
  27307. numOutputChannels = numOuts;
  27308. sampleRate = sampleRate_;
  27309. blockSize = blockSize_;
  27310. }
  27311. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27312. {
  27313. nonRealtime = nonRealtime_;
  27314. }
  27315. void AudioProcessor::setLatencySamples (const int newLatency)
  27316. {
  27317. if (latencySamples != newLatency)
  27318. {
  27319. latencySamples = newLatency;
  27320. updateHostDisplay();
  27321. }
  27322. }
  27323. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27324. const float newValue)
  27325. {
  27326. setParameter (parameterIndex, newValue);
  27327. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27328. }
  27329. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27330. {
  27331. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27332. for (int i = listeners.size(); --i >= 0;)
  27333. {
  27334. listenerLock.enter();
  27335. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27336. listenerLock.exit();
  27337. if (l != 0)
  27338. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27339. }
  27340. }
  27341. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27342. {
  27343. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27344. #ifdef JUCE_DEBUG
  27345. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27346. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27347. jassert (! changingParams [parameterIndex]);
  27348. changingParams.setBit (parameterIndex);
  27349. #endif
  27350. for (int i = listeners.size(); --i >= 0;)
  27351. {
  27352. listenerLock.enter();
  27353. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27354. listenerLock.exit();
  27355. if (l != 0)
  27356. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27357. }
  27358. }
  27359. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27360. {
  27361. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27362. #ifdef JUCE_DEBUG
  27363. // This means you've called endParameterChangeGesture without having previously called
  27364. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27365. // calls matched correctly.
  27366. jassert (changingParams [parameterIndex]);
  27367. changingParams.clearBit (parameterIndex);
  27368. #endif
  27369. for (int i = listeners.size(); --i >= 0;)
  27370. {
  27371. listenerLock.enter();
  27372. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27373. listenerLock.exit();
  27374. if (l != 0)
  27375. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27376. }
  27377. }
  27378. void AudioProcessor::updateHostDisplay()
  27379. {
  27380. for (int i = listeners.size(); --i >= 0;)
  27381. {
  27382. listenerLock.enter();
  27383. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27384. listenerLock.exit();
  27385. if (l != 0)
  27386. l->audioProcessorChanged (this);
  27387. }
  27388. }
  27389. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27390. {
  27391. return true;
  27392. }
  27393. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27394. {
  27395. return false;
  27396. }
  27397. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27398. {
  27399. const ScopedLock sl (callbackLock);
  27400. suspended = shouldBeSuspended;
  27401. }
  27402. void AudioProcessor::reset()
  27403. {
  27404. }
  27405. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27406. {
  27407. const ScopedLock sl (callbackLock);
  27408. jassert (activeEditor == editor);
  27409. if (activeEditor == editor)
  27410. activeEditor = 0;
  27411. }
  27412. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27413. {
  27414. if (activeEditor != 0)
  27415. return activeEditor;
  27416. AudioProcessorEditor* const ed = createEditor();
  27417. if (ed != 0)
  27418. {
  27419. // you must give your editor comp a size before returning it..
  27420. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27421. const ScopedLock sl (callbackLock);
  27422. activeEditor = ed;
  27423. }
  27424. return ed;
  27425. }
  27426. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27427. {
  27428. getStateInformation (destData);
  27429. }
  27430. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27431. {
  27432. setStateInformation (data, sizeInBytes);
  27433. }
  27434. // magic number to identify memory blocks that we've stored as XML
  27435. const uint32 magicXmlNumber = 0x21324356;
  27436. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27437. JUCE_NAMESPACE::MemoryBlock& destData)
  27438. {
  27439. const String xmlString (xml.createDocument (String::empty, true, false));
  27440. const int stringLength = xmlString.length();
  27441. destData.setSize (stringLength + 10);
  27442. char* const d = (char*) destData.getData();
  27443. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  27444. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  27445. xmlString.copyToBuffer (d + 8, stringLength);
  27446. }
  27447. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27448. const int sizeInBytes)
  27449. {
  27450. if (sizeInBytes > 8
  27451. && littleEndianInt ((const char*) data) == magicXmlNumber)
  27452. {
  27453. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  27454. if (stringLength > 0)
  27455. {
  27456. XmlDocument doc (String (((const char*) data) + 8,
  27457. jmin ((sizeInBytes - 8), stringLength)));
  27458. return doc.getDocumentElement();
  27459. }
  27460. }
  27461. return 0;
  27462. }
  27463. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27464. {
  27465. }
  27466. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27467. {
  27468. }
  27469. END_JUCE_NAMESPACE
  27470. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  27471. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  27472. BEGIN_JUCE_NAMESPACE
  27473. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  27474. : owner (owner_)
  27475. {
  27476. // the filter must be valid..
  27477. jassert (owner != 0);
  27478. }
  27479. AudioProcessorEditor::~AudioProcessorEditor()
  27480. {
  27481. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  27482. // filter for some reason..
  27483. jassert (owner->getActiveEditor() != this);
  27484. }
  27485. END_JUCE_NAMESPACE
  27486. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  27487. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  27488. BEGIN_JUCE_NAMESPACE
  27489. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  27490. AudioProcessorGraph::Node::Node (const uint32 id_,
  27491. AudioProcessor* const processor_) throw()
  27492. : id (id_),
  27493. processor (processor_),
  27494. isPrepared (false)
  27495. {
  27496. jassert (processor_ != 0);
  27497. }
  27498. AudioProcessorGraph::Node::~Node()
  27499. {
  27500. delete processor;
  27501. }
  27502. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  27503. AudioProcessorGraph* const graph)
  27504. {
  27505. if (! isPrepared)
  27506. {
  27507. isPrepared = true;
  27508. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27509. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  27510. if (ioProc != 0)
  27511. ioProc->setParentGraph (graph);
  27512. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  27513. processor->getNumOutputChannels(),
  27514. sampleRate, blockSize);
  27515. processor->prepareToPlay (sampleRate, blockSize);
  27516. }
  27517. }
  27518. void AudioProcessorGraph::Node::unprepare()
  27519. {
  27520. if (isPrepared)
  27521. {
  27522. isPrepared = false;
  27523. processor->releaseResources();
  27524. }
  27525. }
  27526. AudioProcessorGraph::AudioProcessorGraph()
  27527. : lastNodeId (0),
  27528. renderingBuffers (1, 1),
  27529. currentAudioOutputBuffer (1, 1)
  27530. {
  27531. }
  27532. AudioProcessorGraph::~AudioProcessorGraph()
  27533. {
  27534. clearRenderingSequence();
  27535. clear();
  27536. }
  27537. const String AudioProcessorGraph::getName() const
  27538. {
  27539. return "Audio Graph";
  27540. }
  27541. void AudioProcessorGraph::clear()
  27542. {
  27543. nodes.clear();
  27544. connections.clear();
  27545. triggerAsyncUpdate();
  27546. }
  27547. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  27548. {
  27549. for (int i = nodes.size(); --i >= 0;)
  27550. if (nodes.getUnchecked(i)->id == nodeId)
  27551. return nodes.getUnchecked(i);
  27552. return 0;
  27553. }
  27554. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  27555. uint32 nodeId)
  27556. {
  27557. if (newProcessor == 0)
  27558. {
  27559. jassertfalse
  27560. return 0;
  27561. }
  27562. if (nodeId == 0)
  27563. {
  27564. nodeId = ++lastNodeId;
  27565. }
  27566. else
  27567. {
  27568. // you can't add a node with an id that already exists in the graph..
  27569. jassert (getNodeForId (nodeId) == 0);
  27570. removeNode (nodeId);
  27571. }
  27572. lastNodeId = nodeId;
  27573. Node* const n = new Node (nodeId, newProcessor);
  27574. nodes.add (n);
  27575. triggerAsyncUpdate();
  27576. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27577. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  27578. if (ioProc != 0)
  27579. ioProc->setParentGraph (this);
  27580. return n;
  27581. }
  27582. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  27583. {
  27584. disconnectNode (nodeId);
  27585. for (int i = nodes.size(); --i >= 0;)
  27586. {
  27587. if (nodes.getUnchecked(i)->id == nodeId)
  27588. {
  27589. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27590. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  27591. if (ioProc != 0)
  27592. ioProc->setParentGraph (0);
  27593. nodes.remove (i);
  27594. triggerAsyncUpdate();
  27595. return true;
  27596. }
  27597. }
  27598. return false;
  27599. }
  27600. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  27601. const int sourceChannelIndex,
  27602. const uint32 destNodeId,
  27603. const int destChannelIndex) const throw()
  27604. {
  27605. for (int i = connections.size(); --i >= 0;)
  27606. {
  27607. const Connection* const c = connections.getUnchecked(i);
  27608. if (c->sourceNodeId == sourceNodeId
  27609. && c->destNodeId == destNodeId
  27610. && c->sourceChannelIndex == sourceChannelIndex
  27611. && c->destChannelIndex == destChannelIndex)
  27612. {
  27613. return c;
  27614. }
  27615. }
  27616. return 0;
  27617. }
  27618. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  27619. const uint32 possibleDestNodeId) const throw()
  27620. {
  27621. for (int i = connections.size(); --i >= 0;)
  27622. {
  27623. const Connection* const c = connections.getUnchecked(i);
  27624. if (c->sourceNodeId == possibleSourceNodeId
  27625. && c->destNodeId == possibleDestNodeId)
  27626. {
  27627. return true;
  27628. }
  27629. }
  27630. return false;
  27631. }
  27632. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  27633. const int sourceChannelIndex,
  27634. const uint32 destNodeId,
  27635. const int destChannelIndex) const throw()
  27636. {
  27637. if (sourceChannelIndex < 0
  27638. || destChannelIndex < 0
  27639. || sourceNodeId == destNodeId
  27640. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  27641. return false;
  27642. const Node* const source = getNodeForId (sourceNodeId);
  27643. if (source == 0
  27644. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  27645. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  27646. return false;
  27647. const Node* const dest = getNodeForId (destNodeId);
  27648. if (dest == 0
  27649. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  27650. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  27651. return false;
  27652. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  27653. destNodeId, destChannelIndex) == 0;
  27654. }
  27655. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  27656. const int sourceChannelIndex,
  27657. const uint32 destNodeId,
  27658. const int destChannelIndex)
  27659. {
  27660. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  27661. return false;
  27662. Connection* const c = new Connection();
  27663. c->sourceNodeId = sourceNodeId;
  27664. c->sourceChannelIndex = sourceChannelIndex;
  27665. c->destNodeId = destNodeId;
  27666. c->destChannelIndex = destChannelIndex;
  27667. connections.add (c);
  27668. triggerAsyncUpdate();
  27669. return true;
  27670. }
  27671. void AudioProcessorGraph::removeConnection (const int index)
  27672. {
  27673. connections.remove (index);
  27674. triggerAsyncUpdate();
  27675. }
  27676. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  27677. const uint32 destNodeId, const int destChannelIndex)
  27678. {
  27679. bool doneAnything = false;
  27680. for (int i = connections.size(); --i >= 0;)
  27681. {
  27682. const Connection* const c = connections.getUnchecked(i);
  27683. if (c->sourceNodeId == sourceNodeId
  27684. && c->destNodeId == destNodeId
  27685. && c->sourceChannelIndex == sourceChannelIndex
  27686. && c->destChannelIndex == destChannelIndex)
  27687. {
  27688. removeConnection (i);
  27689. doneAnything = true;
  27690. triggerAsyncUpdate();
  27691. }
  27692. }
  27693. return doneAnything;
  27694. }
  27695. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  27696. {
  27697. bool doneAnything = false;
  27698. for (int i = connections.size(); --i >= 0;)
  27699. {
  27700. const Connection* const c = connections.getUnchecked(i);
  27701. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  27702. {
  27703. removeConnection (i);
  27704. doneAnything = true;
  27705. triggerAsyncUpdate();
  27706. }
  27707. }
  27708. return doneAnything;
  27709. }
  27710. bool AudioProcessorGraph::removeIllegalConnections()
  27711. {
  27712. bool doneAnything = false;
  27713. for (int i = connections.size(); --i >= 0;)
  27714. {
  27715. const Connection* const c = connections.getUnchecked(i);
  27716. const Node* const source = getNodeForId (c->sourceNodeId);
  27717. const Node* const dest = getNodeForId (c->destNodeId);
  27718. if (source == 0 || dest == 0
  27719. || (c->sourceChannelIndex != midiChannelIndex
  27720. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  27721. || (c->sourceChannelIndex == midiChannelIndex
  27722. && ! source->processor->producesMidi())
  27723. || (c->destChannelIndex != midiChannelIndex
  27724. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  27725. || (c->destChannelIndex == midiChannelIndex
  27726. && ! dest->processor->acceptsMidi()))
  27727. {
  27728. removeConnection (i);
  27729. doneAnything = true;
  27730. triggerAsyncUpdate();
  27731. }
  27732. }
  27733. return doneAnything;
  27734. }
  27735. namespace GraphRenderingOps
  27736. {
  27737. class AudioGraphRenderingOp
  27738. {
  27739. public:
  27740. AudioGraphRenderingOp() throw() {}
  27741. virtual ~AudioGraphRenderingOp() throw() {}
  27742. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  27743. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  27744. const int numSamples) throw() = 0;
  27745. juce_UseDebuggingNewOperator
  27746. };
  27747. class ClearChannelOp : public AudioGraphRenderingOp
  27748. {
  27749. public:
  27750. ClearChannelOp (const int channelNum_) throw()
  27751. : channelNum (channelNum_)
  27752. {}
  27753. ~ClearChannelOp() throw() {}
  27754. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27755. {
  27756. sharedBufferChans.clear (channelNum, 0, numSamples);
  27757. }
  27758. private:
  27759. const int channelNum;
  27760. ClearChannelOp (const ClearChannelOp&);
  27761. const ClearChannelOp& operator= (const ClearChannelOp&);
  27762. };
  27763. class CopyChannelOp : public AudioGraphRenderingOp
  27764. {
  27765. public:
  27766. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27767. : srcChannelNum (srcChannelNum_),
  27768. dstChannelNum (dstChannelNum_)
  27769. {}
  27770. ~CopyChannelOp() throw() {}
  27771. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27772. {
  27773. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27774. }
  27775. private:
  27776. const int srcChannelNum, dstChannelNum;
  27777. CopyChannelOp (const CopyChannelOp&);
  27778. const CopyChannelOp& operator= (const CopyChannelOp&);
  27779. };
  27780. class AddChannelOp : public AudioGraphRenderingOp
  27781. {
  27782. public:
  27783. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27784. : srcChannelNum (srcChannelNum_),
  27785. dstChannelNum (dstChannelNum_)
  27786. {}
  27787. ~AddChannelOp() throw() {}
  27788. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27789. {
  27790. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27791. }
  27792. private:
  27793. const int srcChannelNum, dstChannelNum;
  27794. AddChannelOp (const AddChannelOp&);
  27795. const AddChannelOp& operator= (const AddChannelOp&);
  27796. };
  27797. class ClearMidiBufferOp : public AudioGraphRenderingOp
  27798. {
  27799. public:
  27800. ClearMidiBufferOp (const int bufferNum_) throw()
  27801. : bufferNum (bufferNum_)
  27802. {}
  27803. ~ClearMidiBufferOp() throw() {}
  27804. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27805. {
  27806. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  27807. }
  27808. private:
  27809. const int bufferNum;
  27810. ClearMidiBufferOp (const ClearMidiBufferOp&);
  27811. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  27812. };
  27813. class CopyMidiBufferOp : public AudioGraphRenderingOp
  27814. {
  27815. public:
  27816. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27817. : srcBufferNum (srcBufferNum_),
  27818. dstBufferNum (dstBufferNum_)
  27819. {}
  27820. ~CopyMidiBufferOp() throw() {}
  27821. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27822. {
  27823. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  27824. }
  27825. private:
  27826. const int srcBufferNum, dstBufferNum;
  27827. CopyMidiBufferOp (const CopyMidiBufferOp&);
  27828. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  27829. };
  27830. class AddMidiBufferOp : public AudioGraphRenderingOp
  27831. {
  27832. public:
  27833. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27834. : srcBufferNum (srcBufferNum_),
  27835. dstBufferNum (dstBufferNum_)
  27836. {}
  27837. ~AddMidiBufferOp() throw() {}
  27838. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27839. {
  27840. sharedMidiBuffers.getUnchecked (dstBufferNum)
  27841. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  27842. }
  27843. private:
  27844. const int srcBufferNum, dstBufferNum;
  27845. AddMidiBufferOp (const AddMidiBufferOp&);
  27846. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  27847. };
  27848. class ProcessBufferOp : public AudioGraphRenderingOp
  27849. {
  27850. public:
  27851. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  27852. const Array <int>& audioChannelsToUse_,
  27853. const int totalChans_,
  27854. const int midiBufferToUse_) throw()
  27855. : node (node_),
  27856. processor (node_->processor),
  27857. audioChannelsToUse (audioChannelsToUse_),
  27858. totalChans (jmax (1, totalChans_)),
  27859. midiBufferToUse (midiBufferToUse_)
  27860. {
  27861. channels = (float**) juce_calloc (sizeof (float*) * totalChans);
  27862. while (audioChannelsToUse.size() < totalChans)
  27863. audioChannelsToUse.add (0);
  27864. }
  27865. ~ProcessBufferOp() throw()
  27866. {
  27867. juce_free (channels);
  27868. }
  27869. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27870. {
  27871. for (int i = totalChans; --i >= 0;)
  27872. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  27873. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  27874. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  27875. }
  27876. const AudioProcessorGraph::Node::Ptr node;
  27877. AudioProcessor* const processor;
  27878. private:
  27879. Array <int> audioChannelsToUse;
  27880. float** channels;
  27881. int totalChans;
  27882. int midiBufferToUse;
  27883. ProcessBufferOp (const ProcessBufferOp&);
  27884. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  27885. };
  27886. /** Used to calculate the correct sequence of rendering ops needed, based on
  27887. the best re-use of shared buffers at each stage.
  27888. */
  27889. class RenderingOpSequenceCalculator
  27890. {
  27891. public:
  27892. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  27893. const VoidArray& orderedNodes_,
  27894. VoidArray& renderingOps)
  27895. : graph (graph_),
  27896. orderedNodes (orderedNodes_)
  27897. {
  27898. nodeIds.add (-2); // first buffer is read-only zeros
  27899. channels.add (0);
  27900. midiNodeIds.add (-2);
  27901. for (int i = 0; i < orderedNodes.size(); ++i)
  27902. {
  27903. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  27904. renderingOps, i);
  27905. markAnyUnusedBuffersAsFree (i);
  27906. }
  27907. }
  27908. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  27909. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  27910. juce_UseDebuggingNewOperator
  27911. private:
  27912. AudioProcessorGraph& graph;
  27913. const VoidArray& orderedNodes;
  27914. Array <int> nodeIds, channels, midiNodeIds;
  27915. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  27916. VoidArray& renderingOps,
  27917. const int ourRenderingIndex)
  27918. {
  27919. const int numIns = node->processor->getNumInputChannels();
  27920. const int numOuts = node->processor->getNumOutputChannels();
  27921. const int totalChans = jmax (numIns, numOuts);
  27922. Array <int> audioChannelsToUse;
  27923. int midiBufferToUse = -1;
  27924. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  27925. {
  27926. // get a list of all the inputs to this node
  27927. Array <int> sourceNodes, sourceOutputChans;
  27928. for (int i = graph.getNumConnections(); --i >= 0;)
  27929. {
  27930. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27931. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  27932. {
  27933. sourceNodes.add (c->sourceNodeId);
  27934. sourceOutputChans.add (c->sourceChannelIndex);
  27935. }
  27936. }
  27937. int bufIndex = -1;
  27938. if (sourceNodes.size() == 0)
  27939. {
  27940. // unconnected input channel
  27941. if (inputChan >= numOuts)
  27942. {
  27943. bufIndex = getReadOnlyEmptyBuffer();
  27944. jassert (bufIndex >= 0);
  27945. }
  27946. else
  27947. {
  27948. bufIndex = getFreeBuffer (false);
  27949. renderingOps.add (new ClearChannelOp (bufIndex));
  27950. }
  27951. }
  27952. else if (sourceNodes.size() == 1)
  27953. {
  27954. // channel with a straightforward single input..
  27955. const int srcNode = sourceNodes.getUnchecked(0);
  27956. const int srcChan = sourceOutputChans.getUnchecked(0);
  27957. bufIndex = getBufferContaining (srcNode, srcChan);
  27958. if (bufIndex < 0)
  27959. {
  27960. // if not found, this is probably a feedback loop
  27961. bufIndex = getReadOnlyEmptyBuffer();
  27962. jassert (bufIndex >= 0);
  27963. }
  27964. if (inputChan < numOuts
  27965. && isBufferNeededLater (ourRenderingIndex,
  27966. inputChan,
  27967. srcNode, srcChan))
  27968. {
  27969. // can't mess up this channel because it's needed later by another node, so we
  27970. // need to use a copy of it..
  27971. const int newFreeBuffer = getFreeBuffer (false);
  27972. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  27973. bufIndex = newFreeBuffer;
  27974. }
  27975. }
  27976. else
  27977. {
  27978. // channel with a mix of several inputs..
  27979. // try to find a re-usable channel from our inputs..
  27980. int reusableInputIndex = -1;
  27981. for (int i = 0; i < sourceNodes.size(); ++i)
  27982. {
  27983. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  27984. sourceOutputChans.getUnchecked(i));
  27985. if (sourceBufIndex >= 0
  27986. && ! isBufferNeededLater (ourRenderingIndex,
  27987. inputChan,
  27988. sourceNodes.getUnchecked(i),
  27989. sourceOutputChans.getUnchecked(i)))
  27990. {
  27991. // we've found one of our input chans that can be re-used..
  27992. reusableInputIndex = i;
  27993. bufIndex = sourceBufIndex;
  27994. break;
  27995. }
  27996. }
  27997. if (reusableInputIndex < 0)
  27998. {
  27999. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28000. bufIndex = getFreeBuffer (false);
  28001. jassert (bufIndex != 0);
  28002. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28003. sourceOutputChans.getUnchecked (0));
  28004. if (srcIndex < 0)
  28005. {
  28006. // if not found, this is probably a feedback loop
  28007. renderingOps.add (new ClearChannelOp (bufIndex));
  28008. }
  28009. else
  28010. {
  28011. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28012. }
  28013. reusableInputIndex = 0;
  28014. }
  28015. for (int j = 0; j < sourceNodes.size(); ++j)
  28016. {
  28017. if (j != reusableInputIndex)
  28018. {
  28019. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28020. sourceOutputChans.getUnchecked(j));
  28021. if (srcIndex >= 0)
  28022. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28023. }
  28024. }
  28025. }
  28026. jassert (bufIndex >= 0);
  28027. audioChannelsToUse.add (bufIndex);
  28028. if (inputChan < numOuts)
  28029. markBufferAsContaining (bufIndex, node->id, inputChan);
  28030. }
  28031. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28032. {
  28033. const int bufIndex = getFreeBuffer (false);
  28034. jassert (bufIndex != 0);
  28035. audioChannelsToUse.add (bufIndex);
  28036. markBufferAsContaining (bufIndex, node->id, outputChan);
  28037. }
  28038. // Now the same thing for midi..
  28039. Array <int> midiSourceNodes;
  28040. for (int i = graph.getNumConnections(); --i >= 0;)
  28041. {
  28042. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28043. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28044. midiSourceNodes.add (c->sourceNodeId);
  28045. }
  28046. if (midiSourceNodes.size() == 0)
  28047. {
  28048. // No midi inputs..
  28049. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28050. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28051. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28052. }
  28053. else if (midiSourceNodes.size() == 1)
  28054. {
  28055. // One midi input..
  28056. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28057. AudioProcessorGraph::midiChannelIndex);
  28058. if (midiBufferToUse >= 0)
  28059. {
  28060. if (isBufferNeededLater (ourRenderingIndex,
  28061. AudioProcessorGraph::midiChannelIndex,
  28062. midiSourceNodes.getUnchecked(0),
  28063. AudioProcessorGraph::midiChannelIndex))
  28064. {
  28065. // can't mess up this channel because it's needed later by another node, so we
  28066. // need to use a copy of it..
  28067. const int newFreeBuffer = getFreeBuffer (true);
  28068. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28069. midiBufferToUse = newFreeBuffer;
  28070. }
  28071. }
  28072. else
  28073. {
  28074. // probably a feedback loop, so just use an empty one..
  28075. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28076. }
  28077. }
  28078. else
  28079. {
  28080. // More than one midi input being mixed..
  28081. int reusableInputIndex = -1;
  28082. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28083. {
  28084. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28085. AudioProcessorGraph::midiChannelIndex);
  28086. if (sourceBufIndex >= 0
  28087. && ! isBufferNeededLater (ourRenderingIndex,
  28088. AudioProcessorGraph::midiChannelIndex,
  28089. midiSourceNodes.getUnchecked(i),
  28090. AudioProcessorGraph::midiChannelIndex))
  28091. {
  28092. // we've found one of our input buffers that can be re-used..
  28093. reusableInputIndex = i;
  28094. midiBufferToUse = sourceBufIndex;
  28095. break;
  28096. }
  28097. }
  28098. if (reusableInputIndex < 0)
  28099. {
  28100. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28101. midiBufferToUse = getFreeBuffer (true);
  28102. jassert (midiBufferToUse >= 0);
  28103. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28104. AudioProcessorGraph::midiChannelIndex);
  28105. if (srcIndex >= 0)
  28106. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28107. else
  28108. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28109. reusableInputIndex = 0;
  28110. }
  28111. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28112. {
  28113. if (j != reusableInputIndex)
  28114. {
  28115. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28116. AudioProcessorGraph::midiChannelIndex);
  28117. if (srcIndex >= 0)
  28118. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28119. }
  28120. }
  28121. }
  28122. if (node->processor->producesMidi())
  28123. markBufferAsContaining (midiBufferToUse, node->id,
  28124. AudioProcessorGraph::midiChannelIndex);
  28125. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28126. totalChans, midiBufferToUse));
  28127. }
  28128. int getFreeBuffer (const bool forMidi)
  28129. {
  28130. if (forMidi)
  28131. {
  28132. for (int i = 1; i < midiNodeIds.size(); ++i)
  28133. if (midiNodeIds.getUnchecked(i) < 0)
  28134. return i;
  28135. midiNodeIds.add (-1);
  28136. return midiNodeIds.size() - 1;
  28137. }
  28138. else
  28139. {
  28140. for (int i = 1; i < nodeIds.size(); ++i)
  28141. if (nodeIds.getUnchecked(i) < 0)
  28142. return i;
  28143. nodeIds.add (-1);
  28144. channels.add (0);
  28145. return nodeIds.size() - 1;
  28146. }
  28147. }
  28148. int getReadOnlyEmptyBuffer() const throw()
  28149. {
  28150. return 0;
  28151. }
  28152. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  28153. {
  28154. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28155. {
  28156. for (int i = midiNodeIds.size(); --i >= 0;)
  28157. if (midiNodeIds.getUnchecked(i) == nodeId)
  28158. return i;
  28159. }
  28160. else
  28161. {
  28162. for (int i = nodeIds.size(); --i >= 0;)
  28163. if (nodeIds.getUnchecked(i) == nodeId
  28164. && channels.getUnchecked(i) == outputChannel)
  28165. return i;
  28166. }
  28167. return -1;
  28168. }
  28169. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28170. {
  28171. int i;
  28172. for (i = 0; i < nodeIds.size(); ++i)
  28173. {
  28174. if (nodeIds.getUnchecked(i) >= 0
  28175. && ! isBufferNeededLater (stepIndex, -1,
  28176. nodeIds.getUnchecked(i),
  28177. channels.getUnchecked(i)))
  28178. {
  28179. nodeIds.set (i, -1);
  28180. }
  28181. }
  28182. for (i = 0; i < midiNodeIds.size(); ++i)
  28183. {
  28184. if (midiNodeIds.getUnchecked(i) >= 0
  28185. && ! isBufferNeededLater (stepIndex, -1,
  28186. midiNodeIds.getUnchecked(i),
  28187. AudioProcessorGraph::midiChannelIndex))
  28188. {
  28189. midiNodeIds.set (i, -1);
  28190. }
  28191. }
  28192. }
  28193. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28194. int inputChannelOfIndexToIgnore,
  28195. const int nodeId,
  28196. const int outputChanIndex) const throw()
  28197. {
  28198. while (stepIndexToSearchFrom < orderedNodes.size())
  28199. {
  28200. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28201. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28202. {
  28203. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28204. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28205. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28206. return true;
  28207. }
  28208. else
  28209. {
  28210. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28211. if (i != inputChannelOfIndexToIgnore
  28212. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28213. node->id, i) != 0)
  28214. return true;
  28215. }
  28216. inputChannelOfIndexToIgnore = -1;
  28217. ++stepIndexToSearchFrom;
  28218. }
  28219. return false;
  28220. }
  28221. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28222. {
  28223. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28224. {
  28225. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28226. midiNodeIds.set (bufferNum, nodeId);
  28227. }
  28228. else
  28229. {
  28230. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28231. nodeIds.set (bufferNum, nodeId);
  28232. channels.set (bufferNum, outputIndex);
  28233. }
  28234. }
  28235. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28236. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28237. };
  28238. }
  28239. void AudioProcessorGraph::clearRenderingSequence()
  28240. {
  28241. const ScopedLock sl (renderLock);
  28242. for (int i = renderingOps.size(); --i >= 0;)
  28243. {
  28244. GraphRenderingOps::AudioGraphRenderingOp* const r
  28245. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28246. renderingOps.remove (i);
  28247. delete r;
  28248. }
  28249. }
  28250. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28251. const uint32 possibleDestinationId,
  28252. const int recursionCheck) const throw()
  28253. {
  28254. if (recursionCheck > 0)
  28255. {
  28256. for (int i = connections.size(); --i >= 0;)
  28257. {
  28258. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28259. if (c->destNodeId == possibleDestinationId
  28260. && (c->sourceNodeId == possibleInputId
  28261. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28262. return true;
  28263. }
  28264. }
  28265. return false;
  28266. }
  28267. void AudioProcessorGraph::buildRenderingSequence()
  28268. {
  28269. VoidArray newRenderingOps;
  28270. int numRenderingBuffersNeeded = 2;
  28271. int numMidiBuffersNeeded = 1;
  28272. {
  28273. MessageManagerLock mml;
  28274. VoidArray orderedNodes;
  28275. int i;
  28276. for (i = 0; i < nodes.size(); ++i)
  28277. {
  28278. Node* const node = nodes.getUnchecked(i);
  28279. node->prepare (getSampleRate(), getBlockSize(), this);
  28280. int j = 0;
  28281. for (; j < orderedNodes.size(); ++j)
  28282. if (isAnInputTo (node->id,
  28283. ((Node*) orderedNodes.getUnchecked (j))->id,
  28284. nodes.size() + 1))
  28285. break;
  28286. orderedNodes.insert (j, node);
  28287. }
  28288. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28289. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28290. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28291. }
  28292. VoidArray oldRenderingOps (renderingOps);
  28293. {
  28294. // swap over to the new rendering sequence..
  28295. const ScopedLock sl (renderLock);
  28296. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28297. renderingBuffers.clear();
  28298. for (int i = midiBuffers.size(); --i >= 0;)
  28299. midiBuffers.getUnchecked(i)->clear();
  28300. while (midiBuffers.size() < numMidiBuffersNeeded)
  28301. midiBuffers.add (new MidiBuffer());
  28302. renderingOps = newRenderingOps;
  28303. }
  28304. for (int i = oldRenderingOps.size(); --i >= 0;)
  28305. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28306. }
  28307. void AudioProcessorGraph::handleAsyncUpdate()
  28308. {
  28309. buildRenderingSequence();
  28310. }
  28311. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28312. {
  28313. currentAudioInputBuffer = 0;
  28314. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28315. currentMidiInputBuffer = 0;
  28316. currentMidiOutputBuffer.clear();
  28317. clearRenderingSequence();
  28318. buildRenderingSequence();
  28319. }
  28320. void AudioProcessorGraph::releaseResources()
  28321. {
  28322. for (int i = 0; i < nodes.size(); ++i)
  28323. nodes.getUnchecked(i)->unprepare();
  28324. renderingBuffers.setSize (1, 1);
  28325. midiBuffers.clear();
  28326. currentAudioInputBuffer = 0;
  28327. currentAudioOutputBuffer.setSize (1, 1);
  28328. currentMidiInputBuffer = 0;
  28329. currentMidiOutputBuffer.clear();
  28330. }
  28331. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28332. {
  28333. const int numSamples = buffer.getNumSamples();
  28334. const ScopedLock sl (renderLock);
  28335. currentAudioInputBuffer = &buffer;
  28336. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28337. currentAudioOutputBuffer.clear();
  28338. currentMidiInputBuffer = &midiMessages;
  28339. currentMidiOutputBuffer.clear();
  28340. int i;
  28341. for (i = 0; i < renderingOps.size(); ++i)
  28342. {
  28343. GraphRenderingOps::AudioGraphRenderingOp* const op
  28344. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28345. op->perform (renderingBuffers, midiBuffers, numSamples);
  28346. }
  28347. for (i = 0; i < buffer.getNumChannels(); ++i)
  28348. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28349. }
  28350. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28351. {
  28352. return "Input " + String (channelIndex + 1);
  28353. }
  28354. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28355. {
  28356. return "Output " + String (channelIndex + 1);
  28357. }
  28358. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28359. {
  28360. return true;
  28361. }
  28362. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28363. {
  28364. return true;
  28365. }
  28366. bool AudioProcessorGraph::acceptsMidi() const
  28367. {
  28368. return true;
  28369. }
  28370. bool AudioProcessorGraph::producesMidi() const
  28371. {
  28372. return true;
  28373. }
  28374. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28375. {
  28376. }
  28377. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28378. {
  28379. }
  28380. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28381. : type (type_),
  28382. graph (0)
  28383. {
  28384. }
  28385. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28386. {
  28387. }
  28388. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28389. {
  28390. switch (type)
  28391. {
  28392. case audioOutputNode:
  28393. return "Audio Output";
  28394. case audioInputNode:
  28395. return "Audio Input";
  28396. case midiOutputNode:
  28397. return "Midi Output";
  28398. case midiInputNode:
  28399. return "Midi Input";
  28400. default:
  28401. break;
  28402. }
  28403. return String::empty;
  28404. }
  28405. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28406. {
  28407. d.name = getName();
  28408. d.uid = d.name.hashCode();
  28409. d.category = "I/O devices";
  28410. d.pluginFormatName = "Internal";
  28411. d.manufacturerName = "Raw Material Software";
  28412. d.version = "1.0";
  28413. d.isInstrument = false;
  28414. d.numInputChannels = getNumInputChannels();
  28415. if (type == audioOutputNode && graph != 0)
  28416. d.numInputChannels = graph->getNumInputChannels();
  28417. d.numOutputChannels = getNumOutputChannels();
  28418. if (type == audioInputNode && graph != 0)
  28419. d.numOutputChannels = graph->getNumOutputChannels();
  28420. }
  28421. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28422. {
  28423. jassert (graph != 0);
  28424. }
  28425. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28426. {
  28427. }
  28428. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28429. MidiBuffer& midiMessages)
  28430. {
  28431. jassert (graph != 0);
  28432. switch (type)
  28433. {
  28434. case audioOutputNode:
  28435. {
  28436. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28437. buffer.getNumChannels()); --i >= 0;)
  28438. {
  28439. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28440. }
  28441. break;
  28442. }
  28443. case audioInputNode:
  28444. {
  28445. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28446. buffer.getNumChannels()); --i >= 0;)
  28447. {
  28448. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28449. }
  28450. break;
  28451. }
  28452. case midiOutputNode:
  28453. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28454. break;
  28455. case midiInputNode:
  28456. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28457. break;
  28458. default:
  28459. break;
  28460. }
  28461. }
  28462. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  28463. {
  28464. return type == midiOutputNode;
  28465. }
  28466. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  28467. {
  28468. return type == midiInputNode;
  28469. }
  28470. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  28471. {
  28472. switch (type)
  28473. {
  28474. case audioOutputNode:
  28475. return "Output " + String (channelIndex + 1);
  28476. case midiOutputNode:
  28477. return "Midi Output";
  28478. default:
  28479. break;
  28480. }
  28481. return String::empty;
  28482. }
  28483. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  28484. {
  28485. switch (type)
  28486. {
  28487. case audioInputNode:
  28488. return "Input " + String (channelIndex + 1);
  28489. case midiInputNode:
  28490. return "Midi Input";
  28491. default:
  28492. break;
  28493. }
  28494. return String::empty;
  28495. }
  28496. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  28497. {
  28498. return type == audioInputNode || type == audioOutputNode;
  28499. }
  28500. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  28501. {
  28502. return isInputChannelStereoPair (index);
  28503. }
  28504. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  28505. {
  28506. return type == audioInputNode || type == midiInputNode;
  28507. }
  28508. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  28509. {
  28510. return type == audioOutputNode || type == midiOutputNode;
  28511. }
  28512. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  28513. {
  28514. return 0;
  28515. }
  28516. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  28517. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  28518. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  28519. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  28520. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  28521. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  28522. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  28523. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  28524. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  28525. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  28526. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  28527. {
  28528. }
  28529. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  28530. {
  28531. }
  28532. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  28533. {
  28534. graph = newGraph;
  28535. if (graph != 0)
  28536. {
  28537. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  28538. type == audioInputNode ? graph->getNumInputChannels() : 0,
  28539. getSampleRate(),
  28540. getBlockSize());
  28541. updateHostDisplay();
  28542. }
  28543. }
  28544. END_JUCE_NAMESPACE
  28545. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  28546. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28547. BEGIN_JUCE_NAMESPACE
  28548. AudioProcessorPlayer::AudioProcessorPlayer()
  28549. : processor (0),
  28550. sampleRate (0),
  28551. blockSize (0),
  28552. isPrepared (false),
  28553. numInputChans (0),
  28554. numOutputChans (0),
  28555. tempBuffer (1, 1)
  28556. {
  28557. }
  28558. AudioProcessorPlayer::~AudioProcessorPlayer()
  28559. {
  28560. setProcessor (0);
  28561. }
  28562. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  28563. {
  28564. if (processor != processorToPlay)
  28565. {
  28566. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  28567. {
  28568. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  28569. sampleRate, blockSize);
  28570. processorToPlay->prepareToPlay (sampleRate, blockSize);
  28571. }
  28572. lock.enter();
  28573. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  28574. processor = processorToPlay;
  28575. isPrepared = true;
  28576. lock.exit();
  28577. if (oldOne != 0)
  28578. oldOne->releaseResources();
  28579. }
  28580. }
  28581. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  28582. int numInputChannels,
  28583. float** outputChannelData,
  28584. int numOutputChannels,
  28585. int numSamples)
  28586. {
  28587. // these should have been prepared by audioDeviceAboutToStart()...
  28588. jassert (sampleRate > 0 && blockSize > 0);
  28589. incomingMidi.clear();
  28590. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  28591. int i, totalNumChans = 0;
  28592. if (numInputChannels > numOutputChannels)
  28593. {
  28594. // if there aren't enough output channels for the number of
  28595. // inputs, we need to create some temporary extra ones (can't
  28596. // use the input data in case it gets written to)
  28597. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  28598. false, false, true);
  28599. for (i = 0; i < numOutputChannels; ++i)
  28600. {
  28601. channels[totalNumChans] = outputChannelData[i];
  28602. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28603. ++totalNumChans;
  28604. }
  28605. for (i = numOutputChannels; i < numInputChannels; ++i)
  28606. {
  28607. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  28608. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28609. ++totalNumChans;
  28610. }
  28611. }
  28612. else
  28613. {
  28614. for (i = 0; i < numInputChannels; ++i)
  28615. {
  28616. channels[totalNumChans] = outputChannelData[i];
  28617. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28618. ++totalNumChans;
  28619. }
  28620. for (i = numInputChannels; i < numOutputChannels; ++i)
  28621. {
  28622. channels[totalNumChans] = outputChannelData[i];
  28623. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  28624. ++totalNumChans;
  28625. }
  28626. }
  28627. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  28628. const ScopedLock sl (lock);
  28629. if (processor != 0)
  28630. processor->processBlock (buffer, incomingMidi);
  28631. }
  28632. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  28633. {
  28634. const ScopedLock sl (lock);
  28635. sampleRate = device->getCurrentSampleRate();
  28636. blockSize = device->getCurrentBufferSizeSamples();
  28637. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  28638. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  28639. messageCollector.reset (sampleRate);
  28640. zeromem (channels, sizeof (channels));
  28641. if (processor != 0)
  28642. {
  28643. if (isPrepared)
  28644. processor->releaseResources();
  28645. AudioProcessor* const oldProcessor = processor;
  28646. setProcessor (0);
  28647. setProcessor (oldProcessor);
  28648. }
  28649. }
  28650. void AudioProcessorPlayer::audioDeviceStopped()
  28651. {
  28652. const ScopedLock sl (lock);
  28653. if (processor != 0 && isPrepared)
  28654. processor->releaseResources();
  28655. sampleRate = 0.0;
  28656. blockSize = 0;
  28657. isPrepared = false;
  28658. tempBuffer.setSize (1, 1);
  28659. }
  28660. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  28661. {
  28662. messageCollector.addMessageToQueue (message);
  28663. }
  28664. END_JUCE_NAMESPACE
  28665. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28666. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28667. BEGIN_JUCE_NAMESPACE
  28668. class ProcessorParameterPropertyComp : public PropertyComponent,
  28669. public AudioProcessorListener,
  28670. public AsyncUpdater
  28671. {
  28672. public:
  28673. ProcessorParameterPropertyComp (const String& name,
  28674. AudioProcessor* const owner_,
  28675. const int index_)
  28676. : PropertyComponent (name),
  28677. owner (owner_),
  28678. index (index_)
  28679. {
  28680. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  28681. owner_->addListener (this);
  28682. }
  28683. ~ProcessorParameterPropertyComp()
  28684. {
  28685. owner->removeListener (this);
  28686. deleteAllChildren();
  28687. }
  28688. void refresh()
  28689. {
  28690. slider->setValue (owner->getParameter (index), false);
  28691. }
  28692. void audioProcessorChanged (AudioProcessor*) {}
  28693. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  28694. {
  28695. if (parameterIndex == index)
  28696. triggerAsyncUpdate();
  28697. }
  28698. void handleAsyncUpdate()
  28699. {
  28700. refresh();
  28701. }
  28702. juce_UseDebuggingNewOperator
  28703. private:
  28704. AudioProcessor* const owner;
  28705. const int index;
  28706. Slider* slider;
  28707. class ParamSlider : public Slider
  28708. {
  28709. public:
  28710. ParamSlider (AudioProcessor* const owner_, const int index_)
  28711. : Slider (String::empty),
  28712. owner (owner_),
  28713. index (index_)
  28714. {
  28715. setRange (0.0, 1.0, 0.0);
  28716. setSliderStyle (Slider::LinearBar);
  28717. setTextBoxIsEditable (false);
  28718. setScrollWheelEnabled (false);
  28719. }
  28720. ~ParamSlider()
  28721. {
  28722. }
  28723. void valueChanged()
  28724. {
  28725. const float newVal = (float) getValue();
  28726. if (owner->getParameter (index) != newVal)
  28727. owner->setParameter (index, newVal);
  28728. }
  28729. const String getTextFromValue (double /*value*/)
  28730. {
  28731. return owner->getParameterText (index);
  28732. }
  28733. juce_UseDebuggingNewOperator
  28734. private:
  28735. AudioProcessor* const owner;
  28736. const int index;
  28737. };
  28738. };
  28739. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  28740. : AudioProcessorEditor (owner)
  28741. {
  28742. setOpaque (true);
  28743. addAndMakeVisible (panel = new PropertyPanel());
  28744. Array <PropertyComponent*> params;
  28745. const int numParams = owner->getNumParameters();
  28746. int totalHeight = 0;
  28747. for (int i = 0; i < numParams; ++i)
  28748. {
  28749. String name (owner->getParameterName (i));
  28750. if (name.trim().isEmpty())
  28751. name = "Unnamed";
  28752. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  28753. params.add (pc);
  28754. totalHeight += pc->getPreferredHeight();
  28755. }
  28756. panel->addProperties (params);
  28757. setSize (400, jlimit (25, 400, totalHeight));
  28758. }
  28759. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  28760. {
  28761. deleteAllChildren();
  28762. }
  28763. void GenericAudioProcessorEditor::paint (Graphics& g)
  28764. {
  28765. g.fillAll (Colours::white);
  28766. }
  28767. void GenericAudioProcessorEditor::resized()
  28768. {
  28769. panel->setSize (getWidth(), getHeight());
  28770. }
  28771. END_JUCE_NAMESPACE
  28772. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28773. /********* Start of inlined file: juce_Sampler.cpp *********/
  28774. BEGIN_JUCE_NAMESPACE
  28775. SamplerSound::SamplerSound (const String& name_,
  28776. AudioFormatReader& source,
  28777. const BitArray& midiNotes_,
  28778. const int midiNoteForNormalPitch,
  28779. const double attackTimeSecs,
  28780. const double releaseTimeSecs,
  28781. const double maxSampleLengthSeconds)
  28782. : name (name_),
  28783. midiNotes (midiNotes_),
  28784. midiRootNote (midiNoteForNormalPitch)
  28785. {
  28786. sourceSampleRate = source.sampleRate;
  28787. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  28788. {
  28789. data = 0;
  28790. length = 0;
  28791. attackSamples = 0;
  28792. releaseSamples = 0;
  28793. }
  28794. else
  28795. {
  28796. length = jmin ((int) source.lengthInSamples,
  28797. (int) (maxSampleLengthSeconds * sourceSampleRate));
  28798. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  28799. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  28800. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  28801. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  28802. }
  28803. }
  28804. SamplerSound::~SamplerSound()
  28805. {
  28806. delete data;
  28807. data = 0;
  28808. }
  28809. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  28810. {
  28811. return midiNotes [midiNoteNumber];
  28812. }
  28813. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  28814. {
  28815. return true;
  28816. }
  28817. SamplerVoice::SamplerVoice()
  28818. : pitchRatio (0.0),
  28819. sourceSamplePosition (0.0),
  28820. lgain (0.0f),
  28821. rgain (0.0f),
  28822. isInAttack (false),
  28823. isInRelease (false)
  28824. {
  28825. }
  28826. SamplerVoice::~SamplerVoice()
  28827. {
  28828. }
  28829. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  28830. {
  28831. return dynamic_cast <const SamplerSound*> (sound) != 0;
  28832. }
  28833. void SamplerVoice::startNote (const int midiNoteNumber,
  28834. const float velocity,
  28835. SynthesiserSound* s,
  28836. const int /*currentPitchWheelPosition*/)
  28837. {
  28838. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  28839. jassert (sound != 0); // this object can only play SamplerSounds!
  28840. if (sound != 0)
  28841. {
  28842. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  28843. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  28844. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  28845. sourceSamplePosition = 0.0;
  28846. lgain = velocity;
  28847. rgain = velocity;
  28848. isInAttack = (sound->attackSamples > 0);
  28849. isInRelease = false;
  28850. if (isInAttack)
  28851. {
  28852. attackReleaseLevel = 0.0f;
  28853. attackDelta = (float) (pitchRatio / sound->attackSamples);
  28854. }
  28855. else
  28856. {
  28857. attackReleaseLevel = 1.0f;
  28858. attackDelta = 0.0f;
  28859. }
  28860. if (sound->releaseSamples > 0)
  28861. {
  28862. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  28863. }
  28864. else
  28865. {
  28866. releaseDelta = 0.0f;
  28867. }
  28868. }
  28869. }
  28870. void SamplerVoice::stopNote (const bool allowTailOff)
  28871. {
  28872. if (allowTailOff)
  28873. {
  28874. isInAttack = false;
  28875. isInRelease = true;
  28876. }
  28877. else
  28878. {
  28879. clearCurrentNote();
  28880. }
  28881. }
  28882. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  28883. {
  28884. }
  28885. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  28886. const int /*newValue*/)
  28887. {
  28888. }
  28889. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  28890. {
  28891. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  28892. if (playingSound != 0)
  28893. {
  28894. const float* const inL = playingSound->data->getSampleData (0, 0);
  28895. const float* const inR = playingSound->data->getNumChannels() > 1
  28896. ? playingSound->data->getSampleData (1, 0) : 0;
  28897. float* outL = outputBuffer.getSampleData (0, startSample);
  28898. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  28899. while (--numSamples >= 0)
  28900. {
  28901. const int pos = (int) sourceSamplePosition;
  28902. const float alpha = (float) (sourceSamplePosition - pos);
  28903. const float invAlpha = 1.0f - alpha;
  28904. // just using a very simple linear interpolation here..
  28905. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  28906. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  28907. : l;
  28908. l *= lgain;
  28909. r *= rgain;
  28910. if (isInAttack)
  28911. {
  28912. l *= attackReleaseLevel;
  28913. r *= attackReleaseLevel;
  28914. attackReleaseLevel += attackDelta;
  28915. if (attackReleaseLevel >= 1.0f)
  28916. {
  28917. attackReleaseLevel = 1.0f;
  28918. isInAttack = false;
  28919. }
  28920. }
  28921. else if (isInRelease)
  28922. {
  28923. l *= attackReleaseLevel;
  28924. r *= attackReleaseLevel;
  28925. attackReleaseLevel += releaseDelta;
  28926. if (attackReleaseLevel <= 0.0f)
  28927. {
  28928. stopNote (false);
  28929. break;
  28930. }
  28931. }
  28932. if (outR != 0)
  28933. {
  28934. *outL++ += l;
  28935. *outR++ += r;
  28936. }
  28937. else
  28938. {
  28939. *outL++ += (l + r) * 0.5f;
  28940. }
  28941. sourceSamplePosition += pitchRatio;
  28942. if (sourceSamplePosition > playingSound->length)
  28943. {
  28944. stopNote (false);
  28945. break;
  28946. }
  28947. }
  28948. }
  28949. }
  28950. END_JUCE_NAMESPACE
  28951. /********* End of inlined file: juce_Sampler.cpp *********/
  28952. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  28953. BEGIN_JUCE_NAMESPACE
  28954. SynthesiserSound::SynthesiserSound()
  28955. {
  28956. }
  28957. SynthesiserSound::~SynthesiserSound()
  28958. {
  28959. }
  28960. SynthesiserVoice::SynthesiserVoice()
  28961. : currentSampleRate (44100.0),
  28962. currentlyPlayingNote (-1),
  28963. noteOnTime (0),
  28964. currentlyPlayingSound (0)
  28965. {
  28966. }
  28967. SynthesiserVoice::~SynthesiserVoice()
  28968. {
  28969. }
  28970. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  28971. {
  28972. return currentlyPlayingSound != 0
  28973. && currentlyPlayingSound->appliesToChannel (midiChannel);
  28974. }
  28975. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  28976. {
  28977. currentSampleRate = newRate;
  28978. }
  28979. void SynthesiserVoice::clearCurrentNote()
  28980. {
  28981. currentlyPlayingNote = -1;
  28982. currentlyPlayingSound = 0;
  28983. }
  28984. Synthesiser::Synthesiser()
  28985. : voices (2),
  28986. sounds (2),
  28987. sampleRate (0),
  28988. lastNoteOnCounter (0),
  28989. shouldStealNotes (true)
  28990. {
  28991. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  28992. lastPitchWheelValues[i] = 0x2000;
  28993. }
  28994. Synthesiser::~Synthesiser()
  28995. {
  28996. }
  28997. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  28998. {
  28999. const ScopedLock sl (lock);
  29000. return voices [index];
  29001. }
  29002. void Synthesiser::clearVoices()
  29003. {
  29004. const ScopedLock sl (lock);
  29005. voices.clear();
  29006. }
  29007. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29008. {
  29009. const ScopedLock sl (lock);
  29010. voices.add (newVoice);
  29011. }
  29012. void Synthesiser::removeVoice (const int index)
  29013. {
  29014. const ScopedLock sl (lock);
  29015. voices.remove (index);
  29016. }
  29017. void Synthesiser::clearSounds()
  29018. {
  29019. const ScopedLock sl (lock);
  29020. sounds.clear();
  29021. }
  29022. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29023. {
  29024. const ScopedLock sl (lock);
  29025. sounds.add (newSound);
  29026. }
  29027. void Synthesiser::removeSound (const int index)
  29028. {
  29029. const ScopedLock sl (lock);
  29030. sounds.remove (index);
  29031. }
  29032. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29033. {
  29034. shouldStealNotes = shouldStealNotes_;
  29035. }
  29036. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29037. {
  29038. if (sampleRate != newRate)
  29039. {
  29040. const ScopedLock sl (lock);
  29041. allNotesOff (0, false);
  29042. sampleRate = newRate;
  29043. for (int i = voices.size(); --i >= 0;)
  29044. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29045. }
  29046. }
  29047. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29048. const MidiBuffer& midiData,
  29049. int startSample,
  29050. int numSamples)
  29051. {
  29052. // must set the sample rate before using this!
  29053. jassert (sampleRate != 0);
  29054. const ScopedLock sl (lock);
  29055. MidiBuffer::Iterator midiIterator (midiData);
  29056. midiIterator.setNextSamplePosition (startSample);
  29057. MidiMessage m (0xf4, 0.0);
  29058. while (numSamples > 0)
  29059. {
  29060. int midiEventPos;
  29061. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29062. && midiEventPos < startSample + numSamples;
  29063. const int numThisTime = useEvent ? midiEventPos - startSample
  29064. : numSamples;
  29065. if (numThisTime > 0)
  29066. {
  29067. for (int i = voices.size(); --i >= 0;)
  29068. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29069. }
  29070. if (useEvent)
  29071. {
  29072. if (m.isNoteOn())
  29073. {
  29074. const int channel = m.getChannel();
  29075. noteOn (channel,
  29076. m.getNoteNumber(),
  29077. m.getFloatVelocity());
  29078. }
  29079. else if (m.isNoteOff())
  29080. {
  29081. noteOff (m.getChannel(),
  29082. m.getNoteNumber(),
  29083. true);
  29084. }
  29085. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29086. {
  29087. allNotesOff (m.getChannel(), true);
  29088. }
  29089. else if (m.isPitchWheel())
  29090. {
  29091. const int channel = m.getChannel();
  29092. const int wheelPos = m.getPitchWheelValue();
  29093. lastPitchWheelValues [channel - 1] = wheelPos;
  29094. handlePitchWheel (channel, wheelPos);
  29095. }
  29096. else if (m.isController())
  29097. {
  29098. handleController (m.getChannel(),
  29099. m.getControllerNumber(),
  29100. m.getControllerValue());
  29101. }
  29102. }
  29103. startSample += numThisTime;
  29104. numSamples -= numThisTime;
  29105. }
  29106. }
  29107. void Synthesiser::noteOn (const int midiChannel,
  29108. const int midiNoteNumber,
  29109. const float velocity)
  29110. {
  29111. const ScopedLock sl (lock);
  29112. for (int i = sounds.size(); --i >= 0;)
  29113. {
  29114. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29115. if (sound->appliesToNote (midiNoteNumber)
  29116. && sound->appliesToChannel (midiChannel))
  29117. {
  29118. startVoice (findFreeVoice (sound, shouldStealNotes),
  29119. sound, midiChannel, midiNoteNumber, velocity);
  29120. }
  29121. }
  29122. }
  29123. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29124. SynthesiserSound* const sound,
  29125. const int midiChannel,
  29126. const int midiNoteNumber,
  29127. const float velocity)
  29128. {
  29129. if (voice != 0 && sound != 0)
  29130. {
  29131. if (voice->currentlyPlayingSound != 0)
  29132. voice->stopNote (false);
  29133. voice->startNote (midiNoteNumber,
  29134. velocity,
  29135. sound,
  29136. lastPitchWheelValues [midiChannel - 1]);
  29137. voice->currentlyPlayingNote = midiNoteNumber;
  29138. voice->noteOnTime = ++lastNoteOnCounter;
  29139. voice->currentlyPlayingSound = sound;
  29140. }
  29141. }
  29142. void Synthesiser::noteOff (const int midiChannel,
  29143. const int midiNoteNumber,
  29144. const bool allowTailOff)
  29145. {
  29146. const ScopedLock sl (lock);
  29147. for (int i = voices.size(); --i >= 0;)
  29148. {
  29149. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29150. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29151. {
  29152. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29153. if (sound != 0
  29154. && sound->appliesToNote (midiNoteNumber)
  29155. && sound->appliesToChannel (midiChannel))
  29156. {
  29157. voice->stopNote (allowTailOff);
  29158. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29159. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29160. }
  29161. }
  29162. }
  29163. }
  29164. void Synthesiser::allNotesOff (const int midiChannel,
  29165. const bool allowTailOff)
  29166. {
  29167. const ScopedLock sl (lock);
  29168. for (int i = voices.size(); --i >= 0;)
  29169. {
  29170. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29171. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29172. voice->stopNote (allowTailOff);
  29173. }
  29174. }
  29175. void Synthesiser::handlePitchWheel (const int midiChannel,
  29176. const int wheelValue)
  29177. {
  29178. const ScopedLock sl (lock);
  29179. for (int i = voices.size(); --i >= 0;)
  29180. {
  29181. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29182. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29183. {
  29184. voice->pitchWheelMoved (wheelValue);
  29185. }
  29186. }
  29187. }
  29188. void Synthesiser::handleController (const int midiChannel,
  29189. const int controllerNumber,
  29190. const int controllerValue)
  29191. {
  29192. const ScopedLock sl (lock);
  29193. for (int i = voices.size(); --i >= 0;)
  29194. {
  29195. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29196. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29197. voice->controllerMoved (controllerNumber, controllerValue);
  29198. }
  29199. }
  29200. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29201. const bool stealIfNoneAvailable) const
  29202. {
  29203. const ScopedLock sl (lock);
  29204. for (int i = voices.size(); --i >= 0;)
  29205. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29206. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29207. return voices.getUnchecked (i);
  29208. if (stealIfNoneAvailable)
  29209. {
  29210. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29211. SynthesiserVoice* oldest = 0;
  29212. for (int i = voices.size(); --i >= 0;)
  29213. {
  29214. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29215. if (voice->canPlaySound (soundToPlay)
  29216. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29217. oldest = voice;
  29218. }
  29219. jassert (oldest != 0);
  29220. return oldest;
  29221. }
  29222. return 0;
  29223. }
  29224. END_JUCE_NAMESPACE
  29225. /********* End of inlined file: juce_Synthesiser.cpp *********/
  29226. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  29227. BEGIN_JUCE_NAMESPACE
  29228. ActionBroadcaster::ActionBroadcaster() throw()
  29229. {
  29230. // are you trying to create this object before or after juce has been intialised??
  29231. jassert (MessageManager::instance != 0);
  29232. }
  29233. ActionBroadcaster::~ActionBroadcaster()
  29234. {
  29235. // all event-based objects must be deleted BEFORE juce is shut down!
  29236. jassert (MessageManager::instance != 0);
  29237. }
  29238. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29239. {
  29240. actionListenerList.addActionListener (listener);
  29241. }
  29242. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29243. {
  29244. jassert (actionListenerList.isValidMessageListener());
  29245. if (actionListenerList.isValidMessageListener())
  29246. actionListenerList.removeActionListener (listener);
  29247. }
  29248. void ActionBroadcaster::removeAllActionListeners()
  29249. {
  29250. actionListenerList.removeAllActionListeners();
  29251. }
  29252. void ActionBroadcaster::sendActionMessage (const String& message) const
  29253. {
  29254. actionListenerList.sendActionMessage (message);
  29255. }
  29256. END_JUCE_NAMESPACE
  29257. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  29258. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  29259. BEGIN_JUCE_NAMESPACE
  29260. // special message of our own with a string in it
  29261. class ActionMessage : public Message
  29262. {
  29263. public:
  29264. const String message;
  29265. ActionMessage (const String& messageText,
  29266. void* const listener_) throw()
  29267. : message (messageText)
  29268. {
  29269. pointerParameter = listener_;
  29270. }
  29271. ~ActionMessage() throw()
  29272. {
  29273. }
  29274. private:
  29275. ActionMessage (const ActionMessage&);
  29276. const ActionMessage& operator= (const ActionMessage&);
  29277. };
  29278. ActionListenerList::ActionListenerList() throw()
  29279. {
  29280. }
  29281. ActionListenerList::~ActionListenerList() throw()
  29282. {
  29283. }
  29284. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29285. {
  29286. const ScopedLock sl (actionListenerLock_);
  29287. jassert (listener != 0);
  29288. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29289. if (listener != 0)
  29290. actionListeners_.add (listener);
  29291. }
  29292. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29293. {
  29294. const ScopedLock sl (actionListenerLock_);
  29295. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29296. actionListeners_.removeValue (listener);
  29297. }
  29298. void ActionListenerList::removeAllActionListeners() throw()
  29299. {
  29300. const ScopedLock sl (actionListenerLock_);
  29301. actionListeners_.clear();
  29302. }
  29303. void ActionListenerList::sendActionMessage (const String& message) const
  29304. {
  29305. const ScopedLock sl (actionListenerLock_);
  29306. for (int i = actionListeners_.size(); --i >= 0;)
  29307. {
  29308. postMessage (new ActionMessage (message,
  29309. (ActionListener*) actionListeners_.getUnchecked(i)));
  29310. }
  29311. }
  29312. void ActionListenerList::handleMessage (const Message& message)
  29313. {
  29314. const ActionMessage& am = (const ActionMessage&) message;
  29315. if (actionListeners_.contains (am.pointerParameter))
  29316. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  29317. }
  29318. END_JUCE_NAMESPACE
  29319. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  29320. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  29321. BEGIN_JUCE_NAMESPACE
  29322. AsyncUpdater::AsyncUpdater() throw()
  29323. : asyncMessagePending (false)
  29324. {
  29325. internalAsyncHandler.owner = this;
  29326. }
  29327. AsyncUpdater::~AsyncUpdater()
  29328. {
  29329. }
  29330. void AsyncUpdater::triggerAsyncUpdate() throw()
  29331. {
  29332. if (! asyncMessagePending)
  29333. {
  29334. asyncMessagePending = true;
  29335. internalAsyncHandler.postMessage (new Message());
  29336. }
  29337. }
  29338. void AsyncUpdater::cancelPendingUpdate() throw()
  29339. {
  29340. asyncMessagePending = false;
  29341. }
  29342. void AsyncUpdater::handleUpdateNowIfNeeded()
  29343. {
  29344. if (asyncMessagePending)
  29345. {
  29346. asyncMessagePending = false;
  29347. handleAsyncUpdate();
  29348. }
  29349. }
  29350. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29351. {
  29352. owner->handleUpdateNowIfNeeded();
  29353. }
  29354. END_JUCE_NAMESPACE
  29355. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  29356. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  29357. BEGIN_JUCE_NAMESPACE
  29358. ChangeBroadcaster::ChangeBroadcaster() throw()
  29359. {
  29360. // are you trying to create this object before or after juce has been intialised??
  29361. jassert (MessageManager::instance != 0);
  29362. }
  29363. ChangeBroadcaster::~ChangeBroadcaster()
  29364. {
  29365. // all event-based objects must be deleted BEFORE juce is shut down!
  29366. jassert (MessageManager::instance != 0);
  29367. }
  29368. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29369. {
  29370. changeListenerList.addChangeListener (listener);
  29371. }
  29372. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29373. {
  29374. jassert (changeListenerList.isValidMessageListener());
  29375. if (changeListenerList.isValidMessageListener())
  29376. changeListenerList.removeChangeListener (listener);
  29377. }
  29378. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29379. {
  29380. changeListenerList.removeAllChangeListeners();
  29381. }
  29382. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29383. {
  29384. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29385. }
  29386. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29387. {
  29388. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29389. }
  29390. void ChangeBroadcaster::dispatchPendingMessages()
  29391. {
  29392. changeListenerList.dispatchPendingMessages();
  29393. }
  29394. END_JUCE_NAMESPACE
  29395. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  29396. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  29397. BEGIN_JUCE_NAMESPACE
  29398. ChangeListenerList::ChangeListenerList() throw()
  29399. : lastChangedObject (0),
  29400. messagePending (false)
  29401. {
  29402. }
  29403. ChangeListenerList::~ChangeListenerList() throw()
  29404. {
  29405. }
  29406. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29407. {
  29408. const ScopedLock sl (lock);
  29409. jassert (listener != 0);
  29410. if (listener != 0)
  29411. listeners.add (listener);
  29412. }
  29413. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29414. {
  29415. const ScopedLock sl (lock);
  29416. listeners.removeValue (listener);
  29417. }
  29418. void ChangeListenerList::removeAllChangeListeners() throw()
  29419. {
  29420. const ScopedLock sl (lock);
  29421. listeners.clear();
  29422. }
  29423. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29424. {
  29425. const ScopedLock sl (lock);
  29426. if ((! messagePending) && (listeners.size() > 0))
  29427. {
  29428. lastChangedObject = objectThatHasChanged;
  29429. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29430. messagePending = true;
  29431. }
  29432. }
  29433. void ChangeListenerList::handleMessage (const Message& message)
  29434. {
  29435. sendSynchronousChangeMessage (message.pointerParameter);
  29436. }
  29437. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29438. {
  29439. const ScopedLock sl (lock);
  29440. messagePending = false;
  29441. for (int i = listeners.size(); --i >= 0;)
  29442. {
  29443. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  29444. {
  29445. const ScopedUnlock tempUnlocker (lock);
  29446. l->changeListenerCallback (objectThatHasChanged);
  29447. }
  29448. i = jmin (i, listeners.size());
  29449. }
  29450. }
  29451. void ChangeListenerList::dispatchPendingMessages()
  29452. {
  29453. if (messagePending)
  29454. sendSynchronousChangeMessage (lastChangedObject);
  29455. }
  29456. END_JUCE_NAMESPACE
  29457. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  29458. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  29459. BEGIN_JUCE_NAMESPACE
  29460. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29461. const uint32 magicMessageHeaderNumber)
  29462. : Thread ("Juce IPC connection"),
  29463. socket (0),
  29464. pipe (0),
  29465. callbackConnectionState (false),
  29466. useMessageThread (callbacksOnMessageThread),
  29467. magicMessageHeader (magicMessageHeaderNumber),
  29468. pipeReceiveMessageTimeout (-1)
  29469. {
  29470. }
  29471. InterprocessConnection::~InterprocessConnection()
  29472. {
  29473. callbackConnectionState = false;
  29474. disconnect();
  29475. }
  29476. bool InterprocessConnection::connectToSocket (const String& hostName,
  29477. const int portNumber,
  29478. const int timeOutMillisecs)
  29479. {
  29480. disconnect();
  29481. const ScopedLock sl (pipeAndSocketLock);
  29482. socket = new StreamingSocket();
  29483. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  29484. {
  29485. connectionMadeInt();
  29486. startThread();
  29487. return true;
  29488. }
  29489. else
  29490. {
  29491. deleteAndZero (socket);
  29492. return false;
  29493. }
  29494. }
  29495. bool InterprocessConnection::connectToPipe (const String& pipeName,
  29496. const int pipeReceiveMessageTimeoutMs)
  29497. {
  29498. disconnect();
  29499. NamedPipe* const newPipe = new NamedPipe();
  29500. if (newPipe->openExisting (pipeName))
  29501. {
  29502. const ScopedLock sl (pipeAndSocketLock);
  29503. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29504. initialiseWithPipe (newPipe);
  29505. return true;
  29506. }
  29507. else
  29508. {
  29509. delete newPipe;
  29510. return false;
  29511. }
  29512. }
  29513. bool InterprocessConnection::createPipe (const String& pipeName,
  29514. const int pipeReceiveMessageTimeoutMs)
  29515. {
  29516. disconnect();
  29517. NamedPipe* const newPipe = new NamedPipe();
  29518. if (newPipe->createNewPipe (pipeName))
  29519. {
  29520. const ScopedLock sl (pipeAndSocketLock);
  29521. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29522. initialiseWithPipe (newPipe);
  29523. return true;
  29524. }
  29525. else
  29526. {
  29527. delete newPipe;
  29528. return false;
  29529. }
  29530. }
  29531. void InterprocessConnection::disconnect()
  29532. {
  29533. if (socket != 0)
  29534. socket->close();
  29535. if (pipe != 0)
  29536. {
  29537. pipe->cancelPendingReads();
  29538. pipe->close();
  29539. }
  29540. stopThread (4000);
  29541. {
  29542. const ScopedLock sl (pipeAndSocketLock);
  29543. deleteAndZero (socket);
  29544. deleteAndZero (pipe);
  29545. }
  29546. connectionLostInt();
  29547. }
  29548. bool InterprocessConnection::isConnected() const
  29549. {
  29550. const ScopedLock sl (pipeAndSocketLock);
  29551. return ((socket != 0 && socket->isConnected())
  29552. || (pipe != 0 && pipe->isOpen()))
  29553. && isThreadRunning();
  29554. }
  29555. const String InterprocessConnection::getConnectedHostName() const
  29556. {
  29557. if (pipe != 0)
  29558. {
  29559. return "localhost";
  29560. }
  29561. else if (socket != 0)
  29562. {
  29563. if (! socket->isLocal())
  29564. return socket->getHostName();
  29565. return "localhost";
  29566. }
  29567. return String::empty;
  29568. }
  29569. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  29570. {
  29571. uint32 messageHeader[2];
  29572. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  29573. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  29574. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  29575. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  29576. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  29577. int bytesWritten = 0;
  29578. const ScopedLock sl (pipeAndSocketLock);
  29579. if (socket != 0)
  29580. {
  29581. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  29582. }
  29583. else if (pipe != 0)
  29584. {
  29585. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  29586. }
  29587. if (bytesWritten < 0)
  29588. {
  29589. // error..
  29590. return false;
  29591. }
  29592. return (bytesWritten == messageData.getSize());
  29593. }
  29594. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  29595. {
  29596. jassert (socket == 0);
  29597. socket = socket_;
  29598. connectionMadeInt();
  29599. startThread();
  29600. }
  29601. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  29602. {
  29603. jassert (pipe == 0);
  29604. pipe = pipe_;
  29605. connectionMadeInt();
  29606. startThread();
  29607. }
  29608. const int messageMagicNumber = 0xb734128b;
  29609. void InterprocessConnection::handleMessage (const Message& message)
  29610. {
  29611. if (message.intParameter1 == messageMagicNumber)
  29612. {
  29613. switch (message.intParameter2)
  29614. {
  29615. case 0:
  29616. {
  29617. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  29618. messageReceived (*data);
  29619. delete data;
  29620. break;
  29621. }
  29622. case 1:
  29623. connectionMade();
  29624. break;
  29625. case 2:
  29626. connectionLost();
  29627. break;
  29628. }
  29629. }
  29630. }
  29631. void InterprocessConnection::connectionMadeInt()
  29632. {
  29633. if (! callbackConnectionState)
  29634. {
  29635. callbackConnectionState = true;
  29636. if (useMessageThread)
  29637. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  29638. else
  29639. connectionMade();
  29640. }
  29641. }
  29642. void InterprocessConnection::connectionLostInt()
  29643. {
  29644. if (callbackConnectionState)
  29645. {
  29646. callbackConnectionState = false;
  29647. if (useMessageThread)
  29648. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  29649. else
  29650. connectionLost();
  29651. }
  29652. }
  29653. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  29654. {
  29655. jassert (callbackConnectionState);
  29656. if (useMessageThread)
  29657. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  29658. else
  29659. messageReceived (data);
  29660. }
  29661. bool InterprocessConnection::readNextMessageInt()
  29662. {
  29663. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  29664. uint32 messageHeader[2];
  29665. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  29666. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  29667. if (bytes == sizeof (messageHeader)
  29668. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  29669. {
  29670. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  29671. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  29672. {
  29673. MemoryBlock messageData (bytesInMessage, true);
  29674. int bytesRead = 0;
  29675. while (bytesRead < bytesInMessage)
  29676. {
  29677. if (threadShouldExit())
  29678. return false;
  29679. const int numThisTime = jmin (bytesInMessage, 65536);
  29680. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime, true)
  29681. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  29682. pipeReceiveMessageTimeout);
  29683. if (bytesIn <= 0)
  29684. break;
  29685. bytesRead += bytesIn;
  29686. }
  29687. if (bytesRead >= 0)
  29688. deliverDataInt (messageData);
  29689. }
  29690. }
  29691. else if (bytes < 0)
  29692. {
  29693. {
  29694. const ScopedLock sl (pipeAndSocketLock);
  29695. deleteAndZero (socket);
  29696. }
  29697. connectionLostInt();
  29698. return false;
  29699. }
  29700. return true;
  29701. }
  29702. void InterprocessConnection::run()
  29703. {
  29704. while (! threadShouldExit())
  29705. {
  29706. if (socket != 0)
  29707. {
  29708. const int ready = socket->waitUntilReady (true, 0);
  29709. if (ready < 0)
  29710. {
  29711. {
  29712. const ScopedLock sl (pipeAndSocketLock);
  29713. deleteAndZero (socket);
  29714. }
  29715. connectionLostInt();
  29716. break;
  29717. }
  29718. else if (ready > 0)
  29719. {
  29720. if (! readNextMessageInt())
  29721. break;
  29722. }
  29723. else
  29724. {
  29725. Thread::sleep (2);
  29726. }
  29727. }
  29728. else if (pipe != 0)
  29729. {
  29730. if (! pipe->isOpen())
  29731. {
  29732. {
  29733. const ScopedLock sl (pipeAndSocketLock);
  29734. deleteAndZero (pipe);
  29735. }
  29736. connectionLostInt();
  29737. break;
  29738. }
  29739. else
  29740. {
  29741. if (! readNextMessageInt())
  29742. break;
  29743. }
  29744. }
  29745. else
  29746. {
  29747. break;
  29748. }
  29749. }
  29750. }
  29751. END_JUCE_NAMESPACE
  29752. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  29753. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29754. BEGIN_JUCE_NAMESPACE
  29755. InterprocessConnectionServer::InterprocessConnectionServer()
  29756. : Thread ("Juce IPC server"),
  29757. socket (0)
  29758. {
  29759. }
  29760. InterprocessConnectionServer::~InterprocessConnectionServer()
  29761. {
  29762. stop();
  29763. }
  29764. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  29765. {
  29766. stop();
  29767. socket = new StreamingSocket();
  29768. if (socket->createListener (portNumber))
  29769. {
  29770. startThread();
  29771. return true;
  29772. }
  29773. deleteAndZero (socket);
  29774. return false;
  29775. }
  29776. void InterprocessConnectionServer::stop()
  29777. {
  29778. signalThreadShouldExit();
  29779. if (socket != 0)
  29780. socket->close();
  29781. stopThread (4000);
  29782. deleteAndZero (socket);
  29783. }
  29784. void InterprocessConnectionServer::run()
  29785. {
  29786. while ((! threadShouldExit()) && socket != 0)
  29787. {
  29788. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  29789. if (clientSocket != 0)
  29790. {
  29791. InterprocessConnection* newConnection = createConnectionObject();
  29792. if (newConnection != 0)
  29793. {
  29794. newConnection->initialiseWithSocket (clientSocket);
  29795. }
  29796. else
  29797. {
  29798. delete clientSocket;
  29799. }
  29800. }
  29801. }
  29802. }
  29803. END_JUCE_NAMESPACE
  29804. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29805. /********* Start of inlined file: juce_Message.cpp *********/
  29806. BEGIN_JUCE_NAMESPACE
  29807. Message::Message() throw()
  29808. {
  29809. }
  29810. Message::~Message() throw()
  29811. {
  29812. }
  29813. Message::Message (const int intParameter1_,
  29814. const int intParameter2_,
  29815. const int intParameter3_,
  29816. void* const pointerParameter_) throw()
  29817. : intParameter1 (intParameter1_),
  29818. intParameter2 (intParameter2_),
  29819. intParameter3 (intParameter3_),
  29820. pointerParameter (pointerParameter_)
  29821. {
  29822. }
  29823. END_JUCE_NAMESPACE
  29824. /********* End of inlined file: juce_Message.cpp *********/
  29825. /********* Start of inlined file: juce_MessageListener.cpp *********/
  29826. BEGIN_JUCE_NAMESPACE
  29827. MessageListener::MessageListener() throw()
  29828. {
  29829. // are you trying to create a messagelistener before or after juce has been intialised??
  29830. jassert (MessageManager::instance != 0);
  29831. if (MessageManager::instance != 0)
  29832. MessageManager::instance->messageListeners.add (this);
  29833. }
  29834. MessageListener::~MessageListener()
  29835. {
  29836. if (MessageManager::instance != 0)
  29837. MessageManager::instance->messageListeners.removeValue (this);
  29838. }
  29839. void MessageListener::postMessage (Message* const message) const throw()
  29840. {
  29841. message->messageRecipient = const_cast <MessageListener*> (this);
  29842. if (MessageManager::instance == 0)
  29843. MessageManager::getInstance();
  29844. MessageManager::instance->postMessageToQueue (message);
  29845. }
  29846. bool MessageListener::isValidMessageListener() const throw()
  29847. {
  29848. return (MessageManager::instance != 0)
  29849. && MessageManager::instance->messageListeners.contains (this);
  29850. }
  29851. END_JUCE_NAMESPACE
  29852. /********* End of inlined file: juce_MessageListener.cpp *********/
  29853. /********* Start of inlined file: juce_MessageManager.cpp *********/
  29854. BEGIN_JUCE_NAMESPACE
  29855. // platform-specific functions..
  29856. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  29857. bool juce_postMessageToSystemQueue (void* message);
  29858. MessageManager* MessageManager::instance = 0;
  29859. static const int quitMessageId = 0xfffff321;
  29860. MessageManager::MessageManager() throw()
  29861. : broadcastListeners (0),
  29862. quitMessagePosted (false),
  29863. quitMessageReceived (false),
  29864. threadWithLock (0)
  29865. {
  29866. messageThreadId = Thread::getCurrentThreadId();
  29867. }
  29868. MessageManager::~MessageManager() throw()
  29869. {
  29870. deleteAndZero (broadcastListeners);
  29871. doPlatformSpecificShutdown();
  29872. jassert (instance == this);
  29873. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  29874. }
  29875. MessageManager* MessageManager::getInstance() throw()
  29876. {
  29877. if (instance == 0)
  29878. {
  29879. instance = new MessageManager();
  29880. doPlatformSpecificInitialisation();
  29881. }
  29882. return instance;
  29883. }
  29884. void MessageManager::postMessageToQueue (Message* const message)
  29885. {
  29886. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  29887. delete message;
  29888. }
  29889. CallbackMessage::CallbackMessage() throw() {}
  29890. CallbackMessage::~CallbackMessage() throw() {}
  29891. void CallbackMessage::post()
  29892. {
  29893. if (MessageManager::instance != 0)
  29894. MessageManager::instance->postCallbackMessage (this);
  29895. }
  29896. void MessageManager::postCallbackMessage (Message* const message)
  29897. {
  29898. message->messageRecipient = 0;
  29899. postMessageToQueue (message);
  29900. }
  29901. // not for public use..
  29902. void MessageManager::deliverMessage (void* message)
  29903. {
  29904. Message* const m = (Message*) message;
  29905. MessageListener* const recipient = m->messageRecipient;
  29906. JUCE_TRY
  29907. {
  29908. if (messageListeners.contains (recipient))
  29909. {
  29910. recipient->handleMessage (*m);
  29911. }
  29912. else if (recipient == 0)
  29913. {
  29914. if (m->intParameter1 == quitMessageId)
  29915. {
  29916. quitMessageReceived = true;
  29917. }
  29918. else if (dynamic_cast <CallbackMessage*> (m) != 0)
  29919. {
  29920. (dynamic_cast <CallbackMessage*> (m))->messageCallback();
  29921. }
  29922. }
  29923. }
  29924. JUCE_CATCH_EXCEPTION
  29925. delete m;
  29926. }
  29927. #if ! (JUCE_MAC || JUCE_IPHONE)
  29928. void MessageManager::runDispatchLoop()
  29929. {
  29930. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29931. runDispatchLoopUntil (-1);
  29932. }
  29933. void MessageManager::stopDispatchLoop()
  29934. {
  29935. Message* const m = new Message (quitMessageId, 0, 0, 0);
  29936. m->messageRecipient = 0;
  29937. postMessageToQueue (m);
  29938. quitMessagePosted = true;
  29939. }
  29940. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  29941. {
  29942. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29943. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  29944. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  29945. && ! quitMessageReceived)
  29946. {
  29947. JUCE_TRY
  29948. {
  29949. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  29950. {
  29951. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  29952. if (msToWait > 0)
  29953. Thread::sleep (jmin (5, msToWait));
  29954. }
  29955. }
  29956. JUCE_CATCH_EXCEPTION
  29957. }
  29958. return ! quitMessageReceived;
  29959. }
  29960. #endif
  29961. void MessageManager::deliverBroadcastMessage (const String& value)
  29962. {
  29963. if (broadcastListeners != 0)
  29964. broadcastListeners->sendActionMessage (value);
  29965. }
  29966. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29967. {
  29968. if (broadcastListeners == 0)
  29969. broadcastListeners = new ActionListenerList();
  29970. broadcastListeners->addActionListener (listener);
  29971. }
  29972. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29973. {
  29974. if (broadcastListeners != 0)
  29975. broadcastListeners->removeActionListener (listener);
  29976. }
  29977. bool MessageManager::isThisTheMessageThread() const throw()
  29978. {
  29979. return Thread::getCurrentThreadId() == messageThreadId;
  29980. }
  29981. void MessageManager::setCurrentMessageThread (const Thread::ThreadID threadId) throw()
  29982. {
  29983. messageThreadId = threadId;
  29984. }
  29985. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  29986. {
  29987. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  29988. return thisThread == messageThreadId || thisThread == threadWithLock;
  29989. }
  29990. /* The only safe way to lock the message thread while another thread does
  29991. some work is by posting a special message, whose purpose is to tie up the event
  29992. loop until the other thread has finished its business.
  29993. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  29994. get locked before making an event callback, because if the same OS lock gets indirectly
  29995. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  29996. in Cocoa).
  29997. */
  29998. class SharedLockingEvents : public ReferenceCountedObject
  29999. {
  30000. public:
  30001. SharedLockingEvents() throw() {}
  30002. ~SharedLockingEvents() {}
  30003. /* This class just holds a couple of events to communicate between the MMLockMessage
  30004. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30005. this shared data must be kept in a separate, ref-counted container. */
  30006. WaitableEvent lockedEvent, releaseEvent;
  30007. };
  30008. class MMLockMessage : public CallbackMessage
  30009. {
  30010. public:
  30011. MMLockMessage (SharedLockingEvents* const events_) throw()
  30012. : events (events_)
  30013. {}
  30014. ~MMLockMessage() throw() {}
  30015. ReferenceCountedObjectPtr <SharedLockingEvents> events;
  30016. void messageCallback()
  30017. {
  30018. events->lockedEvent.signal();
  30019. events->releaseEvent.wait();
  30020. }
  30021. juce_UseDebuggingNewOperator
  30022. MMLockMessage (const MMLockMessage&);
  30023. const MMLockMessage& operator= (const MMLockMessage&);
  30024. };
  30025. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30026. : locked (false),
  30027. needsUnlocking (false)
  30028. {
  30029. init (threadToCheck, 0);
  30030. }
  30031. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30032. : locked (false),
  30033. needsUnlocking (false)
  30034. {
  30035. init (0, jobToCheckForExitSignal);
  30036. }
  30037. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30038. {
  30039. if (MessageManager::instance != 0)
  30040. {
  30041. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30042. {
  30043. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30044. }
  30045. else
  30046. {
  30047. if (threadToCheck == 0 && job == 0)
  30048. {
  30049. MessageManager::instance->lockingLock.enter();
  30050. }
  30051. else
  30052. {
  30053. while (! MessageManager::instance->lockingLock.tryEnter())
  30054. {
  30055. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30056. || (job != 0 && job->shouldExit()))
  30057. return;
  30058. Thread::sleep (1);
  30059. }
  30060. }
  30061. SharedLockingEvents* const events = new SharedLockingEvents();
  30062. sharedEvents = events;
  30063. events->incReferenceCount();
  30064. (new MMLockMessage (events))->post();
  30065. while (! events->lockedEvent.wait (50))
  30066. {
  30067. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30068. || (job != 0 && job->shouldExit()))
  30069. {
  30070. events->releaseEvent.signal();
  30071. events->decReferenceCount();
  30072. MessageManager::instance->lockingLock.exit();
  30073. return;
  30074. }
  30075. }
  30076. jassert (MessageManager::instance->threadWithLock == 0);
  30077. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30078. locked = true;
  30079. needsUnlocking = true;
  30080. }
  30081. }
  30082. }
  30083. MessageManagerLock::~MessageManagerLock() throw()
  30084. {
  30085. if (needsUnlocking && MessageManager::instance != 0)
  30086. {
  30087. jassert (MessageManager::instance->currentThreadHasLockedMessageManager());
  30088. ((SharedLockingEvents*) sharedEvents)->releaseEvent.signal();
  30089. ((SharedLockingEvents*) sharedEvents)->decReferenceCount();
  30090. MessageManager::instance->threadWithLock = 0;
  30091. MessageManager::instance->lockingLock.exit();
  30092. }
  30093. }
  30094. END_JUCE_NAMESPACE
  30095. /********* End of inlined file: juce_MessageManager.cpp *********/
  30096. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  30097. BEGIN_JUCE_NAMESPACE
  30098. class InternalMultiTimerCallback : public Timer
  30099. {
  30100. public:
  30101. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30102. : timerId (timerId_),
  30103. owner (owner_)
  30104. {
  30105. }
  30106. ~InternalMultiTimerCallback()
  30107. {
  30108. }
  30109. void timerCallback()
  30110. {
  30111. owner.timerCallback (timerId);
  30112. }
  30113. const int timerId;
  30114. private:
  30115. MultiTimer& owner;
  30116. };
  30117. MultiTimer::MultiTimer() throw()
  30118. {
  30119. }
  30120. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30121. {
  30122. }
  30123. MultiTimer::~MultiTimer()
  30124. {
  30125. const ScopedLock sl (timerListLock);
  30126. for (int i = timers.size(); --i >= 0;)
  30127. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30128. timers.clear();
  30129. }
  30130. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30131. {
  30132. const ScopedLock sl (timerListLock);
  30133. for (int i = timers.size(); --i >= 0;)
  30134. {
  30135. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30136. if (t->timerId == timerId)
  30137. {
  30138. t->startTimer (intervalInMilliseconds);
  30139. return;
  30140. }
  30141. }
  30142. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  30143. timers.add (newTimer);
  30144. newTimer->startTimer (intervalInMilliseconds);
  30145. }
  30146. void MultiTimer::stopTimer (const int timerId) throw()
  30147. {
  30148. const ScopedLock sl (timerListLock);
  30149. for (int i = timers.size(); --i >= 0;)
  30150. {
  30151. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30152. if (t->timerId == timerId)
  30153. t->stopTimer();
  30154. }
  30155. }
  30156. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30157. {
  30158. const ScopedLock sl (timerListLock);
  30159. for (int i = timers.size(); --i >= 0;)
  30160. {
  30161. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30162. if (t->timerId == timerId)
  30163. return t->isTimerRunning();
  30164. }
  30165. return false;
  30166. }
  30167. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30168. {
  30169. const ScopedLock sl (timerListLock);
  30170. for (int i = timers.size(); --i >= 0;)
  30171. {
  30172. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30173. if (t->timerId == timerId)
  30174. return t->getTimerInterval();
  30175. }
  30176. return 0;
  30177. }
  30178. END_JUCE_NAMESPACE
  30179. /********* End of inlined file: juce_MultiTimer.cpp *********/
  30180. /********* Start of inlined file: juce_Timer.cpp *********/
  30181. BEGIN_JUCE_NAMESPACE
  30182. class InternalTimerThread : private Thread,
  30183. private MessageListener,
  30184. private DeletedAtShutdown,
  30185. private AsyncUpdater
  30186. {
  30187. private:
  30188. friend class Timer;
  30189. static InternalTimerThread* instance;
  30190. static CriticalSection lock;
  30191. Timer* volatile firstTimer;
  30192. bool volatile callbackNeeded;
  30193. InternalTimerThread (const InternalTimerThread&);
  30194. const InternalTimerThread& operator= (const InternalTimerThread&);
  30195. void addTimer (Timer* const t) throw()
  30196. {
  30197. #ifdef JUCE_DEBUG
  30198. Timer* tt = firstTimer;
  30199. while (tt != 0)
  30200. {
  30201. // trying to add a timer that's already here - shouldn't get to this point,
  30202. // so if you get this assertion, let me know!
  30203. jassert (tt != t);
  30204. tt = tt->next;
  30205. }
  30206. jassert (t->previous == 0 && t->next == 0);
  30207. #endif
  30208. Timer* i = firstTimer;
  30209. if (i == 0 || i->countdownMs > t->countdownMs)
  30210. {
  30211. t->next = firstTimer;
  30212. firstTimer = t;
  30213. }
  30214. else
  30215. {
  30216. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30217. i = i->next;
  30218. jassert (i != 0);
  30219. t->next = i->next;
  30220. t->previous = i;
  30221. i->next = t;
  30222. }
  30223. if (t->next != 0)
  30224. t->next->previous = t;
  30225. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30226. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30227. notify();
  30228. }
  30229. void removeTimer (Timer* const t) throw()
  30230. {
  30231. #ifdef JUCE_DEBUG
  30232. Timer* tt = firstTimer;
  30233. bool found = false;
  30234. while (tt != 0)
  30235. {
  30236. if (tt == t)
  30237. {
  30238. found = true;
  30239. break;
  30240. }
  30241. tt = tt->next;
  30242. }
  30243. // trying to remove a timer that's not here - shouldn't get to this point,
  30244. // so if you get this assertion, let me know!
  30245. jassert (found);
  30246. #endif
  30247. if (t->previous != 0)
  30248. {
  30249. jassert (firstTimer != t);
  30250. t->previous->next = t->next;
  30251. }
  30252. else
  30253. {
  30254. jassert (firstTimer == t);
  30255. firstTimer = t->next;
  30256. }
  30257. if (t->next != 0)
  30258. t->next->previous = t->previous;
  30259. t->next = 0;
  30260. t->previous = 0;
  30261. }
  30262. void decrementAllCounters (const int numMillisecs) const
  30263. {
  30264. Timer* t = firstTimer;
  30265. while (t != 0)
  30266. {
  30267. t->countdownMs -= numMillisecs;
  30268. t = t->next;
  30269. }
  30270. }
  30271. void handleAsyncUpdate()
  30272. {
  30273. startThread (7);
  30274. }
  30275. public:
  30276. InternalTimerThread()
  30277. : Thread ("Juce Timer"),
  30278. firstTimer (0),
  30279. callbackNeeded (false)
  30280. {
  30281. triggerAsyncUpdate();
  30282. }
  30283. ~InternalTimerThread() throw()
  30284. {
  30285. stopThread (4000);
  30286. jassert (instance == this || instance == 0);
  30287. if (instance == this)
  30288. instance = 0;
  30289. }
  30290. void run()
  30291. {
  30292. uint32 lastTime = Time::getMillisecondCounter();
  30293. while (! threadShouldExit())
  30294. {
  30295. uint32 now = Time::getMillisecondCounter();
  30296. if (now <= lastTime)
  30297. {
  30298. wait (2);
  30299. continue;
  30300. }
  30301. const int elapsed = now - lastTime;
  30302. lastTime = now;
  30303. lock.enter();
  30304. decrementAllCounters (elapsed);
  30305. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  30306. : 1000;
  30307. lock.exit();
  30308. if (timeUntilFirstTimer <= 0)
  30309. {
  30310. callbackNeeded = true;
  30311. postMessage (new Message());
  30312. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  30313. // so this is how long to wait before assuming the message has been lost and trying again.
  30314. const uint32 messageDeliveryTimeout = now + 2000;
  30315. while (callbackNeeded)
  30316. {
  30317. wait (4);
  30318. if (threadShouldExit())
  30319. return;
  30320. now = Time::getMillisecondCounter();
  30321. if (now > messageDeliveryTimeout)
  30322. break;
  30323. }
  30324. }
  30325. else
  30326. {
  30327. // don't wait for too long because running this loop also helps keep the
  30328. // Time::getApproximateMillisecondTimer value stay up-to-date
  30329. wait (jlimit (1, 50, timeUntilFirstTimer));
  30330. }
  30331. }
  30332. }
  30333. void handleMessage (const Message&)
  30334. {
  30335. const ScopedLock sl (lock);
  30336. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30337. {
  30338. Timer* const t = firstTimer;
  30339. t->countdownMs = t->periodMs;
  30340. removeTimer (t);
  30341. addTimer (t);
  30342. const ScopedUnlock ul (lock);
  30343. JUCE_TRY
  30344. {
  30345. t->timerCallback();
  30346. }
  30347. JUCE_CATCH_EXCEPTION
  30348. }
  30349. callbackNeeded = false;
  30350. }
  30351. static void callAnyTimersSynchronously()
  30352. {
  30353. if (InternalTimerThread::instance != 0)
  30354. {
  30355. const Message m;
  30356. InternalTimerThread::instance->handleMessage (m);
  30357. }
  30358. }
  30359. static inline void add (Timer* const tim) throw()
  30360. {
  30361. if (instance == 0)
  30362. instance = new InternalTimerThread();
  30363. const ScopedLock sl (instance->lock);
  30364. instance->addTimer (tim);
  30365. }
  30366. static inline void remove (Timer* const tim) throw()
  30367. {
  30368. if (instance != 0)
  30369. {
  30370. const ScopedLock sl (instance->lock);
  30371. instance->removeTimer (tim);
  30372. }
  30373. }
  30374. static inline void resetCounter (Timer* const tim,
  30375. const int newCounter) throw()
  30376. {
  30377. if (instance != 0)
  30378. {
  30379. tim->countdownMs = newCounter;
  30380. tim->periodMs = newCounter;
  30381. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30382. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30383. {
  30384. const ScopedLock sl (instance->lock);
  30385. instance->removeTimer (tim);
  30386. instance->addTimer (tim);
  30387. }
  30388. }
  30389. }
  30390. };
  30391. InternalTimerThread* InternalTimerThread::instance = 0;
  30392. CriticalSection InternalTimerThread::lock;
  30393. void juce_callAnyTimersSynchronously()
  30394. {
  30395. InternalTimerThread::callAnyTimersSynchronously();
  30396. }
  30397. #ifdef JUCE_DEBUG
  30398. static SortedSet <Timer*> activeTimers;
  30399. #endif
  30400. Timer::Timer() throw()
  30401. : countdownMs (0),
  30402. periodMs (0),
  30403. previous (0),
  30404. next (0)
  30405. {
  30406. #ifdef JUCE_DEBUG
  30407. activeTimers.add (this);
  30408. #endif
  30409. }
  30410. Timer::Timer (const Timer&) throw()
  30411. : countdownMs (0),
  30412. periodMs (0),
  30413. previous (0),
  30414. next (0)
  30415. {
  30416. #ifdef JUCE_DEBUG
  30417. activeTimers.add (this);
  30418. #endif
  30419. }
  30420. Timer::~Timer()
  30421. {
  30422. stopTimer();
  30423. #ifdef JUCE_DEBUG
  30424. activeTimers.removeValue (this);
  30425. #endif
  30426. }
  30427. void Timer::startTimer (const int interval) throw()
  30428. {
  30429. const ScopedLock sl (InternalTimerThread::lock);
  30430. #ifdef JUCE_DEBUG
  30431. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30432. jassert (activeTimers.contains (this));
  30433. #endif
  30434. if (periodMs == 0)
  30435. {
  30436. countdownMs = interval;
  30437. periodMs = jmax (1, interval);
  30438. InternalTimerThread::add (this);
  30439. }
  30440. else
  30441. {
  30442. InternalTimerThread::resetCounter (this, interval);
  30443. }
  30444. }
  30445. void Timer::stopTimer() throw()
  30446. {
  30447. const ScopedLock sl (InternalTimerThread::lock);
  30448. #ifdef JUCE_DEBUG
  30449. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30450. jassert (activeTimers.contains (this));
  30451. #endif
  30452. if (periodMs > 0)
  30453. {
  30454. InternalTimerThread::remove (this);
  30455. periodMs = 0;
  30456. }
  30457. }
  30458. END_JUCE_NAMESPACE
  30459. /********* End of inlined file: juce_Timer.cpp *********/
  30460. /********* Start of inlined file: juce_Component.cpp *********/
  30461. BEGIN_JUCE_NAMESPACE
  30462. Component* Component::componentUnderMouse = 0;
  30463. Component* Component::currentlyFocusedComponent = 0;
  30464. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  30465. static Array <int> modalReturnValues (4);
  30466. static const int customCommandMessage = 0x7fff0001;
  30467. static const int exitModalStateMessage = 0x7fff0002;
  30468. // these are also used by ComponentPeer
  30469. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  30470. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  30471. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  30472. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  30473. int juce_LastMousePosX = 0;
  30474. int juce_LastMousePosY = 0;
  30475. int juce_MouseClickCounter = 0;
  30476. bool juce_MouseHasMovedSignificantlySincePressed = false;
  30477. static int countMouseClicks() throw()
  30478. {
  30479. int numClicks = 0;
  30480. if (juce_recentMouseDownTimes[0] != 0)
  30481. {
  30482. if (! juce_MouseHasMovedSignificantlySincePressed)
  30483. ++numClicks;
  30484. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  30485. {
  30486. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  30487. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  30488. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  30489. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  30490. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  30491. {
  30492. ++numClicks;
  30493. }
  30494. else
  30495. {
  30496. break;
  30497. }
  30498. }
  30499. }
  30500. return numClicks;
  30501. }
  30502. static int unboundedMouseOffsetX = 0;
  30503. static int unboundedMouseOffsetY = 0;
  30504. static bool isUnboundedMouseModeOn = false;
  30505. static bool isCursorVisibleUntilOffscreen;
  30506. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30507. static uint32 nextComponentUID = 0;
  30508. Component::Component() throw()
  30509. : parentComponent_ (0),
  30510. componentUID (++nextComponentUID),
  30511. numDeepMouseListeners (0),
  30512. childComponentList_ (16),
  30513. lookAndFeel_ (0),
  30514. effect_ (0),
  30515. bufferedImage_ (0),
  30516. mouseListeners_ (0),
  30517. keyListeners_ (0),
  30518. componentListeners_ (0),
  30519. propertySet_ (0),
  30520. componentFlags_ (0)
  30521. {
  30522. }
  30523. Component::Component (const String& name) throw()
  30524. : componentName_ (name),
  30525. parentComponent_ (0),
  30526. componentUID (++nextComponentUID),
  30527. numDeepMouseListeners (0),
  30528. childComponentList_ (16),
  30529. lookAndFeel_ (0),
  30530. effect_ (0),
  30531. bufferedImage_ (0),
  30532. mouseListeners_ (0),
  30533. keyListeners_ (0),
  30534. componentListeners_ (0),
  30535. propertySet_ (0),
  30536. componentFlags_ (0)
  30537. {
  30538. }
  30539. Component::~Component()
  30540. {
  30541. if (parentComponent_ != 0)
  30542. {
  30543. parentComponent_->removeChildComponent (this);
  30544. }
  30545. else if ((currentlyFocusedComponent == this)
  30546. || isParentOf (currentlyFocusedComponent))
  30547. {
  30548. giveAwayFocus();
  30549. }
  30550. if (componentUnderMouse == this)
  30551. componentUnderMouse = 0;
  30552. if (flags.hasHeavyweightPeerFlag)
  30553. removeFromDesktop();
  30554. modalComponentStack.removeValue (this);
  30555. for (int i = childComponentList_.size(); --i >= 0;)
  30556. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  30557. delete bufferedImage_;
  30558. delete mouseListeners_;
  30559. delete keyListeners_;
  30560. delete componentListeners_;
  30561. delete propertySet_;
  30562. }
  30563. void Component::setName (const String& name)
  30564. {
  30565. // if component methods are being called from threads other than the message
  30566. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30567. checkMessageManagerIsLocked
  30568. if (componentName_ != name)
  30569. {
  30570. componentName_ = name;
  30571. if (flags.hasHeavyweightPeerFlag)
  30572. {
  30573. ComponentPeer* const peer = getPeer();
  30574. jassert (peer != 0);
  30575. if (peer != 0)
  30576. peer->setTitle (name);
  30577. }
  30578. if (componentListeners_ != 0)
  30579. {
  30580. const ComponentDeletionWatcher deletionChecker (this);
  30581. for (int i = componentListeners_->size(); --i >= 0;)
  30582. {
  30583. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30584. ->componentNameChanged (*this);
  30585. if (deletionChecker.hasBeenDeleted())
  30586. return;
  30587. i = jmin (i, componentListeners_->size());
  30588. }
  30589. }
  30590. }
  30591. }
  30592. void Component::setVisible (bool shouldBeVisible)
  30593. {
  30594. if (flags.visibleFlag != shouldBeVisible)
  30595. {
  30596. // if component methods are being called from threads other than the message
  30597. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30598. checkMessageManagerIsLocked
  30599. const ComponentDeletionWatcher deletionChecker (this);
  30600. flags.visibleFlag = shouldBeVisible;
  30601. internalRepaint (0, 0, getWidth(), getHeight());
  30602. sendFakeMouseMove();
  30603. if (! shouldBeVisible)
  30604. {
  30605. if (currentlyFocusedComponent == this
  30606. || isParentOf (currentlyFocusedComponent))
  30607. {
  30608. if (parentComponent_ != 0)
  30609. parentComponent_->grabKeyboardFocus();
  30610. else
  30611. giveAwayFocus();
  30612. }
  30613. }
  30614. sendVisibilityChangeMessage();
  30615. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  30616. {
  30617. ComponentPeer* const peer = getPeer();
  30618. jassert (peer != 0);
  30619. if (peer != 0)
  30620. {
  30621. peer->setVisible (shouldBeVisible);
  30622. internalHierarchyChanged();
  30623. }
  30624. }
  30625. }
  30626. }
  30627. void Component::visibilityChanged()
  30628. {
  30629. }
  30630. void Component::sendVisibilityChangeMessage()
  30631. {
  30632. const ComponentDeletionWatcher deletionChecker (this);
  30633. visibilityChanged();
  30634. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  30635. {
  30636. for (int i = componentListeners_->size(); --i >= 0;)
  30637. {
  30638. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30639. ->componentVisibilityChanged (*this);
  30640. if (deletionChecker.hasBeenDeleted())
  30641. return;
  30642. i = jmin (i, componentListeners_->size());
  30643. }
  30644. }
  30645. }
  30646. bool Component::isShowing() const throw()
  30647. {
  30648. if (flags.visibleFlag)
  30649. {
  30650. if (parentComponent_ != 0)
  30651. {
  30652. return parentComponent_->isShowing();
  30653. }
  30654. else
  30655. {
  30656. const ComponentPeer* const peer = getPeer();
  30657. return peer != 0 && ! peer->isMinimised();
  30658. }
  30659. }
  30660. return false;
  30661. }
  30662. class FadeOutProxyComponent : public Component,
  30663. public Timer
  30664. {
  30665. public:
  30666. FadeOutProxyComponent (Component* comp,
  30667. const int fadeLengthMs,
  30668. const int deltaXToMove,
  30669. const int deltaYToMove,
  30670. const float scaleFactorAtEnd)
  30671. : lastTime (0),
  30672. alpha (1.0f),
  30673. scale (1.0f)
  30674. {
  30675. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  30676. setBounds (comp->getBounds());
  30677. comp->getParentComponent()->addAndMakeVisible (this);
  30678. toBehind (comp);
  30679. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  30680. centreX = comp->getX() + comp->getWidth() * 0.5f;
  30681. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  30682. centreY = comp->getY() + comp->getHeight() * 0.5f;
  30683. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  30684. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  30685. setInterceptsMouseClicks (false, false);
  30686. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  30687. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  30688. }
  30689. ~FadeOutProxyComponent()
  30690. {
  30691. delete image;
  30692. }
  30693. void paint (Graphics& g)
  30694. {
  30695. g.setOpacity (alpha);
  30696. g.drawImage (image,
  30697. 0, 0, getWidth(), getHeight(),
  30698. 0, 0, image->getWidth(), image->getHeight());
  30699. }
  30700. void timerCallback()
  30701. {
  30702. const uint32 now = Time::getMillisecondCounter();
  30703. if (lastTime == 0)
  30704. lastTime = now;
  30705. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  30706. lastTime = now;
  30707. alpha += alphaChangePerMs * msPassed;
  30708. if (alpha > 0)
  30709. {
  30710. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  30711. {
  30712. centreX += xChangePerMs * msPassed;
  30713. centreY += yChangePerMs * msPassed;
  30714. scale += scaleChangePerMs * msPassed;
  30715. const int w = roundFloatToInt (image->getWidth() * scale);
  30716. const int h = roundFloatToInt (image->getHeight() * scale);
  30717. setBounds (roundFloatToInt (centreX) - w / 2,
  30718. roundFloatToInt (centreY) - h / 2,
  30719. w, h);
  30720. }
  30721. repaint();
  30722. }
  30723. else
  30724. {
  30725. delete this;
  30726. }
  30727. }
  30728. juce_UseDebuggingNewOperator
  30729. private:
  30730. Image* image;
  30731. uint32 lastTime;
  30732. float alpha, alphaChangePerMs;
  30733. float centreX, xChangePerMs;
  30734. float centreY, yChangePerMs;
  30735. float scale, scaleChangePerMs;
  30736. FadeOutProxyComponent (const FadeOutProxyComponent&);
  30737. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  30738. };
  30739. void Component::fadeOutComponent (const int millisecondsToFade,
  30740. const int deltaXToMove,
  30741. const int deltaYToMove,
  30742. const float scaleFactorAtEnd)
  30743. {
  30744. //xxx won't work for comps without parents
  30745. if (isShowing() && millisecondsToFade > 0)
  30746. new FadeOutProxyComponent (this, millisecondsToFade,
  30747. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  30748. setVisible (false);
  30749. }
  30750. bool Component::isValidComponent() const throw()
  30751. {
  30752. return (this != 0) && isValidMessageListener();
  30753. }
  30754. void* Component::getWindowHandle() const throw()
  30755. {
  30756. const ComponentPeer* const peer = getPeer();
  30757. if (peer != 0)
  30758. return peer->getNativeHandle();
  30759. return 0;
  30760. }
  30761. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  30762. {
  30763. // if component methods are being called from threads other than the message
  30764. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30765. checkMessageManagerIsLocked
  30766. if (! isOpaque())
  30767. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  30768. int currentStyleFlags = 0;
  30769. // don't use getPeer(), so that we only get the peer that's specifically
  30770. // for this comp, and not for one of its parents.
  30771. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  30772. if (peer != 0)
  30773. currentStyleFlags = peer->getStyleFlags();
  30774. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  30775. {
  30776. const ComponentDeletionWatcher deletionChecker (this);
  30777. #if JUCE_LINUX
  30778. // it's wise to give the component a non-zero size before
  30779. // putting it on the desktop, as X windows get confused by this, and
  30780. // a (1, 1) minimum size is enforced here.
  30781. setSize (jmax (1, getWidth()),
  30782. jmax (1, getHeight()));
  30783. #endif
  30784. int x = 0, y = 0;
  30785. relativePositionToGlobal (x, y);
  30786. bool wasFullscreen = false;
  30787. bool wasMinimised = false;
  30788. ComponentBoundsConstrainer* currentConstainer = 0;
  30789. Rectangle oldNonFullScreenBounds;
  30790. if (peer != 0)
  30791. {
  30792. wasFullscreen = peer->isFullScreen();
  30793. wasMinimised = peer->isMinimised();
  30794. currentConstainer = peer->getConstrainer();
  30795. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  30796. removeFromDesktop();
  30797. setTopLeftPosition (x, y);
  30798. }
  30799. if (parentComponent_ != 0)
  30800. parentComponent_->removeChildComponent (this);
  30801. if (! deletionChecker.hasBeenDeleted())
  30802. {
  30803. flags.hasHeavyweightPeerFlag = true;
  30804. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  30805. Desktop::getInstance().addDesktopComponent (this);
  30806. bounds_.setPosition (x, y);
  30807. peer->setBounds (x, y, getWidth(), getHeight(), false);
  30808. peer->setVisible (isVisible());
  30809. if (wasFullscreen)
  30810. {
  30811. peer->setFullScreen (true);
  30812. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  30813. }
  30814. if (wasMinimised)
  30815. peer->setMinimised (true);
  30816. if (isAlwaysOnTop())
  30817. peer->setAlwaysOnTop (true);
  30818. peer->setConstrainer (currentConstainer);
  30819. repaint();
  30820. }
  30821. internalHierarchyChanged();
  30822. }
  30823. }
  30824. void Component::removeFromDesktop()
  30825. {
  30826. // if component methods are being called from threads other than the message
  30827. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30828. checkMessageManagerIsLocked
  30829. if (flags.hasHeavyweightPeerFlag)
  30830. {
  30831. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30832. flags.hasHeavyweightPeerFlag = false;
  30833. jassert (peer != 0);
  30834. delete peer;
  30835. Desktop::getInstance().removeDesktopComponent (this);
  30836. }
  30837. }
  30838. bool Component::isOnDesktop() const throw()
  30839. {
  30840. return flags.hasHeavyweightPeerFlag;
  30841. }
  30842. void Component::userTriedToCloseWindow()
  30843. {
  30844. /* This means that the user's trying to get rid of your window with the 'close window' system
  30845. menu option (on windows) or possibly the task manager - you should really handle this
  30846. and delete or hide your component in an appropriate way.
  30847. If you want to ignore the event and don't want to trigger this assertion, just override
  30848. this method and do nothing.
  30849. */
  30850. jassertfalse
  30851. }
  30852. void Component::minimisationStateChanged (bool)
  30853. {
  30854. }
  30855. void Component::setOpaque (const bool shouldBeOpaque) throw()
  30856. {
  30857. if (shouldBeOpaque != flags.opaqueFlag)
  30858. {
  30859. flags.opaqueFlag = shouldBeOpaque;
  30860. if (flags.hasHeavyweightPeerFlag)
  30861. {
  30862. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30863. if (peer != 0)
  30864. {
  30865. // to make it recreate the heavyweight window
  30866. addToDesktop (peer->getStyleFlags());
  30867. }
  30868. }
  30869. repaint();
  30870. }
  30871. }
  30872. bool Component::isOpaque() const throw()
  30873. {
  30874. return flags.opaqueFlag;
  30875. }
  30876. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  30877. {
  30878. if (shouldBeBuffered != flags.bufferToImageFlag)
  30879. {
  30880. deleteAndZero (bufferedImage_);
  30881. flags.bufferToImageFlag = shouldBeBuffered;
  30882. }
  30883. }
  30884. void Component::toFront (const bool setAsForeground)
  30885. {
  30886. // if component methods are being called from threads other than the message
  30887. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30888. checkMessageManagerIsLocked
  30889. if (flags.hasHeavyweightPeerFlag)
  30890. {
  30891. ComponentPeer* const peer = getPeer();
  30892. if (peer != 0)
  30893. {
  30894. peer->toFront (setAsForeground);
  30895. if (setAsForeground && ! hasKeyboardFocus (true))
  30896. grabKeyboardFocus();
  30897. }
  30898. }
  30899. else if (parentComponent_ != 0)
  30900. {
  30901. if (parentComponent_->childComponentList_.getLast() != this)
  30902. {
  30903. const int index = parentComponent_->childComponentList_.indexOf (this);
  30904. if (index >= 0)
  30905. {
  30906. int insertIndex = -1;
  30907. if (! flags.alwaysOnTopFlag)
  30908. {
  30909. insertIndex = parentComponent_->childComponentList_.size() - 1;
  30910. while (insertIndex > 0
  30911. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30912. {
  30913. --insertIndex;
  30914. }
  30915. }
  30916. if (index != insertIndex)
  30917. {
  30918. parentComponent_->childComponentList_.move (index, insertIndex);
  30919. sendFakeMouseMove();
  30920. repaintParent();
  30921. }
  30922. }
  30923. }
  30924. if (setAsForeground)
  30925. {
  30926. internalBroughtToFront();
  30927. grabKeyboardFocus();
  30928. }
  30929. }
  30930. }
  30931. void Component::toBehind (Component* const other)
  30932. {
  30933. if (other != 0)
  30934. {
  30935. // the two components must belong to the same parent..
  30936. jassert (parentComponent_ == other->parentComponent_);
  30937. if (parentComponent_ != 0)
  30938. {
  30939. const int index = parentComponent_->childComponentList_.indexOf (this);
  30940. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  30941. if (index >= 0
  30942. && otherIndex >= 0
  30943. && index != otherIndex - 1
  30944. && other != this)
  30945. {
  30946. if (index < otherIndex)
  30947. --otherIndex;
  30948. parentComponent_->childComponentList_.move (index, otherIndex);
  30949. sendFakeMouseMove();
  30950. repaintParent();
  30951. }
  30952. }
  30953. else if (isOnDesktop())
  30954. {
  30955. jassert (other->isOnDesktop());
  30956. if (other->isOnDesktop())
  30957. {
  30958. ComponentPeer* const us = getPeer();
  30959. ComponentPeer* const them = other->getPeer();
  30960. jassert (us != 0 && them != 0);
  30961. if (us != 0 && them != 0)
  30962. us->toBehind (them);
  30963. }
  30964. }
  30965. }
  30966. }
  30967. void Component::toBack()
  30968. {
  30969. if (isOnDesktop())
  30970. {
  30971. jassertfalse //xxx need to add this to native window
  30972. }
  30973. else if (parentComponent_ != 0
  30974. && parentComponent_->childComponentList_.getFirst() != this)
  30975. {
  30976. const int index = parentComponent_->childComponentList_.indexOf (this);
  30977. if (index > 0)
  30978. {
  30979. int insertIndex = 0;
  30980. if (flags.alwaysOnTopFlag)
  30981. {
  30982. while (insertIndex < parentComponent_->childComponentList_.size()
  30983. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30984. {
  30985. ++insertIndex;
  30986. }
  30987. }
  30988. if (index != insertIndex)
  30989. {
  30990. parentComponent_->childComponentList_.move (index, insertIndex);
  30991. sendFakeMouseMove();
  30992. repaintParent();
  30993. }
  30994. }
  30995. }
  30996. }
  30997. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  30998. {
  30999. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31000. {
  31001. flags.alwaysOnTopFlag = shouldStayOnTop;
  31002. if (isOnDesktop())
  31003. {
  31004. ComponentPeer* const peer = getPeer();
  31005. jassert (peer != 0);
  31006. if (peer != 0)
  31007. {
  31008. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31009. {
  31010. // some kinds of peer can't change their always-on-top status, so
  31011. // for these, we'll need to create a new window
  31012. const int oldFlags = peer->getStyleFlags();
  31013. removeFromDesktop();
  31014. addToDesktop (oldFlags);
  31015. }
  31016. }
  31017. }
  31018. if (shouldStayOnTop)
  31019. toFront (false);
  31020. internalHierarchyChanged();
  31021. }
  31022. }
  31023. bool Component::isAlwaysOnTop() const throw()
  31024. {
  31025. return flags.alwaysOnTopFlag;
  31026. }
  31027. int Component::proportionOfWidth (const float proportion) const throw()
  31028. {
  31029. return roundDoubleToInt (proportion * bounds_.getWidth());
  31030. }
  31031. int Component::proportionOfHeight (const float proportion) const throw()
  31032. {
  31033. return roundDoubleToInt (proportion * bounds_.getHeight());
  31034. }
  31035. int Component::getParentWidth() const throw()
  31036. {
  31037. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31038. : getParentMonitorArea().getWidth();
  31039. }
  31040. int Component::getParentHeight() const throw()
  31041. {
  31042. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31043. : getParentMonitorArea().getHeight();
  31044. }
  31045. int Component::getScreenX() const throw()
  31046. {
  31047. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  31048. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  31049. : getX());
  31050. }
  31051. int Component::getScreenY() const throw()
  31052. {
  31053. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  31054. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  31055. : getY());
  31056. }
  31057. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  31058. {
  31059. const Component* c = this;
  31060. do
  31061. {
  31062. if (c->flags.hasHeavyweightPeerFlag)
  31063. {
  31064. c->getPeer()->relativePositionToGlobal (x, y);
  31065. break;
  31066. }
  31067. x += c->getX();
  31068. y += c->getY();
  31069. c = c->parentComponent_;
  31070. }
  31071. while (c != 0);
  31072. }
  31073. void Component::globalPositionToRelative (int& x, int& y) const throw()
  31074. {
  31075. if (flags.hasHeavyweightPeerFlag)
  31076. {
  31077. getPeer()->globalPositionToRelative (x, y);
  31078. }
  31079. else
  31080. {
  31081. if (parentComponent_ != 0)
  31082. parentComponent_->globalPositionToRelative (x, y);
  31083. x -= getX();
  31084. y -= getY();
  31085. }
  31086. }
  31087. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  31088. {
  31089. if (targetComponent != 0)
  31090. {
  31091. const Component* c = this;
  31092. do
  31093. {
  31094. if (c == targetComponent)
  31095. return;
  31096. if (c->flags.hasHeavyweightPeerFlag)
  31097. {
  31098. c->getPeer()->relativePositionToGlobal (x, y);
  31099. break;
  31100. }
  31101. x += c->getX();
  31102. y += c->getY();
  31103. c = c->parentComponent_;
  31104. }
  31105. while (c != 0);
  31106. targetComponent->globalPositionToRelative (x, y);
  31107. }
  31108. }
  31109. void Component::setBounds (int x, int y, int w, int h)
  31110. {
  31111. // if component methods are being called from threads other than the message
  31112. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31113. checkMessageManagerIsLocked
  31114. if (w < 0) w = 0;
  31115. if (h < 0) h = 0;
  31116. const bool wasResized = (getWidth() != w || getHeight() != h);
  31117. const bool wasMoved = (getX() != x || getY() != y);
  31118. #ifdef JUCE_DEBUG
  31119. // It's a very bad idea to try to resize a window during its paint() method!
  31120. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31121. #endif
  31122. if (wasMoved || wasResized)
  31123. {
  31124. if (flags.visibleFlag)
  31125. {
  31126. // send a fake mouse move to trigger enter/exit messages if needed..
  31127. sendFakeMouseMove();
  31128. if (! flags.hasHeavyweightPeerFlag)
  31129. repaintParent();
  31130. }
  31131. bounds_.setBounds (x, y, w, h);
  31132. if (wasResized)
  31133. repaint();
  31134. else if (! flags.hasHeavyweightPeerFlag)
  31135. repaintParent();
  31136. if (flags.hasHeavyweightPeerFlag)
  31137. {
  31138. ComponentPeer* const peer = getPeer();
  31139. if (peer != 0)
  31140. {
  31141. if (wasMoved && wasResized)
  31142. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31143. else if (wasMoved)
  31144. peer->setPosition (getX(), getY());
  31145. else if (wasResized)
  31146. peer->setSize (getWidth(), getHeight());
  31147. }
  31148. }
  31149. sendMovedResizedMessages (wasMoved, wasResized);
  31150. }
  31151. }
  31152. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31153. {
  31154. JUCE_TRY
  31155. {
  31156. if (wasMoved)
  31157. moved();
  31158. if (wasResized)
  31159. {
  31160. resized();
  31161. for (int i = childComponentList_.size(); --i >= 0;)
  31162. {
  31163. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31164. i = jmin (i, childComponentList_.size());
  31165. }
  31166. }
  31167. if (parentComponent_ != 0)
  31168. parentComponent_->childBoundsChanged (this);
  31169. if (componentListeners_ != 0)
  31170. {
  31171. const ComponentDeletionWatcher deletionChecker (this);
  31172. for (int i = componentListeners_->size(); --i >= 0;)
  31173. {
  31174. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31175. ->componentMovedOrResized (*this, wasMoved, wasResized);
  31176. if (deletionChecker.hasBeenDeleted())
  31177. return;
  31178. i = jmin (i, componentListeners_->size());
  31179. }
  31180. }
  31181. }
  31182. JUCE_CATCH_EXCEPTION
  31183. }
  31184. void Component::setSize (const int w, const int h)
  31185. {
  31186. setBounds (getX(), getY(), w, h);
  31187. }
  31188. void Component::setTopLeftPosition (const int x, const int y)
  31189. {
  31190. setBounds (x, y, getWidth(), getHeight());
  31191. }
  31192. void Component::setTopRightPosition (const int x, const int y)
  31193. {
  31194. setTopLeftPosition (x - getWidth(), y);
  31195. }
  31196. void Component::setBounds (const Rectangle& r)
  31197. {
  31198. setBounds (r.getX(),
  31199. r.getY(),
  31200. r.getWidth(),
  31201. r.getHeight());
  31202. }
  31203. void Component::setBoundsRelative (const float x, const float y,
  31204. const float w, const float h)
  31205. {
  31206. const int pw = getParentWidth();
  31207. const int ph = getParentHeight();
  31208. setBounds (roundFloatToInt (x * pw),
  31209. roundFloatToInt (y * ph),
  31210. roundFloatToInt (w * pw),
  31211. roundFloatToInt (h * ph));
  31212. }
  31213. void Component::setCentrePosition (const int x, const int y)
  31214. {
  31215. setTopLeftPosition (x - getWidth() / 2,
  31216. y - getHeight() / 2);
  31217. }
  31218. void Component::setCentreRelative (const float x, const float y)
  31219. {
  31220. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  31221. roundFloatToInt (getParentHeight() * y));
  31222. }
  31223. void Component::centreWithSize (const int width, const int height)
  31224. {
  31225. setBounds ((getParentWidth() - width) / 2,
  31226. (getParentHeight() - height) / 2,
  31227. width,
  31228. height);
  31229. }
  31230. void Component::setBoundsInset (const BorderSize& borders)
  31231. {
  31232. setBounds (borders.getLeft(),
  31233. borders.getTop(),
  31234. getParentWidth() - (borders.getLeftAndRight()),
  31235. getParentHeight() - (borders.getTopAndBottom()));
  31236. }
  31237. void Component::setBoundsToFit (int x, int y, int width, int height,
  31238. const Justification& justification,
  31239. const bool onlyReduceInSize)
  31240. {
  31241. // it's no good calling this method unless both the component and
  31242. // target rectangle have a finite size.
  31243. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31244. if (getWidth() > 0 && getHeight() > 0
  31245. && width > 0 && height > 0)
  31246. {
  31247. int newW, newH;
  31248. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31249. {
  31250. newW = getWidth();
  31251. newH = getHeight();
  31252. }
  31253. else
  31254. {
  31255. const double imageRatio = getHeight() / (double) getWidth();
  31256. const double targetRatio = height / (double) width;
  31257. if (imageRatio <= targetRatio)
  31258. {
  31259. newW = width;
  31260. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  31261. }
  31262. else
  31263. {
  31264. newH = height;
  31265. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  31266. }
  31267. }
  31268. if (newW > 0 && newH > 0)
  31269. {
  31270. int newX, newY;
  31271. justification.applyToRectangle (newX, newY, newW, newH,
  31272. x, y, width, height);
  31273. setBounds (newX, newY, newW, newH);
  31274. }
  31275. }
  31276. }
  31277. bool Component::hitTest (int x, int y)
  31278. {
  31279. if (! flags.ignoresMouseClicksFlag)
  31280. return true;
  31281. if (flags.allowChildMouseClicksFlag)
  31282. {
  31283. for (int i = getNumChildComponents(); --i >= 0;)
  31284. {
  31285. Component* const c = getChildComponent (i);
  31286. if (c->isVisible()
  31287. && c->bounds_.contains (x, y)
  31288. && c->hitTest (x - c->getX(),
  31289. y - c->getY()))
  31290. {
  31291. return true;
  31292. }
  31293. }
  31294. }
  31295. return false;
  31296. }
  31297. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31298. const bool allowClicksOnChildComponents) throw()
  31299. {
  31300. flags.ignoresMouseClicksFlag = ! allowClicks;
  31301. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31302. }
  31303. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31304. bool& allowsClicksOnChildComponents) const throw()
  31305. {
  31306. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31307. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31308. }
  31309. bool Component::contains (const int x, const int y)
  31310. {
  31311. if (((unsigned int) x) < (unsigned int) getWidth()
  31312. && ((unsigned int) y) < (unsigned int) getHeight()
  31313. && hitTest (x, y))
  31314. {
  31315. if (parentComponent_ != 0)
  31316. {
  31317. return parentComponent_->contains (x + getX(),
  31318. y + getY());
  31319. }
  31320. else if (flags.hasHeavyweightPeerFlag)
  31321. {
  31322. const ComponentPeer* const peer = getPeer();
  31323. if (peer != 0)
  31324. return peer->contains (x, y, true);
  31325. }
  31326. }
  31327. return false;
  31328. }
  31329. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31330. {
  31331. if (! contains (x, y))
  31332. return false;
  31333. Component* p = this;
  31334. while (p->parentComponent_ != 0)
  31335. {
  31336. x += p->getX();
  31337. y += p->getY();
  31338. p = p->parentComponent_;
  31339. }
  31340. const Component* const c = p->getComponentAt (x, y);
  31341. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31342. }
  31343. Component* Component::getComponentAt (const int x, const int y)
  31344. {
  31345. if (flags.visibleFlag
  31346. && ((unsigned int) x) < (unsigned int) getWidth()
  31347. && ((unsigned int) y) < (unsigned int) getHeight()
  31348. && hitTest (x, y))
  31349. {
  31350. for (int i = childComponentList_.size(); --i >= 0;)
  31351. {
  31352. Component* const child = childComponentList_.getUnchecked(i);
  31353. Component* const c = child->getComponentAt (x - child->getX(),
  31354. y - child->getY());
  31355. if (c != 0)
  31356. return c;
  31357. }
  31358. return this;
  31359. }
  31360. return 0;
  31361. }
  31362. void Component::addChildComponent (Component* const child, int zOrder)
  31363. {
  31364. // if component methods are being called from threads other than the message
  31365. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31366. checkMessageManagerIsLocked
  31367. if (child != 0 && child->parentComponent_ != this)
  31368. {
  31369. if (child->parentComponent_ != 0)
  31370. child->parentComponent_->removeChildComponent (child);
  31371. else
  31372. child->removeFromDesktop();
  31373. child->parentComponent_ = this;
  31374. if (child->isVisible())
  31375. child->repaintParent();
  31376. if (! child->isAlwaysOnTop())
  31377. {
  31378. if (zOrder < 0 || zOrder > childComponentList_.size())
  31379. zOrder = childComponentList_.size();
  31380. while (zOrder > 0)
  31381. {
  31382. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31383. break;
  31384. --zOrder;
  31385. }
  31386. }
  31387. childComponentList_.insert (zOrder, child);
  31388. child->internalHierarchyChanged();
  31389. internalChildrenChanged();
  31390. }
  31391. }
  31392. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31393. {
  31394. if (child != 0)
  31395. {
  31396. child->setVisible (true);
  31397. addChildComponent (child, zOrder);
  31398. }
  31399. }
  31400. void Component::removeChildComponent (Component* const child)
  31401. {
  31402. removeChildComponent (childComponentList_.indexOf (child));
  31403. }
  31404. Component* Component::removeChildComponent (const int index)
  31405. {
  31406. // if component methods are being called from threads other than the message
  31407. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31408. checkMessageManagerIsLocked
  31409. Component* const child = childComponentList_ [index];
  31410. if (child != 0)
  31411. {
  31412. sendFakeMouseMove();
  31413. child->repaintParent();
  31414. childComponentList_.remove (index);
  31415. child->parentComponent_ = 0;
  31416. JUCE_TRY
  31417. {
  31418. if ((currentlyFocusedComponent == child)
  31419. || child->isParentOf (currentlyFocusedComponent))
  31420. {
  31421. // get rid first to force the grabKeyboardFocus to change to us.
  31422. giveAwayFocus();
  31423. grabKeyboardFocus();
  31424. }
  31425. }
  31426. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31427. catch (const std::exception& e)
  31428. {
  31429. currentlyFocusedComponent = 0;
  31430. Desktop::getInstance().triggerFocusCallback();
  31431. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31432. }
  31433. catch (...)
  31434. {
  31435. currentlyFocusedComponent = 0;
  31436. Desktop::getInstance().triggerFocusCallback();
  31437. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31438. }
  31439. #endif
  31440. child->internalHierarchyChanged();
  31441. internalChildrenChanged();
  31442. }
  31443. return child;
  31444. }
  31445. void Component::removeAllChildren()
  31446. {
  31447. for (int i = childComponentList_.size(); --i >= 0;)
  31448. removeChildComponent (i);
  31449. }
  31450. void Component::deleteAllChildren()
  31451. {
  31452. for (int i = childComponentList_.size(); --i >= 0;)
  31453. delete (removeChildComponent (i));
  31454. }
  31455. int Component::getNumChildComponents() const throw()
  31456. {
  31457. return childComponentList_.size();
  31458. }
  31459. Component* Component::getChildComponent (const int index) const throw()
  31460. {
  31461. return childComponentList_ [index];
  31462. }
  31463. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31464. {
  31465. return childComponentList_.indexOf (const_cast <Component*> (child));
  31466. }
  31467. Component* Component::getTopLevelComponent() const throw()
  31468. {
  31469. const Component* comp = this;
  31470. while (comp->parentComponent_ != 0)
  31471. comp = comp->parentComponent_;
  31472. return (Component*) comp;
  31473. }
  31474. bool Component::isParentOf (const Component* possibleChild) const throw()
  31475. {
  31476. while (possibleChild->isValidComponent())
  31477. {
  31478. possibleChild = possibleChild->parentComponent_;
  31479. if (possibleChild == this)
  31480. return true;
  31481. }
  31482. return false;
  31483. }
  31484. void Component::parentHierarchyChanged()
  31485. {
  31486. }
  31487. void Component::childrenChanged()
  31488. {
  31489. }
  31490. void Component::internalChildrenChanged()
  31491. {
  31492. const ComponentDeletionWatcher deletionChecker (this);
  31493. const bool hasListeners = componentListeners_ != 0;
  31494. childrenChanged();
  31495. if (hasListeners)
  31496. {
  31497. if (deletionChecker.hasBeenDeleted())
  31498. return;
  31499. for (int i = componentListeners_->size(); --i >= 0;)
  31500. {
  31501. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31502. ->componentChildrenChanged (*this);
  31503. if (deletionChecker.hasBeenDeleted())
  31504. return;
  31505. i = jmin (i, componentListeners_->size());
  31506. }
  31507. }
  31508. }
  31509. void Component::internalHierarchyChanged()
  31510. {
  31511. parentHierarchyChanged();
  31512. const ComponentDeletionWatcher deletionChecker (this);
  31513. if (componentListeners_ != 0)
  31514. {
  31515. for (int i = componentListeners_->size(); --i >= 0;)
  31516. {
  31517. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31518. ->componentParentHierarchyChanged (*this);
  31519. if (deletionChecker.hasBeenDeleted())
  31520. return;
  31521. i = jmin (i, componentListeners_->size());
  31522. }
  31523. }
  31524. for (int i = childComponentList_.size(); --i >= 0;)
  31525. {
  31526. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  31527. // you really shouldn't delete the parent component during a callback telling you
  31528. // that it's changed..
  31529. jassert (! deletionChecker.hasBeenDeleted());
  31530. if (deletionChecker.hasBeenDeleted())
  31531. return;
  31532. i = jmin (i, childComponentList_.size());
  31533. }
  31534. }
  31535. void* Component::runModalLoopCallback (void* userData)
  31536. {
  31537. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  31538. }
  31539. int Component::runModalLoop()
  31540. {
  31541. if (! MessageManager::getInstance()->isThisTheMessageThread())
  31542. {
  31543. // use a callback so this can be called from non-gui threads
  31544. return (int) (pointer_sized_int)
  31545. MessageManager::getInstance()
  31546. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  31547. }
  31548. Component* const prevFocused = getCurrentlyFocusedComponent();
  31549. ComponentDeletionWatcher* deletionChecker = 0;
  31550. if (prevFocused != 0)
  31551. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  31552. if (! isCurrentlyModal())
  31553. enterModalState();
  31554. JUCE_TRY
  31555. {
  31556. while (flags.currentlyModalFlag && flags.visibleFlag)
  31557. {
  31558. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  31559. break;
  31560. // check whether this component was deleted during the last message
  31561. if (! isValidMessageListener())
  31562. break;
  31563. }
  31564. }
  31565. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31566. catch (const std::exception& e)
  31567. {
  31568. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31569. return 0;
  31570. }
  31571. catch (...)
  31572. {
  31573. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31574. return 0;
  31575. }
  31576. #endif
  31577. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31578. int returnValue = 0;
  31579. if (modalIndex >= 0)
  31580. {
  31581. modalComponentReturnValueKeys.remove (modalIndex);
  31582. returnValue = modalReturnValues.remove (modalIndex);
  31583. }
  31584. modalComponentStack.removeValue (this);
  31585. if (deletionChecker != 0)
  31586. {
  31587. if (! deletionChecker->hasBeenDeleted())
  31588. prevFocused->grabKeyboardFocus();
  31589. delete deletionChecker;
  31590. }
  31591. return returnValue;
  31592. }
  31593. void Component::enterModalState (const bool takeKeyboardFocus)
  31594. {
  31595. // if component methods are being called from threads other than the message
  31596. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31597. checkMessageManagerIsLocked
  31598. // Check for an attempt to make a component modal when it already is!
  31599. // This can cause nasty problems..
  31600. jassert (! flags.currentlyModalFlag);
  31601. if (! isCurrentlyModal())
  31602. {
  31603. modalComponentStack.add (this);
  31604. modalComponentReturnValueKeys.add (this);
  31605. modalReturnValues.add (0);
  31606. flags.currentlyModalFlag = true;
  31607. setVisible (true);
  31608. if (takeKeyboardFocus)
  31609. grabKeyboardFocus();
  31610. }
  31611. }
  31612. void Component::exitModalState (const int returnValue)
  31613. {
  31614. if (isCurrentlyModal())
  31615. {
  31616. if (MessageManager::getInstance()->isThisTheMessageThread())
  31617. {
  31618. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31619. if (modalIndex >= 0)
  31620. {
  31621. modalReturnValues.set (modalIndex, returnValue);
  31622. }
  31623. else
  31624. {
  31625. modalComponentReturnValueKeys.add (this);
  31626. modalReturnValues.add (returnValue);
  31627. }
  31628. modalComponentStack.removeValue (this);
  31629. flags.currentlyModalFlag = false;
  31630. bringModalComponentToFront();
  31631. }
  31632. else
  31633. {
  31634. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  31635. }
  31636. }
  31637. }
  31638. bool Component::isCurrentlyModal() const throw()
  31639. {
  31640. return flags.currentlyModalFlag
  31641. && getCurrentlyModalComponent() == this;
  31642. }
  31643. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  31644. {
  31645. Component* const mc = getCurrentlyModalComponent();
  31646. return mc != 0
  31647. && mc != this
  31648. && (! mc->isParentOf (this))
  31649. && ! mc->canModalEventBeSentToComponent (this);
  31650. }
  31651. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  31652. {
  31653. return modalComponentStack.size();
  31654. }
  31655. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  31656. {
  31657. Component* const c = (Component*) (modalComponentStack [modalComponentStack.size() - index - 1]);
  31658. return c->isValidComponent() ? c : 0;
  31659. }
  31660. void Component::bringModalComponentToFront()
  31661. {
  31662. ComponentPeer* lastOne = 0;
  31663. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  31664. {
  31665. Component* const c = getCurrentlyModalComponent (i);
  31666. if (c == 0)
  31667. break;
  31668. ComponentPeer* peer = c->getPeer();
  31669. if (peer != 0 && peer != lastOne)
  31670. {
  31671. if (lastOne == 0)
  31672. {
  31673. peer->toFront (true);
  31674. peer->grabFocus();
  31675. }
  31676. else
  31677. peer->toBehind (lastOne);
  31678. lastOne = peer;
  31679. }
  31680. }
  31681. }
  31682. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  31683. {
  31684. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  31685. }
  31686. bool Component::isBroughtToFrontOnMouseClick() const throw()
  31687. {
  31688. return flags.bringToFrontOnClickFlag;
  31689. }
  31690. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  31691. {
  31692. cursor_ = cursor;
  31693. if (flags.visibleFlag)
  31694. {
  31695. int mx, my;
  31696. getMouseXYRelative (mx, my);
  31697. if (flags.draggingFlag || reallyContains (mx, my, false))
  31698. {
  31699. internalUpdateMouseCursor (false);
  31700. }
  31701. }
  31702. }
  31703. const MouseCursor Component::getMouseCursor()
  31704. {
  31705. return cursor_;
  31706. }
  31707. void Component::updateMouseCursor() const throw()
  31708. {
  31709. sendFakeMouseMove();
  31710. }
  31711. void Component::internalUpdateMouseCursor (bool forcedUpdate) throw()
  31712. {
  31713. ComponentPeer* const peer = getPeer();
  31714. if (peer != 0)
  31715. {
  31716. MouseCursor mc (getMouseCursor());
  31717. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  31718. || unboundedMouseOffsetY != 0
  31719. || ! isCursorVisibleUntilOffscreen))
  31720. {
  31721. mc = MouseCursor::NoCursor;
  31722. forcedUpdate = true;
  31723. }
  31724. static void* currentCursorHandle = 0;
  31725. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  31726. {
  31727. currentCursorHandle = mc.getHandle();
  31728. mc.showInWindow (peer);
  31729. }
  31730. }
  31731. }
  31732. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  31733. {
  31734. flags.repaintOnMouseActivityFlag = shouldRepaint;
  31735. }
  31736. void Component::repaintParent() throw()
  31737. {
  31738. if (flags.visibleFlag)
  31739. internalRepaint (0, 0, getWidth(), getHeight());
  31740. }
  31741. void Component::repaint() throw()
  31742. {
  31743. repaint (0, 0, getWidth(), getHeight());
  31744. }
  31745. void Component::repaint (const int x, const int y,
  31746. const int w, const int h) throw()
  31747. {
  31748. deleteAndZero (bufferedImage_);
  31749. if (flags.visibleFlag)
  31750. internalRepaint (x, y, w, h);
  31751. }
  31752. void Component::internalRepaint (int x, int y, int w, int h)
  31753. {
  31754. // if component methods are being called from threads other than the message
  31755. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31756. checkMessageManagerIsLocked
  31757. if (x < 0)
  31758. {
  31759. w += x;
  31760. x = 0;
  31761. }
  31762. if (x + w > getWidth())
  31763. w = getWidth() - x;
  31764. if (w > 0)
  31765. {
  31766. if (y < 0)
  31767. {
  31768. h += y;
  31769. y = 0;
  31770. }
  31771. if (y + h > getHeight())
  31772. h = getHeight() - y;
  31773. if (h > 0)
  31774. {
  31775. if (parentComponent_ != 0)
  31776. {
  31777. x += getX();
  31778. y += getY();
  31779. if (parentComponent_->flags.visibleFlag)
  31780. parentComponent_->internalRepaint (x, y, w, h);
  31781. }
  31782. else if (flags.hasHeavyweightPeerFlag)
  31783. {
  31784. ComponentPeer* const peer = getPeer();
  31785. if (peer != 0)
  31786. peer->repaint (x, y, w, h);
  31787. }
  31788. }
  31789. }
  31790. }
  31791. void Component::paintEntireComponent (Graphics& originalContext)
  31792. {
  31793. jassert (! originalContext.isClipEmpty());
  31794. #ifdef JUCE_DEBUG
  31795. flags.isInsidePaintCall = true;
  31796. #endif
  31797. Graphics* g = &originalContext;
  31798. Image* effectImage = 0;
  31799. if (effect_ != 0)
  31800. {
  31801. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31802. getWidth(), getHeight(),
  31803. ! flags.opaqueFlag);
  31804. g = new Graphics (*effectImage);
  31805. }
  31806. g->saveState();
  31807. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  31808. if (! g->isClipEmpty())
  31809. {
  31810. if (bufferedImage_ != 0)
  31811. {
  31812. g->setColour (Colours::black);
  31813. g->drawImageAt (bufferedImage_, 0, 0);
  31814. }
  31815. else
  31816. {
  31817. if (flags.bufferToImageFlag)
  31818. {
  31819. if (bufferedImage_ == 0)
  31820. {
  31821. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31822. getWidth(), getHeight(), ! flags.opaqueFlag);
  31823. Graphics imG (*bufferedImage_);
  31824. paint (imG);
  31825. }
  31826. g->setColour (Colours::black);
  31827. g->drawImageAt (bufferedImage_, 0, 0);
  31828. }
  31829. else
  31830. {
  31831. paint (*g);
  31832. g->resetToDefaultState();
  31833. }
  31834. }
  31835. }
  31836. g->restoreState();
  31837. for (int i = 0; i < childComponentList_.size(); ++i)
  31838. {
  31839. Component* const child = childComponentList_.getUnchecked (i);
  31840. if (child->isVisible())
  31841. {
  31842. g->saveState();
  31843. if (g->reduceClipRegion (child->getX(), child->getY(),
  31844. child->getWidth(), child->getHeight()))
  31845. {
  31846. for (int j = i + 1; j < childComponentList_.size(); ++j)
  31847. {
  31848. const Component* const sibling = childComponentList_.getUnchecked (j);
  31849. if (sibling->flags.opaqueFlag && sibling->isVisible())
  31850. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  31851. sibling->getWidth(), sibling->getHeight());
  31852. }
  31853. if (! g->isClipEmpty())
  31854. {
  31855. g->setOrigin (child->getX(), child->getY());
  31856. child->paintEntireComponent (*g);
  31857. }
  31858. }
  31859. g->restoreState();
  31860. }
  31861. }
  31862. JUCE_TRY
  31863. {
  31864. g->saveState();
  31865. paintOverChildren (*g);
  31866. g->restoreState();
  31867. }
  31868. JUCE_CATCH_EXCEPTION
  31869. if (effect_ != 0)
  31870. {
  31871. delete g;
  31872. effect_->applyEffect (*effectImage, originalContext);
  31873. delete effectImage;
  31874. }
  31875. #ifdef JUCE_DEBUG
  31876. flags.isInsidePaintCall = false;
  31877. #endif
  31878. }
  31879. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  31880. const bool clipImageToComponentBounds)
  31881. {
  31882. Rectangle r (areaToGrab);
  31883. if (clipImageToComponentBounds)
  31884. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  31885. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31886. jmax (1, r.getWidth()),
  31887. jmax (1, r.getHeight()),
  31888. true);
  31889. Graphics imageContext (*componentImage);
  31890. imageContext.setOrigin (-r.getX(),
  31891. -r.getY());
  31892. paintEntireComponent (imageContext);
  31893. return componentImage;
  31894. }
  31895. void Component::setComponentEffect (ImageEffectFilter* const effect)
  31896. {
  31897. if (effect_ != effect)
  31898. {
  31899. effect_ = effect;
  31900. repaint();
  31901. }
  31902. }
  31903. LookAndFeel& Component::getLookAndFeel() const throw()
  31904. {
  31905. const Component* c = this;
  31906. do
  31907. {
  31908. if (c->lookAndFeel_ != 0)
  31909. return *(c->lookAndFeel_);
  31910. c = c->parentComponent_;
  31911. }
  31912. while (c != 0);
  31913. return LookAndFeel::getDefaultLookAndFeel();
  31914. }
  31915. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  31916. {
  31917. if (lookAndFeel_ != newLookAndFeel)
  31918. {
  31919. lookAndFeel_ = newLookAndFeel;
  31920. sendLookAndFeelChange();
  31921. }
  31922. }
  31923. void Component::lookAndFeelChanged()
  31924. {
  31925. }
  31926. void Component::sendLookAndFeelChange()
  31927. {
  31928. repaint();
  31929. lookAndFeelChanged();
  31930. // (it's not a great idea to do anything that would delete this component
  31931. // during the lookAndFeelChanged() callback)
  31932. jassert (isValidComponent());
  31933. const ComponentDeletionWatcher deletionChecker (this);
  31934. for (int i = childComponentList_.size(); --i >= 0;)
  31935. {
  31936. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  31937. if (deletionChecker.hasBeenDeleted())
  31938. return;
  31939. i = jmin (i, childComponentList_.size());
  31940. }
  31941. }
  31942. static const String getColourPropertyName (const int colourId) throw()
  31943. {
  31944. String s;
  31945. s.preallocateStorage (18);
  31946. s << T("jcclr_") << colourId;
  31947. return s;
  31948. }
  31949. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  31950. {
  31951. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  31952. inheritFromParent,
  31953. String::empty));
  31954. if (customColour.isNotEmpty())
  31955. return Colour (customColour.getIntValue());
  31956. return getLookAndFeel().findColour (colourId);
  31957. }
  31958. bool Component::isColourSpecified (const int colourId) const throw()
  31959. {
  31960. return getComponentProperty (getColourPropertyName (colourId),
  31961. false,
  31962. String::empty).isNotEmpty();
  31963. }
  31964. void Component::removeColour (const int colourId)
  31965. {
  31966. if (isColourSpecified (colourId))
  31967. {
  31968. removeComponentProperty (getColourPropertyName (colourId));
  31969. colourChanged();
  31970. }
  31971. }
  31972. void Component::setColour (const int colourId, const Colour& colour)
  31973. {
  31974. const String colourName (getColourPropertyName (colourId));
  31975. const String customColour (getComponentProperty (colourName, false, String::empty));
  31976. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  31977. {
  31978. setComponentProperty (colourName, colour);
  31979. colourChanged();
  31980. }
  31981. }
  31982. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  31983. {
  31984. if (propertySet_ != 0)
  31985. {
  31986. const StringPairArray& props = propertySet_->getAllProperties();
  31987. const StringArray& keys = props.getAllKeys();
  31988. for (int i = 0; i < keys.size(); ++i)
  31989. {
  31990. if (keys[i].startsWith (T("jcclr_")))
  31991. {
  31992. target.setComponentProperty (keys[i],
  31993. props.getAllValues() [i]);
  31994. }
  31995. }
  31996. target.colourChanged();
  31997. }
  31998. }
  31999. void Component::colourChanged()
  32000. {
  32001. }
  32002. const Rectangle Component::getUnclippedArea() const
  32003. {
  32004. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32005. Component* p = parentComponent_;
  32006. int px = getX();
  32007. int py = getY();
  32008. while (p != 0)
  32009. {
  32010. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32011. return Rectangle();
  32012. px += p->getX();
  32013. py += p->getY();
  32014. p = p->parentComponent_;
  32015. }
  32016. return Rectangle (x, y, w, h);
  32017. }
  32018. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  32019. const int deltaX, const int deltaY) const throw()
  32020. {
  32021. for (int i = childComponentList_.size(); --i >= 0;)
  32022. {
  32023. const Component* const c = childComponentList_.getUnchecked(i);
  32024. if (c->isVisible())
  32025. {
  32026. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  32027. if (! newClip.isEmpty())
  32028. {
  32029. if (c->isOpaque())
  32030. {
  32031. g.excludeClipRegion (deltaX + newClip.getX(),
  32032. deltaY + newClip.getY(),
  32033. newClip.getWidth(),
  32034. newClip.getHeight());
  32035. }
  32036. else
  32037. {
  32038. newClip.translate (-c->getX(), -c->getY());
  32039. c->clipObscuredRegions (g, newClip,
  32040. c->getX() + deltaX,
  32041. c->getY() + deltaY);
  32042. }
  32043. }
  32044. }
  32045. }
  32046. }
  32047. void Component::getVisibleArea (RectangleList& result,
  32048. const bool includeSiblings) const
  32049. {
  32050. result.clear();
  32051. const Rectangle unclipped (getUnclippedArea());
  32052. if (! unclipped.isEmpty())
  32053. {
  32054. result.add (unclipped);
  32055. if (includeSiblings)
  32056. {
  32057. const Component* const c = getTopLevelComponent();
  32058. int x = 0, y = 0;
  32059. c->relativePositionToOtherComponent (this, x, y);
  32060. c->subtractObscuredRegions (result, x, y,
  32061. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  32062. this);
  32063. }
  32064. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  32065. result.consolidate();
  32066. }
  32067. }
  32068. void Component::subtractObscuredRegions (RectangleList& result,
  32069. const int deltaX,
  32070. const int deltaY,
  32071. const Rectangle& clipRect,
  32072. const Component* const compToAvoid) const throw()
  32073. {
  32074. for (int i = childComponentList_.size(); --i >= 0;)
  32075. {
  32076. const Component* const c = childComponentList_.getUnchecked(i);
  32077. if (c != compToAvoid && c->isVisible())
  32078. {
  32079. if (c->isOpaque())
  32080. {
  32081. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  32082. childBounds.translate (deltaX, deltaY);
  32083. result.subtract (childBounds);
  32084. }
  32085. else
  32086. {
  32087. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  32088. newClip.translate (-c->getX(), -c->getY());
  32089. c->subtractObscuredRegions (result,
  32090. c->getX() + deltaX,
  32091. c->getY() + deltaY,
  32092. newClip,
  32093. compToAvoid);
  32094. }
  32095. }
  32096. }
  32097. }
  32098. void Component::mouseEnter (const MouseEvent&)
  32099. {
  32100. // base class does nothing
  32101. }
  32102. void Component::mouseExit (const MouseEvent&)
  32103. {
  32104. // base class does nothing
  32105. }
  32106. void Component::mouseDown (const MouseEvent&)
  32107. {
  32108. // base class does nothing
  32109. }
  32110. void Component::mouseUp (const MouseEvent&)
  32111. {
  32112. // base class does nothing
  32113. }
  32114. void Component::mouseDrag (const MouseEvent&)
  32115. {
  32116. // base class does nothing
  32117. }
  32118. void Component::mouseMove (const MouseEvent&)
  32119. {
  32120. // base class does nothing
  32121. }
  32122. void Component::mouseDoubleClick (const MouseEvent&)
  32123. {
  32124. // base class does nothing
  32125. }
  32126. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32127. {
  32128. // the base class just passes this event up to its parent..
  32129. if (parentComponent_ != 0)
  32130. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32131. wheelIncrementX, wheelIncrementY);
  32132. }
  32133. void Component::resized()
  32134. {
  32135. // base class does nothing
  32136. }
  32137. void Component::moved()
  32138. {
  32139. // base class does nothing
  32140. }
  32141. void Component::childBoundsChanged (Component*)
  32142. {
  32143. // base class does nothing
  32144. }
  32145. void Component::parentSizeChanged()
  32146. {
  32147. // base class does nothing
  32148. }
  32149. void Component::addComponentListener (ComponentListener* const newListener) throw()
  32150. {
  32151. if (componentListeners_ == 0)
  32152. componentListeners_ = new VoidArray (4);
  32153. componentListeners_->addIfNotAlreadyThere (newListener);
  32154. }
  32155. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  32156. {
  32157. jassert (isValidComponent());
  32158. if (componentListeners_ != 0)
  32159. componentListeners_->removeValue (listenerToRemove);
  32160. }
  32161. void Component::inputAttemptWhenModal()
  32162. {
  32163. bringModalComponentToFront();
  32164. getLookAndFeel().playAlertSound();
  32165. }
  32166. bool Component::canModalEventBeSentToComponent (const Component*)
  32167. {
  32168. return false;
  32169. }
  32170. void Component::internalModalInputAttempt()
  32171. {
  32172. Component* const current = getCurrentlyModalComponent();
  32173. if (current != 0)
  32174. current->inputAttemptWhenModal();
  32175. }
  32176. void Component::paint (Graphics&)
  32177. {
  32178. // all painting is done in the subclasses
  32179. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32180. }
  32181. void Component::paintOverChildren (Graphics&)
  32182. {
  32183. // all painting is done in the subclasses
  32184. }
  32185. void Component::handleMessage (const Message& message)
  32186. {
  32187. if (message.intParameter1 == exitModalStateMessage)
  32188. {
  32189. exitModalState (message.intParameter2);
  32190. }
  32191. else if (message.intParameter1 == customCommandMessage)
  32192. {
  32193. handleCommandMessage (message.intParameter2);
  32194. }
  32195. }
  32196. void Component::postCommandMessage (const int commandId) throw()
  32197. {
  32198. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32199. }
  32200. void Component::handleCommandMessage (int)
  32201. {
  32202. // used by subclasses
  32203. }
  32204. void Component::addMouseListener (MouseListener* const newListener,
  32205. const bool wantsEventsForAllNestedChildComponents) throw()
  32206. {
  32207. // if component methods are being called from threads other than the message
  32208. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32209. checkMessageManagerIsLocked
  32210. if (mouseListeners_ == 0)
  32211. mouseListeners_ = new VoidArray (4);
  32212. if (! mouseListeners_->contains (newListener))
  32213. {
  32214. if (wantsEventsForAllNestedChildComponents)
  32215. {
  32216. mouseListeners_->insert (0, newListener);
  32217. ++numDeepMouseListeners;
  32218. }
  32219. else
  32220. {
  32221. mouseListeners_->add (newListener);
  32222. }
  32223. }
  32224. }
  32225. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  32226. {
  32227. // if component methods are being called from threads other than the message
  32228. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32229. checkMessageManagerIsLocked
  32230. if (mouseListeners_ != 0)
  32231. {
  32232. const int index = mouseListeners_->indexOf (listenerToRemove);
  32233. if (index >= 0)
  32234. {
  32235. if (index < numDeepMouseListeners)
  32236. --numDeepMouseListeners;
  32237. mouseListeners_->remove (index);
  32238. }
  32239. }
  32240. }
  32241. void Component::internalMouseEnter (int x, int y, int64 time)
  32242. {
  32243. if (isCurrentlyBlockedByAnotherModalComponent())
  32244. {
  32245. // if something else is modal, always just show a normal mouse cursor
  32246. if (componentUnderMouse == this)
  32247. {
  32248. ComponentPeer* const peer = getPeer();
  32249. if (peer != 0)
  32250. {
  32251. MouseCursor mc (MouseCursor::NormalCursor);
  32252. mc.showInWindow (peer);
  32253. }
  32254. }
  32255. return;
  32256. }
  32257. if (! flags.mouseInsideFlag)
  32258. {
  32259. flags.mouseInsideFlag = true;
  32260. flags.mouseOverFlag = true;
  32261. flags.draggingFlag = false;
  32262. if (isValidComponent())
  32263. {
  32264. const ComponentDeletionWatcher deletionChecker (this);
  32265. if (flags.repaintOnMouseActivityFlag)
  32266. repaint();
  32267. const MouseEvent me (x, y,
  32268. ModifierKeys::getCurrentModifiers(),
  32269. this,
  32270. Time (time),
  32271. x, y,
  32272. Time (time),
  32273. 0, false);
  32274. mouseEnter (me);
  32275. if (deletionChecker.hasBeenDeleted())
  32276. return;
  32277. Desktop::getInstance().resetTimer();
  32278. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32279. {
  32280. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  32281. if (deletionChecker.hasBeenDeleted())
  32282. return;
  32283. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32284. }
  32285. if (mouseListeners_ != 0)
  32286. {
  32287. for (int i = mouseListeners_->size(); --i >= 0;)
  32288. {
  32289. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  32290. if (deletionChecker.hasBeenDeleted())
  32291. return;
  32292. i = jmin (i, mouseListeners_->size());
  32293. }
  32294. }
  32295. const Component* p = parentComponent_;
  32296. while (p != 0)
  32297. {
  32298. const ComponentDeletionWatcher parentDeletionChecker (p);
  32299. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32300. {
  32301. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  32302. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32303. return;
  32304. i = jmin (i, p->numDeepMouseListeners);
  32305. }
  32306. p = p->parentComponent_;
  32307. }
  32308. }
  32309. }
  32310. if (componentUnderMouse == this)
  32311. internalUpdateMouseCursor (true);
  32312. }
  32313. void Component::internalMouseExit (int x, int y, int64 time)
  32314. {
  32315. const ComponentDeletionWatcher deletionChecker (this);
  32316. if (flags.draggingFlag)
  32317. {
  32318. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  32319. if (deletionChecker.hasBeenDeleted())
  32320. return;
  32321. }
  32322. enableUnboundedMouseMovement (false);
  32323. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32324. {
  32325. flags.mouseInsideFlag = false;
  32326. flags.mouseOverFlag = false;
  32327. flags.draggingFlag = false;
  32328. if (flags.repaintOnMouseActivityFlag)
  32329. repaint();
  32330. const MouseEvent me (x, y,
  32331. ModifierKeys::getCurrentModifiers(),
  32332. this,
  32333. Time (time),
  32334. x, y,
  32335. Time (time),
  32336. 0, false);
  32337. mouseExit (me);
  32338. if (deletionChecker.hasBeenDeleted())
  32339. return;
  32340. Desktop::getInstance().resetTimer();
  32341. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32342. {
  32343. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  32344. if (deletionChecker.hasBeenDeleted())
  32345. return;
  32346. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32347. }
  32348. if (mouseListeners_ != 0)
  32349. {
  32350. for (int i = mouseListeners_->size(); --i >= 0;)
  32351. {
  32352. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32353. if (deletionChecker.hasBeenDeleted())
  32354. return;
  32355. i = jmin (i, mouseListeners_->size());
  32356. }
  32357. }
  32358. const Component* p = parentComponent_;
  32359. while (p != 0)
  32360. {
  32361. const ComponentDeletionWatcher parentDeletionChecker (p);
  32362. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32363. {
  32364. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  32365. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32366. return;
  32367. i = jmin (i, p->numDeepMouseListeners);
  32368. }
  32369. p = p->parentComponent_;
  32370. }
  32371. }
  32372. }
  32373. class InternalDragRepeater : public Timer
  32374. {
  32375. public:
  32376. InternalDragRepeater()
  32377. {}
  32378. ~InternalDragRepeater()
  32379. {}
  32380. void timerCallback()
  32381. {
  32382. Component* const c = Component::getComponentUnderMouse();
  32383. if (c != 0 && c->isMouseButtonDown())
  32384. {
  32385. int x, y;
  32386. c->getMouseXYRelative (x, y);
  32387. // the offsets have been added on, so must be taken off before calling the
  32388. // drag.. otherwise they'll be added twice
  32389. x -= unboundedMouseOffsetX;
  32390. y -= unboundedMouseOffsetY;
  32391. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  32392. }
  32393. }
  32394. juce_UseDebuggingNewOperator
  32395. };
  32396. static InternalDragRepeater* dragRepeater = 0;
  32397. void Component::beginDragAutoRepeat (const int interval)
  32398. {
  32399. if (interval > 0)
  32400. {
  32401. if (dragRepeater == 0)
  32402. dragRepeater = new InternalDragRepeater();
  32403. if (dragRepeater->getTimerInterval() != interval)
  32404. dragRepeater->startTimer (interval);
  32405. }
  32406. else
  32407. {
  32408. deleteAndZero (dragRepeater);
  32409. }
  32410. }
  32411. void Component::internalMouseDown (const int x, const int y)
  32412. {
  32413. const ComponentDeletionWatcher deletionChecker (this);
  32414. if (isCurrentlyBlockedByAnotherModalComponent())
  32415. {
  32416. internalModalInputAttempt();
  32417. if (deletionChecker.hasBeenDeleted())
  32418. return;
  32419. // If processing the input attempt has exited the modal loop, we'll allow the event
  32420. // to be delivered..
  32421. if (isCurrentlyBlockedByAnotherModalComponent())
  32422. {
  32423. // allow blocked mouse-events to go to global listeners..
  32424. const MouseEvent me (x, y,
  32425. ModifierKeys::getCurrentModifiers(),
  32426. this,
  32427. Time (juce_recentMouseDownTimes[0]),
  32428. x, y,
  32429. Time (juce_recentMouseDownTimes[0]),
  32430. countMouseClicks(),
  32431. false);
  32432. Desktop::getInstance().resetTimer();
  32433. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32434. {
  32435. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32436. if (deletionChecker.hasBeenDeleted())
  32437. return;
  32438. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32439. }
  32440. return;
  32441. }
  32442. }
  32443. {
  32444. Component* c = this;
  32445. while (c != 0)
  32446. {
  32447. if (c->isBroughtToFrontOnMouseClick())
  32448. {
  32449. c->toFront (true);
  32450. if (deletionChecker.hasBeenDeleted())
  32451. return;
  32452. }
  32453. c = c->parentComponent_;
  32454. }
  32455. }
  32456. if (! flags.dontFocusOnMouseClickFlag)
  32457. grabFocusInternal (focusChangedByMouseClick);
  32458. if (! deletionChecker.hasBeenDeleted())
  32459. {
  32460. flags.draggingFlag = true;
  32461. flags.mouseOverFlag = true;
  32462. if (flags.repaintOnMouseActivityFlag)
  32463. repaint();
  32464. const MouseEvent me (x, y,
  32465. ModifierKeys::getCurrentModifiers(),
  32466. this,
  32467. Time (juce_recentMouseDownTimes[0]),
  32468. x, y,
  32469. Time (juce_recentMouseDownTimes[0]),
  32470. countMouseClicks(),
  32471. false);
  32472. mouseDown (me);
  32473. if (deletionChecker.hasBeenDeleted())
  32474. return;
  32475. Desktop::getInstance().resetTimer();
  32476. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32477. {
  32478. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32479. if (deletionChecker.hasBeenDeleted())
  32480. return;
  32481. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32482. }
  32483. if (mouseListeners_ != 0)
  32484. {
  32485. for (int i = mouseListeners_->size(); --i >= 0;)
  32486. {
  32487. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32488. if (deletionChecker.hasBeenDeleted())
  32489. return;
  32490. i = jmin (i, mouseListeners_->size());
  32491. }
  32492. }
  32493. const Component* p = parentComponent_;
  32494. while (p != 0)
  32495. {
  32496. const ComponentDeletionWatcher parentDeletionChecker (p);
  32497. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32498. {
  32499. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  32500. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32501. return;
  32502. i = jmin (i, p->numDeepMouseListeners);
  32503. }
  32504. p = p->parentComponent_;
  32505. }
  32506. }
  32507. }
  32508. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  32509. {
  32510. if (isValidComponent() && flags.draggingFlag)
  32511. {
  32512. flags.draggingFlag = false;
  32513. deleteAndZero (dragRepeater);
  32514. x += unboundedMouseOffsetX;
  32515. y += unboundedMouseOffsetY;
  32516. juce_LastMousePosX = x;
  32517. juce_LastMousePosY = y;
  32518. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32519. const ComponentDeletionWatcher deletionChecker (this);
  32520. if (flags.repaintOnMouseActivityFlag)
  32521. repaint();
  32522. int mdx = juce_recentMouseDownX[0];
  32523. int mdy = juce_recentMouseDownY[0];
  32524. globalPositionToRelative (mdx, mdy);
  32525. const MouseEvent me (x, y,
  32526. oldModifiers,
  32527. this,
  32528. Time (time),
  32529. mdx, mdy,
  32530. Time (juce_recentMouseDownTimes [0]),
  32531. countMouseClicks(),
  32532. juce_MouseHasMovedSignificantlySincePressed
  32533. || juce_recentMouseDownTimes[0] + 300 < time);
  32534. mouseUp (me);
  32535. if (deletionChecker.hasBeenDeleted())
  32536. return;
  32537. Desktop::getInstance().resetTimer();
  32538. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32539. {
  32540. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  32541. if (deletionChecker.hasBeenDeleted())
  32542. return;
  32543. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32544. }
  32545. if (mouseListeners_ != 0)
  32546. {
  32547. for (int i = mouseListeners_->size(); --i >= 0;)
  32548. {
  32549. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32550. if (deletionChecker.hasBeenDeleted())
  32551. return;
  32552. i = jmin (i, mouseListeners_->size());
  32553. }
  32554. }
  32555. {
  32556. const Component* p = parentComponent_;
  32557. while (p != 0)
  32558. {
  32559. const ComponentDeletionWatcher parentDeletionChecker (p);
  32560. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32561. {
  32562. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  32563. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32564. return;
  32565. i = jmin (i, p->numDeepMouseListeners);
  32566. }
  32567. p = p->parentComponent_;
  32568. }
  32569. }
  32570. // check for double-click
  32571. if (me.getNumberOfClicks() >= 2)
  32572. {
  32573. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32574. mouseDoubleClick (me);
  32575. int i;
  32576. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32577. {
  32578. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  32579. if (deletionChecker.hasBeenDeleted())
  32580. return;
  32581. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32582. }
  32583. for (i = numListeners; --i >= 0;)
  32584. {
  32585. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  32586. return;
  32587. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32588. if (ml != 0)
  32589. ml->mouseDoubleClick (me);
  32590. }
  32591. if (deletionChecker.hasBeenDeleted())
  32592. return;
  32593. const Component* p = parentComponent_;
  32594. while (p != 0)
  32595. {
  32596. const ComponentDeletionWatcher parentDeletionChecker (p);
  32597. for (i = p->numDeepMouseListeners; --i >= 0;)
  32598. {
  32599. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  32600. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32601. return;
  32602. i = jmin (i, p->numDeepMouseListeners);
  32603. }
  32604. p = p->parentComponent_;
  32605. }
  32606. }
  32607. }
  32608. enableUnboundedMouseMovement (false);
  32609. }
  32610. void Component::internalMouseDrag (int x, int y, const int64 time)
  32611. {
  32612. if (isValidComponent() && flags.draggingFlag)
  32613. {
  32614. flags.mouseOverFlag = reallyContains (x, y, false);
  32615. x += unboundedMouseOffsetX;
  32616. y += unboundedMouseOffsetY;
  32617. juce_LastMousePosX = x;
  32618. juce_LastMousePosY = y;
  32619. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32620. juce_MouseHasMovedSignificantlySincePressed
  32621. = juce_MouseHasMovedSignificantlySincePressed
  32622. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  32623. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  32624. const ComponentDeletionWatcher deletionChecker (this);
  32625. int mdx = juce_recentMouseDownX[0];
  32626. int mdy = juce_recentMouseDownY[0];
  32627. globalPositionToRelative (mdx, mdy);
  32628. const MouseEvent me (x, y,
  32629. ModifierKeys::getCurrentModifiers(),
  32630. this,
  32631. Time (time),
  32632. mdx, mdy,
  32633. Time (juce_recentMouseDownTimes[0]),
  32634. countMouseClicks(),
  32635. juce_MouseHasMovedSignificantlySincePressed
  32636. || juce_recentMouseDownTimes[0] + 300 < time);
  32637. mouseDrag (me);
  32638. if (deletionChecker.hasBeenDeleted())
  32639. return;
  32640. Desktop::getInstance().resetTimer();
  32641. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32642. {
  32643. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  32644. if (deletionChecker.hasBeenDeleted())
  32645. return;
  32646. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32647. }
  32648. if (mouseListeners_ != 0)
  32649. {
  32650. for (int i = mouseListeners_->size(); --i >= 0;)
  32651. {
  32652. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  32653. if (deletionChecker.hasBeenDeleted())
  32654. return;
  32655. i = jmin (i, mouseListeners_->size());
  32656. }
  32657. }
  32658. const Component* p = parentComponent_;
  32659. while (p != 0)
  32660. {
  32661. const ComponentDeletionWatcher parentDeletionChecker (p);
  32662. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32663. {
  32664. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  32665. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32666. return;
  32667. i = jmin (i, p->numDeepMouseListeners);
  32668. }
  32669. p = p->parentComponent_;
  32670. }
  32671. if (this == componentUnderMouse)
  32672. {
  32673. if (isUnboundedMouseModeOn)
  32674. {
  32675. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  32676. int mx, my;
  32677. Desktop::getMousePosition (mx, my);
  32678. if (! screenArea.contains (mx, my))
  32679. {
  32680. int deltaX = 0, deltaY = 0;
  32681. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  32682. deltaX = getScreenX() + getWidth() / 2 - mx;
  32683. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  32684. deltaY = getScreenY() + getHeight() / 2 - my;
  32685. unboundedMouseOffsetX -= deltaX;
  32686. unboundedMouseOffsetY -= deltaY;
  32687. Desktop::setMousePosition (mx + deltaX,
  32688. my + deltaY);
  32689. }
  32690. else if (isCursorVisibleUntilOffscreen
  32691. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  32692. && screenArea.contains (mx + unboundedMouseOffsetX,
  32693. my + unboundedMouseOffsetY))
  32694. {
  32695. mx += unboundedMouseOffsetX;
  32696. my += unboundedMouseOffsetY;
  32697. unboundedMouseOffsetX = 0;
  32698. unboundedMouseOffsetY = 0;
  32699. Desktop::setMousePosition (mx, my);
  32700. }
  32701. }
  32702. internalUpdateMouseCursor (false);
  32703. }
  32704. }
  32705. }
  32706. void Component::internalMouseMove (const int x, const int y, const int64 time)
  32707. {
  32708. const ComponentDeletionWatcher deletionChecker (this);
  32709. if (isValidComponent())
  32710. {
  32711. const MouseEvent me (x, y,
  32712. ModifierKeys::getCurrentModifiers(),
  32713. this,
  32714. Time (time),
  32715. x, y,
  32716. Time (time),
  32717. 0, false);
  32718. if (isCurrentlyBlockedByAnotherModalComponent())
  32719. {
  32720. // allow blocked mouse-events to go to global listeners..
  32721. Desktop::getInstance().sendMouseMove();
  32722. }
  32723. else
  32724. {
  32725. if (this == componentUnderMouse)
  32726. internalUpdateMouseCursor (false);
  32727. flags.mouseOverFlag = true;
  32728. mouseMove (me);
  32729. if (deletionChecker.hasBeenDeleted())
  32730. return;
  32731. Desktop::getInstance().resetTimer();
  32732. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32733. {
  32734. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  32735. if (deletionChecker.hasBeenDeleted())
  32736. return;
  32737. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32738. }
  32739. if (mouseListeners_ != 0)
  32740. {
  32741. for (int i = mouseListeners_->size(); --i >= 0;)
  32742. {
  32743. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  32744. if (deletionChecker.hasBeenDeleted())
  32745. return;
  32746. i = jmin (i, mouseListeners_->size());
  32747. }
  32748. }
  32749. const Component* p = parentComponent_;
  32750. while (p != 0)
  32751. {
  32752. const ComponentDeletionWatcher parentDeletionChecker (p);
  32753. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32754. {
  32755. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  32756. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32757. return;
  32758. i = jmin (i, p->numDeepMouseListeners);
  32759. }
  32760. p = p->parentComponent_;
  32761. }
  32762. }
  32763. }
  32764. }
  32765. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  32766. {
  32767. const ComponentDeletionWatcher deletionChecker (this);
  32768. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  32769. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  32770. int mx, my;
  32771. getMouseXYRelative (mx, my);
  32772. const MouseEvent me (mx, my,
  32773. ModifierKeys::getCurrentModifiers(),
  32774. this,
  32775. Time (time),
  32776. mx, my,
  32777. Time (time),
  32778. 0, false);
  32779. if (isCurrentlyBlockedByAnotherModalComponent())
  32780. {
  32781. // allow blocked mouse-events to go to global listeners..
  32782. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32783. {
  32784. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32785. if (deletionChecker.hasBeenDeleted())
  32786. return;
  32787. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32788. }
  32789. }
  32790. else
  32791. {
  32792. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32793. if (deletionChecker.hasBeenDeleted())
  32794. return;
  32795. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32796. {
  32797. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32798. if (deletionChecker.hasBeenDeleted())
  32799. return;
  32800. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32801. }
  32802. if (mouseListeners_ != 0)
  32803. {
  32804. for (int i = mouseListeners_->size(); --i >= 0;)
  32805. {
  32806. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32807. if (deletionChecker.hasBeenDeleted())
  32808. return;
  32809. i = jmin (i, mouseListeners_->size());
  32810. }
  32811. }
  32812. const Component* p = parentComponent_;
  32813. while (p != 0)
  32814. {
  32815. const ComponentDeletionWatcher parentDeletionChecker (p);
  32816. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32817. {
  32818. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32819. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32820. return;
  32821. i = jmin (i, p->numDeepMouseListeners);
  32822. }
  32823. p = p->parentComponent_;
  32824. }
  32825. sendFakeMouseMove();
  32826. }
  32827. }
  32828. void Component::sendFakeMouseMove() const
  32829. {
  32830. ComponentPeer* const peer = getPeer();
  32831. if (peer != 0)
  32832. peer->sendFakeMouseMove();
  32833. }
  32834. void Component::broughtToFront()
  32835. {
  32836. }
  32837. void Component::internalBroughtToFront()
  32838. {
  32839. if (isValidComponent())
  32840. {
  32841. if (flags.hasHeavyweightPeerFlag)
  32842. Desktop::getInstance().componentBroughtToFront (this);
  32843. const ComponentDeletionWatcher deletionChecker (this);
  32844. broughtToFront();
  32845. if (deletionChecker.hasBeenDeleted())
  32846. return;
  32847. if (componentListeners_ != 0)
  32848. {
  32849. for (int i = componentListeners_->size(); --i >= 0;)
  32850. {
  32851. ((ComponentListener*) componentListeners_->getUnchecked (i))
  32852. ->componentBroughtToFront (*this);
  32853. if (deletionChecker.hasBeenDeleted())
  32854. return;
  32855. i = jmin (i, componentListeners_->size());
  32856. }
  32857. }
  32858. // when brought to the front and there's a modal component blocking this one,
  32859. // we need to bring the modal one to the front instead..
  32860. Component* const cm = getCurrentlyModalComponent();
  32861. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  32862. bringModalComponentToFront();
  32863. }
  32864. }
  32865. void Component::focusGained (FocusChangeType)
  32866. {
  32867. // base class does nothing
  32868. }
  32869. void Component::internalFocusGain (const FocusChangeType cause)
  32870. {
  32871. const ComponentDeletionWatcher deletionChecker (this);
  32872. focusGained (cause);
  32873. if (! deletionChecker.hasBeenDeleted())
  32874. internalChildFocusChange (cause);
  32875. }
  32876. void Component::focusLost (FocusChangeType)
  32877. {
  32878. // base class does nothing
  32879. }
  32880. void Component::internalFocusLoss (const FocusChangeType cause)
  32881. {
  32882. const ComponentDeletionWatcher deletionChecker (this);
  32883. focusLost (focusChangedDirectly);
  32884. if (! deletionChecker.hasBeenDeleted())
  32885. internalChildFocusChange (cause);
  32886. }
  32887. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  32888. {
  32889. // base class does nothing
  32890. }
  32891. void Component::internalChildFocusChange (FocusChangeType cause)
  32892. {
  32893. const bool childIsNowFocused = hasKeyboardFocus (true);
  32894. if (flags.childCompFocusedFlag != childIsNowFocused)
  32895. {
  32896. flags.childCompFocusedFlag = childIsNowFocused;
  32897. const ComponentDeletionWatcher deletionChecker (this);
  32898. focusOfChildComponentChanged (cause);
  32899. if (deletionChecker.hasBeenDeleted())
  32900. return;
  32901. }
  32902. if (parentComponent_ != 0)
  32903. parentComponent_->internalChildFocusChange (cause);
  32904. }
  32905. bool Component::isEnabled() const throw()
  32906. {
  32907. return (! flags.isDisabledFlag)
  32908. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  32909. }
  32910. void Component::setEnabled (const bool shouldBeEnabled)
  32911. {
  32912. if (flags.isDisabledFlag == shouldBeEnabled)
  32913. {
  32914. flags.isDisabledFlag = ! shouldBeEnabled;
  32915. // if any parent components are disabled, setting our flag won't make a difference,
  32916. // so no need to send a change message
  32917. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  32918. sendEnablementChangeMessage();
  32919. }
  32920. }
  32921. void Component::sendEnablementChangeMessage()
  32922. {
  32923. const ComponentDeletionWatcher deletionChecker (this);
  32924. enablementChanged();
  32925. if (deletionChecker.hasBeenDeleted())
  32926. return;
  32927. for (int i = getNumChildComponents(); --i >= 0;)
  32928. {
  32929. Component* const c = getChildComponent (i);
  32930. if (c != 0)
  32931. {
  32932. c->sendEnablementChangeMessage();
  32933. if (deletionChecker.hasBeenDeleted())
  32934. return;
  32935. }
  32936. }
  32937. }
  32938. void Component::enablementChanged()
  32939. {
  32940. }
  32941. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  32942. {
  32943. flags.wantsFocusFlag = wantsFocus;
  32944. }
  32945. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  32946. {
  32947. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  32948. }
  32949. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  32950. {
  32951. return ! flags.dontFocusOnMouseClickFlag;
  32952. }
  32953. bool Component::getWantsKeyboardFocus() const throw()
  32954. {
  32955. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  32956. }
  32957. void Component::setFocusContainer (const bool isFocusContainer) throw()
  32958. {
  32959. flags.isFocusContainerFlag = isFocusContainer;
  32960. }
  32961. bool Component::isFocusContainer() const throw()
  32962. {
  32963. return flags.isFocusContainerFlag;
  32964. }
  32965. int Component::getExplicitFocusOrder() const throw()
  32966. {
  32967. return getComponentPropertyInt (T("_jexfo"), false, 0);
  32968. }
  32969. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  32970. {
  32971. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  32972. }
  32973. KeyboardFocusTraverser* Component::createFocusTraverser()
  32974. {
  32975. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  32976. return new KeyboardFocusTraverser();
  32977. return parentComponent_->createFocusTraverser();
  32978. }
  32979. void Component::takeKeyboardFocus (const FocusChangeType cause)
  32980. {
  32981. // give the focus to this component
  32982. if (currentlyFocusedComponent != this)
  32983. {
  32984. JUCE_TRY
  32985. {
  32986. // get the focus onto our desktop window
  32987. ComponentPeer* const peer = getPeer();
  32988. if (peer != 0)
  32989. {
  32990. const ComponentDeletionWatcher deletionChecker (this);
  32991. peer->grabFocus();
  32992. if (peer->isFocused() && currentlyFocusedComponent != this)
  32993. {
  32994. Component* const componentLosingFocus = currentlyFocusedComponent;
  32995. currentlyFocusedComponent = this;
  32996. Desktop::getInstance().triggerFocusCallback();
  32997. // call this after setting currentlyFocusedComponent so that the one that's
  32998. // losing it has a chance to see where focus is going
  32999. if (componentLosingFocus->isValidComponent())
  33000. componentLosingFocus->internalFocusLoss (cause);
  33001. if (currentlyFocusedComponent == this)
  33002. {
  33003. focusGained (cause);
  33004. if (! deletionChecker.hasBeenDeleted())
  33005. internalChildFocusChange (cause);
  33006. }
  33007. }
  33008. }
  33009. }
  33010. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33011. catch (const std::exception& e)
  33012. {
  33013. currentlyFocusedComponent = 0;
  33014. Desktop::getInstance().triggerFocusCallback();
  33015. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33016. }
  33017. catch (...)
  33018. {
  33019. currentlyFocusedComponent = 0;
  33020. Desktop::getInstance().triggerFocusCallback();
  33021. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33022. }
  33023. #endif
  33024. }
  33025. }
  33026. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33027. {
  33028. if (isShowing())
  33029. {
  33030. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33031. {
  33032. takeKeyboardFocus (cause);
  33033. }
  33034. else
  33035. {
  33036. if (isParentOf (currentlyFocusedComponent)
  33037. && currentlyFocusedComponent->isShowing())
  33038. {
  33039. // do nothing if the focused component is actually a child of ours..
  33040. }
  33041. else
  33042. {
  33043. // find the default child component..
  33044. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  33045. if (traverser != 0)
  33046. {
  33047. Component* const defaultComp = traverser->getDefaultComponent (this);
  33048. delete traverser;
  33049. if (defaultComp != 0)
  33050. {
  33051. defaultComp->grabFocusInternal (cause, false);
  33052. return;
  33053. }
  33054. }
  33055. if (canTryParent && parentComponent_ != 0)
  33056. {
  33057. // if no children want it and we're allowed to try our parent comp,
  33058. // then pass up to parent, which will try our siblings.
  33059. parentComponent_->grabFocusInternal (cause, true);
  33060. }
  33061. }
  33062. }
  33063. }
  33064. }
  33065. void Component::grabKeyboardFocus()
  33066. {
  33067. // if component methods are being called from threads other than the message
  33068. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33069. checkMessageManagerIsLocked
  33070. grabFocusInternal (focusChangedDirectly);
  33071. }
  33072. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33073. {
  33074. // if component methods are being called from threads other than the message
  33075. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33076. checkMessageManagerIsLocked
  33077. if (parentComponent_ != 0)
  33078. {
  33079. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  33080. if (traverser != 0)
  33081. {
  33082. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33083. : traverser->getPreviousComponent (this);
  33084. delete traverser;
  33085. if (nextComp != 0)
  33086. {
  33087. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33088. {
  33089. const ComponentDeletionWatcher deletionChecker (nextComp);
  33090. internalModalInputAttempt();
  33091. if (deletionChecker.hasBeenDeleted()
  33092. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33093. return;
  33094. }
  33095. nextComp->grabFocusInternal (focusChangedByTabKey);
  33096. return;
  33097. }
  33098. }
  33099. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33100. }
  33101. }
  33102. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  33103. {
  33104. return (currentlyFocusedComponent == this)
  33105. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33106. }
  33107. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33108. {
  33109. return currentlyFocusedComponent;
  33110. }
  33111. void Component::giveAwayFocus()
  33112. {
  33113. // use a copy so we can clear the value before the call
  33114. Component* const componentLosingFocus = currentlyFocusedComponent;
  33115. currentlyFocusedComponent = 0;
  33116. Desktop::getInstance().triggerFocusCallback();
  33117. if (componentLosingFocus->isValidComponent())
  33118. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33119. }
  33120. bool Component::isMouseOver() const throw()
  33121. {
  33122. return flags.mouseOverFlag;
  33123. }
  33124. bool Component::isMouseButtonDown() const throw()
  33125. {
  33126. return flags.draggingFlag;
  33127. }
  33128. bool Component::isMouseOverOrDragging() const throw()
  33129. {
  33130. return flags.mouseOverFlag || flags.draggingFlag;
  33131. }
  33132. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33133. {
  33134. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33135. }
  33136. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  33137. {
  33138. Desktop::getMousePosition (mx, my);
  33139. globalPositionToRelative (mx, my);
  33140. mx += unboundedMouseOffsetX;
  33141. my += unboundedMouseOffsetY;
  33142. }
  33143. void Component::enableUnboundedMouseMovement (bool enable,
  33144. bool keepCursorVisibleUntilOffscreen) throw()
  33145. {
  33146. enable = enable && isMouseButtonDown();
  33147. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  33148. if (enable != isUnboundedMouseModeOn)
  33149. {
  33150. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  33151. || unboundedMouseOffsetX != 0
  33152. || unboundedMouseOffsetY != 0))
  33153. {
  33154. // when released, return the mouse to within the component's bounds
  33155. int mx, my;
  33156. getMouseXYRelative (mx, my);
  33157. mx = jlimit (0, getWidth(), mx);
  33158. my = jlimit (0, getHeight(), my);
  33159. relativePositionToGlobal (mx, my);
  33160. Desktop::setMousePosition (mx, my);
  33161. }
  33162. isUnboundedMouseModeOn = enable;
  33163. unboundedMouseOffsetX = 0;
  33164. unboundedMouseOffsetY = 0;
  33165. internalUpdateMouseCursor (true);
  33166. }
  33167. }
  33168. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  33169. {
  33170. return componentUnderMouse;
  33171. }
  33172. const Rectangle Component::getParentMonitorArea() const throw()
  33173. {
  33174. int centreX = getWidth() / 2;
  33175. int centreY = getHeight() / 2;
  33176. relativePositionToGlobal (centreX, centreY);
  33177. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  33178. }
  33179. void Component::addKeyListener (KeyListener* const newListener) throw()
  33180. {
  33181. if (keyListeners_ == 0)
  33182. keyListeners_ = new VoidArray (4);
  33183. keyListeners_->addIfNotAlreadyThere (newListener);
  33184. }
  33185. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  33186. {
  33187. if (keyListeners_ != 0)
  33188. keyListeners_->removeValue (listenerToRemove);
  33189. }
  33190. bool Component::keyPressed (const KeyPress&)
  33191. {
  33192. return false;
  33193. }
  33194. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33195. {
  33196. return false;
  33197. }
  33198. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33199. {
  33200. if (parentComponent_ != 0)
  33201. parentComponent_->modifierKeysChanged (modifiers);
  33202. }
  33203. void Component::internalModifierKeysChanged()
  33204. {
  33205. sendFakeMouseMove();
  33206. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33207. }
  33208. ComponentPeer* Component::getPeer() const throw()
  33209. {
  33210. if (flags.hasHeavyweightPeerFlag)
  33211. return ComponentPeer::getPeerFor (this);
  33212. else if (parentComponent_ != 0)
  33213. return parentComponent_->getPeer();
  33214. else
  33215. return 0;
  33216. }
  33217. const String Component::getComponentProperty (const String& keyName,
  33218. const bool useParentComponentIfNotFound,
  33219. const String& defaultReturnValue) const throw()
  33220. {
  33221. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33222. return propertySet_->getValue (keyName, defaultReturnValue);
  33223. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33224. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  33225. return defaultReturnValue;
  33226. }
  33227. int Component::getComponentPropertyInt (const String& keyName,
  33228. const bool useParentComponentIfNotFound,
  33229. const int defaultReturnValue) const throw()
  33230. {
  33231. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33232. return propertySet_->getIntValue (keyName, defaultReturnValue);
  33233. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33234. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  33235. return defaultReturnValue;
  33236. }
  33237. double Component::getComponentPropertyDouble (const String& keyName,
  33238. const bool useParentComponentIfNotFound,
  33239. const double defaultReturnValue) const throw()
  33240. {
  33241. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33242. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  33243. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33244. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  33245. return defaultReturnValue;
  33246. }
  33247. bool Component::getComponentPropertyBool (const String& keyName,
  33248. const bool useParentComponentIfNotFound,
  33249. const bool defaultReturnValue) const throw()
  33250. {
  33251. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33252. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  33253. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33254. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  33255. return defaultReturnValue;
  33256. }
  33257. const Colour Component::getComponentPropertyColour (const String& keyName,
  33258. const bool useParentComponentIfNotFound,
  33259. const Colour& defaultReturnValue) const throw()
  33260. {
  33261. return Colour ((uint32) getComponentPropertyInt (keyName,
  33262. useParentComponentIfNotFound,
  33263. defaultReturnValue.getARGB()));
  33264. }
  33265. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  33266. {
  33267. if (propertySet_ == 0)
  33268. propertySet_ = new PropertySet();
  33269. propertySet_->setValue (keyName, value);
  33270. }
  33271. void Component::setComponentProperty (const String& keyName, const int value) throw()
  33272. {
  33273. if (propertySet_ == 0)
  33274. propertySet_ = new PropertySet();
  33275. propertySet_->setValue (keyName, value);
  33276. }
  33277. void Component::setComponentProperty (const String& keyName, const double value) throw()
  33278. {
  33279. if (propertySet_ == 0)
  33280. propertySet_ = new PropertySet();
  33281. propertySet_->setValue (keyName, value);
  33282. }
  33283. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  33284. {
  33285. if (propertySet_ == 0)
  33286. propertySet_ = new PropertySet();
  33287. propertySet_->setValue (keyName, value);
  33288. }
  33289. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  33290. {
  33291. setComponentProperty (keyName, (int) colour.getARGB());
  33292. }
  33293. void Component::removeComponentProperty (const String& keyName) throw()
  33294. {
  33295. if (propertySet_ != 0)
  33296. propertySet_->removeValue (keyName);
  33297. }
  33298. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  33299. : componentToWatch (componentToWatch_),
  33300. componentUID (componentToWatch_->getComponentUID())
  33301. {
  33302. // not possible to check on an already-deleted object..
  33303. jassert (componentToWatch_->isValidComponent());
  33304. }
  33305. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  33306. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  33307. {
  33308. return ! (componentToWatch->isValidComponent()
  33309. && componentToWatch->getComponentUID() == componentUID);
  33310. }
  33311. const Component* ComponentDeletionWatcher::getComponent() const throw()
  33312. {
  33313. return hasBeenDeleted() ? 0 : componentToWatch;
  33314. }
  33315. END_JUCE_NAMESPACE
  33316. /********* End of inlined file: juce_Component.cpp *********/
  33317. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  33318. BEGIN_JUCE_NAMESPACE
  33319. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  33320. {
  33321. }
  33322. void ComponentListener::componentBroughtToFront (Component&)
  33323. {
  33324. }
  33325. void ComponentListener::componentVisibilityChanged (Component&)
  33326. {
  33327. }
  33328. void ComponentListener::componentChildrenChanged (Component&)
  33329. {
  33330. }
  33331. void ComponentListener::componentParentHierarchyChanged (Component&)
  33332. {
  33333. }
  33334. void ComponentListener::componentNameChanged (Component&)
  33335. {
  33336. }
  33337. END_JUCE_NAMESPACE
  33338. /********* End of inlined file: juce_ComponentListener.cpp *********/
  33339. /********* Start of inlined file: juce_Desktop.cpp *********/
  33340. BEGIN_JUCE_NAMESPACE
  33341. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  33342. const bool clipToWorkArea) throw();
  33343. static Desktop* juce_desktopInstance = 0;
  33344. Desktop::Desktop() throw()
  33345. : mouseListeners (2),
  33346. desktopComponents (4),
  33347. monitorCoordsClipped (2),
  33348. monitorCoordsUnclipped (2),
  33349. lastMouseX (0),
  33350. lastMouseY (0),
  33351. kioskModeComponent (0)
  33352. {
  33353. refreshMonitorSizes();
  33354. }
  33355. Desktop::~Desktop() throw()
  33356. {
  33357. jassert (juce_desktopInstance == this);
  33358. juce_desktopInstance = 0;
  33359. // doh! If you don't delete all your windows before exiting, you're going to
  33360. // be leaking memory!
  33361. jassert (desktopComponents.size() == 0);
  33362. }
  33363. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  33364. {
  33365. if (juce_desktopInstance == 0)
  33366. juce_desktopInstance = new Desktop();
  33367. return *juce_desktopInstance;
  33368. }
  33369. void Desktop::refreshMonitorSizes() throw()
  33370. {
  33371. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  33372. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  33373. monitorCoordsClipped.clear();
  33374. monitorCoordsUnclipped.clear();
  33375. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33376. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33377. jassert (monitorCoordsClipped.size() > 0
  33378. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33379. if (oldClipped != monitorCoordsClipped
  33380. || oldUnclipped != monitorCoordsUnclipped)
  33381. {
  33382. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33383. {
  33384. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33385. if (p != 0)
  33386. p->handleScreenSizeChange();
  33387. }
  33388. }
  33389. }
  33390. int Desktop::getNumDisplayMonitors() const throw()
  33391. {
  33392. return monitorCoordsClipped.size();
  33393. }
  33394. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33395. {
  33396. return clippedToWorkArea ? monitorCoordsClipped [index]
  33397. : monitorCoordsUnclipped [index];
  33398. }
  33399. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33400. {
  33401. RectangleList rl;
  33402. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33403. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33404. return rl;
  33405. }
  33406. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33407. {
  33408. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33409. }
  33410. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  33411. {
  33412. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  33413. double bestDistance = 1.0e10;
  33414. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33415. {
  33416. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33417. if (rect.contains (cx, cy))
  33418. return rect;
  33419. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  33420. (double) (rect.getCentreY() - cy));
  33421. if (distance < bestDistance)
  33422. {
  33423. bestDistance = distance;
  33424. best = rect;
  33425. }
  33426. }
  33427. return best;
  33428. }
  33429. int Desktop::getNumComponents() const throw()
  33430. {
  33431. return desktopComponents.size();
  33432. }
  33433. Component* Desktop::getComponent (const int index) const throw()
  33434. {
  33435. return (Component*) desktopComponents [index];
  33436. }
  33437. Component* Desktop::findComponentAt (const int screenX,
  33438. const int screenY) const
  33439. {
  33440. for (int i = desktopComponents.size(); --i >= 0;)
  33441. {
  33442. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  33443. int x = screenX, y = screenY;
  33444. c->globalPositionToRelative (x, y);
  33445. if (c->contains (x, y))
  33446. return c->getComponentAt (x, y);
  33447. }
  33448. return 0;
  33449. }
  33450. void Desktop::addDesktopComponent (Component* const c) throw()
  33451. {
  33452. jassert (c != 0);
  33453. jassert (! desktopComponents.contains (c));
  33454. desktopComponents.addIfNotAlreadyThere (c);
  33455. }
  33456. void Desktop::removeDesktopComponent (Component* const c) throw()
  33457. {
  33458. desktopComponents.removeValue (c);
  33459. }
  33460. void Desktop::componentBroughtToFront (Component* const c) throw()
  33461. {
  33462. const int index = desktopComponents.indexOf (c);
  33463. jassert (index >= 0);
  33464. if (index >= 0)
  33465. desktopComponents.move (index, -1);
  33466. }
  33467. // from Component.cpp
  33468. extern int juce_recentMouseDownX [4];
  33469. extern int juce_recentMouseDownY [4];
  33470. extern int juce_MouseClickCounter;
  33471. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  33472. {
  33473. x = juce_recentMouseDownX [0];
  33474. y = juce_recentMouseDownY [0];
  33475. }
  33476. int Desktop::getMouseButtonClickCounter() throw()
  33477. {
  33478. return juce_MouseClickCounter;
  33479. }
  33480. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  33481. {
  33482. jassert (listener != 0);
  33483. if (listener != 0)
  33484. {
  33485. mouseListeners.add (listener);
  33486. resetTimer();
  33487. }
  33488. }
  33489. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  33490. {
  33491. mouseListeners.removeValue (listener);
  33492. resetTimer();
  33493. }
  33494. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  33495. {
  33496. jassert (listener != 0);
  33497. if (listener != 0)
  33498. focusListeners.add (listener);
  33499. }
  33500. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  33501. {
  33502. focusListeners.removeValue (listener);
  33503. }
  33504. void Desktop::triggerFocusCallback() throw()
  33505. {
  33506. triggerAsyncUpdate();
  33507. }
  33508. void Desktop::handleAsyncUpdate()
  33509. {
  33510. for (int i = focusListeners.size(); --i >= 0;)
  33511. {
  33512. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  33513. i = jmin (i, focusListeners.size());
  33514. }
  33515. }
  33516. void Desktop::timerCallback()
  33517. {
  33518. int x, y;
  33519. getMousePosition (x, y);
  33520. if (lastMouseX != x || lastMouseY != y)
  33521. sendMouseMove();
  33522. }
  33523. void Desktop::sendMouseMove()
  33524. {
  33525. if (mouseListeners.size() > 0)
  33526. {
  33527. startTimer (20);
  33528. int x, y;
  33529. getMousePosition (x, y);
  33530. lastMouseX = x;
  33531. lastMouseY = y;
  33532. Component* const target = findComponentAt (x, y);
  33533. if (target != 0)
  33534. {
  33535. target->globalPositionToRelative (x, y);
  33536. ComponentDeletionWatcher deletionChecker (target);
  33537. const MouseEvent me (x, y,
  33538. ModifierKeys::getCurrentModifiers(),
  33539. target,
  33540. Time::getCurrentTime(),
  33541. x, y,
  33542. Time::getCurrentTime(),
  33543. 0, false);
  33544. for (int i = mouseListeners.size(); --i >= 0;)
  33545. {
  33546. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  33547. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  33548. else
  33549. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  33550. if (deletionChecker.hasBeenDeleted())
  33551. return;
  33552. i = jmin (i, mouseListeners.size());
  33553. }
  33554. }
  33555. }
  33556. }
  33557. void Desktop::resetTimer() throw()
  33558. {
  33559. if (mouseListeners.size() == 0)
  33560. stopTimer();
  33561. else
  33562. startTimer (100);
  33563. getMousePosition (lastMouseX, lastMouseY);
  33564. }
  33565. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33566. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33567. {
  33568. if (kioskModeComponent != componentToUse)
  33569. {
  33570. // agh! Don't delete a component without first stopping it being the kiosk comp
  33571. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33572. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33573. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33574. if (kioskModeComponent->isValidComponent())
  33575. {
  33576. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33577. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33578. }
  33579. kioskModeComponent = componentToUse;
  33580. if (kioskModeComponent != 0)
  33581. {
  33582. jassert (kioskModeComponent->isValidComponent());
  33583. // Only components that are already on the desktop can be put into kiosk mode!
  33584. jassert (kioskModeComponent->isOnDesktop());
  33585. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33586. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33587. }
  33588. }
  33589. }
  33590. END_JUCE_NAMESPACE
  33591. /********* End of inlined file: juce_Desktop.cpp *********/
  33592. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  33593. BEGIN_JUCE_NAMESPACE
  33594. ArrowButton::ArrowButton (const String& name,
  33595. float arrowDirectionInRadians,
  33596. const Colour& arrowColour)
  33597. : Button (name),
  33598. colour (arrowColour)
  33599. {
  33600. path.lineTo (0.0f, 1.0f);
  33601. path.lineTo (1.0f, 0.5f);
  33602. path.closeSubPath();
  33603. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33604. 0.5f, 0.5f));
  33605. setComponentEffect (&shadow);
  33606. buttonStateChanged();
  33607. }
  33608. ArrowButton::~ArrowButton()
  33609. {
  33610. }
  33611. void ArrowButton::paintButton (Graphics& g,
  33612. bool /*isMouseOverButton*/,
  33613. bool /*isButtonDown*/)
  33614. {
  33615. g.setColour (colour);
  33616. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33617. (float) offset,
  33618. (float) (getWidth() - 3),
  33619. (float) (getHeight() - 3),
  33620. false));
  33621. }
  33622. void ArrowButton::buttonStateChanged()
  33623. {
  33624. offset = (isDown()) ? 1 : 0;
  33625. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33626. 0.3f, -1, 0);
  33627. }
  33628. END_JUCE_NAMESPACE
  33629. /********* End of inlined file: juce_ArrowButton.cpp *********/
  33630. /********* Start of inlined file: juce_Button.cpp *********/
  33631. BEGIN_JUCE_NAMESPACE
  33632. Button::Button (const String& name)
  33633. : Component (name),
  33634. shortcuts (2),
  33635. keySource (0),
  33636. text (name),
  33637. buttonListeners (2),
  33638. repeatTimer (0),
  33639. buttonPressTime (0),
  33640. lastTimeCallbackTime (0),
  33641. commandManagerToUse (0),
  33642. autoRepeatDelay (-1),
  33643. autoRepeatSpeed (0),
  33644. autoRepeatMinimumDelay (-1),
  33645. radioGroupId (0),
  33646. commandID (0),
  33647. connectedEdgeFlags (0),
  33648. buttonState (buttonNormal),
  33649. isOn (false),
  33650. clickTogglesState (false),
  33651. needsToRelease (false),
  33652. needsRepainting (false),
  33653. isKeyDown (false),
  33654. triggerOnMouseDown (false),
  33655. generateTooltip (false)
  33656. {
  33657. setWantsKeyboardFocus (true);
  33658. }
  33659. Button::~Button()
  33660. {
  33661. if (commandManagerToUse != 0)
  33662. commandManagerToUse->removeListener (this);
  33663. delete repeatTimer;
  33664. clearShortcuts();
  33665. }
  33666. void Button::setButtonText (const String& newText) throw()
  33667. {
  33668. if (text != newText)
  33669. {
  33670. text = newText;
  33671. repaint();
  33672. }
  33673. }
  33674. void Button::setTooltip (const String& newTooltip)
  33675. {
  33676. SettableTooltipClient::setTooltip (newTooltip);
  33677. generateTooltip = false;
  33678. }
  33679. const String Button::getTooltip()
  33680. {
  33681. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33682. {
  33683. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33684. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33685. for (int i = 0; i < keyPresses.size(); ++i)
  33686. {
  33687. const String key (keyPresses.getReference(i).getTextDescription());
  33688. if (key.length() == 1)
  33689. tt << " [shortcut: '" << key << "']";
  33690. else
  33691. tt << " [" << key << ']';
  33692. }
  33693. return tt;
  33694. }
  33695. return SettableTooltipClient::getTooltip();
  33696. }
  33697. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  33698. {
  33699. if (connectedEdgeFlags != connectedEdgeFlags_)
  33700. {
  33701. connectedEdgeFlags = connectedEdgeFlags_;
  33702. repaint();
  33703. }
  33704. }
  33705. void Button::setToggleState (const bool shouldBeOn,
  33706. const bool sendChangeNotification)
  33707. {
  33708. if (shouldBeOn != isOn)
  33709. {
  33710. const ComponentDeletionWatcher deletionWatcher (this);
  33711. isOn = shouldBeOn;
  33712. repaint();
  33713. if (sendChangeNotification)
  33714. sendClickMessage (ModifierKeys());
  33715. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  33716. turnOffOtherButtonsInGroup (sendChangeNotification);
  33717. }
  33718. }
  33719. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33720. {
  33721. clickTogglesState = shouldToggle;
  33722. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33723. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33724. // it is that this button represents, and the button will update its state to reflect this
  33725. // in the applicationCommandListChanged() method.
  33726. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33727. }
  33728. bool Button::getClickingTogglesState() const throw()
  33729. {
  33730. return clickTogglesState;
  33731. }
  33732. void Button::setRadioGroupId (const int newGroupId)
  33733. {
  33734. if (radioGroupId != newGroupId)
  33735. {
  33736. radioGroupId = newGroupId;
  33737. if (isOn)
  33738. turnOffOtherButtonsInGroup (true);
  33739. }
  33740. }
  33741. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33742. {
  33743. Component* const p = getParentComponent();
  33744. if (p != 0 && radioGroupId != 0)
  33745. {
  33746. const ComponentDeletionWatcher deletionWatcher (this);
  33747. for (int i = p->getNumChildComponents(); --i >= 0;)
  33748. {
  33749. Component* const c = p->getChildComponent (i);
  33750. if (c != this)
  33751. {
  33752. Button* const b = dynamic_cast <Button*> (c);
  33753. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33754. {
  33755. b->setToggleState (false, sendChangeNotification);
  33756. if (deletionWatcher.hasBeenDeleted())
  33757. return;
  33758. }
  33759. }
  33760. }
  33761. }
  33762. }
  33763. void Button::enablementChanged()
  33764. {
  33765. updateState (0);
  33766. repaint();
  33767. }
  33768. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  33769. {
  33770. ButtonState state = buttonNormal;
  33771. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33772. {
  33773. int mx, my;
  33774. if (e == 0)
  33775. {
  33776. getMouseXYRelative (mx, my);
  33777. }
  33778. else
  33779. {
  33780. const MouseEvent e2 (e->getEventRelativeTo (this));
  33781. mx = e2.x;
  33782. my = e2.y;
  33783. }
  33784. const bool over = reallyContains (mx, my, true);
  33785. const bool down = isMouseButtonDown();
  33786. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33787. state = buttonDown;
  33788. else if (over)
  33789. state = buttonOver;
  33790. }
  33791. setState (state);
  33792. return state;
  33793. }
  33794. void Button::setState (const ButtonState newState)
  33795. {
  33796. if (buttonState != newState)
  33797. {
  33798. buttonState = newState;
  33799. repaint();
  33800. if (buttonState == buttonDown)
  33801. {
  33802. buttonPressTime = Time::getApproximateMillisecondCounter();
  33803. lastTimeCallbackTime = buttonPressTime;
  33804. }
  33805. sendStateMessage();
  33806. }
  33807. }
  33808. bool Button::isDown() const throw()
  33809. {
  33810. return buttonState == buttonDown;
  33811. }
  33812. bool Button::isOver() const throw()
  33813. {
  33814. return buttonState != buttonNormal;
  33815. }
  33816. void Button::buttonStateChanged()
  33817. {
  33818. }
  33819. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  33820. {
  33821. const uint32 now = Time::getApproximateMillisecondCounter();
  33822. return now > buttonPressTime ? now - buttonPressTime : 0;
  33823. }
  33824. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  33825. {
  33826. triggerOnMouseDown = isTriggeredOnMouseDown;
  33827. }
  33828. void Button::clicked()
  33829. {
  33830. }
  33831. void Button::clicked (const ModifierKeys& /*modifiers*/)
  33832. {
  33833. clicked();
  33834. }
  33835. static const int clickMessageId = 0x2f3f4f99;
  33836. void Button::triggerClick()
  33837. {
  33838. postCommandMessage (clickMessageId);
  33839. }
  33840. void Button::internalClickCallback (const ModifierKeys& modifiers)
  33841. {
  33842. if (clickTogglesState)
  33843. setToggleState ((radioGroupId != 0) || ! isOn, false);
  33844. sendClickMessage (modifiers);
  33845. }
  33846. void Button::flashButtonState() throw()
  33847. {
  33848. if (isEnabled())
  33849. {
  33850. needsToRelease = true;
  33851. setState (buttonDown);
  33852. getRepeatTimer().startTimer (100);
  33853. }
  33854. }
  33855. void Button::handleCommandMessage (int commandId)
  33856. {
  33857. if (commandId == clickMessageId)
  33858. {
  33859. if (isEnabled())
  33860. {
  33861. flashButtonState();
  33862. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33863. }
  33864. }
  33865. else
  33866. {
  33867. Component::handleCommandMessage (commandId);
  33868. }
  33869. }
  33870. void Button::addButtonListener (ButtonListener* const newListener) throw()
  33871. {
  33872. jassert (newListener != 0);
  33873. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  33874. if (newListener != 0)
  33875. buttonListeners.add (newListener);
  33876. }
  33877. void Button::removeButtonListener (ButtonListener* const listener) throw()
  33878. {
  33879. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  33880. buttonListeners.removeValue (listener);
  33881. }
  33882. void Button::sendClickMessage (const ModifierKeys& modifiers)
  33883. {
  33884. const ComponentDeletionWatcher cdw (this);
  33885. if (commandManagerToUse != 0 && commandID != 0)
  33886. {
  33887. ApplicationCommandTarget::InvocationInfo info (commandID);
  33888. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  33889. info.originatingComponent = this;
  33890. commandManagerToUse->invoke (info, true);
  33891. }
  33892. clicked (modifiers);
  33893. if (! cdw.hasBeenDeleted())
  33894. {
  33895. for (int i = buttonListeners.size(); --i >= 0;)
  33896. {
  33897. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33898. if (bl != 0)
  33899. {
  33900. bl->buttonClicked (this);
  33901. if (cdw.hasBeenDeleted())
  33902. return;
  33903. }
  33904. }
  33905. }
  33906. }
  33907. void Button::sendStateMessage()
  33908. {
  33909. const ComponentDeletionWatcher cdw (this);
  33910. buttonStateChanged();
  33911. if (cdw.hasBeenDeleted())
  33912. return;
  33913. for (int i = buttonListeners.size(); --i >= 0;)
  33914. {
  33915. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33916. if (bl != 0)
  33917. {
  33918. bl->buttonStateChanged (this);
  33919. if (cdw.hasBeenDeleted())
  33920. return;
  33921. }
  33922. }
  33923. }
  33924. void Button::paint (Graphics& g)
  33925. {
  33926. if (needsToRelease && isEnabled())
  33927. {
  33928. needsToRelease = false;
  33929. needsRepainting = true;
  33930. }
  33931. paintButton (g, isOver(), isDown());
  33932. }
  33933. void Button::mouseEnter (const MouseEvent& e)
  33934. {
  33935. updateState (&e);
  33936. }
  33937. void Button::mouseExit (const MouseEvent& e)
  33938. {
  33939. updateState (&e);
  33940. }
  33941. void Button::mouseDown (const MouseEvent& e)
  33942. {
  33943. updateState (&e);
  33944. if (isDown())
  33945. {
  33946. if (autoRepeatDelay >= 0)
  33947. getRepeatTimer().startTimer (autoRepeatDelay);
  33948. if (triggerOnMouseDown)
  33949. internalClickCallback (e.mods);
  33950. }
  33951. }
  33952. void Button::mouseUp (const MouseEvent& e)
  33953. {
  33954. const bool wasDown = isDown();
  33955. updateState (&e);
  33956. if (wasDown && isOver() && ! triggerOnMouseDown)
  33957. internalClickCallback (e.mods);
  33958. }
  33959. void Button::mouseDrag (const MouseEvent& e)
  33960. {
  33961. const ButtonState oldState = buttonState;
  33962. updateState (&e);
  33963. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  33964. getRepeatTimer().startTimer (autoRepeatSpeed);
  33965. }
  33966. void Button::focusGained (FocusChangeType)
  33967. {
  33968. updateState (0);
  33969. repaint();
  33970. }
  33971. void Button::focusLost (FocusChangeType)
  33972. {
  33973. updateState (0);
  33974. repaint();
  33975. }
  33976. void Button::setVisible (bool shouldBeVisible)
  33977. {
  33978. if (shouldBeVisible != isVisible())
  33979. {
  33980. Component::setVisible (shouldBeVisible);
  33981. if (! shouldBeVisible)
  33982. needsToRelease = false;
  33983. updateState (0);
  33984. }
  33985. else
  33986. {
  33987. Component::setVisible (shouldBeVisible);
  33988. }
  33989. }
  33990. void Button::parentHierarchyChanged()
  33991. {
  33992. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  33993. if (newKeySource != keySource)
  33994. {
  33995. if (keySource->isValidComponent())
  33996. keySource->removeKeyListener (this);
  33997. keySource = newKeySource;
  33998. if (keySource->isValidComponent())
  33999. keySource->addKeyListener (this);
  34000. }
  34001. }
  34002. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34003. const int commandID_,
  34004. const bool generateTooltip_)
  34005. {
  34006. commandID = commandID_;
  34007. generateTooltip = generateTooltip_;
  34008. if (commandManagerToUse != commandManagerToUse_)
  34009. {
  34010. if (commandManagerToUse != 0)
  34011. commandManagerToUse->removeListener (this);
  34012. commandManagerToUse = commandManagerToUse_;
  34013. if (commandManagerToUse != 0)
  34014. commandManagerToUse->addListener (this);
  34015. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34016. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34017. // it is that this button represents, and the button will update its state to reflect this
  34018. // in the applicationCommandListChanged() method.
  34019. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34020. }
  34021. if (commandManagerToUse != 0)
  34022. applicationCommandListChanged();
  34023. else
  34024. setEnabled (true);
  34025. }
  34026. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34027. {
  34028. if (info.commandID == commandID
  34029. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34030. {
  34031. flashButtonState();
  34032. }
  34033. }
  34034. void Button::applicationCommandListChanged()
  34035. {
  34036. if (commandManagerToUse != 0)
  34037. {
  34038. ApplicationCommandInfo info (0);
  34039. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34040. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34041. if (target != 0)
  34042. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34043. }
  34044. }
  34045. void Button::addShortcut (const KeyPress& key)
  34046. {
  34047. if (key.isValid())
  34048. {
  34049. jassert (! isRegisteredForShortcut (key)); // already registered!
  34050. shortcuts.add (key);
  34051. parentHierarchyChanged();
  34052. }
  34053. }
  34054. void Button::clearShortcuts()
  34055. {
  34056. shortcuts.clear();
  34057. parentHierarchyChanged();
  34058. }
  34059. bool Button::isShortcutPressed() const throw()
  34060. {
  34061. if (! isCurrentlyBlockedByAnotherModalComponent())
  34062. {
  34063. for (int i = shortcuts.size(); --i >= 0;)
  34064. if (shortcuts.getReference(i).isCurrentlyDown())
  34065. return true;
  34066. }
  34067. return false;
  34068. }
  34069. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  34070. {
  34071. for (int i = shortcuts.size(); --i >= 0;)
  34072. if (key == shortcuts.getReference(i))
  34073. return true;
  34074. return false;
  34075. }
  34076. bool Button::keyStateChanged (const bool, Component*)
  34077. {
  34078. if (! isEnabled())
  34079. return false;
  34080. const bool wasDown = isKeyDown;
  34081. isKeyDown = isShortcutPressed();
  34082. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34083. getRepeatTimer().startTimer (autoRepeatDelay);
  34084. updateState (0);
  34085. if (isEnabled() && wasDown && ! isKeyDown)
  34086. {
  34087. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34088. // (return immediately - this button may now have been deleted)
  34089. return true;
  34090. }
  34091. return wasDown || isKeyDown;
  34092. }
  34093. bool Button::keyPressed (const KeyPress&, Component*)
  34094. {
  34095. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34096. return isShortcutPressed();
  34097. }
  34098. bool Button::keyPressed (const KeyPress& key)
  34099. {
  34100. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34101. {
  34102. triggerClick();
  34103. return true;
  34104. }
  34105. return false;
  34106. }
  34107. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34108. const int repeatMillisecs,
  34109. const int minimumDelayInMillisecs) throw()
  34110. {
  34111. autoRepeatDelay = initialDelayMillisecs;
  34112. autoRepeatSpeed = repeatMillisecs;
  34113. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34114. }
  34115. void Button::repeatTimerCallback() throw()
  34116. {
  34117. if (needsRepainting)
  34118. {
  34119. getRepeatTimer().stopTimer();
  34120. updateState (0);
  34121. needsRepainting = false;
  34122. }
  34123. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34124. {
  34125. int repeatSpeed = autoRepeatSpeed;
  34126. if (autoRepeatMinimumDelay >= 0)
  34127. {
  34128. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34129. timeHeldDown *= timeHeldDown;
  34130. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34131. }
  34132. repeatSpeed = jmax (1, repeatSpeed);
  34133. getRepeatTimer().startTimer (repeatSpeed);
  34134. const uint32 now = Time::getApproximateMillisecondCounter();
  34135. const int numTimesToCallback
  34136. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34137. lastTimeCallbackTime = now;
  34138. const ComponentDeletionWatcher cdw (this);
  34139. for (int i = numTimesToCallback; --i >= 0;)
  34140. {
  34141. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34142. if (cdw.hasBeenDeleted() || ! isDown())
  34143. return;
  34144. }
  34145. }
  34146. else if (! needsToRelease)
  34147. {
  34148. getRepeatTimer().stopTimer();
  34149. }
  34150. }
  34151. class InternalButtonRepeatTimer : public Timer
  34152. {
  34153. public:
  34154. InternalButtonRepeatTimer (Button& owner_) throw()
  34155. : owner (owner_)
  34156. {
  34157. }
  34158. ~InternalButtonRepeatTimer()
  34159. {
  34160. }
  34161. void timerCallback()
  34162. {
  34163. owner.repeatTimerCallback();
  34164. }
  34165. private:
  34166. Button& owner;
  34167. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  34168. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  34169. };
  34170. Timer& Button::getRepeatTimer() throw()
  34171. {
  34172. if (repeatTimer == 0)
  34173. repeatTimer = new InternalButtonRepeatTimer (*this);
  34174. return *repeatTimer;
  34175. }
  34176. END_JUCE_NAMESPACE
  34177. /********* End of inlined file: juce_Button.cpp *********/
  34178. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  34179. BEGIN_JUCE_NAMESPACE
  34180. DrawableButton::DrawableButton (const String& name,
  34181. const DrawableButton::ButtonStyle buttonStyle)
  34182. : Button (name),
  34183. style (buttonStyle),
  34184. normalImage (0),
  34185. overImage (0),
  34186. downImage (0),
  34187. disabledImage (0),
  34188. normalImageOn (0),
  34189. overImageOn (0),
  34190. downImageOn (0),
  34191. disabledImageOn (0),
  34192. edgeIndent (3)
  34193. {
  34194. if (buttonStyle == ImageOnButtonBackground)
  34195. {
  34196. backgroundOff = Colour (0xffbbbbff);
  34197. backgroundOn = Colour (0xff3333ff);
  34198. }
  34199. else
  34200. {
  34201. backgroundOff = Colours::transparentBlack;
  34202. backgroundOn = Colour (0xaabbbbff);
  34203. }
  34204. }
  34205. DrawableButton::~DrawableButton()
  34206. {
  34207. deleteImages();
  34208. }
  34209. void DrawableButton::deleteImages()
  34210. {
  34211. deleteAndZero (normalImage);
  34212. deleteAndZero (overImage);
  34213. deleteAndZero (downImage);
  34214. deleteAndZero (disabledImage);
  34215. deleteAndZero (normalImageOn);
  34216. deleteAndZero (overImageOn);
  34217. deleteAndZero (downImageOn);
  34218. deleteAndZero (disabledImageOn);
  34219. }
  34220. void DrawableButton::setImages (const Drawable* normal,
  34221. const Drawable* over,
  34222. const Drawable* down,
  34223. const Drawable* disabled,
  34224. const Drawable* normalOn,
  34225. const Drawable* overOn,
  34226. const Drawable* downOn,
  34227. const Drawable* disabledOn)
  34228. {
  34229. deleteImages();
  34230. jassert (normal != 0); // you really need to give it at least a normal image..
  34231. if (normal != 0)
  34232. normalImage = normal->createCopy();
  34233. if (over != 0)
  34234. overImage = over->createCopy();
  34235. if (down != 0)
  34236. downImage = down->createCopy();
  34237. if (disabled != 0)
  34238. disabledImage = disabled->createCopy();
  34239. if (normalOn != 0)
  34240. normalImageOn = normalOn->createCopy();
  34241. if (overOn != 0)
  34242. overImageOn = overOn->createCopy();
  34243. if (downOn != 0)
  34244. downImageOn = downOn->createCopy();
  34245. if (disabledOn != 0)
  34246. disabledImageOn = disabledOn->createCopy();
  34247. repaint();
  34248. }
  34249. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34250. {
  34251. if (style != newStyle)
  34252. {
  34253. style = newStyle;
  34254. repaint();
  34255. }
  34256. }
  34257. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34258. const Colour& toggledOnColour)
  34259. {
  34260. if (backgroundOff != toggledOffColour
  34261. || backgroundOn != toggledOnColour)
  34262. {
  34263. backgroundOff = toggledOffColour;
  34264. backgroundOn = toggledOnColour;
  34265. repaint();
  34266. }
  34267. }
  34268. const Colour& DrawableButton::getBackgroundColour() const throw()
  34269. {
  34270. return getToggleState() ? backgroundOn
  34271. : backgroundOff;
  34272. }
  34273. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34274. {
  34275. edgeIndent = numPixelsIndent;
  34276. repaint();
  34277. }
  34278. void DrawableButton::paintButton (Graphics& g,
  34279. bool isMouseOverButton,
  34280. bool isButtonDown)
  34281. {
  34282. Rectangle imageSpace;
  34283. if (style == ImageOnButtonBackground)
  34284. {
  34285. const int insetX = getWidth() / 4;
  34286. const int insetY = getHeight() / 4;
  34287. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34288. getLookAndFeel().drawButtonBackground (g, *this,
  34289. getBackgroundColour(),
  34290. isMouseOverButton,
  34291. isButtonDown);
  34292. }
  34293. else
  34294. {
  34295. g.fillAll (getBackgroundColour());
  34296. const int textH = (style == ImageAboveTextLabel)
  34297. ? jmin (16, proportionOfHeight (0.25f))
  34298. : 0;
  34299. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34300. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34301. imageSpace.setBounds (indentX, indentY,
  34302. getWidth() - indentX * 2,
  34303. getHeight() - indentY * 2 - textH);
  34304. if (textH > 0)
  34305. {
  34306. g.setFont ((float) textH);
  34307. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34308. g.drawFittedText (getButtonText(),
  34309. 2, getHeight() - textH - 1,
  34310. getWidth() - 4, textH,
  34311. Justification::centred, 1);
  34312. }
  34313. }
  34314. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34315. g.setOpacity (1.0f);
  34316. const Drawable* imageToDraw = 0;
  34317. if (isEnabled())
  34318. {
  34319. imageToDraw = getCurrentImage();
  34320. }
  34321. else
  34322. {
  34323. imageToDraw = getToggleState() ? disabledImageOn
  34324. : disabledImage;
  34325. if (imageToDraw == 0)
  34326. {
  34327. g.setOpacity (0.4f);
  34328. imageToDraw = getNormalImage();
  34329. }
  34330. }
  34331. if (imageToDraw != 0)
  34332. {
  34333. if (style == ImageRaw)
  34334. {
  34335. imageToDraw->draw (g);
  34336. }
  34337. else
  34338. {
  34339. imageToDraw->drawWithin (g,
  34340. imageSpace.getX(),
  34341. imageSpace.getY(),
  34342. imageSpace.getWidth(),
  34343. imageSpace.getHeight(),
  34344. RectanglePlacement::centred);
  34345. }
  34346. }
  34347. }
  34348. const Drawable* DrawableButton::getCurrentImage() const throw()
  34349. {
  34350. if (isDown())
  34351. return getDownImage();
  34352. if (isOver())
  34353. return getOverImage();
  34354. return getNormalImage();
  34355. }
  34356. const Drawable* DrawableButton::getNormalImage() const throw()
  34357. {
  34358. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34359. : normalImage;
  34360. }
  34361. const Drawable* DrawableButton::getOverImage() const throw()
  34362. {
  34363. const Drawable* d = normalImage;
  34364. if (getToggleState())
  34365. {
  34366. if (overImageOn != 0)
  34367. d = overImageOn;
  34368. else if (normalImageOn != 0)
  34369. d = normalImageOn;
  34370. else if (overImage != 0)
  34371. d = overImage;
  34372. }
  34373. else
  34374. {
  34375. if (overImage != 0)
  34376. d = overImage;
  34377. }
  34378. return d;
  34379. }
  34380. const Drawable* DrawableButton::getDownImage() const throw()
  34381. {
  34382. const Drawable* d = normalImage;
  34383. if (getToggleState())
  34384. {
  34385. if (downImageOn != 0)
  34386. d = downImageOn;
  34387. else if (overImageOn != 0)
  34388. d = overImageOn;
  34389. else if (normalImageOn != 0)
  34390. d = normalImageOn;
  34391. else if (downImage != 0)
  34392. d = downImage;
  34393. else
  34394. d = getOverImage();
  34395. }
  34396. else
  34397. {
  34398. if (downImage != 0)
  34399. d = downImage;
  34400. else
  34401. d = getOverImage();
  34402. }
  34403. return d;
  34404. }
  34405. END_JUCE_NAMESPACE
  34406. /********* End of inlined file: juce_DrawableButton.cpp *********/
  34407. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  34408. BEGIN_JUCE_NAMESPACE
  34409. HyperlinkButton::HyperlinkButton (const String& linkText,
  34410. const URL& linkURL)
  34411. : Button (linkText),
  34412. url (linkURL),
  34413. font (14.0f, Font::underlined),
  34414. resizeFont (true),
  34415. justification (Justification::centred)
  34416. {
  34417. setMouseCursor (MouseCursor::PointingHandCursor);
  34418. setTooltip (linkURL.toString (false));
  34419. }
  34420. HyperlinkButton::~HyperlinkButton()
  34421. {
  34422. }
  34423. void HyperlinkButton::setFont (const Font& newFont,
  34424. const bool resizeToMatchComponentHeight,
  34425. const Justification& justificationType)
  34426. {
  34427. font = newFont;
  34428. resizeFont = resizeToMatchComponentHeight;
  34429. justification = justificationType;
  34430. repaint();
  34431. }
  34432. void HyperlinkButton::setURL (const URL& newURL) throw()
  34433. {
  34434. url = newURL;
  34435. setTooltip (newURL.toString (false));
  34436. }
  34437. const Font HyperlinkButton::getFontToUse() const
  34438. {
  34439. Font f (font);
  34440. if (resizeFont)
  34441. f.setHeight (getHeight() * 0.7f);
  34442. return f;
  34443. }
  34444. void HyperlinkButton::changeWidthToFitText()
  34445. {
  34446. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34447. }
  34448. void HyperlinkButton::colourChanged()
  34449. {
  34450. repaint();
  34451. }
  34452. void HyperlinkButton::clicked()
  34453. {
  34454. if (url.isWellFormed())
  34455. url.launchInDefaultBrowser();
  34456. }
  34457. void HyperlinkButton::paintButton (Graphics& g,
  34458. bool isMouseOverButton,
  34459. bool isButtonDown)
  34460. {
  34461. const Colour textColour (findColour (textColourId));
  34462. if (isEnabled())
  34463. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34464. : textColour);
  34465. else
  34466. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34467. g.setFont (getFontToUse());
  34468. g.drawText (getButtonText(),
  34469. 2, 0, getWidth() - 2, getHeight(),
  34470. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34471. true);
  34472. }
  34473. END_JUCE_NAMESPACE
  34474. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  34475. /********* Start of inlined file: juce_ImageButton.cpp *********/
  34476. BEGIN_JUCE_NAMESPACE
  34477. ImageButton::ImageButton (const String& text_)
  34478. : Button (text_),
  34479. scaleImageToFit (true),
  34480. preserveProportions (true),
  34481. alphaThreshold (0),
  34482. imageX (0),
  34483. imageY (0),
  34484. imageW (0),
  34485. imageH (0),
  34486. normalImage (0),
  34487. overImage (0),
  34488. downImage (0)
  34489. {
  34490. }
  34491. ImageButton::~ImageButton()
  34492. {
  34493. deleteImages();
  34494. }
  34495. void ImageButton::deleteImages()
  34496. {
  34497. if (normalImage != 0)
  34498. {
  34499. if (ImageCache::isImageInCache (normalImage))
  34500. ImageCache::release (normalImage);
  34501. else
  34502. delete normalImage;
  34503. }
  34504. if (overImage != 0)
  34505. {
  34506. if (ImageCache::isImageInCache (overImage))
  34507. ImageCache::release (overImage);
  34508. else
  34509. delete overImage;
  34510. }
  34511. if (downImage != 0)
  34512. {
  34513. if (ImageCache::isImageInCache (downImage))
  34514. ImageCache::release (downImage);
  34515. else
  34516. delete downImage;
  34517. }
  34518. }
  34519. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34520. const bool rescaleImagesWhenButtonSizeChanges,
  34521. const bool preserveImageProportions,
  34522. Image* const normalImage_,
  34523. const float imageOpacityWhenNormal,
  34524. const Colour& overlayColourWhenNormal,
  34525. Image* const overImage_,
  34526. const float imageOpacityWhenOver,
  34527. const Colour& overlayColourWhenOver,
  34528. Image* const downImage_,
  34529. const float imageOpacityWhenDown,
  34530. const Colour& overlayColourWhenDown,
  34531. const float hitTestAlphaThreshold)
  34532. {
  34533. deleteImages();
  34534. normalImage = normalImage_;
  34535. overImage = overImage_;
  34536. downImage = downImage_;
  34537. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34538. {
  34539. imageW = normalImage->getWidth();
  34540. imageH = normalImage->getHeight();
  34541. setSize (imageW, imageH);
  34542. }
  34543. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34544. preserveProportions = preserveImageProportions;
  34545. normalOpacity = imageOpacityWhenNormal;
  34546. normalOverlay = overlayColourWhenNormal;
  34547. overOpacity = imageOpacityWhenOver;
  34548. overOverlay = overlayColourWhenOver;
  34549. downOpacity = imageOpacityWhenDown;
  34550. downOverlay = overlayColourWhenDown;
  34551. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  34552. repaint();
  34553. }
  34554. Image* ImageButton::getCurrentImage() const
  34555. {
  34556. if (isDown() || getToggleState())
  34557. return getDownImage();
  34558. if (isOver())
  34559. return getOverImage();
  34560. return getNormalImage();
  34561. }
  34562. Image* ImageButton::getNormalImage() const throw()
  34563. {
  34564. return normalImage;
  34565. }
  34566. Image* ImageButton::getOverImage() const throw()
  34567. {
  34568. return (overImage != 0) ? overImage
  34569. : normalImage;
  34570. }
  34571. Image* ImageButton::getDownImage() const throw()
  34572. {
  34573. return (downImage != 0) ? downImage
  34574. : getOverImage();
  34575. }
  34576. void ImageButton::paintButton (Graphics& g,
  34577. bool isMouseOverButton,
  34578. bool isButtonDown)
  34579. {
  34580. if (! isEnabled())
  34581. {
  34582. isMouseOverButton = false;
  34583. isButtonDown = false;
  34584. }
  34585. Image* const im = getCurrentImage();
  34586. if (im != 0)
  34587. {
  34588. const int iw = im->getWidth();
  34589. const int ih = im->getHeight();
  34590. imageW = getWidth();
  34591. imageH = getHeight();
  34592. imageX = (imageW - iw) >> 1;
  34593. imageY = (imageH - ih) >> 1;
  34594. if (scaleImageToFit)
  34595. {
  34596. if (preserveProportions)
  34597. {
  34598. int newW, newH;
  34599. const float imRatio = ih / (float)iw;
  34600. const float destRatio = imageH / (float)imageW;
  34601. if (imRatio > destRatio)
  34602. {
  34603. newW = roundFloatToInt (imageH / imRatio);
  34604. newH = imageH;
  34605. }
  34606. else
  34607. {
  34608. newW = imageW;
  34609. newH = roundFloatToInt (imageW * imRatio);
  34610. }
  34611. imageX = (imageW - newW) / 2;
  34612. imageY = (imageH - newH) / 2;
  34613. imageW = newW;
  34614. imageH = newH;
  34615. }
  34616. else
  34617. {
  34618. imageX = 0;
  34619. imageY = 0;
  34620. }
  34621. }
  34622. if (! scaleImageToFit)
  34623. {
  34624. imageW = iw;
  34625. imageH = ih;
  34626. }
  34627. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34628. isButtonDown ? downOverlay
  34629. : (isMouseOverButton ? overOverlay
  34630. : normalOverlay),
  34631. isButtonDown ? downOpacity
  34632. : (isMouseOverButton ? overOpacity
  34633. : normalOpacity),
  34634. *this);
  34635. }
  34636. }
  34637. bool ImageButton::hitTest (int x, int y)
  34638. {
  34639. if (alphaThreshold == 0)
  34640. return true;
  34641. Image* const im = getCurrentImage();
  34642. return im == 0
  34643. || (imageW > 0 && imageH > 0
  34644. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34645. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34646. }
  34647. END_JUCE_NAMESPACE
  34648. /********* End of inlined file: juce_ImageButton.cpp *********/
  34649. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  34650. BEGIN_JUCE_NAMESPACE
  34651. ShapeButton::ShapeButton (const String& text,
  34652. const Colour& normalColour_,
  34653. const Colour& overColour_,
  34654. const Colour& downColour_)
  34655. : Button (text),
  34656. normalColour (normalColour_),
  34657. overColour (overColour_),
  34658. downColour (downColour_),
  34659. maintainShapeProportions (false),
  34660. outlineWidth (0.0f)
  34661. {
  34662. }
  34663. ShapeButton::~ShapeButton()
  34664. {
  34665. }
  34666. void ShapeButton::setColours (const Colour& newNormalColour,
  34667. const Colour& newOverColour,
  34668. const Colour& newDownColour)
  34669. {
  34670. normalColour = newNormalColour;
  34671. overColour = newOverColour;
  34672. downColour = newDownColour;
  34673. }
  34674. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34675. const float newOutlineWidth)
  34676. {
  34677. outlineColour = newOutlineColour;
  34678. outlineWidth = newOutlineWidth;
  34679. }
  34680. void ShapeButton::setShape (const Path& newShape,
  34681. const bool resizeNowToFitThisShape,
  34682. const bool maintainShapeProportions_,
  34683. const bool hasShadow)
  34684. {
  34685. shape = newShape;
  34686. maintainShapeProportions = maintainShapeProportions_;
  34687. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34688. setComponentEffect ((hasShadow) ? &shadow : 0);
  34689. if (resizeNowToFitThisShape)
  34690. {
  34691. float x, y, w, h;
  34692. shape.getBounds (x, y, w, h);
  34693. shape.applyTransform (AffineTransform::translation (-x, -y));
  34694. if (hasShadow)
  34695. {
  34696. w += 4.0f;
  34697. h += 4.0f;
  34698. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  34699. }
  34700. setSize (1 + (int) (w + outlineWidth),
  34701. 1 + (int) (h + outlineWidth));
  34702. }
  34703. }
  34704. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34705. {
  34706. if (! isEnabled())
  34707. {
  34708. isMouseOverButton = false;
  34709. isButtonDown = false;
  34710. }
  34711. g.setColour ((isButtonDown) ? downColour
  34712. : (isMouseOverButton) ? overColour
  34713. : normalColour);
  34714. int w = getWidth();
  34715. int h = getHeight();
  34716. if (getComponentEffect() != 0)
  34717. {
  34718. w -= 4;
  34719. h -= 4;
  34720. }
  34721. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34722. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34723. w - offset - outlineWidth,
  34724. h - offset - outlineWidth,
  34725. maintainShapeProportions));
  34726. g.fillPath (shape, trans);
  34727. if (outlineWidth > 0.0f)
  34728. {
  34729. g.setColour (outlineColour);
  34730. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34731. }
  34732. }
  34733. END_JUCE_NAMESPACE
  34734. /********* End of inlined file: juce_ShapeButton.cpp *********/
  34735. /********* Start of inlined file: juce_TextButton.cpp *********/
  34736. BEGIN_JUCE_NAMESPACE
  34737. TextButton::TextButton (const String& name,
  34738. const String& toolTip)
  34739. : Button (name)
  34740. {
  34741. setTooltip (toolTip);
  34742. }
  34743. TextButton::~TextButton()
  34744. {
  34745. }
  34746. void TextButton::paintButton (Graphics& g,
  34747. bool isMouseOverButton,
  34748. bool isButtonDown)
  34749. {
  34750. getLookAndFeel().drawButtonBackground (g, *this,
  34751. findColour (getToggleState() ? buttonOnColourId
  34752. : buttonColourId),
  34753. isMouseOverButton,
  34754. isButtonDown);
  34755. getLookAndFeel().drawButtonText (g, *this,
  34756. isMouseOverButton,
  34757. isButtonDown);
  34758. }
  34759. void TextButton::colourChanged()
  34760. {
  34761. repaint();
  34762. }
  34763. const Font TextButton::getFont()
  34764. {
  34765. return Font (jmin (15.0f, getHeight() * 0.6f));
  34766. }
  34767. void TextButton::changeWidthToFitText (const int newHeight)
  34768. {
  34769. if (newHeight >= 0)
  34770. setSize (jmax (1, getWidth()), newHeight);
  34771. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34772. getHeight());
  34773. }
  34774. END_JUCE_NAMESPACE
  34775. /********* End of inlined file: juce_TextButton.cpp *********/
  34776. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  34777. BEGIN_JUCE_NAMESPACE
  34778. ToggleButton::ToggleButton (const String& buttonText)
  34779. : Button (buttonText)
  34780. {
  34781. setClickingTogglesState (true);
  34782. }
  34783. ToggleButton::~ToggleButton()
  34784. {
  34785. }
  34786. void ToggleButton::paintButton (Graphics& g,
  34787. bool isMouseOverButton,
  34788. bool isButtonDown)
  34789. {
  34790. getLookAndFeel().drawToggleButton (g, *this,
  34791. isMouseOverButton,
  34792. isButtonDown);
  34793. }
  34794. void ToggleButton::changeWidthToFitText()
  34795. {
  34796. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34797. }
  34798. void ToggleButton::colourChanged()
  34799. {
  34800. repaint();
  34801. }
  34802. END_JUCE_NAMESPACE
  34803. /********* End of inlined file: juce_ToggleButton.cpp *********/
  34804. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  34805. BEGIN_JUCE_NAMESPACE
  34806. ToolbarButton::ToolbarButton (const int itemId_,
  34807. const String& buttonText,
  34808. Drawable* const normalImage_,
  34809. Drawable* const toggledOnImage_)
  34810. : ToolbarItemComponent (itemId_, buttonText, true),
  34811. normalImage (normalImage_),
  34812. toggledOnImage (toggledOnImage_)
  34813. {
  34814. }
  34815. ToolbarButton::~ToolbarButton()
  34816. {
  34817. delete normalImage;
  34818. delete toggledOnImage;
  34819. }
  34820. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34821. bool /*isToolbarVertical*/,
  34822. int& preferredSize,
  34823. int& minSize, int& maxSize)
  34824. {
  34825. preferredSize = minSize = maxSize = toolbarDepth;
  34826. return true;
  34827. }
  34828. void ToolbarButton::paintButtonArea (Graphics& g,
  34829. int width, int height,
  34830. bool /*isMouseOver*/,
  34831. bool /*isMouseDown*/)
  34832. {
  34833. Drawable* d = normalImage;
  34834. if (getToggleState() && toggledOnImage != 0)
  34835. d = toggledOnImage;
  34836. if (! isEnabled())
  34837. {
  34838. Image im (Image::ARGB, width, height, true);
  34839. Graphics g2 (im);
  34840. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  34841. im.desaturate();
  34842. g.drawImageAt (&im, 0, 0);
  34843. }
  34844. else
  34845. {
  34846. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  34847. }
  34848. }
  34849. void ToolbarButton::contentAreaChanged (const Rectangle&)
  34850. {
  34851. }
  34852. END_JUCE_NAMESPACE
  34853. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  34854. /********* Start of inlined file: juce_ComboBox.cpp *********/
  34855. BEGIN_JUCE_NAMESPACE
  34856. ComboBox::ComboBox (const String& name)
  34857. : Component (name),
  34858. items (4),
  34859. currentIndex (-1),
  34860. isButtonDown (false),
  34861. separatorPending (false),
  34862. menuActive (false),
  34863. listeners (2),
  34864. label (0)
  34865. {
  34866. noChoicesMessage = TRANS("(no choices)");
  34867. setRepaintsOnMouseActivity (true);
  34868. lookAndFeelChanged();
  34869. }
  34870. ComboBox::~ComboBox()
  34871. {
  34872. if (menuActive)
  34873. PopupMenu::dismissAllActiveMenus();
  34874. deleteAllChildren();
  34875. }
  34876. void ComboBox::setEditableText (const bool isEditable)
  34877. {
  34878. label->setEditable (isEditable, isEditable, false);
  34879. setWantsKeyboardFocus (! isEditable);
  34880. resized();
  34881. }
  34882. bool ComboBox::isTextEditable() const throw()
  34883. {
  34884. return label->isEditable();
  34885. }
  34886. void ComboBox::setJustificationType (const Justification& justification) throw()
  34887. {
  34888. label->setJustificationType (justification);
  34889. }
  34890. const Justification ComboBox::getJustificationType() const throw()
  34891. {
  34892. return label->getJustificationType();
  34893. }
  34894. void ComboBox::setTooltip (const String& newTooltip)
  34895. {
  34896. SettableTooltipClient::setTooltip (newTooltip);
  34897. label->setTooltip (newTooltip);
  34898. }
  34899. void ComboBox::addItem (const String& newItemText,
  34900. const int newItemId) throw()
  34901. {
  34902. // you can't add empty strings to the list..
  34903. jassert (newItemText.isNotEmpty());
  34904. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  34905. jassert (newItemId != 0);
  34906. // you shouldn't use duplicate item IDs!
  34907. jassert (getItemForId (newItemId) == 0);
  34908. if (newItemText.isNotEmpty() && newItemId != 0)
  34909. {
  34910. if (separatorPending)
  34911. {
  34912. separatorPending = false;
  34913. ItemInfo* const item = new ItemInfo();
  34914. item->itemId = 0;
  34915. item->isEnabled = false;
  34916. item->isHeading = false;
  34917. items.add (item);
  34918. }
  34919. ItemInfo* const item = new ItemInfo();
  34920. item->name = newItemText;
  34921. item->itemId = newItemId;
  34922. item->isEnabled = true;
  34923. item->isHeading = false;
  34924. items.add (item);
  34925. }
  34926. }
  34927. void ComboBox::addSeparator() throw()
  34928. {
  34929. separatorPending = (items.size() > 0);
  34930. }
  34931. void ComboBox::addSectionHeading (const String& headingName) throw()
  34932. {
  34933. // you can't add empty strings to the list..
  34934. jassert (headingName.isNotEmpty());
  34935. if (headingName.isNotEmpty())
  34936. {
  34937. if (separatorPending)
  34938. {
  34939. separatorPending = false;
  34940. ItemInfo* const item = new ItemInfo();
  34941. item->itemId = 0;
  34942. item->isEnabled = false;
  34943. item->isHeading = false;
  34944. items.add (item);
  34945. }
  34946. ItemInfo* const item = new ItemInfo();
  34947. item->name = headingName;
  34948. item->itemId = 0;
  34949. item->isEnabled = true;
  34950. item->isHeading = true;
  34951. items.add (item);
  34952. }
  34953. }
  34954. void ComboBox::setItemEnabled (const int itemId,
  34955. const bool isEnabled) throw()
  34956. {
  34957. ItemInfo* const item = getItemForId (itemId);
  34958. if (item != 0)
  34959. item->isEnabled = isEnabled;
  34960. }
  34961. void ComboBox::changeItemText (const int itemId,
  34962. const String& newText) throw()
  34963. {
  34964. ItemInfo* const item = getItemForId (itemId);
  34965. jassert (item != 0);
  34966. if (item != 0)
  34967. item->name = newText;
  34968. }
  34969. void ComboBox::clear (const bool dontSendChangeMessage)
  34970. {
  34971. items.clear();
  34972. separatorPending = false;
  34973. if (! label->isEditable())
  34974. setSelectedItemIndex (-1, dontSendChangeMessage);
  34975. }
  34976. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  34977. {
  34978. jassert (itemId != 0);
  34979. if (itemId != 0)
  34980. {
  34981. for (int i = items.size(); --i >= 0;)
  34982. if (items.getUnchecked(i)->itemId == itemId)
  34983. return items.getUnchecked(i);
  34984. }
  34985. return 0;
  34986. }
  34987. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  34988. {
  34989. int n = 0;
  34990. for (int i = 0; i < items.size(); ++i)
  34991. {
  34992. ItemInfo* const item = items.getUnchecked(i);
  34993. if (item->isRealItem())
  34994. {
  34995. if (n++ == index)
  34996. return item;
  34997. }
  34998. }
  34999. return 0;
  35000. }
  35001. int ComboBox::getNumItems() const throw()
  35002. {
  35003. int n = 0;
  35004. for (int i = items.size(); --i >= 0;)
  35005. {
  35006. ItemInfo* const item = items.getUnchecked(i);
  35007. if (item->isRealItem())
  35008. ++n;
  35009. }
  35010. return n;
  35011. }
  35012. const String ComboBox::getItemText (const int index) const throw()
  35013. {
  35014. ItemInfo* const item = getItemForIndex (index);
  35015. if (item != 0)
  35016. return item->name;
  35017. return String::empty;
  35018. }
  35019. int ComboBox::getItemId (const int index) const throw()
  35020. {
  35021. ItemInfo* const item = getItemForIndex (index);
  35022. return (item != 0) ? item->itemId : 0;
  35023. }
  35024. bool ComboBox::ItemInfo::isSeparator() const throw()
  35025. {
  35026. return name.isEmpty();
  35027. }
  35028. bool ComboBox::ItemInfo::isRealItem() const throw()
  35029. {
  35030. return ! (isHeading || name.isEmpty());
  35031. }
  35032. int ComboBox::getSelectedItemIndex() const throw()
  35033. {
  35034. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  35035. ? currentIndex
  35036. : -1;
  35037. }
  35038. void ComboBox::setSelectedItemIndex (const int index,
  35039. const bool dontSendChangeMessage) throw()
  35040. {
  35041. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  35042. {
  35043. if (((unsigned int) index) < (unsigned int) getNumItems())
  35044. currentIndex = index;
  35045. else
  35046. currentIndex = -1;
  35047. label->setText (getItemText (currentIndex), false);
  35048. if (! dontSendChangeMessage)
  35049. triggerAsyncUpdate();
  35050. }
  35051. }
  35052. void ComboBox::setSelectedId (const int newItemId,
  35053. const bool dontSendChangeMessage) throw()
  35054. {
  35055. for (int i = getNumItems(); --i >= 0;)
  35056. {
  35057. if (getItemId(i) == newItemId)
  35058. {
  35059. setSelectedItemIndex (i, dontSendChangeMessage);
  35060. break;
  35061. }
  35062. }
  35063. }
  35064. int ComboBox::getSelectedId() const throw()
  35065. {
  35066. const ItemInfo* const item = getItemForIndex (currentIndex);
  35067. return (item != 0 && getText() == item->name)
  35068. ? item->itemId
  35069. : 0;
  35070. }
  35071. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  35072. {
  35073. jassert (listener != 0);
  35074. if (listener != 0)
  35075. listeners.add (listener);
  35076. }
  35077. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  35078. {
  35079. listeners.removeValue (listener);
  35080. }
  35081. void ComboBox::handleAsyncUpdate()
  35082. {
  35083. for (int i = listeners.size(); --i >= 0;)
  35084. {
  35085. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  35086. i = jmin (i, listeners.size());
  35087. }
  35088. }
  35089. const String ComboBox::getText() const throw()
  35090. {
  35091. return label->getText();
  35092. }
  35093. void ComboBox::setText (const String& newText,
  35094. const bool dontSendChangeMessage) throw()
  35095. {
  35096. for (int i = items.size(); --i >= 0;)
  35097. {
  35098. ItemInfo* const item = items.getUnchecked(i);
  35099. if (item->isRealItem()
  35100. && item->name == newText)
  35101. {
  35102. setSelectedId (item->itemId, dontSendChangeMessage);
  35103. return;
  35104. }
  35105. }
  35106. currentIndex = -1;
  35107. if (label->getText() != newText)
  35108. {
  35109. label->setText (newText, false);
  35110. if (! dontSendChangeMessage)
  35111. triggerAsyncUpdate();
  35112. }
  35113. repaint();
  35114. }
  35115. void ComboBox::showEditor()
  35116. {
  35117. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  35118. label->showEditor();
  35119. }
  35120. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  35121. {
  35122. textWhenNothingSelected = newMessage;
  35123. repaint();
  35124. }
  35125. const String ComboBox::getTextWhenNothingSelected() const throw()
  35126. {
  35127. return textWhenNothingSelected;
  35128. }
  35129. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  35130. {
  35131. noChoicesMessage = newMessage;
  35132. }
  35133. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  35134. {
  35135. return noChoicesMessage;
  35136. }
  35137. void ComboBox::paint (Graphics& g)
  35138. {
  35139. getLookAndFeel().drawComboBox (g,
  35140. getWidth(),
  35141. getHeight(),
  35142. isButtonDown,
  35143. label->getRight(),
  35144. 0,
  35145. getWidth() - label->getRight(),
  35146. getHeight(),
  35147. *this);
  35148. if (textWhenNothingSelected.isNotEmpty()
  35149. && label->getText().isEmpty()
  35150. && ! label->isBeingEdited())
  35151. {
  35152. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  35153. g.setFont (label->getFont());
  35154. g.drawFittedText (textWhenNothingSelected,
  35155. label->getX() + 2, label->getY() + 1,
  35156. label->getWidth() - 4, label->getHeight() - 2,
  35157. label->getJustificationType(),
  35158. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  35159. }
  35160. }
  35161. void ComboBox::resized()
  35162. {
  35163. if (getHeight() > 0 && getWidth() > 0)
  35164. getLookAndFeel().positionComboBoxText (*this, *label);
  35165. }
  35166. void ComboBox::enablementChanged()
  35167. {
  35168. repaint();
  35169. }
  35170. void ComboBox::lookAndFeelChanged()
  35171. {
  35172. repaint();
  35173. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  35174. if (label != 0)
  35175. {
  35176. newLabel->setEditable (label->isEditable());
  35177. newLabel->setJustificationType (label->getJustificationType());
  35178. newLabel->setTooltip (label->getTooltip());
  35179. newLabel->setText (label->getText(), false);
  35180. }
  35181. delete label;
  35182. label = newLabel;
  35183. addAndMakeVisible (newLabel);
  35184. newLabel->addListener (this);
  35185. newLabel->addMouseListener (this, false);
  35186. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  35187. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  35188. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  35189. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35190. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  35191. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35192. resized();
  35193. }
  35194. void ComboBox::colourChanged()
  35195. {
  35196. lookAndFeelChanged();
  35197. }
  35198. bool ComboBox::keyPressed (const KeyPress& key)
  35199. {
  35200. bool used = false;
  35201. if (key.isKeyCode (KeyPress::upKey)
  35202. || key.isKeyCode (KeyPress::leftKey))
  35203. {
  35204. setSelectedItemIndex (jmax (0, currentIndex - 1));
  35205. used = true;
  35206. }
  35207. else if (key.isKeyCode (KeyPress::downKey)
  35208. || key.isKeyCode (KeyPress::rightKey))
  35209. {
  35210. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  35211. used = true;
  35212. }
  35213. else if (key.isKeyCode (KeyPress::returnKey))
  35214. {
  35215. showPopup();
  35216. used = true;
  35217. }
  35218. return used;
  35219. }
  35220. bool ComboBox::keyStateChanged (const bool isKeyDown)
  35221. {
  35222. // only forward key events that aren't used by this component
  35223. return isKeyDown
  35224. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35225. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  35226. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35227. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  35228. }
  35229. void ComboBox::focusGained (FocusChangeType)
  35230. {
  35231. repaint();
  35232. }
  35233. void ComboBox::focusLost (FocusChangeType)
  35234. {
  35235. repaint();
  35236. }
  35237. void ComboBox::labelTextChanged (Label*)
  35238. {
  35239. triggerAsyncUpdate();
  35240. }
  35241. void ComboBox::showPopup()
  35242. {
  35243. if (! menuActive)
  35244. {
  35245. const int currentId = getSelectedId();
  35246. ComponentDeletionWatcher deletionWatcher (this);
  35247. PopupMenu menu;
  35248. menu.setLookAndFeel (&getLookAndFeel());
  35249. for (int i = 0; i < items.size(); ++i)
  35250. {
  35251. const ItemInfo* const item = items.getUnchecked(i);
  35252. if (item->isSeparator())
  35253. menu.addSeparator();
  35254. else if (item->isHeading)
  35255. menu.addSectionHeader (item->name);
  35256. else
  35257. menu.addItem (item->itemId, item->name,
  35258. item->isEnabled, item->itemId == currentId);
  35259. }
  35260. if (items.size() == 0)
  35261. menu.addItem (1, noChoicesMessage, false);
  35262. const int itemHeight = jlimit (12, 24, getHeight());
  35263. menuActive = true;
  35264. const int resultId = menu.showAt (this, currentId,
  35265. getWidth(), 1, itemHeight);
  35266. if (deletionWatcher.hasBeenDeleted())
  35267. return;
  35268. menuActive = false;
  35269. if (resultId != 0)
  35270. setSelectedId (resultId);
  35271. }
  35272. }
  35273. void ComboBox::mouseDown (const MouseEvent& e)
  35274. {
  35275. beginDragAutoRepeat (300);
  35276. isButtonDown = isEnabled();
  35277. if (isButtonDown
  35278. && (e.eventComponent == this || ! label->isEditable()))
  35279. {
  35280. showPopup();
  35281. }
  35282. }
  35283. void ComboBox::mouseDrag (const MouseEvent& e)
  35284. {
  35285. beginDragAutoRepeat (50);
  35286. if (isButtonDown && ! e.mouseWasClicked())
  35287. showPopup();
  35288. }
  35289. void ComboBox::mouseUp (const MouseEvent& e2)
  35290. {
  35291. if (isButtonDown)
  35292. {
  35293. isButtonDown = false;
  35294. repaint();
  35295. const MouseEvent e (e2.getEventRelativeTo (this));
  35296. if (reallyContains (e.x, e.y, true)
  35297. && (e2.eventComponent == this || ! label->isEditable()))
  35298. {
  35299. showPopup();
  35300. }
  35301. }
  35302. }
  35303. END_JUCE_NAMESPACE
  35304. /********* End of inlined file: juce_ComboBox.cpp *********/
  35305. /********* Start of inlined file: juce_Label.cpp *********/
  35306. BEGIN_JUCE_NAMESPACE
  35307. Label::Label (const String& componentName,
  35308. const String& labelText)
  35309. : Component (componentName),
  35310. text (labelText),
  35311. font (15.0f),
  35312. justification (Justification::centredLeft),
  35313. editor (0),
  35314. listeners (2),
  35315. ownerComponent (0),
  35316. deletionWatcher (0),
  35317. horizontalBorderSize (3),
  35318. verticalBorderSize (1),
  35319. minimumHorizontalScale (0.7f),
  35320. editSingleClick (false),
  35321. editDoubleClick (false),
  35322. lossOfFocusDiscardsChanges (false)
  35323. {
  35324. setColour (TextEditor::textColourId, Colours::black);
  35325. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35326. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35327. }
  35328. Label::~Label()
  35329. {
  35330. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35331. ownerComponent->removeComponentListener (this);
  35332. deleteAndZero (deletionWatcher);
  35333. if (editor != 0)
  35334. delete editor;
  35335. }
  35336. void Label::setText (const String& newText,
  35337. const bool broadcastChangeMessage)
  35338. {
  35339. hideEditor (true);
  35340. if (text != newText)
  35341. {
  35342. text = newText;
  35343. repaint();
  35344. textWasChanged();
  35345. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35346. componentMovedOrResized (*ownerComponent, true, true);
  35347. if (broadcastChangeMessage)
  35348. callChangeListeners();
  35349. }
  35350. }
  35351. const String Label::getText (const bool returnActiveEditorContents) const throw()
  35352. {
  35353. return (returnActiveEditorContents && isBeingEdited())
  35354. ? editor->getText()
  35355. : text;
  35356. }
  35357. void Label::setFont (const Font& newFont) throw()
  35358. {
  35359. font = newFont;
  35360. repaint();
  35361. }
  35362. const Font& Label::getFont() const throw()
  35363. {
  35364. return font;
  35365. }
  35366. void Label::setEditable (const bool editOnSingleClick,
  35367. const bool editOnDoubleClick,
  35368. const bool lossOfFocusDiscardsChanges_) throw()
  35369. {
  35370. editSingleClick = editOnSingleClick;
  35371. editDoubleClick = editOnDoubleClick;
  35372. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  35373. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  35374. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  35375. }
  35376. void Label::setJustificationType (const Justification& justification_) throw()
  35377. {
  35378. justification = justification_;
  35379. repaint();
  35380. }
  35381. void Label::setBorderSize (int h, int v)
  35382. {
  35383. horizontalBorderSize = h;
  35384. verticalBorderSize = v;
  35385. repaint();
  35386. }
  35387. void Label::attachToComponent (Component* owner,
  35388. const bool onLeft)
  35389. {
  35390. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35391. ownerComponent->removeComponentListener (this);
  35392. deleteAndZero (deletionWatcher);
  35393. ownerComponent = owner;
  35394. leftOfOwnerComp = onLeft;
  35395. if (ownerComponent != 0)
  35396. {
  35397. deletionWatcher = new ComponentDeletionWatcher (owner);
  35398. setVisible (owner->isVisible());
  35399. ownerComponent->addComponentListener (this);
  35400. componentParentHierarchyChanged (*ownerComponent);
  35401. componentMovedOrResized (*ownerComponent, true, true);
  35402. }
  35403. }
  35404. void Label::componentMovedOrResized (Component& component,
  35405. bool /*wasMoved*/,
  35406. bool /*wasResized*/)
  35407. {
  35408. if (leftOfOwnerComp)
  35409. {
  35410. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  35411. component.getHeight());
  35412. setTopRightPosition (component.getX(), component.getY());
  35413. }
  35414. else
  35415. {
  35416. setSize (component.getWidth(),
  35417. 8 + roundFloatToInt (getFont().getHeight()));
  35418. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  35419. }
  35420. }
  35421. void Label::componentParentHierarchyChanged (Component& component)
  35422. {
  35423. if (component.getParentComponent() != 0)
  35424. component.getParentComponent()->addChildComponent (this);
  35425. }
  35426. void Label::componentVisibilityChanged (Component& component)
  35427. {
  35428. setVisible (component.isVisible());
  35429. }
  35430. void Label::textWasEdited()
  35431. {
  35432. }
  35433. void Label::textWasChanged()
  35434. {
  35435. }
  35436. void Label::showEditor()
  35437. {
  35438. if (editor == 0)
  35439. {
  35440. addAndMakeVisible (editor = createEditorComponent());
  35441. editor->setText (getText(), false);
  35442. editor->addListener (this);
  35443. editor->grabKeyboardFocus();
  35444. editor->setHighlightedRegion (0, text.length());
  35445. editor->addListener (this);
  35446. resized();
  35447. repaint();
  35448. editorShown (editor);
  35449. enterModalState();
  35450. editor->grabKeyboardFocus();
  35451. }
  35452. }
  35453. void Label::editorShown (TextEditor* editorComponent)
  35454. {
  35455. }
  35456. void Label::editorAboutToBeHidden (TextEditor* editorComponent)
  35457. {
  35458. }
  35459. bool Label::updateFromTextEditorContents()
  35460. {
  35461. jassert (editor != 0);
  35462. const String newText (editor->getText());
  35463. if (text != newText)
  35464. {
  35465. text = newText;
  35466. repaint();
  35467. textWasChanged();
  35468. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35469. componentMovedOrResized (*ownerComponent, true, true);
  35470. return true;
  35471. }
  35472. return false;
  35473. }
  35474. void Label::hideEditor (const bool discardCurrentEditorContents)
  35475. {
  35476. if (editor != 0)
  35477. {
  35478. editorAboutToBeHidden (editor);
  35479. const bool changed = (! discardCurrentEditorContents)
  35480. && updateFromTextEditorContents();
  35481. deleteAndZero (editor);
  35482. repaint();
  35483. if (changed)
  35484. textWasEdited();
  35485. exitModalState (0);
  35486. if (changed && isValidComponent())
  35487. callChangeListeners();
  35488. }
  35489. }
  35490. void Label::inputAttemptWhenModal()
  35491. {
  35492. if (editor != 0)
  35493. {
  35494. if (lossOfFocusDiscardsChanges)
  35495. textEditorEscapeKeyPressed (*editor);
  35496. else
  35497. textEditorReturnKeyPressed (*editor);
  35498. }
  35499. }
  35500. bool Label::isBeingEdited() const throw()
  35501. {
  35502. return editor != 0;
  35503. }
  35504. TextEditor* Label::createEditorComponent()
  35505. {
  35506. TextEditor* const ed = new TextEditor (getName());
  35507. ed->setFont (font);
  35508. // copy these colours from our own settings..
  35509. const int cols[] = { TextEditor::backgroundColourId,
  35510. TextEditor::textColourId,
  35511. TextEditor::highlightColourId,
  35512. TextEditor::highlightedTextColourId,
  35513. TextEditor::caretColourId,
  35514. TextEditor::outlineColourId,
  35515. TextEditor::focusedOutlineColourId,
  35516. TextEditor::shadowColourId };
  35517. for (int i = 0; i < numElementsInArray (cols); ++i)
  35518. ed->setColour (cols[i], findColour (cols[i]));
  35519. return ed;
  35520. }
  35521. void Label::paint (Graphics& g)
  35522. {
  35523. getLookAndFeel().drawLabel (g, *this);
  35524. }
  35525. void Label::mouseUp (const MouseEvent& e)
  35526. {
  35527. if (editSingleClick
  35528. && e.mouseWasClicked()
  35529. && contains (e.x, e.y)
  35530. && ! e.mods.isPopupMenu())
  35531. {
  35532. showEditor();
  35533. }
  35534. }
  35535. void Label::mouseDoubleClick (const MouseEvent& e)
  35536. {
  35537. if (editDoubleClick && ! e.mods.isPopupMenu())
  35538. showEditor();
  35539. }
  35540. void Label::resized()
  35541. {
  35542. if (editor != 0)
  35543. editor->setBoundsInset (BorderSize (0));
  35544. }
  35545. void Label::focusGained (FocusChangeType cause)
  35546. {
  35547. if (editSingleClick && cause == focusChangedByTabKey)
  35548. showEditor();
  35549. }
  35550. void Label::enablementChanged()
  35551. {
  35552. repaint();
  35553. }
  35554. void Label::colourChanged()
  35555. {
  35556. repaint();
  35557. }
  35558. void Label::setMinimumHorizontalScale (const float newScale)
  35559. {
  35560. if (minimumHorizontalScale != newScale)
  35561. {
  35562. minimumHorizontalScale = newScale;
  35563. repaint();
  35564. }
  35565. }
  35566. // We'll use a custom focus traverser here to make sure focus goes from the
  35567. // text editor to another component rather than back to the label itself.
  35568. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  35569. {
  35570. public:
  35571. LabelKeyboardFocusTraverser() {}
  35572. Component* getNextComponent (Component* current)
  35573. {
  35574. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  35575. ? current->getParentComponent() : current);
  35576. }
  35577. Component* getPreviousComponent (Component* current)
  35578. {
  35579. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  35580. ? current->getParentComponent() : current);
  35581. }
  35582. };
  35583. KeyboardFocusTraverser* Label::createFocusTraverser()
  35584. {
  35585. return new LabelKeyboardFocusTraverser();
  35586. }
  35587. void Label::addListener (LabelListener* const listener) throw()
  35588. {
  35589. jassert (listener != 0);
  35590. if (listener != 0)
  35591. listeners.add (listener);
  35592. }
  35593. void Label::removeListener (LabelListener* const listener) throw()
  35594. {
  35595. listeners.removeValue (listener);
  35596. }
  35597. void Label::callChangeListeners()
  35598. {
  35599. for (int i = listeners.size(); --i >= 0;)
  35600. {
  35601. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  35602. i = jmin (i, listeners.size());
  35603. }
  35604. }
  35605. void Label::textEditorTextChanged (TextEditor& ed)
  35606. {
  35607. if (editor != 0)
  35608. {
  35609. jassert (&ed == editor);
  35610. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  35611. {
  35612. if (lossOfFocusDiscardsChanges)
  35613. textEditorEscapeKeyPressed (ed);
  35614. else
  35615. textEditorReturnKeyPressed (ed);
  35616. }
  35617. }
  35618. }
  35619. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  35620. {
  35621. if (editor != 0)
  35622. {
  35623. jassert (&ed == editor);
  35624. (void) ed;
  35625. const bool changed = updateFromTextEditorContents();
  35626. hideEditor (true);
  35627. if (changed)
  35628. {
  35629. textWasEdited();
  35630. if (isValidComponent())
  35631. callChangeListeners();
  35632. }
  35633. }
  35634. }
  35635. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  35636. {
  35637. if (editor != 0)
  35638. {
  35639. jassert (&ed == editor);
  35640. (void) ed;
  35641. editor->setText (text, false);
  35642. hideEditor (true);
  35643. }
  35644. }
  35645. void Label::textEditorFocusLost (TextEditor& ed)
  35646. {
  35647. textEditorTextChanged (ed);
  35648. }
  35649. END_JUCE_NAMESPACE
  35650. /********* End of inlined file: juce_Label.cpp *********/
  35651. /********* Start of inlined file: juce_ListBox.cpp *********/
  35652. BEGIN_JUCE_NAMESPACE
  35653. class ListBoxRowComponent : public Component
  35654. {
  35655. public:
  35656. ListBoxRowComponent (ListBox& owner_)
  35657. : owner (owner_),
  35658. row (-1),
  35659. selected (false),
  35660. isDragging (false)
  35661. {
  35662. }
  35663. ~ListBoxRowComponent()
  35664. {
  35665. deleteAllChildren();
  35666. }
  35667. void paint (Graphics& g)
  35668. {
  35669. if (owner.getModel() != 0)
  35670. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  35671. }
  35672. void update (const int row_, const bool selected_)
  35673. {
  35674. if (row != row_ || selected != selected_)
  35675. {
  35676. repaint();
  35677. row = row_;
  35678. selected = selected_;
  35679. }
  35680. if (owner.getModel() != 0)
  35681. {
  35682. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  35683. if (customComp != 0)
  35684. {
  35685. addAndMakeVisible (customComp);
  35686. customComp->setBounds (0, 0, getWidth(), getHeight());
  35687. for (int i = getNumChildComponents(); --i >= 0;)
  35688. if (getChildComponent (i) != customComp)
  35689. delete getChildComponent (i);
  35690. }
  35691. else
  35692. {
  35693. deleteAllChildren();
  35694. }
  35695. }
  35696. }
  35697. void mouseDown (const MouseEvent& e)
  35698. {
  35699. isDragging = false;
  35700. selectRowOnMouseUp = false;
  35701. if (isEnabled())
  35702. {
  35703. if (! selected)
  35704. {
  35705. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35706. if (owner.getModel() != 0)
  35707. owner.getModel()->listBoxItemClicked (row, e);
  35708. }
  35709. else
  35710. {
  35711. selectRowOnMouseUp = true;
  35712. }
  35713. }
  35714. }
  35715. void mouseUp (const MouseEvent& e)
  35716. {
  35717. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  35718. {
  35719. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35720. if (owner.getModel() != 0)
  35721. owner.getModel()->listBoxItemClicked (row, e);
  35722. }
  35723. }
  35724. void mouseDoubleClick (const MouseEvent& e)
  35725. {
  35726. if (owner.getModel() != 0 && isEnabled())
  35727. owner.getModel()->listBoxItemDoubleClicked (row, e);
  35728. }
  35729. void mouseDrag (const MouseEvent& e)
  35730. {
  35731. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  35732. {
  35733. const SparseSet <int> selectedRows (owner.getSelectedRows());
  35734. if (selectedRows.size() > 0)
  35735. {
  35736. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  35737. if (dragDescription.isNotEmpty())
  35738. {
  35739. isDragging = true;
  35740. DragAndDropContainer* const dragContainer
  35741. = DragAndDropContainer::findParentDragContainerFor (this);
  35742. if (dragContainer != 0)
  35743. {
  35744. Image* dragImage = owner.createSnapshotOfSelectedRows();
  35745. dragImage->multiplyAllAlphas (0.6f);
  35746. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  35747. }
  35748. else
  35749. {
  35750. // to be able to do a drag-and-drop operation, the listbox needs to
  35751. // be inside a component which is also a DragAndDropContainer.
  35752. jassertfalse
  35753. }
  35754. }
  35755. }
  35756. }
  35757. }
  35758. void resized()
  35759. {
  35760. if (getNumChildComponents() > 0)
  35761. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  35762. }
  35763. juce_UseDebuggingNewOperator
  35764. bool neededFlag;
  35765. private:
  35766. ListBox& owner;
  35767. int row;
  35768. bool selected, isDragging, selectRowOnMouseUp;
  35769. ListBoxRowComponent (const ListBoxRowComponent&);
  35770. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  35771. };
  35772. class ListViewport : public Viewport
  35773. {
  35774. public:
  35775. int firstIndex, firstWholeIndex, lastWholeIndex;
  35776. bool hasUpdated;
  35777. ListViewport (ListBox& owner_)
  35778. : owner (owner_)
  35779. {
  35780. setWantsKeyboardFocus (false);
  35781. setViewedComponent (new Component());
  35782. getViewedComponent()->addMouseListener (this, false);
  35783. getViewedComponent()->setWantsKeyboardFocus (false);
  35784. }
  35785. ~ListViewport()
  35786. {
  35787. getViewedComponent()->removeMouseListener (this);
  35788. getViewedComponent()->deleteAllChildren();
  35789. }
  35790. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  35791. {
  35792. return (ListBoxRowComponent*) getViewedComponent()
  35793. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  35794. }
  35795. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  35796. {
  35797. const int index = getIndexOfChildComponent (rowComponent);
  35798. const int num = getViewedComponent()->getNumChildComponents();
  35799. for (int i = num; --i >= 0;)
  35800. if (((firstIndex + i) % jmax (1, num)) == index)
  35801. return firstIndex + i;
  35802. return -1;
  35803. }
  35804. Component* getComponentForRowIfOnscreen (const int row) const throw()
  35805. {
  35806. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  35807. ? getComponentForRow (row) : 0;
  35808. }
  35809. void visibleAreaChanged (int, int, int, int)
  35810. {
  35811. updateVisibleArea (true);
  35812. if (owner.getModel() != 0)
  35813. owner.getModel()->listWasScrolled();
  35814. }
  35815. void updateVisibleArea (const bool makeSureItUpdatesContent)
  35816. {
  35817. hasUpdated = false;
  35818. const int newX = getViewedComponent()->getX();
  35819. int newY = getViewedComponent()->getY();
  35820. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  35821. const int newH = owner.totalItems * owner.getRowHeight();
  35822. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  35823. newY = getMaximumVisibleHeight() - newH;
  35824. getViewedComponent()->setBounds (newX, newY, newW, newH);
  35825. if (makeSureItUpdatesContent && ! hasUpdated)
  35826. updateContents();
  35827. }
  35828. void updateContents()
  35829. {
  35830. hasUpdated = true;
  35831. const int rowHeight = owner.getRowHeight();
  35832. if (rowHeight > 0)
  35833. {
  35834. const int y = getViewPositionY();
  35835. const int w = getViewedComponent()->getWidth();
  35836. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  35837. while (numNeeded > getViewedComponent()->getNumChildComponents())
  35838. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  35839. jassert (numNeeded >= 0);
  35840. while (numNeeded < getViewedComponent()->getNumChildComponents())
  35841. {
  35842. Component* const rowToRemove
  35843. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  35844. delete rowToRemove;
  35845. }
  35846. firstIndex = y / rowHeight;
  35847. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  35848. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  35849. for (int i = 0; i < numNeeded; ++i)
  35850. {
  35851. const int row = i + firstIndex;
  35852. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  35853. if (rowComp != 0)
  35854. {
  35855. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  35856. rowComp->update (row, owner.isRowSelected (row));
  35857. }
  35858. }
  35859. }
  35860. if (owner.headerComponent != 0)
  35861. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  35862. owner.outlineThickness,
  35863. jmax (owner.getWidth() - owner.outlineThickness * 2,
  35864. getViewedComponent()->getWidth()),
  35865. owner.headerComponent->getHeight());
  35866. }
  35867. void paint (Graphics& g)
  35868. {
  35869. if (isOpaque())
  35870. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  35871. }
  35872. bool keyPressed (const KeyPress& key)
  35873. {
  35874. if (key.isKeyCode (KeyPress::upKey)
  35875. || key.isKeyCode (KeyPress::downKey)
  35876. || key.isKeyCode (KeyPress::pageUpKey)
  35877. || key.isKeyCode (KeyPress::pageDownKey)
  35878. || key.isKeyCode (KeyPress::homeKey)
  35879. || key.isKeyCode (KeyPress::endKey))
  35880. {
  35881. // we want to avoid these keypresses going to the viewport, and instead allow
  35882. // them to pass up to our listbox..
  35883. return false;
  35884. }
  35885. return Viewport::keyPressed (key);
  35886. }
  35887. juce_UseDebuggingNewOperator
  35888. private:
  35889. ListBox& owner;
  35890. ListViewport (const ListViewport&);
  35891. const ListViewport& operator= (const ListViewport&);
  35892. };
  35893. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  35894. : Component (name),
  35895. model (model_),
  35896. headerComponent (0),
  35897. totalItems (0),
  35898. rowHeight (22),
  35899. minimumRowWidth (0),
  35900. outlineThickness (0),
  35901. lastRowSelected (-1),
  35902. mouseMoveSelects (false),
  35903. multipleSelection (false),
  35904. hasDoneInitialUpdate (false)
  35905. {
  35906. addAndMakeVisible (viewport = new ListViewport (*this));
  35907. setWantsKeyboardFocus (true);
  35908. colourChanged();
  35909. }
  35910. ListBox::~ListBox()
  35911. {
  35912. deleteAllChildren();
  35913. }
  35914. void ListBox::setModel (ListBoxModel* const newModel)
  35915. {
  35916. if (model != newModel)
  35917. {
  35918. model = newModel;
  35919. updateContent();
  35920. }
  35921. }
  35922. void ListBox::setMultipleSelectionEnabled (bool b)
  35923. {
  35924. multipleSelection = b;
  35925. }
  35926. void ListBox::setMouseMoveSelectsRows (bool b)
  35927. {
  35928. mouseMoveSelects = b;
  35929. if (b)
  35930. addMouseListener (this, true);
  35931. }
  35932. void ListBox::paint (Graphics& g)
  35933. {
  35934. if (! hasDoneInitialUpdate)
  35935. updateContent();
  35936. g.fillAll (findColour (backgroundColourId));
  35937. }
  35938. void ListBox::paintOverChildren (Graphics& g)
  35939. {
  35940. if (outlineThickness > 0)
  35941. {
  35942. g.setColour (findColour (outlineColourId));
  35943. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  35944. }
  35945. }
  35946. void ListBox::resized()
  35947. {
  35948. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  35949. outlineThickness,
  35950. outlineThickness,
  35951. outlineThickness));
  35952. viewport->setSingleStepSizes (20, getRowHeight());
  35953. viewport->updateVisibleArea (false);
  35954. }
  35955. void ListBox::visibilityChanged()
  35956. {
  35957. viewport->updateVisibleArea (true);
  35958. }
  35959. Viewport* ListBox::getViewport() const throw()
  35960. {
  35961. return viewport;
  35962. }
  35963. void ListBox::updateContent()
  35964. {
  35965. hasDoneInitialUpdate = true;
  35966. totalItems = (model != 0) ? model->getNumRows() : 0;
  35967. bool selectionChanged = false;
  35968. if (selected [selected.size() - 1] >= totalItems)
  35969. {
  35970. selected.removeRange (totalItems, INT_MAX - totalItems);
  35971. lastRowSelected = getSelectedRow (0);
  35972. selectionChanged = true;
  35973. }
  35974. viewport->updateVisibleArea (isVisible());
  35975. viewport->resized();
  35976. if (selectionChanged && model != 0)
  35977. model->selectedRowsChanged (lastRowSelected);
  35978. }
  35979. void ListBox::selectRow (const int row,
  35980. bool dontScroll,
  35981. bool deselectOthersFirst)
  35982. {
  35983. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  35984. }
  35985. void ListBox::selectRowInternal (const int row,
  35986. bool dontScroll,
  35987. bool deselectOthersFirst,
  35988. bool isMouseClick)
  35989. {
  35990. if (! multipleSelection)
  35991. deselectOthersFirst = true;
  35992. if ((! isRowSelected (row))
  35993. || (deselectOthersFirst && getNumSelectedRows() > 1))
  35994. {
  35995. if (((unsigned int) row) < (unsigned int) totalItems)
  35996. {
  35997. if (deselectOthersFirst)
  35998. selected.clear();
  35999. selected.addRange (row, 1);
  36000. if (getHeight() == 0 || getWidth() == 0)
  36001. dontScroll = true;
  36002. viewport->hasUpdated = false;
  36003. if (row < viewport->firstWholeIndex && ! dontScroll)
  36004. {
  36005. viewport->setViewPosition (viewport->getViewPositionX(),
  36006. row * getRowHeight());
  36007. }
  36008. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  36009. {
  36010. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  36011. if (row >= lastRowSelected + rowsOnScreen
  36012. && rowsOnScreen < totalItems - 1
  36013. && ! isMouseClick)
  36014. {
  36015. viewport->setViewPosition (viewport->getViewPositionX(),
  36016. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  36017. * getRowHeight());
  36018. }
  36019. else
  36020. {
  36021. viewport->setViewPosition (viewport->getViewPositionX(),
  36022. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36023. }
  36024. }
  36025. if (! viewport->hasUpdated)
  36026. viewport->updateContents();
  36027. lastRowSelected = row;
  36028. model->selectedRowsChanged (row);
  36029. }
  36030. else
  36031. {
  36032. if (deselectOthersFirst)
  36033. deselectAllRows();
  36034. }
  36035. }
  36036. }
  36037. void ListBox::deselectRow (const int row)
  36038. {
  36039. if (selected.contains (row))
  36040. {
  36041. selected.removeRange (row, 1);
  36042. if (row == lastRowSelected)
  36043. lastRowSelected = getSelectedRow (0);
  36044. viewport->updateContents();
  36045. model->selectedRowsChanged (lastRowSelected);
  36046. }
  36047. }
  36048. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  36049. const bool sendNotificationEventToModel)
  36050. {
  36051. selected = setOfRowsToBeSelected;
  36052. selected.removeRange (totalItems, INT_MAX - totalItems);
  36053. if (! isRowSelected (lastRowSelected))
  36054. lastRowSelected = getSelectedRow (0);
  36055. viewport->updateContents();
  36056. if ((model != 0) && sendNotificationEventToModel)
  36057. model->selectedRowsChanged (lastRowSelected);
  36058. }
  36059. const SparseSet<int> ListBox::getSelectedRows() const
  36060. {
  36061. return selected;
  36062. }
  36063. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  36064. {
  36065. if (multipleSelection && (firstRow != lastRow))
  36066. {
  36067. const int numRows = totalItems - 1;
  36068. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  36069. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  36070. selected.addRange (jmin (firstRow, lastRow),
  36071. abs (firstRow - lastRow) + 1);
  36072. selected.removeRange (lastRow, 1);
  36073. }
  36074. selectRowInternal (lastRow, false, false, true);
  36075. }
  36076. void ListBox::flipRowSelection (const int row)
  36077. {
  36078. if (isRowSelected (row))
  36079. deselectRow (row);
  36080. else
  36081. selectRowInternal (row, false, false, true);
  36082. }
  36083. void ListBox::deselectAllRows()
  36084. {
  36085. if (! selected.isEmpty())
  36086. {
  36087. selected.clear();
  36088. lastRowSelected = -1;
  36089. viewport->updateContents();
  36090. if (model != 0)
  36091. model->selectedRowsChanged (lastRowSelected);
  36092. }
  36093. }
  36094. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  36095. const ModifierKeys& mods)
  36096. {
  36097. if (multipleSelection && mods.isCommandDown())
  36098. {
  36099. flipRowSelection (row);
  36100. }
  36101. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  36102. {
  36103. selectRangeOfRows (lastRowSelected, row);
  36104. }
  36105. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  36106. {
  36107. selectRowInternal (row, false, true, true);
  36108. }
  36109. }
  36110. int ListBox::getNumSelectedRows() const
  36111. {
  36112. return selected.size();
  36113. }
  36114. int ListBox::getSelectedRow (const int index) const
  36115. {
  36116. return (((unsigned int) index) < (unsigned int) selected.size())
  36117. ? selected [index] : -1;
  36118. }
  36119. bool ListBox::isRowSelected (const int row) const
  36120. {
  36121. return selected.contains (row);
  36122. }
  36123. int ListBox::getLastRowSelected() const
  36124. {
  36125. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  36126. }
  36127. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  36128. {
  36129. if (((unsigned int) x) < (unsigned int) getWidth())
  36130. {
  36131. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  36132. if (((unsigned int) row) < (unsigned int) totalItems)
  36133. return row;
  36134. }
  36135. return -1;
  36136. }
  36137. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  36138. {
  36139. if (((unsigned int) x) < (unsigned int) getWidth())
  36140. {
  36141. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  36142. return jlimit (0, totalItems, row);
  36143. }
  36144. return -1;
  36145. }
  36146. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  36147. {
  36148. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  36149. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  36150. }
  36151. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  36152. {
  36153. return viewport->getRowNumberOfComponent (rowComponent);
  36154. }
  36155. const Rectangle ListBox::getRowPosition (const int rowNumber,
  36156. const bool relativeToComponentTopLeft) const throw()
  36157. {
  36158. const int rowHeight = getRowHeight();
  36159. int y = viewport->getY() + rowHeight * rowNumber;
  36160. if (relativeToComponentTopLeft)
  36161. y -= viewport->getViewPositionY();
  36162. return Rectangle (viewport->getX(), y,
  36163. viewport->getViewedComponent()->getWidth(), rowHeight);
  36164. }
  36165. void ListBox::setVerticalPosition (const double proportion)
  36166. {
  36167. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36168. viewport->setViewPosition (viewport->getViewPositionX(),
  36169. jmax (0, roundDoubleToInt (proportion * offscreen)));
  36170. }
  36171. double ListBox::getVerticalPosition() const
  36172. {
  36173. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36174. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  36175. : 0;
  36176. }
  36177. int ListBox::getVisibleRowWidth() const throw()
  36178. {
  36179. return viewport->getViewWidth();
  36180. }
  36181. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  36182. {
  36183. if (row < viewport->firstWholeIndex)
  36184. {
  36185. viewport->setViewPosition (viewport->getViewPositionX(),
  36186. row * getRowHeight());
  36187. }
  36188. else if (row >= viewport->lastWholeIndex)
  36189. {
  36190. viewport->setViewPosition (viewport->getViewPositionX(),
  36191. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36192. }
  36193. }
  36194. bool ListBox::keyPressed (const KeyPress& key)
  36195. {
  36196. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  36197. const bool multiple = multipleSelection
  36198. && (lastRowSelected >= 0)
  36199. && (key.getModifiers().isShiftDown()
  36200. || key.getModifiers().isCtrlDown()
  36201. || key.getModifiers().isCommandDown());
  36202. if (key.isKeyCode (KeyPress::upKey))
  36203. {
  36204. if (multiple)
  36205. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  36206. else
  36207. selectRow (jmax (0, lastRowSelected - 1));
  36208. }
  36209. else if (key.isKeyCode (KeyPress::returnKey)
  36210. && isRowSelected (lastRowSelected))
  36211. {
  36212. if (model != 0)
  36213. model->returnKeyPressed (lastRowSelected);
  36214. }
  36215. else if (key.isKeyCode (KeyPress::pageUpKey))
  36216. {
  36217. if (multiple)
  36218. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  36219. else
  36220. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  36221. }
  36222. else if (key.isKeyCode (KeyPress::pageDownKey))
  36223. {
  36224. if (multiple)
  36225. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  36226. else
  36227. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  36228. }
  36229. else if (key.isKeyCode (KeyPress::homeKey))
  36230. {
  36231. if (multiple && key.getModifiers().isShiftDown())
  36232. selectRangeOfRows (lastRowSelected, 0);
  36233. else
  36234. selectRow (0);
  36235. }
  36236. else if (key.isKeyCode (KeyPress::endKey))
  36237. {
  36238. if (multiple && key.getModifiers().isShiftDown())
  36239. selectRangeOfRows (lastRowSelected, totalItems - 1);
  36240. else
  36241. selectRow (totalItems - 1);
  36242. }
  36243. else if (key.isKeyCode (KeyPress::downKey))
  36244. {
  36245. if (multiple)
  36246. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  36247. else
  36248. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  36249. }
  36250. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  36251. && isRowSelected (lastRowSelected))
  36252. {
  36253. if (model != 0)
  36254. model->deleteKeyPressed (lastRowSelected);
  36255. }
  36256. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  36257. {
  36258. selectRangeOfRows (0, INT_MAX);
  36259. }
  36260. else
  36261. {
  36262. return false;
  36263. }
  36264. return true;
  36265. }
  36266. bool ListBox::keyStateChanged (const bool isKeyDown)
  36267. {
  36268. return isKeyDown
  36269. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  36270. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  36271. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  36272. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  36273. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  36274. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  36275. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  36276. }
  36277. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36278. {
  36279. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  36280. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  36281. }
  36282. void ListBox::mouseMove (const MouseEvent& e)
  36283. {
  36284. if (mouseMoveSelects)
  36285. {
  36286. const MouseEvent e2 (e.getEventRelativeTo (this));
  36287. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  36288. lastMouseX = e2.x;
  36289. lastMouseY = e2.y;
  36290. }
  36291. }
  36292. void ListBox::mouseExit (const MouseEvent& e)
  36293. {
  36294. mouseMove (e);
  36295. }
  36296. void ListBox::mouseUp (const MouseEvent& e)
  36297. {
  36298. if (e.mouseWasClicked() && model != 0)
  36299. model->backgroundClicked();
  36300. }
  36301. void ListBox::setRowHeight (const int newHeight)
  36302. {
  36303. rowHeight = jmax (1, newHeight);
  36304. viewport->setSingleStepSizes (20, rowHeight);
  36305. updateContent();
  36306. }
  36307. int ListBox::getNumRowsOnScreen() const throw()
  36308. {
  36309. return viewport->getMaximumVisibleHeight() / rowHeight;
  36310. }
  36311. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  36312. {
  36313. minimumRowWidth = newMinimumWidth;
  36314. updateContent();
  36315. }
  36316. int ListBox::getVisibleContentWidth() const throw()
  36317. {
  36318. return viewport->getMaximumVisibleWidth();
  36319. }
  36320. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  36321. {
  36322. return viewport->getVerticalScrollBar();
  36323. }
  36324. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  36325. {
  36326. return viewport->getHorizontalScrollBar();
  36327. }
  36328. void ListBox::colourChanged()
  36329. {
  36330. setOpaque (findColour (backgroundColourId).isOpaque());
  36331. viewport->setOpaque (isOpaque());
  36332. repaint();
  36333. }
  36334. void ListBox::setOutlineThickness (const int outlineThickness_)
  36335. {
  36336. outlineThickness = outlineThickness_;
  36337. resized();
  36338. }
  36339. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  36340. {
  36341. if (headerComponent != newHeaderComponent)
  36342. {
  36343. if (headerComponent != 0)
  36344. delete headerComponent;
  36345. headerComponent = newHeaderComponent;
  36346. addAndMakeVisible (newHeaderComponent);
  36347. ListBox::resized();
  36348. }
  36349. }
  36350. void ListBox::repaintRow (const int rowNumber) throw()
  36351. {
  36352. const Rectangle r (getRowPosition (rowNumber, true));
  36353. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  36354. }
  36355. Image* ListBox::createSnapshotOfSelectedRows()
  36356. {
  36357. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  36358. Graphics g (*snapshot);
  36359. const int firstRow = getRowContainingPosition (0, 0);
  36360. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  36361. {
  36362. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  36363. if (rowComp != 0 && isRowSelected (firstRow + i))
  36364. {
  36365. g.saveState();
  36366. int x = 0, y = 0;
  36367. rowComp->relativePositionToOtherComponent (this, x, y);
  36368. g.setOrigin (x, y);
  36369. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  36370. rowComp->paintEntireComponent (g);
  36371. g.restoreState();
  36372. }
  36373. }
  36374. return snapshot;
  36375. }
  36376. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  36377. {
  36378. (void) existingComponentToUpdate;
  36379. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36380. return 0;
  36381. }
  36382. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  36383. {
  36384. }
  36385. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  36386. {
  36387. }
  36388. void ListBoxModel::backgroundClicked()
  36389. {
  36390. }
  36391. void ListBoxModel::selectedRowsChanged (int)
  36392. {
  36393. }
  36394. void ListBoxModel::deleteKeyPressed (int)
  36395. {
  36396. }
  36397. void ListBoxModel::returnKeyPressed (int)
  36398. {
  36399. }
  36400. void ListBoxModel::listWasScrolled()
  36401. {
  36402. }
  36403. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36404. {
  36405. return String::empty;
  36406. }
  36407. END_JUCE_NAMESPACE
  36408. /********* End of inlined file: juce_ListBox.cpp *********/
  36409. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  36410. BEGIN_JUCE_NAMESPACE
  36411. ProgressBar::ProgressBar (double& progress_)
  36412. : progress (progress_),
  36413. displayPercentage (true),
  36414. lastCallbackTime (0)
  36415. {
  36416. currentValue = jlimit (0.0, 1.0, progress);
  36417. }
  36418. ProgressBar::~ProgressBar()
  36419. {
  36420. }
  36421. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  36422. {
  36423. displayPercentage = shouldDisplayPercentage;
  36424. repaint();
  36425. }
  36426. void ProgressBar::setTextToDisplay (const String& text)
  36427. {
  36428. displayPercentage = false;
  36429. displayedMessage = text;
  36430. }
  36431. void ProgressBar::lookAndFeelChanged()
  36432. {
  36433. setOpaque (findColour (backgroundColourId).isOpaque());
  36434. }
  36435. void ProgressBar::colourChanged()
  36436. {
  36437. lookAndFeelChanged();
  36438. }
  36439. void ProgressBar::paint (Graphics& g)
  36440. {
  36441. String text;
  36442. if (displayPercentage)
  36443. {
  36444. if (currentValue >= 0 && currentValue <= 1.0)
  36445. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  36446. }
  36447. else
  36448. {
  36449. text = displayedMessage;
  36450. }
  36451. getLookAndFeel().drawProgressBar (g, *this,
  36452. getWidth(), getHeight(),
  36453. currentValue, text);
  36454. }
  36455. void ProgressBar::visibilityChanged()
  36456. {
  36457. if (isVisible())
  36458. startTimer (30);
  36459. else
  36460. stopTimer();
  36461. }
  36462. void ProgressBar::timerCallback()
  36463. {
  36464. double newProgress = progress;
  36465. if (currentValue != newProgress
  36466. || newProgress < 0 || newProgress >= 1.0
  36467. || currentMessage != displayedMessage)
  36468. {
  36469. if (currentValue < newProgress
  36470. && newProgress >= 0 && newProgress < 1.0
  36471. && currentValue >= 0 && currentValue < 1.0)
  36472. {
  36473. const uint32 now = Time::getMillisecondCounter();
  36474. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  36475. lastCallbackTime = now;
  36476. newProgress = jmin (currentValue + 0.00018 * timeSinceLastCallback,
  36477. newProgress);
  36478. }
  36479. currentValue = newProgress;
  36480. currentMessage = displayedMessage;
  36481. repaint();
  36482. }
  36483. }
  36484. END_JUCE_NAMESPACE
  36485. /********* End of inlined file: juce_ProgressBar.cpp *********/
  36486. /********* Start of inlined file: juce_Slider.cpp *********/
  36487. BEGIN_JUCE_NAMESPACE
  36488. class SliderPopupDisplayComponent : public BubbleComponent
  36489. {
  36490. public:
  36491. SliderPopupDisplayComponent (Slider* const owner_)
  36492. : owner (owner_),
  36493. font (15.0f, Font::bold)
  36494. {
  36495. setAlwaysOnTop (true);
  36496. }
  36497. ~SliderPopupDisplayComponent()
  36498. {
  36499. }
  36500. void paintContent (Graphics& g, int w, int h)
  36501. {
  36502. g.setFont (font);
  36503. g.setColour (Colours::black);
  36504. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  36505. }
  36506. void getContentSize (int& w, int& h)
  36507. {
  36508. w = font.getStringWidth (text) + 18;
  36509. h = (int) (font.getHeight() * 1.6f);
  36510. }
  36511. void updatePosition (const String& newText)
  36512. {
  36513. if (text != newText)
  36514. {
  36515. text = newText;
  36516. repaint();
  36517. }
  36518. BubbleComponent::setPosition (owner);
  36519. }
  36520. juce_UseDebuggingNewOperator
  36521. private:
  36522. Slider* owner;
  36523. Font font;
  36524. String text;
  36525. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  36526. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  36527. };
  36528. Slider::Slider (const String& name)
  36529. : Component (name),
  36530. listeners (2),
  36531. currentValue (0.0),
  36532. valueMin (0.0),
  36533. valueMax (0.0),
  36534. minimum (0),
  36535. maximum (10),
  36536. interval (0),
  36537. skewFactor (1.0),
  36538. velocityModeSensitivity (1.0),
  36539. velocityModeOffset (0.0),
  36540. velocityModeThreshold (1),
  36541. rotaryStart (float_Pi * 1.2f),
  36542. rotaryEnd (float_Pi * 2.8f),
  36543. numDecimalPlaces (7),
  36544. sliderRegionStart (0),
  36545. sliderRegionSize (1),
  36546. sliderBeingDragged (-1),
  36547. pixelsForFullDragExtent (250),
  36548. style (LinearHorizontal),
  36549. textBoxPos (TextBoxLeft),
  36550. textBoxWidth (80),
  36551. textBoxHeight (20),
  36552. incDecButtonMode (incDecButtonsNotDraggable),
  36553. editableText (true),
  36554. doubleClickToValue (false),
  36555. isVelocityBased (false),
  36556. userKeyOverridesVelocity (true),
  36557. rotaryStop (true),
  36558. incDecButtonsSideBySide (false),
  36559. sendChangeOnlyOnRelease (false),
  36560. popupDisplayEnabled (false),
  36561. menuEnabled (false),
  36562. menuShown (false),
  36563. scrollWheelEnabled (true),
  36564. snapsToMousePos (true),
  36565. valueBox (0),
  36566. incButton (0),
  36567. decButton (0),
  36568. popupDisplay (0),
  36569. parentForPopupDisplay (0)
  36570. {
  36571. setWantsKeyboardFocus (false);
  36572. setRepaintsOnMouseActivity (true);
  36573. lookAndFeelChanged();
  36574. updateText();
  36575. }
  36576. Slider::~Slider()
  36577. {
  36578. deleteAndZero (popupDisplay);
  36579. deleteAllChildren();
  36580. }
  36581. void Slider::handleAsyncUpdate()
  36582. {
  36583. cancelPendingUpdate();
  36584. for (int i = listeners.size(); --i >= 0;)
  36585. {
  36586. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  36587. i = jmin (i, listeners.size());
  36588. }
  36589. }
  36590. void Slider::sendDragStart()
  36591. {
  36592. startedDragging();
  36593. for (int i = listeners.size(); --i >= 0;)
  36594. {
  36595. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  36596. i = jmin (i, listeners.size());
  36597. }
  36598. }
  36599. void Slider::sendDragEnd()
  36600. {
  36601. stoppedDragging();
  36602. sliderBeingDragged = -1;
  36603. for (int i = listeners.size(); --i >= 0;)
  36604. {
  36605. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  36606. i = jmin (i, listeners.size());
  36607. }
  36608. }
  36609. void Slider::addListener (SliderListener* const listener) throw()
  36610. {
  36611. jassert (listener != 0);
  36612. if (listener != 0)
  36613. listeners.add (listener);
  36614. }
  36615. void Slider::removeListener (SliderListener* const listener) throw()
  36616. {
  36617. listeners.removeValue (listener);
  36618. }
  36619. void Slider::setSliderStyle (const SliderStyle newStyle)
  36620. {
  36621. if (style != newStyle)
  36622. {
  36623. style = newStyle;
  36624. repaint();
  36625. lookAndFeelChanged();
  36626. }
  36627. }
  36628. void Slider::setRotaryParameters (const float startAngleRadians,
  36629. const float endAngleRadians,
  36630. const bool stopAtEnd)
  36631. {
  36632. // make sure the values are sensible..
  36633. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  36634. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  36635. jassert (rotaryStart < rotaryEnd);
  36636. rotaryStart = startAngleRadians;
  36637. rotaryEnd = endAngleRadians;
  36638. rotaryStop = stopAtEnd;
  36639. }
  36640. void Slider::setVelocityBasedMode (const bool velBased) throw()
  36641. {
  36642. isVelocityBased = velBased;
  36643. }
  36644. void Slider::setVelocityModeParameters (const double sensitivity,
  36645. const int threshold,
  36646. const double offset,
  36647. const bool userCanPressKeyToSwapMode) throw()
  36648. {
  36649. jassert (threshold >= 0);
  36650. jassert (sensitivity > 0);
  36651. jassert (offset >= 0);
  36652. velocityModeSensitivity = sensitivity;
  36653. velocityModeOffset = offset;
  36654. velocityModeThreshold = threshold;
  36655. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  36656. }
  36657. void Slider::setSkewFactor (const double factor) throw()
  36658. {
  36659. skewFactor = factor;
  36660. }
  36661. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  36662. {
  36663. if (maximum > minimum)
  36664. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  36665. / (maximum - minimum));
  36666. }
  36667. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  36668. {
  36669. jassert (distanceForFullScaleDrag > 0);
  36670. pixelsForFullDragExtent = distanceForFullScaleDrag;
  36671. }
  36672. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  36673. {
  36674. if (incDecButtonMode != mode)
  36675. {
  36676. incDecButtonMode = mode;
  36677. lookAndFeelChanged();
  36678. }
  36679. }
  36680. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  36681. const bool isReadOnly,
  36682. const int textEntryBoxWidth,
  36683. const int textEntryBoxHeight)
  36684. {
  36685. textBoxPos = newPosition;
  36686. editableText = ! isReadOnly;
  36687. textBoxWidth = textEntryBoxWidth;
  36688. textBoxHeight = textEntryBoxHeight;
  36689. repaint();
  36690. lookAndFeelChanged();
  36691. }
  36692. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  36693. {
  36694. editableText = shouldBeEditable;
  36695. if (valueBox != 0)
  36696. valueBox->setEditable (shouldBeEditable && isEnabled());
  36697. }
  36698. void Slider::showTextBox()
  36699. {
  36700. jassert (editableText); // this should probably be avoided in read-only sliders.
  36701. if (valueBox != 0)
  36702. valueBox->showEditor();
  36703. }
  36704. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  36705. {
  36706. if (valueBox != 0)
  36707. {
  36708. valueBox->hideEditor (discardCurrentEditorContents);
  36709. if (discardCurrentEditorContents)
  36710. updateText();
  36711. }
  36712. }
  36713. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  36714. {
  36715. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  36716. }
  36717. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  36718. {
  36719. snapsToMousePos = shouldSnapToMouse;
  36720. }
  36721. void Slider::setPopupDisplayEnabled (const bool enabled,
  36722. Component* const parentComponentToUse) throw()
  36723. {
  36724. popupDisplayEnabled = enabled;
  36725. parentForPopupDisplay = parentComponentToUse;
  36726. }
  36727. void Slider::colourChanged()
  36728. {
  36729. lookAndFeelChanged();
  36730. }
  36731. void Slider::lookAndFeelChanged()
  36732. {
  36733. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  36734. : getTextFromValue (currentValue));
  36735. deleteAllChildren();
  36736. valueBox = 0;
  36737. LookAndFeel& lf = getLookAndFeel();
  36738. if (textBoxPos != NoTextBox)
  36739. {
  36740. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  36741. valueBox->setWantsKeyboardFocus (false);
  36742. valueBox->setText (previousTextBoxContent, false);
  36743. valueBox->setEditable (editableText && isEnabled());
  36744. valueBox->addListener (this);
  36745. if (style == LinearBar)
  36746. valueBox->addMouseListener (this, false);
  36747. valueBox->setTooltip (getTooltip());
  36748. }
  36749. if (style == IncDecButtons)
  36750. {
  36751. addAndMakeVisible (incButton = lf.createSliderButton (true));
  36752. incButton->addButtonListener (this);
  36753. addAndMakeVisible (decButton = lf.createSliderButton (false));
  36754. decButton->addButtonListener (this);
  36755. if (incDecButtonMode != incDecButtonsNotDraggable)
  36756. {
  36757. incButton->addMouseListener (this, false);
  36758. decButton->addMouseListener (this, false);
  36759. }
  36760. else
  36761. {
  36762. incButton->setRepeatSpeed (300, 100, 20);
  36763. incButton->addMouseListener (decButton, false);
  36764. decButton->setRepeatSpeed (300, 100, 20);
  36765. decButton->addMouseListener (incButton, false);
  36766. }
  36767. incButton->setTooltip (getTooltip());
  36768. decButton->setTooltip (getTooltip());
  36769. }
  36770. setComponentEffect (lf.getSliderEffect());
  36771. resized();
  36772. repaint();
  36773. }
  36774. void Slider::setRange (const double newMin,
  36775. const double newMax,
  36776. const double newInt)
  36777. {
  36778. if (minimum != newMin
  36779. || maximum != newMax
  36780. || interval != newInt)
  36781. {
  36782. minimum = newMin;
  36783. maximum = newMax;
  36784. interval = newInt;
  36785. // figure out the number of DPs needed to display all values at this
  36786. // interval setting.
  36787. numDecimalPlaces = 7;
  36788. if (newInt != 0)
  36789. {
  36790. int v = abs ((int) (newInt * 10000000));
  36791. while ((v % 10) == 0)
  36792. {
  36793. --numDecimalPlaces;
  36794. v /= 10;
  36795. }
  36796. }
  36797. // keep the current values inside the new range..
  36798. if (style != TwoValueHorizontal && style != TwoValueVertical)
  36799. {
  36800. setValue (currentValue, false, false);
  36801. }
  36802. else
  36803. {
  36804. setMinValue (getMinValue(), false, false);
  36805. setMaxValue (getMaxValue(), false, false);
  36806. }
  36807. updateText();
  36808. }
  36809. }
  36810. void Slider::triggerChangeMessage (const bool synchronous)
  36811. {
  36812. if (synchronous)
  36813. handleAsyncUpdate();
  36814. else
  36815. triggerAsyncUpdate();
  36816. valueChanged();
  36817. }
  36818. double Slider::getValue() const throw()
  36819. {
  36820. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  36821. // methods to get the two values.
  36822. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36823. return currentValue;
  36824. }
  36825. void Slider::setValue (double newValue,
  36826. const bool sendUpdateMessage,
  36827. const bool sendMessageSynchronously)
  36828. {
  36829. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  36830. // methods to set the two values.
  36831. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36832. newValue = constrainedValue (newValue);
  36833. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36834. {
  36835. jassert (valueMin <= valueMax);
  36836. newValue = jlimit (valueMin, valueMax, newValue);
  36837. }
  36838. if (currentValue != newValue)
  36839. {
  36840. if (valueBox != 0)
  36841. valueBox->hideEditor (true);
  36842. currentValue = newValue;
  36843. updateText();
  36844. repaint();
  36845. if (popupDisplay != 0)
  36846. {
  36847. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  36848. popupDisplay->repaint();
  36849. }
  36850. if (sendUpdateMessage)
  36851. triggerChangeMessage (sendMessageSynchronously);
  36852. }
  36853. }
  36854. double Slider::getMinValue() const throw()
  36855. {
  36856. // The minimum value only applies to sliders that are in two- or three-value mode.
  36857. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36858. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36859. return valueMin;
  36860. }
  36861. double Slider::getMaxValue() const throw()
  36862. {
  36863. // The maximum value only applies to sliders that are in two- or three-value mode.
  36864. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36865. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36866. return valueMax;
  36867. }
  36868. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36869. {
  36870. // The minimum value only applies to sliders that are in two- or three-value mode.
  36871. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36872. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36873. newValue = constrainedValue (newValue);
  36874. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36875. {
  36876. if (allowNudgingOfOtherValues && newValue > valueMax)
  36877. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36878. newValue = jmin (valueMax, newValue);
  36879. }
  36880. else
  36881. {
  36882. if (allowNudgingOfOtherValues && newValue > currentValue)
  36883. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36884. newValue = jmin (currentValue, newValue);
  36885. }
  36886. if (valueMin != newValue)
  36887. {
  36888. valueMin = newValue;
  36889. repaint();
  36890. if (popupDisplay != 0)
  36891. {
  36892. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  36893. popupDisplay->repaint();
  36894. }
  36895. if (sendUpdateMessage)
  36896. triggerChangeMessage (sendMessageSynchronously);
  36897. }
  36898. }
  36899. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36900. {
  36901. // The maximum value only applies to sliders that are in two- or three-value mode.
  36902. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36903. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36904. newValue = constrainedValue (newValue);
  36905. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36906. {
  36907. if (allowNudgingOfOtherValues && newValue < valueMin)
  36908. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36909. newValue = jmax (valueMin, newValue);
  36910. }
  36911. else
  36912. {
  36913. if (allowNudgingOfOtherValues && newValue < currentValue)
  36914. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36915. newValue = jmax (currentValue, newValue);
  36916. }
  36917. if (valueMax != newValue)
  36918. {
  36919. valueMax = newValue;
  36920. repaint();
  36921. if (popupDisplay != 0)
  36922. {
  36923. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  36924. popupDisplay->repaint();
  36925. }
  36926. if (sendUpdateMessage)
  36927. triggerChangeMessage (sendMessageSynchronously);
  36928. }
  36929. }
  36930. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  36931. const double valueToSetOnDoubleClick) throw()
  36932. {
  36933. doubleClickToValue = isDoubleClickEnabled;
  36934. doubleClickReturnValue = valueToSetOnDoubleClick;
  36935. }
  36936. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  36937. {
  36938. isEnabled_ = doubleClickToValue;
  36939. return doubleClickReturnValue;
  36940. }
  36941. void Slider::updateText()
  36942. {
  36943. if (valueBox != 0)
  36944. valueBox->setText (getTextFromValue (currentValue), false);
  36945. }
  36946. void Slider::setTextValueSuffix (const String& suffix)
  36947. {
  36948. if (textSuffix != suffix)
  36949. {
  36950. textSuffix = suffix;
  36951. updateText();
  36952. }
  36953. }
  36954. const String Slider::getTextFromValue (double v)
  36955. {
  36956. if (numDecimalPlaces > 0)
  36957. return String (v, numDecimalPlaces) + textSuffix;
  36958. else
  36959. return String (roundDoubleToInt (v)) + textSuffix;
  36960. }
  36961. double Slider::getValueFromText (const String& text)
  36962. {
  36963. String t (text.trimStart());
  36964. if (t.endsWith (textSuffix))
  36965. t = t.substring (0, t.length() - textSuffix.length());
  36966. while (t.startsWithChar (T('+')))
  36967. t = t.substring (1).trimStart();
  36968. return t.initialSectionContainingOnly (T("0123456789.,-"))
  36969. .getDoubleValue();
  36970. }
  36971. double Slider::proportionOfLengthToValue (double proportion)
  36972. {
  36973. if (skewFactor != 1.0 && proportion > 0.0)
  36974. proportion = exp (log (proportion) / skewFactor);
  36975. return minimum + (maximum - minimum) * proportion;
  36976. }
  36977. double Slider::valueToProportionOfLength (double value)
  36978. {
  36979. const double n = (value - minimum) / (maximum - minimum);
  36980. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  36981. }
  36982. double Slider::snapValue (double attemptedValue, const bool)
  36983. {
  36984. return attemptedValue;
  36985. }
  36986. void Slider::startedDragging()
  36987. {
  36988. }
  36989. void Slider::stoppedDragging()
  36990. {
  36991. }
  36992. void Slider::valueChanged()
  36993. {
  36994. }
  36995. void Slider::enablementChanged()
  36996. {
  36997. repaint();
  36998. }
  36999. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  37000. {
  37001. menuEnabled = menuEnabled_;
  37002. }
  37003. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  37004. {
  37005. scrollWheelEnabled = enabled;
  37006. }
  37007. void Slider::labelTextChanged (Label* label)
  37008. {
  37009. const double newValue = snapValue (getValueFromText (label->getText()), false);
  37010. if (getValue() != newValue)
  37011. {
  37012. sendDragStart();
  37013. setValue (newValue, true, true);
  37014. sendDragEnd();
  37015. }
  37016. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  37017. }
  37018. void Slider::buttonClicked (Button* button)
  37019. {
  37020. if (style == IncDecButtons)
  37021. {
  37022. sendDragStart();
  37023. if (button == incButton)
  37024. setValue (snapValue (getValue() + interval, false), true, true);
  37025. else if (button == decButton)
  37026. setValue (snapValue (getValue() - interval, false), true, true);
  37027. sendDragEnd();
  37028. }
  37029. }
  37030. double Slider::constrainedValue (double value) const throw()
  37031. {
  37032. if (interval > 0)
  37033. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  37034. if (value <= minimum || maximum <= minimum)
  37035. value = minimum;
  37036. else if (value >= maximum)
  37037. value = maximum;
  37038. return value;
  37039. }
  37040. float Slider::getLinearSliderPos (const double value)
  37041. {
  37042. double sliderPosProportional;
  37043. if (maximum > minimum)
  37044. {
  37045. if (value < minimum)
  37046. {
  37047. sliderPosProportional = 0.0;
  37048. }
  37049. else if (value > maximum)
  37050. {
  37051. sliderPosProportional = 1.0;
  37052. }
  37053. else
  37054. {
  37055. sliderPosProportional = valueToProportionOfLength (value);
  37056. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  37057. }
  37058. }
  37059. else
  37060. {
  37061. sliderPosProportional = 0.5;
  37062. }
  37063. if (isVertical() || style == IncDecButtons)
  37064. sliderPosProportional = 1.0 - sliderPosProportional;
  37065. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  37066. }
  37067. bool Slider::isHorizontal() const throw()
  37068. {
  37069. return style == LinearHorizontal
  37070. || style == LinearBar
  37071. || style == TwoValueHorizontal
  37072. || style == ThreeValueHorizontal;
  37073. }
  37074. bool Slider::isVertical() const throw()
  37075. {
  37076. return style == LinearVertical
  37077. || style == TwoValueVertical
  37078. || style == ThreeValueVertical;
  37079. }
  37080. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  37081. {
  37082. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  37083. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  37084. }
  37085. float Slider::getPositionOfValue (const double value)
  37086. {
  37087. if (isHorizontal() || isVertical())
  37088. {
  37089. return getLinearSliderPos (value);
  37090. }
  37091. else
  37092. {
  37093. jassertfalse // not a valid call on a slider that doesn't work linearly!
  37094. return 0.0f;
  37095. }
  37096. }
  37097. void Slider::paint (Graphics& g)
  37098. {
  37099. if (style != IncDecButtons)
  37100. {
  37101. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37102. {
  37103. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  37104. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  37105. getLookAndFeel().drawRotarySlider (g,
  37106. sliderRect.getX(),
  37107. sliderRect.getY(),
  37108. sliderRect.getWidth(),
  37109. sliderRect.getHeight(),
  37110. sliderPos,
  37111. rotaryStart, rotaryEnd,
  37112. *this);
  37113. }
  37114. else
  37115. {
  37116. getLookAndFeel().drawLinearSlider (g,
  37117. sliderRect.getX(),
  37118. sliderRect.getY(),
  37119. sliderRect.getWidth(),
  37120. sliderRect.getHeight(),
  37121. getLinearSliderPos (currentValue),
  37122. getLinearSliderPos (valueMin),
  37123. getLinearSliderPos (valueMax),
  37124. style,
  37125. *this);
  37126. }
  37127. if (style == LinearBar && valueBox == 0)
  37128. {
  37129. g.setColour (findColour (Slider::textBoxOutlineColourId));
  37130. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  37131. }
  37132. }
  37133. }
  37134. void Slider::resized()
  37135. {
  37136. int minXSpace = 0;
  37137. int minYSpace = 0;
  37138. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37139. minXSpace = 30;
  37140. else
  37141. minYSpace = 15;
  37142. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  37143. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  37144. if (style == LinearBar)
  37145. {
  37146. if (valueBox != 0)
  37147. valueBox->setBounds (0, 0, getWidth(), getHeight());
  37148. }
  37149. else
  37150. {
  37151. if (textBoxPos == NoTextBox)
  37152. {
  37153. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  37154. }
  37155. else if (textBoxPos == TextBoxLeft)
  37156. {
  37157. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  37158. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  37159. }
  37160. else if (textBoxPos == TextBoxRight)
  37161. {
  37162. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  37163. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  37164. }
  37165. else if (textBoxPos == TextBoxAbove)
  37166. {
  37167. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  37168. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  37169. }
  37170. else if (textBoxPos == TextBoxBelow)
  37171. {
  37172. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  37173. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  37174. }
  37175. }
  37176. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  37177. if (style == LinearBar)
  37178. {
  37179. const int barIndent = 1;
  37180. sliderRegionStart = barIndent;
  37181. sliderRegionSize = getWidth() - barIndent * 2;
  37182. sliderRect.setBounds (sliderRegionStart, barIndent,
  37183. sliderRegionSize, getHeight() - barIndent * 2);
  37184. }
  37185. else if (isHorizontal())
  37186. {
  37187. sliderRegionStart = sliderRect.getX() + indent;
  37188. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  37189. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  37190. sliderRegionSize, sliderRect.getHeight());
  37191. }
  37192. else if (isVertical())
  37193. {
  37194. sliderRegionStart = sliderRect.getY() + indent;
  37195. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  37196. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  37197. sliderRect.getWidth(), sliderRegionSize);
  37198. }
  37199. else
  37200. {
  37201. sliderRegionStart = 0;
  37202. sliderRegionSize = 100;
  37203. }
  37204. if (style == IncDecButtons)
  37205. {
  37206. Rectangle buttonRect (sliderRect);
  37207. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37208. buttonRect.expand (-2, 0);
  37209. else
  37210. buttonRect.expand (0, -2);
  37211. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  37212. if (incDecButtonsSideBySide)
  37213. {
  37214. decButton->setBounds (buttonRect.getX(),
  37215. buttonRect.getY(),
  37216. buttonRect.getWidth() / 2,
  37217. buttonRect.getHeight());
  37218. decButton->setConnectedEdges (Button::ConnectedOnRight);
  37219. incButton->setBounds (buttonRect.getCentreX(),
  37220. buttonRect.getY(),
  37221. buttonRect.getWidth() / 2,
  37222. buttonRect.getHeight());
  37223. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  37224. }
  37225. else
  37226. {
  37227. incButton->setBounds (buttonRect.getX(),
  37228. buttonRect.getY(),
  37229. buttonRect.getWidth(),
  37230. buttonRect.getHeight() / 2);
  37231. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  37232. decButton->setBounds (buttonRect.getX(),
  37233. buttonRect.getCentreY(),
  37234. buttonRect.getWidth(),
  37235. buttonRect.getHeight() / 2);
  37236. decButton->setConnectedEdges (Button::ConnectedOnTop);
  37237. }
  37238. }
  37239. }
  37240. void Slider::focusOfChildComponentChanged (FocusChangeType)
  37241. {
  37242. repaint();
  37243. }
  37244. void Slider::mouseDown (const MouseEvent& e)
  37245. {
  37246. mouseWasHidden = false;
  37247. incDecDragged = false;
  37248. mouseXWhenLastDragged = e.x;
  37249. mouseYWhenLastDragged = e.y;
  37250. mouseDragStartX = e.getMouseDownX();
  37251. mouseDragStartY = e.getMouseDownY();
  37252. if (isEnabled())
  37253. {
  37254. if (e.mods.isPopupMenu() && menuEnabled)
  37255. {
  37256. menuShown = true;
  37257. PopupMenu m;
  37258. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  37259. m.addSeparator();
  37260. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37261. {
  37262. PopupMenu rotaryMenu;
  37263. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  37264. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  37265. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  37266. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  37267. }
  37268. const int r = m.show();
  37269. if (r == 1)
  37270. {
  37271. setVelocityBasedMode (! isVelocityBased);
  37272. }
  37273. else if (r == 2)
  37274. {
  37275. setSliderStyle (Rotary);
  37276. }
  37277. else if (r == 3)
  37278. {
  37279. setSliderStyle (RotaryHorizontalDrag);
  37280. }
  37281. else if (r == 4)
  37282. {
  37283. setSliderStyle (RotaryVerticalDrag);
  37284. }
  37285. }
  37286. else if (maximum > minimum)
  37287. {
  37288. menuShown = false;
  37289. if (valueBox != 0)
  37290. valueBox->hideEditor (true);
  37291. sliderBeingDragged = 0;
  37292. if (style == TwoValueHorizontal
  37293. || style == TwoValueVertical
  37294. || style == ThreeValueHorizontal
  37295. || style == ThreeValueVertical)
  37296. {
  37297. const float mousePos = (float) (isVertical() ? e.y : e.x);
  37298. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  37299. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  37300. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  37301. if (style == TwoValueHorizontal || style == TwoValueVertical)
  37302. {
  37303. if (maxPosDistance <= minPosDistance)
  37304. sliderBeingDragged = 2;
  37305. else
  37306. sliderBeingDragged = 1;
  37307. }
  37308. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  37309. {
  37310. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  37311. sliderBeingDragged = 1;
  37312. else if (normalPosDistance >= maxPosDistance)
  37313. sliderBeingDragged = 2;
  37314. }
  37315. }
  37316. minMaxDiff = valueMax - valueMin;
  37317. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  37318. * valueToProportionOfLength (currentValue);
  37319. if (sliderBeingDragged == 2)
  37320. valueWhenLastDragged = valueMax;
  37321. else if (sliderBeingDragged == 1)
  37322. valueWhenLastDragged = valueMin;
  37323. else
  37324. valueWhenLastDragged = currentValue;
  37325. valueOnMouseDown = valueWhenLastDragged;
  37326. if (popupDisplayEnabled)
  37327. {
  37328. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  37329. popupDisplay = popup;
  37330. if (parentForPopupDisplay != 0)
  37331. {
  37332. parentForPopupDisplay->addChildComponent (popup);
  37333. }
  37334. else
  37335. {
  37336. popup->addToDesktop (0);
  37337. }
  37338. popup->setVisible (true);
  37339. }
  37340. sendDragStart();
  37341. mouseDrag (e);
  37342. }
  37343. }
  37344. }
  37345. void Slider::mouseUp (const MouseEvent&)
  37346. {
  37347. if (isEnabled()
  37348. && (! menuShown)
  37349. && (maximum > minimum)
  37350. && (style != IncDecButtons || incDecDragged))
  37351. {
  37352. restoreMouseIfHidden();
  37353. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  37354. triggerChangeMessage (false);
  37355. sendDragEnd();
  37356. deleteAndZero (popupDisplay);
  37357. if (style == IncDecButtons)
  37358. {
  37359. incButton->setState (Button::buttonNormal);
  37360. decButton->setState (Button::buttonNormal);
  37361. }
  37362. }
  37363. }
  37364. void Slider::restoreMouseIfHidden()
  37365. {
  37366. if (mouseWasHidden)
  37367. {
  37368. mouseWasHidden = false;
  37369. Component* c = Component::getComponentUnderMouse();
  37370. if (c == 0)
  37371. c = this;
  37372. c->enableUnboundedMouseMovement (false);
  37373. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  37374. : ((sliderBeingDragged == 1) ? getMinValue()
  37375. : currentValue);
  37376. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37377. {
  37378. int x, y, downX, downY;
  37379. Desktop::getMousePosition (x, y);
  37380. Desktop::getLastMouseDownPosition (downX, downY);
  37381. if (style == RotaryHorizontalDrag)
  37382. {
  37383. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  37384. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  37385. y = downY;
  37386. }
  37387. else
  37388. {
  37389. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  37390. x = downX;
  37391. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  37392. }
  37393. Desktop::setMousePosition (x, y);
  37394. }
  37395. else
  37396. {
  37397. const int pixelPos = (int) getLinearSliderPos (pos);
  37398. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  37399. int y = isVertical() ? pixelPos : (getHeight() / 2);
  37400. relativePositionToGlobal (x, y);
  37401. Desktop::setMousePosition (x, y);
  37402. }
  37403. }
  37404. }
  37405. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  37406. {
  37407. if (isEnabled()
  37408. && style != IncDecButtons
  37409. && style != Rotary
  37410. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  37411. {
  37412. restoreMouseIfHidden();
  37413. }
  37414. }
  37415. static double smallestAngleBetween (double a1, double a2)
  37416. {
  37417. return jmin (fabs (a1 - a2),
  37418. fabs (a1 + double_Pi * 2.0 - a2),
  37419. fabs (a2 + double_Pi * 2.0 - a1));
  37420. }
  37421. void Slider::mouseDrag (const MouseEvent& e)
  37422. {
  37423. if (isEnabled()
  37424. && (! menuShown)
  37425. && (maximum > minimum))
  37426. {
  37427. if (style == Rotary)
  37428. {
  37429. int dx = e.x - sliderRect.getCentreX();
  37430. int dy = e.y - sliderRect.getCentreY();
  37431. if (dx * dx + dy * dy > 25)
  37432. {
  37433. double angle = atan2 ((double) dx, (double) -dy);
  37434. while (angle < 0.0)
  37435. angle += double_Pi * 2.0;
  37436. if (rotaryStop && ! e.mouseWasClicked())
  37437. {
  37438. if (fabs (angle - lastAngle) > double_Pi)
  37439. {
  37440. if (angle >= lastAngle)
  37441. angle -= double_Pi * 2.0;
  37442. else
  37443. angle += double_Pi * 2.0;
  37444. }
  37445. if (angle >= lastAngle)
  37446. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  37447. else
  37448. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  37449. }
  37450. else
  37451. {
  37452. while (angle < rotaryStart)
  37453. angle += double_Pi * 2.0;
  37454. if (angle > rotaryEnd)
  37455. {
  37456. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  37457. angle = rotaryStart;
  37458. else
  37459. angle = rotaryEnd;
  37460. }
  37461. }
  37462. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  37463. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  37464. lastAngle = angle;
  37465. }
  37466. }
  37467. else
  37468. {
  37469. if (style == LinearBar && e.mouseWasClicked()
  37470. && valueBox != 0 && valueBox->isEditable())
  37471. return;
  37472. if (style == IncDecButtons && ! incDecDragged)
  37473. {
  37474. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  37475. return;
  37476. incDecDragged = true;
  37477. mouseDragStartX = e.x;
  37478. mouseDragStartY = e.y;
  37479. }
  37480. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  37481. : false))
  37482. || ((maximum - minimum) / sliderRegionSize < interval))
  37483. {
  37484. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  37485. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  37486. if (style == RotaryHorizontalDrag
  37487. || style == RotaryVerticalDrag
  37488. || style == IncDecButtons
  37489. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  37490. && ! snapsToMousePos))
  37491. {
  37492. const int mouseDiff = (style == RotaryHorizontalDrag
  37493. || style == LinearHorizontal
  37494. || style == LinearBar
  37495. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37496. ? e.x - mouseDragStartX
  37497. : mouseDragStartY - e.y;
  37498. double newPos = valueToProportionOfLength (valueOnMouseDown)
  37499. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  37500. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  37501. if (style == IncDecButtons)
  37502. {
  37503. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  37504. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  37505. }
  37506. }
  37507. else
  37508. {
  37509. if (isVertical())
  37510. scaledMousePos = 1.0 - scaledMousePos;
  37511. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  37512. }
  37513. }
  37514. else
  37515. {
  37516. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  37517. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37518. ? e.x - mouseXWhenLastDragged
  37519. : e.y - mouseYWhenLastDragged;
  37520. const double maxSpeed = jmax (200, sliderRegionSize);
  37521. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  37522. if (speed != 0)
  37523. {
  37524. speed = 0.2 * velocityModeSensitivity
  37525. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  37526. + jmax (0.0, (double) (speed - velocityModeThreshold))
  37527. / maxSpeed))));
  37528. if (mouseDiff < 0)
  37529. speed = -speed;
  37530. if (isVertical() || style == RotaryVerticalDrag
  37531. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  37532. speed = -speed;
  37533. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  37534. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  37535. e.originalComponent->enableUnboundedMouseMovement (true, false);
  37536. mouseWasHidden = true;
  37537. }
  37538. }
  37539. }
  37540. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  37541. if (sliderBeingDragged == 0)
  37542. {
  37543. setValue (snapValue (valueWhenLastDragged, true),
  37544. ! sendChangeOnlyOnRelease, true);
  37545. }
  37546. else if (sliderBeingDragged == 1)
  37547. {
  37548. setMinValue (snapValue (valueWhenLastDragged, true),
  37549. ! sendChangeOnlyOnRelease, false, true);
  37550. if (e.mods.isShiftDown())
  37551. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  37552. else
  37553. minMaxDiff = valueMax - valueMin;
  37554. }
  37555. else
  37556. {
  37557. jassert (sliderBeingDragged == 2);
  37558. setMaxValue (snapValue (valueWhenLastDragged, true),
  37559. ! sendChangeOnlyOnRelease, false, true);
  37560. if (e.mods.isShiftDown())
  37561. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  37562. else
  37563. minMaxDiff = valueMax - valueMin;
  37564. }
  37565. mouseXWhenLastDragged = e.x;
  37566. mouseYWhenLastDragged = e.y;
  37567. }
  37568. }
  37569. void Slider::mouseDoubleClick (const MouseEvent&)
  37570. {
  37571. if (doubleClickToValue
  37572. && isEnabled()
  37573. && style != IncDecButtons
  37574. && minimum <= doubleClickReturnValue
  37575. && maximum >= doubleClickReturnValue)
  37576. {
  37577. sendDragStart();
  37578. setValue (doubleClickReturnValue, true, true);
  37579. sendDragEnd();
  37580. }
  37581. }
  37582. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37583. {
  37584. if (scrollWheelEnabled && isEnabled()
  37585. && style != TwoValueHorizontal
  37586. && style != TwoValueVertical)
  37587. {
  37588. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  37589. {
  37590. if (valueBox != 0)
  37591. valueBox->hideEditor (false);
  37592. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  37593. const double currentPos = valueToProportionOfLength (currentValue);
  37594. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  37595. double delta = (newValue != currentValue)
  37596. ? jmax (fabs (newValue - currentValue), interval) : 0;
  37597. if (currentValue > newValue)
  37598. delta = -delta;
  37599. sendDragStart();
  37600. setValue (snapValue (currentValue + delta, false), true, true);
  37601. sendDragEnd();
  37602. }
  37603. }
  37604. else
  37605. {
  37606. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37607. }
  37608. }
  37609. void SliderListener::sliderDragStarted (Slider*)
  37610. {
  37611. }
  37612. void SliderListener::sliderDragEnded (Slider*)
  37613. {
  37614. }
  37615. END_JUCE_NAMESPACE
  37616. /********* End of inlined file: juce_Slider.cpp *********/
  37617. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  37618. BEGIN_JUCE_NAMESPACE
  37619. class DragOverlayComp : public Component
  37620. {
  37621. public:
  37622. DragOverlayComp (Image* const image_)
  37623. : image (image_)
  37624. {
  37625. image->multiplyAllAlphas (0.8f);
  37626. setAlwaysOnTop (true);
  37627. }
  37628. ~DragOverlayComp()
  37629. {
  37630. delete image;
  37631. }
  37632. void paint (Graphics& g)
  37633. {
  37634. g.drawImageAt (image, 0, 0);
  37635. }
  37636. private:
  37637. Image* image;
  37638. DragOverlayComp (const DragOverlayComp&);
  37639. const DragOverlayComp& operator= (const DragOverlayComp&);
  37640. };
  37641. TableHeaderComponent::TableHeaderComponent()
  37642. : listeners (2),
  37643. dragOverlayComp (0),
  37644. columnsChanged (false),
  37645. columnsResized (false),
  37646. sortChanged (false),
  37647. menuActive (true),
  37648. stretchToFit (false),
  37649. columnIdBeingResized (0),
  37650. columnIdBeingDragged (0),
  37651. columnIdUnderMouse (0),
  37652. lastDeliberateWidth (0)
  37653. {
  37654. }
  37655. TableHeaderComponent::~TableHeaderComponent()
  37656. {
  37657. delete dragOverlayComp;
  37658. }
  37659. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  37660. {
  37661. menuActive = hasMenu;
  37662. }
  37663. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  37664. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  37665. {
  37666. if (onlyCountVisibleColumns)
  37667. {
  37668. int num = 0;
  37669. for (int i = columns.size(); --i >= 0;)
  37670. if (columns.getUnchecked(i)->isVisible())
  37671. ++num;
  37672. return num;
  37673. }
  37674. else
  37675. {
  37676. return columns.size();
  37677. }
  37678. }
  37679. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  37680. {
  37681. const ColumnInfo* const ci = getInfoForId (columnId);
  37682. return ci != 0 ? ci->name : String::empty;
  37683. }
  37684. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  37685. {
  37686. ColumnInfo* const ci = getInfoForId (columnId);
  37687. if (ci != 0 && ci->name != newName)
  37688. {
  37689. ci->name = newName;
  37690. sendColumnsChanged();
  37691. }
  37692. }
  37693. void TableHeaderComponent::addColumn (const String& columnName,
  37694. const int columnId,
  37695. const int width,
  37696. const int minimumWidth,
  37697. const int maximumWidth,
  37698. const int propertyFlags,
  37699. const int insertIndex)
  37700. {
  37701. // can't have a duplicate or null ID!
  37702. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  37703. jassert (width > 0);
  37704. ColumnInfo* const ci = new ColumnInfo();
  37705. ci->name = columnName;
  37706. ci->id = columnId;
  37707. ci->width = width;
  37708. ci->lastDeliberateWidth = width;
  37709. ci->minimumWidth = minimumWidth;
  37710. ci->maximumWidth = maximumWidth;
  37711. if (ci->maximumWidth < 0)
  37712. ci->maximumWidth = INT_MAX;
  37713. jassert (ci->maximumWidth >= ci->minimumWidth);
  37714. ci->propertyFlags = propertyFlags;
  37715. columns.insert (insertIndex, ci);
  37716. sendColumnsChanged();
  37717. }
  37718. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  37719. {
  37720. const int index = getIndexOfColumnId (columnIdToRemove, false);
  37721. if (index >= 0)
  37722. {
  37723. columns.remove (index);
  37724. sortChanged = true;
  37725. sendColumnsChanged();
  37726. }
  37727. }
  37728. void TableHeaderComponent::removeAllColumns()
  37729. {
  37730. if (columns.size() > 0)
  37731. {
  37732. columns.clear();
  37733. sendColumnsChanged();
  37734. }
  37735. }
  37736. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  37737. {
  37738. const int currentIndex = getIndexOfColumnId (columnId, false);
  37739. newIndex = visibleIndexToTotalIndex (newIndex);
  37740. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  37741. {
  37742. columns.move (currentIndex, newIndex);
  37743. sendColumnsChanged();
  37744. }
  37745. }
  37746. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  37747. {
  37748. ColumnInfo* const ci = getInfoForId (columnId);
  37749. if (ci != 0 && ci->width != newWidth)
  37750. {
  37751. const int numColumns = getNumColumns (true);
  37752. ci->lastDeliberateWidth = ci->width
  37753. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  37754. if (stretchToFit)
  37755. {
  37756. const int index = getIndexOfColumnId (columnId, true) + 1;
  37757. if (((unsigned int) index) < (unsigned int) numColumns)
  37758. {
  37759. const int x = getColumnPosition (index).getX();
  37760. if (lastDeliberateWidth == 0)
  37761. lastDeliberateWidth = getTotalWidth();
  37762. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  37763. }
  37764. }
  37765. repaint();
  37766. columnsResized = true;
  37767. triggerAsyncUpdate();
  37768. }
  37769. }
  37770. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  37771. {
  37772. int n = 0;
  37773. for (int i = 0; i < columns.size(); ++i)
  37774. {
  37775. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  37776. {
  37777. if (columns.getUnchecked(i)->id == columnId)
  37778. return n;
  37779. ++n;
  37780. }
  37781. }
  37782. return -1;
  37783. }
  37784. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  37785. {
  37786. if (onlyCountVisibleColumns)
  37787. index = visibleIndexToTotalIndex (index);
  37788. const ColumnInfo* const ci = columns [index];
  37789. return (ci != 0) ? ci->id : 0;
  37790. }
  37791. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  37792. {
  37793. int x = 0, width = 0, n = 0;
  37794. for (int i = 0; i < columns.size(); ++i)
  37795. {
  37796. x += width;
  37797. if (columns.getUnchecked(i)->isVisible())
  37798. {
  37799. width = columns.getUnchecked(i)->width;
  37800. if (n++ == index)
  37801. break;
  37802. }
  37803. else
  37804. {
  37805. width = 0;
  37806. }
  37807. }
  37808. return Rectangle (x, 0, width, getHeight());
  37809. }
  37810. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  37811. {
  37812. if (xToFind >= 0)
  37813. {
  37814. int x = 0;
  37815. for (int i = 0; i < columns.size(); ++i)
  37816. {
  37817. const ColumnInfo* const ci = columns.getUnchecked(i);
  37818. if (ci->isVisible())
  37819. {
  37820. x += ci->width;
  37821. if (xToFind < x)
  37822. return ci->id;
  37823. }
  37824. }
  37825. }
  37826. return 0;
  37827. }
  37828. int TableHeaderComponent::getTotalWidth() const throw()
  37829. {
  37830. int w = 0;
  37831. for (int i = columns.size(); --i >= 0;)
  37832. if (columns.getUnchecked(i)->isVisible())
  37833. w += columns.getUnchecked(i)->width;
  37834. return w;
  37835. }
  37836. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  37837. {
  37838. stretchToFit = shouldStretchToFit;
  37839. lastDeliberateWidth = getTotalWidth();
  37840. resized();
  37841. }
  37842. bool TableHeaderComponent::isStretchToFitActive() const throw()
  37843. {
  37844. return stretchToFit;
  37845. }
  37846. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  37847. {
  37848. if (stretchToFit && getWidth() > 0
  37849. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  37850. {
  37851. lastDeliberateWidth = targetTotalWidth;
  37852. resizeColumnsToFit (0, targetTotalWidth);
  37853. }
  37854. }
  37855. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  37856. {
  37857. targetTotalWidth = jmax (targetTotalWidth, 0);
  37858. StretchableObjectResizer sor;
  37859. int i;
  37860. for (i = firstColumnIndex; i < columns.size(); ++i)
  37861. {
  37862. ColumnInfo* const ci = columns.getUnchecked(i);
  37863. if (ci->isVisible())
  37864. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  37865. }
  37866. sor.resizeToFit (targetTotalWidth);
  37867. int visIndex = 0;
  37868. for (i = firstColumnIndex; i < columns.size(); ++i)
  37869. {
  37870. ColumnInfo* const ci = columns.getUnchecked(i);
  37871. if (ci->isVisible())
  37872. {
  37873. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  37874. (int) floor (sor.getItemSize (visIndex++)));
  37875. if (newWidth != ci->width)
  37876. {
  37877. ci->width = newWidth;
  37878. repaint();
  37879. columnsResized = true;
  37880. triggerAsyncUpdate();
  37881. }
  37882. }
  37883. }
  37884. }
  37885. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  37886. {
  37887. ColumnInfo* const ci = getInfoForId (columnId);
  37888. if (ci != 0 && shouldBeVisible != ci->isVisible())
  37889. {
  37890. if (shouldBeVisible)
  37891. ci->propertyFlags |= visible;
  37892. else
  37893. ci->propertyFlags &= ~visible;
  37894. sendColumnsChanged();
  37895. resized();
  37896. }
  37897. }
  37898. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  37899. {
  37900. const ColumnInfo* const ci = getInfoForId (columnId);
  37901. return ci != 0 && ci->isVisible();
  37902. }
  37903. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  37904. {
  37905. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  37906. {
  37907. for (int i = columns.size(); --i >= 0;)
  37908. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  37909. ColumnInfo* const ci = getInfoForId (columnId);
  37910. if (ci != 0)
  37911. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  37912. reSortTable();
  37913. }
  37914. }
  37915. int TableHeaderComponent::getSortColumnId() const throw()
  37916. {
  37917. for (int i = columns.size(); --i >= 0;)
  37918. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37919. return columns.getUnchecked(i)->id;
  37920. return 0;
  37921. }
  37922. bool TableHeaderComponent::isSortedForwards() const throw()
  37923. {
  37924. for (int i = columns.size(); --i >= 0;)
  37925. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37926. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  37927. return true;
  37928. }
  37929. void TableHeaderComponent::reSortTable()
  37930. {
  37931. sortChanged = true;
  37932. repaint();
  37933. triggerAsyncUpdate();
  37934. }
  37935. const String TableHeaderComponent::toString() const
  37936. {
  37937. String s;
  37938. XmlElement doc (T("TABLELAYOUT"));
  37939. doc.setAttribute (T("sortedCol"), getSortColumnId());
  37940. doc.setAttribute (T("sortForwards"), isSortedForwards());
  37941. for (int i = 0; i < columns.size(); ++i)
  37942. {
  37943. const ColumnInfo* const ci = columns.getUnchecked (i);
  37944. XmlElement* const e = new XmlElement (T("COLUMN"));
  37945. doc.addChildElement (e);
  37946. e->setAttribute (T("id"), ci->id);
  37947. e->setAttribute (T("visible"), ci->isVisible());
  37948. e->setAttribute (T("width"), ci->width);
  37949. }
  37950. return doc.createDocument (String::empty, true, false);
  37951. }
  37952. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  37953. {
  37954. XmlDocument doc (storedVersion);
  37955. XmlElement* const storedXml = doc.getDocumentElement();
  37956. int index = 0;
  37957. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  37958. {
  37959. forEachXmlChildElement (*storedXml, col)
  37960. {
  37961. const int tabId = col->getIntAttribute (T("id"));
  37962. ColumnInfo* const ci = getInfoForId (tabId);
  37963. if (ci != 0)
  37964. {
  37965. columns.move (columns.indexOf (ci), index);
  37966. ci->width = col->getIntAttribute (T("width"));
  37967. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  37968. }
  37969. ++index;
  37970. }
  37971. columnsResized = true;
  37972. sendColumnsChanged();
  37973. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  37974. storedXml->getBoolAttribute (T("sortForwards"), true));
  37975. }
  37976. delete storedXml;
  37977. }
  37978. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  37979. {
  37980. listeners.addIfNotAlreadyThere (newListener);
  37981. }
  37982. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  37983. {
  37984. listeners.removeValue (listenerToRemove);
  37985. }
  37986. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  37987. {
  37988. const ColumnInfo* const ci = getInfoForId (columnId);
  37989. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  37990. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  37991. }
  37992. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  37993. {
  37994. for (int i = 0; i < columns.size(); ++i)
  37995. {
  37996. const ColumnInfo* const ci = columns.getUnchecked(i);
  37997. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  37998. menu.addItem (ci->id, ci->name,
  37999. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  38000. isColumnVisible (ci->id));
  38001. }
  38002. }
  38003. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  38004. {
  38005. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  38006. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  38007. }
  38008. void TableHeaderComponent::paint (Graphics& g)
  38009. {
  38010. LookAndFeel& lf = getLookAndFeel();
  38011. lf.drawTableHeaderBackground (g, *this);
  38012. const Rectangle clip (g.getClipBounds());
  38013. int x = 0;
  38014. for (int i = 0; i < columns.size(); ++i)
  38015. {
  38016. const ColumnInfo* const ci = columns.getUnchecked(i);
  38017. if (ci->isVisible())
  38018. {
  38019. if (x + ci->width > clip.getX()
  38020. && (ci->id != columnIdBeingDragged
  38021. || dragOverlayComp == 0
  38022. || ! dragOverlayComp->isVisible()))
  38023. {
  38024. g.saveState();
  38025. g.setOrigin (x, 0);
  38026. g.reduceClipRegion (0, 0, ci->width, getHeight());
  38027. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  38028. ci->id == columnIdUnderMouse,
  38029. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  38030. ci->propertyFlags);
  38031. g.restoreState();
  38032. }
  38033. x += ci->width;
  38034. if (x >= clip.getRight())
  38035. break;
  38036. }
  38037. }
  38038. }
  38039. void TableHeaderComponent::resized()
  38040. {
  38041. }
  38042. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  38043. {
  38044. updateColumnUnderMouse (e.x, e.y);
  38045. }
  38046. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  38047. {
  38048. updateColumnUnderMouse (e.x, e.y);
  38049. }
  38050. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  38051. {
  38052. updateColumnUnderMouse (e.x, e.y);
  38053. }
  38054. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  38055. {
  38056. repaint();
  38057. columnIdBeingResized = 0;
  38058. columnIdBeingDragged = 0;
  38059. if (columnIdUnderMouse != 0)
  38060. {
  38061. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  38062. if (e.mods.isPopupMenu())
  38063. columnClicked (columnIdUnderMouse, e.mods);
  38064. }
  38065. if (menuActive && e.mods.isPopupMenu())
  38066. showColumnChooserMenu (columnIdUnderMouse);
  38067. }
  38068. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  38069. {
  38070. if (columnIdBeingResized == 0
  38071. && columnIdBeingDragged == 0
  38072. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  38073. {
  38074. deleteAndZero (dragOverlayComp);
  38075. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  38076. if (columnIdBeingResized != 0)
  38077. {
  38078. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  38079. initialColumnWidth = ci->width;
  38080. }
  38081. else
  38082. {
  38083. beginDrag (e);
  38084. }
  38085. }
  38086. if (columnIdBeingResized != 0)
  38087. {
  38088. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  38089. if (ci != 0)
  38090. {
  38091. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  38092. initialColumnWidth + e.getDistanceFromDragStartX());
  38093. if (stretchToFit)
  38094. {
  38095. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  38096. int minWidthOnRight = 0;
  38097. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  38098. if (columns.getUnchecked (i)->isVisible())
  38099. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  38100. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  38101. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  38102. }
  38103. setColumnWidth (columnIdBeingResized, w);
  38104. }
  38105. }
  38106. else if (columnIdBeingDragged != 0)
  38107. {
  38108. if (e.y >= -50 && e.y < getHeight() + 50)
  38109. {
  38110. if (dragOverlayComp != 0)
  38111. {
  38112. dragOverlayComp->setVisible (true);
  38113. dragOverlayComp->setBounds (jlimit (0,
  38114. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  38115. e.x - draggingColumnOffset),
  38116. 0,
  38117. dragOverlayComp->getWidth(),
  38118. getHeight());
  38119. for (int i = columns.size(); --i >= 0;)
  38120. {
  38121. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38122. int newIndex = currentIndex;
  38123. if (newIndex > 0)
  38124. {
  38125. // if the previous column isn't draggable, we can't move our column
  38126. // past it, because that'd change the undraggable column's position..
  38127. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  38128. if ((previous->propertyFlags & draggable) != 0)
  38129. {
  38130. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  38131. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  38132. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  38133. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  38134. {
  38135. --newIndex;
  38136. }
  38137. }
  38138. }
  38139. if (newIndex < columns.size() - 1)
  38140. {
  38141. // if the next column isn't draggable, we can't move our column
  38142. // past it, because that'd change the undraggable column's position..
  38143. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  38144. if ((nextCol->propertyFlags & draggable) != 0)
  38145. {
  38146. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  38147. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  38148. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  38149. > abs (dragOverlayComp->getRight() - rightOfNext))
  38150. {
  38151. ++newIndex;
  38152. }
  38153. }
  38154. }
  38155. if (newIndex != currentIndex)
  38156. moveColumn (columnIdBeingDragged, newIndex);
  38157. else
  38158. break;
  38159. }
  38160. }
  38161. }
  38162. else
  38163. {
  38164. endDrag (draggingColumnOriginalIndex);
  38165. }
  38166. }
  38167. }
  38168. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  38169. {
  38170. if (columnIdBeingDragged == 0)
  38171. {
  38172. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  38173. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  38174. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  38175. {
  38176. columnIdBeingDragged = 0;
  38177. }
  38178. else
  38179. {
  38180. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38181. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  38182. const int temp = columnIdBeingDragged;
  38183. columnIdBeingDragged = 0;
  38184. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  38185. columnIdBeingDragged = temp;
  38186. dragOverlayComp->setBounds (columnRect);
  38187. for (int i = listeners.size(); --i >= 0;)
  38188. {
  38189. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  38190. i = jmin (i, listeners.size() - 1);
  38191. }
  38192. }
  38193. }
  38194. }
  38195. void TableHeaderComponent::endDrag (const int finalIndex)
  38196. {
  38197. if (columnIdBeingDragged != 0)
  38198. {
  38199. moveColumn (columnIdBeingDragged, finalIndex);
  38200. columnIdBeingDragged = 0;
  38201. repaint();
  38202. for (int i = listeners.size(); --i >= 0;)
  38203. {
  38204. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  38205. i = jmin (i, listeners.size() - 1);
  38206. }
  38207. }
  38208. }
  38209. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  38210. {
  38211. mouseDrag (e);
  38212. for (int i = columns.size(); --i >= 0;)
  38213. if (columns.getUnchecked (i)->isVisible())
  38214. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  38215. columnIdBeingResized = 0;
  38216. repaint();
  38217. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  38218. updateColumnUnderMouse (e.x, e.y);
  38219. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  38220. columnClicked (columnIdUnderMouse, e.mods);
  38221. deleteAndZero (dragOverlayComp);
  38222. }
  38223. const MouseCursor TableHeaderComponent::getMouseCursor()
  38224. {
  38225. int x, y;
  38226. getMouseXYRelative (x, y);
  38227. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  38228. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  38229. return Component::getMouseCursor();
  38230. }
  38231. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  38232. {
  38233. return (propertyFlags & TableHeaderComponent::visible) != 0;
  38234. }
  38235. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  38236. {
  38237. for (int i = columns.size(); --i >= 0;)
  38238. if (columns.getUnchecked(i)->id == id)
  38239. return columns.getUnchecked(i);
  38240. return 0;
  38241. }
  38242. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  38243. {
  38244. int n = 0;
  38245. for (int i = 0; i < columns.size(); ++i)
  38246. {
  38247. if (columns.getUnchecked(i)->isVisible())
  38248. {
  38249. if (n == visibleIndex)
  38250. return i;
  38251. ++n;
  38252. }
  38253. }
  38254. return -1;
  38255. }
  38256. void TableHeaderComponent::sendColumnsChanged()
  38257. {
  38258. if (stretchToFit && lastDeliberateWidth > 0)
  38259. resizeAllColumnsToFit (lastDeliberateWidth);
  38260. repaint();
  38261. columnsChanged = true;
  38262. triggerAsyncUpdate();
  38263. }
  38264. void TableHeaderComponent::handleAsyncUpdate()
  38265. {
  38266. const bool changed = columnsChanged || sortChanged;
  38267. const bool sized = columnsResized || changed;
  38268. const bool sorted = sortChanged;
  38269. columnsChanged = false;
  38270. columnsResized = false;
  38271. sortChanged = false;
  38272. if (sorted)
  38273. {
  38274. for (int i = listeners.size(); --i >= 0;)
  38275. {
  38276. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  38277. i = jmin (i, listeners.size() - 1);
  38278. }
  38279. }
  38280. if (changed)
  38281. {
  38282. for (int i = listeners.size(); --i >= 0;)
  38283. {
  38284. listeners.getUnchecked(i)->tableColumnsChanged (this);
  38285. i = jmin (i, listeners.size() - 1);
  38286. }
  38287. }
  38288. if (sized)
  38289. {
  38290. for (int i = listeners.size(); --i >= 0;)
  38291. {
  38292. listeners.getUnchecked(i)->tableColumnsResized (this);
  38293. i = jmin (i, listeners.size() - 1);
  38294. }
  38295. }
  38296. }
  38297. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  38298. {
  38299. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  38300. {
  38301. const int draggableDistance = 3;
  38302. int x = 0;
  38303. for (int i = 0; i < columns.size(); ++i)
  38304. {
  38305. const ColumnInfo* const ci = columns.getUnchecked(i);
  38306. if (ci->isVisible())
  38307. {
  38308. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  38309. && (ci->propertyFlags & resizable) != 0)
  38310. return ci->id;
  38311. x += ci->width;
  38312. }
  38313. }
  38314. }
  38315. return 0;
  38316. }
  38317. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  38318. {
  38319. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  38320. ? getColumnIdAtX (x) : 0;
  38321. if (newCol != columnIdUnderMouse)
  38322. {
  38323. columnIdUnderMouse = newCol;
  38324. repaint();
  38325. }
  38326. }
  38327. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  38328. {
  38329. PopupMenu m;
  38330. addMenuItems (m, columnIdClicked);
  38331. if (m.getNumItems() > 0)
  38332. {
  38333. const int result = m.show();
  38334. if (result != 0)
  38335. reactToMenuItem (result, columnIdClicked);
  38336. }
  38337. }
  38338. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  38339. {
  38340. }
  38341. END_JUCE_NAMESPACE
  38342. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  38343. /********* Start of inlined file: juce_TableListBox.cpp *********/
  38344. BEGIN_JUCE_NAMESPACE
  38345. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  38346. class TableListRowComp : public Component
  38347. {
  38348. public:
  38349. TableListRowComp (TableListBox& owner_)
  38350. : owner (owner_),
  38351. row (-1),
  38352. isSelected (false)
  38353. {
  38354. }
  38355. ~TableListRowComp()
  38356. {
  38357. deleteAllChildren();
  38358. }
  38359. void paint (Graphics& g)
  38360. {
  38361. TableListBoxModel* const model = owner.getModel();
  38362. if (model != 0)
  38363. {
  38364. const TableHeaderComponent* const header = owner.getHeader();
  38365. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  38366. const int numColumns = header->getNumColumns (true);
  38367. for (int i = 0; i < numColumns; ++i)
  38368. {
  38369. if (! columnsWithComponents [i])
  38370. {
  38371. const int columnId = header->getColumnIdOfIndex (i, true);
  38372. Rectangle columnRect (header->getColumnPosition (i));
  38373. columnRect.setSize (columnRect.getWidth(), getHeight());
  38374. g.saveState();
  38375. g.reduceClipRegion (columnRect);
  38376. g.setOrigin (columnRect.getX(), 0);
  38377. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  38378. g.restoreState();
  38379. }
  38380. }
  38381. }
  38382. }
  38383. void update (const int newRow, const bool isNowSelected)
  38384. {
  38385. if (newRow != row || isNowSelected != isSelected)
  38386. {
  38387. row = newRow;
  38388. isSelected = isNowSelected;
  38389. repaint();
  38390. }
  38391. if (row < owner.getNumRows())
  38392. {
  38393. jassert (row >= 0);
  38394. const tchar* const tagPropertyName = T("_tableLastUseNum");
  38395. const int newTag = Random::getSystemRandom().nextInt();
  38396. const TableHeaderComponent* const header = owner.getHeader();
  38397. const int numColumns = header->getNumColumns (true);
  38398. int i;
  38399. columnsWithComponents.clear();
  38400. if (owner.getModel() != 0)
  38401. {
  38402. for (i = 0; i < numColumns; ++i)
  38403. {
  38404. const int columnId = header->getColumnIdOfIndex (i, true);
  38405. Component* const newComp
  38406. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  38407. findChildComponentForColumn (columnId));
  38408. if (newComp != 0)
  38409. {
  38410. addAndMakeVisible (newComp);
  38411. newComp->setComponentProperty (tagPropertyName, newTag);
  38412. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  38413. const Rectangle columnRect (header->getColumnPosition (i));
  38414. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38415. columnsWithComponents.setBit (i);
  38416. }
  38417. }
  38418. }
  38419. for (i = getNumChildComponents(); --i >= 0;)
  38420. {
  38421. Component* const c = getChildComponent (i);
  38422. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  38423. delete c;
  38424. }
  38425. }
  38426. else
  38427. {
  38428. columnsWithComponents.clear();
  38429. deleteAllChildren();
  38430. }
  38431. }
  38432. void resized()
  38433. {
  38434. for (int i = getNumChildComponents(); --i >= 0;)
  38435. {
  38436. Component* const c = getChildComponent (i);
  38437. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  38438. if (columnId != 0)
  38439. {
  38440. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  38441. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38442. }
  38443. }
  38444. }
  38445. void mouseDown (const MouseEvent& e)
  38446. {
  38447. isDragging = false;
  38448. selectRowOnMouseUp = false;
  38449. if (isEnabled())
  38450. {
  38451. if (! isSelected)
  38452. {
  38453. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38454. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38455. if (columnId != 0 && owner.getModel() != 0)
  38456. owner.getModel()->cellClicked (row, columnId, e);
  38457. }
  38458. else
  38459. {
  38460. selectRowOnMouseUp = true;
  38461. }
  38462. }
  38463. }
  38464. void mouseDrag (const MouseEvent& e)
  38465. {
  38466. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38467. {
  38468. const SparseSet <int> selectedRows (owner.getSelectedRows());
  38469. if (selectedRows.size() > 0)
  38470. {
  38471. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38472. if (dragDescription.isNotEmpty())
  38473. {
  38474. isDragging = true;
  38475. DragAndDropContainer* const dragContainer
  38476. = DragAndDropContainer::findParentDragContainerFor (this);
  38477. if (dragContainer != 0)
  38478. {
  38479. Image* dragImage = owner.createSnapshotOfSelectedRows();
  38480. dragImage->multiplyAllAlphas (0.6f);
  38481. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  38482. }
  38483. else
  38484. {
  38485. // to be able to do a drag-and-drop operation, the listbox needs to
  38486. // be inside a component which is also a DragAndDropContainer.
  38487. jassertfalse
  38488. }
  38489. }
  38490. }
  38491. }
  38492. }
  38493. void mouseUp (const MouseEvent& e)
  38494. {
  38495. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  38496. {
  38497. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38498. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38499. if (columnId != 0 && owner.getModel() != 0)
  38500. owner.getModel()->cellClicked (row, columnId, e);
  38501. }
  38502. }
  38503. void mouseDoubleClick (const MouseEvent& e)
  38504. {
  38505. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38506. if (columnId != 0 && owner.getModel() != 0)
  38507. owner.getModel()->cellDoubleClicked (row, columnId, e);
  38508. }
  38509. juce_UseDebuggingNewOperator
  38510. private:
  38511. TableListBox& owner;
  38512. int row;
  38513. bool isSelected, isDragging, selectRowOnMouseUp;
  38514. BitArray columnsWithComponents;
  38515. Component* findChildComponentForColumn (const int columnId) const
  38516. {
  38517. for (int i = getNumChildComponents(); --i >= 0;)
  38518. {
  38519. Component* const c = getChildComponent (i);
  38520. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  38521. return c;
  38522. }
  38523. return 0;
  38524. }
  38525. TableListRowComp (const TableListRowComp&);
  38526. const TableListRowComp& operator= (const TableListRowComp&);
  38527. };
  38528. class TableListBoxHeader : public TableHeaderComponent
  38529. {
  38530. public:
  38531. TableListBoxHeader (TableListBox& owner_)
  38532. : owner (owner_)
  38533. {
  38534. }
  38535. ~TableListBoxHeader()
  38536. {
  38537. }
  38538. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  38539. {
  38540. if (owner.isAutoSizeMenuOptionShown())
  38541. {
  38542. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  38543. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  38544. menu.addSeparator();
  38545. }
  38546. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  38547. }
  38548. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  38549. {
  38550. if (menuReturnId == 0xf836743)
  38551. {
  38552. owner.autoSizeColumn (columnIdClicked);
  38553. }
  38554. else if (menuReturnId == 0xf836744)
  38555. {
  38556. owner.autoSizeAllColumns();
  38557. }
  38558. else
  38559. {
  38560. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  38561. }
  38562. }
  38563. juce_UseDebuggingNewOperator
  38564. private:
  38565. TableListBox& owner;
  38566. TableListBoxHeader (const TableListBoxHeader&);
  38567. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  38568. };
  38569. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  38570. : ListBox (name, 0),
  38571. model (model_),
  38572. autoSizeOptionsShown (true)
  38573. {
  38574. ListBox::model = this;
  38575. header = new TableListBoxHeader (*this);
  38576. header->setSize (100, 28);
  38577. header->addListener (this);
  38578. setHeaderComponent (header);
  38579. }
  38580. TableListBox::~TableListBox()
  38581. {
  38582. deleteAllChildren();
  38583. }
  38584. void TableListBox::setModel (TableListBoxModel* const newModel)
  38585. {
  38586. if (model != newModel)
  38587. {
  38588. model = newModel;
  38589. updateContent();
  38590. }
  38591. }
  38592. int TableListBox::getHeaderHeight() const throw()
  38593. {
  38594. return header->getHeight();
  38595. }
  38596. void TableListBox::setHeaderHeight (const int newHeight)
  38597. {
  38598. header->setSize (header->getWidth(), newHeight);
  38599. resized();
  38600. }
  38601. void TableListBox::autoSizeColumn (const int columnId)
  38602. {
  38603. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  38604. if (width > 0)
  38605. header->setColumnWidth (columnId, width);
  38606. }
  38607. void TableListBox::autoSizeAllColumns()
  38608. {
  38609. for (int i = 0; i < header->getNumColumns (true); ++i)
  38610. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  38611. }
  38612. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  38613. {
  38614. autoSizeOptionsShown = shouldBeShown;
  38615. }
  38616. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  38617. {
  38618. return autoSizeOptionsShown;
  38619. }
  38620. const Rectangle TableListBox::getCellPosition (const int columnId,
  38621. const int rowNumber,
  38622. const bool relativeToComponentTopLeft) const
  38623. {
  38624. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38625. if (relativeToComponentTopLeft)
  38626. headerCell.translate (header->getX(), 0);
  38627. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  38628. return Rectangle (headerCell.getX(), row.getY(),
  38629. headerCell.getWidth(), row.getHeight());
  38630. }
  38631. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  38632. {
  38633. ScrollBar* const scrollbar = getHorizontalScrollBar();
  38634. if (scrollbar != 0)
  38635. {
  38636. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38637. double x = scrollbar->getCurrentRangeStart();
  38638. const double w = scrollbar->getCurrentRangeSize();
  38639. if (pos.getX() < x)
  38640. x = pos.getX();
  38641. else if (pos.getRight() > x + w)
  38642. x += jmax (0.0, pos.getRight() - (x + w));
  38643. scrollbar->setCurrentRangeStart (x);
  38644. }
  38645. }
  38646. int TableListBox::getNumRows()
  38647. {
  38648. return model != 0 ? model->getNumRows() : 0;
  38649. }
  38650. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  38651. {
  38652. }
  38653. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  38654. {
  38655. if (existingComponentToUpdate == 0)
  38656. existingComponentToUpdate = new TableListRowComp (*this);
  38657. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  38658. return existingComponentToUpdate;
  38659. }
  38660. void TableListBox::selectedRowsChanged (int row)
  38661. {
  38662. if (model != 0)
  38663. model->selectedRowsChanged (row);
  38664. }
  38665. void TableListBox::deleteKeyPressed (int row)
  38666. {
  38667. if (model != 0)
  38668. model->deleteKeyPressed (row);
  38669. }
  38670. void TableListBox::returnKeyPressed (int row)
  38671. {
  38672. if (model != 0)
  38673. model->returnKeyPressed (row);
  38674. }
  38675. void TableListBox::backgroundClicked()
  38676. {
  38677. if (model != 0)
  38678. model->backgroundClicked();
  38679. }
  38680. void TableListBox::listWasScrolled()
  38681. {
  38682. if (model != 0)
  38683. model->listWasScrolled();
  38684. }
  38685. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  38686. {
  38687. setMinimumContentWidth (header->getTotalWidth());
  38688. repaint();
  38689. updateColumnComponents();
  38690. }
  38691. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  38692. {
  38693. setMinimumContentWidth (header->getTotalWidth());
  38694. repaint();
  38695. updateColumnComponents();
  38696. }
  38697. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  38698. {
  38699. if (model != 0)
  38700. model->sortOrderChanged (header->getSortColumnId(),
  38701. header->isSortedForwards());
  38702. }
  38703. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  38704. {
  38705. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  38706. repaint();
  38707. }
  38708. void TableListBox::resized()
  38709. {
  38710. ListBox::resized();
  38711. header->resizeAllColumnsToFit (getVisibleContentWidth());
  38712. setMinimumContentWidth (header->getTotalWidth());
  38713. }
  38714. void TableListBox::updateColumnComponents() const
  38715. {
  38716. const int firstRow = getRowContainingPosition (0, 0);
  38717. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  38718. {
  38719. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  38720. if (rowComp != 0)
  38721. rowComp->resized();
  38722. }
  38723. }
  38724. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  38725. {
  38726. }
  38727. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  38728. {
  38729. }
  38730. void TableListBoxModel::backgroundClicked()
  38731. {
  38732. }
  38733. void TableListBoxModel::sortOrderChanged (int, const bool)
  38734. {
  38735. }
  38736. int TableListBoxModel::getColumnAutoSizeWidth (int)
  38737. {
  38738. return 0;
  38739. }
  38740. void TableListBoxModel::selectedRowsChanged (int)
  38741. {
  38742. }
  38743. void TableListBoxModel::deleteKeyPressed (int)
  38744. {
  38745. }
  38746. void TableListBoxModel::returnKeyPressed (int)
  38747. {
  38748. }
  38749. void TableListBoxModel::listWasScrolled()
  38750. {
  38751. }
  38752. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38753. {
  38754. return String::empty;
  38755. }
  38756. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  38757. {
  38758. (void) existingComponentToUpdate;
  38759. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38760. return 0;
  38761. }
  38762. END_JUCE_NAMESPACE
  38763. /********* End of inlined file: juce_TableListBox.cpp *********/
  38764. /********* Start of inlined file: juce_TextEditor.cpp *********/
  38765. BEGIN_JUCE_NAMESPACE
  38766. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  38767. // a word or space that can't be broken down any further
  38768. struct TextAtom
  38769. {
  38770. String atomText;
  38771. float width;
  38772. uint16 numChars;
  38773. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  38774. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  38775. const String getText (const tchar passwordCharacter) const throw()
  38776. {
  38777. if (passwordCharacter == 0)
  38778. return atomText;
  38779. else
  38780. return String::repeatedString (String::charToString (passwordCharacter),
  38781. atomText.length());
  38782. }
  38783. const String getTrimmedText (const tchar passwordCharacter) const throw()
  38784. {
  38785. if (passwordCharacter == 0)
  38786. return atomText.substring (0, numChars);
  38787. else if (isNewLine())
  38788. return String::empty;
  38789. else
  38790. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  38791. }
  38792. };
  38793. // a run of text with a single font and colour
  38794. class UniformTextSection
  38795. {
  38796. public:
  38797. UniformTextSection (const String& text,
  38798. const Font& font_,
  38799. const Colour& colour_,
  38800. const tchar passwordCharacter) throw()
  38801. : font (font_),
  38802. colour (colour_),
  38803. atoms (64)
  38804. {
  38805. initialiseAtoms (text, passwordCharacter);
  38806. }
  38807. UniformTextSection (const UniformTextSection& other) throw()
  38808. : font (other.font),
  38809. colour (other.colour),
  38810. atoms (64)
  38811. {
  38812. for (int i = 0; i < other.atoms.size(); ++i)
  38813. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  38814. }
  38815. ~UniformTextSection() throw()
  38816. {
  38817. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  38818. }
  38819. void clear() throw()
  38820. {
  38821. for (int i = atoms.size(); --i >= 0;)
  38822. {
  38823. TextAtom* const atom = getAtom(i);
  38824. delete atom;
  38825. }
  38826. atoms.clear();
  38827. }
  38828. int getNumAtoms() const throw()
  38829. {
  38830. return atoms.size();
  38831. }
  38832. TextAtom* getAtom (const int index) const throw()
  38833. {
  38834. return (TextAtom*) atoms.getUnchecked (index);
  38835. }
  38836. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  38837. {
  38838. if (other.atoms.size() > 0)
  38839. {
  38840. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  38841. int i = 0;
  38842. if (lastAtom != 0)
  38843. {
  38844. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  38845. {
  38846. TextAtom* const first = other.getAtom(0);
  38847. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  38848. {
  38849. lastAtom->atomText += first->atomText;
  38850. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  38851. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  38852. delete first;
  38853. ++i;
  38854. }
  38855. }
  38856. }
  38857. while (i < other.atoms.size())
  38858. {
  38859. atoms.add (other.getAtom(i));
  38860. ++i;
  38861. }
  38862. }
  38863. }
  38864. UniformTextSection* split (const int indexToBreakAt,
  38865. const tchar passwordCharacter) throw()
  38866. {
  38867. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  38868. font, colour,
  38869. passwordCharacter);
  38870. int index = 0;
  38871. for (int i = 0; i < atoms.size(); ++i)
  38872. {
  38873. TextAtom* const atom = getAtom(i);
  38874. const int nextIndex = index + atom->numChars;
  38875. if (index == indexToBreakAt)
  38876. {
  38877. int j;
  38878. for (j = i; j < atoms.size(); ++j)
  38879. section2->atoms.add (getAtom (j));
  38880. for (j = atoms.size(); --j >= i;)
  38881. atoms.remove (j);
  38882. break;
  38883. }
  38884. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  38885. {
  38886. TextAtom* const secondAtom = new TextAtom();
  38887. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  38888. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  38889. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  38890. section2->atoms.add (secondAtom);
  38891. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  38892. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38893. atom->numChars = (uint16) (indexToBreakAt - index);
  38894. int j;
  38895. for (j = i + 1; j < atoms.size(); ++j)
  38896. section2->atoms.add (getAtom (j));
  38897. for (j = atoms.size(); --j > i;)
  38898. atoms.remove (j);
  38899. break;
  38900. }
  38901. index = nextIndex;
  38902. }
  38903. return section2;
  38904. }
  38905. const String getAllText() const throw()
  38906. {
  38907. String s;
  38908. s.preallocateStorage (getTotalLength());
  38909. tchar* endOfString = (tchar*) &(s[0]);
  38910. for (int i = 0; i < atoms.size(); ++i)
  38911. {
  38912. const TextAtom* const atom = getAtom(i);
  38913. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  38914. endOfString += atom->numChars;
  38915. }
  38916. *endOfString = 0;
  38917. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  38918. return s;
  38919. }
  38920. const String getTextSubstring (const int startCharacter,
  38921. const int endCharacter) const throw()
  38922. {
  38923. int index = 0;
  38924. int totalLen = 0;
  38925. int i;
  38926. for (i = 0; i < atoms.size(); ++i)
  38927. {
  38928. const TextAtom* const atom = getAtom (i);
  38929. const int nextIndex = index + atom->numChars;
  38930. if (startCharacter < nextIndex)
  38931. {
  38932. if (endCharacter <= index)
  38933. break;
  38934. const int start = jmax (0, startCharacter - index);
  38935. const int end = jmin (endCharacter - index, atom->numChars);
  38936. jassert (end >= start);
  38937. totalLen += end - start;
  38938. }
  38939. index = nextIndex;
  38940. }
  38941. String s;
  38942. s.preallocateStorage (totalLen + 1);
  38943. tchar* psz = (tchar*) (const tchar*) s;
  38944. index = 0;
  38945. for (i = 0; i < atoms.size(); ++i)
  38946. {
  38947. const TextAtom* const atom = getAtom (i);
  38948. const int nextIndex = index + atom->numChars;
  38949. if (startCharacter < nextIndex)
  38950. {
  38951. if (endCharacter <= index)
  38952. break;
  38953. const int start = jmax (0, startCharacter - index);
  38954. const int len = jmin (endCharacter - index, atom->numChars) - start;
  38955. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  38956. psz += len;
  38957. *psz = 0;
  38958. }
  38959. index = nextIndex;
  38960. }
  38961. return s;
  38962. }
  38963. int getTotalLength() const throw()
  38964. {
  38965. int c = 0;
  38966. for (int i = atoms.size(); --i >= 0;)
  38967. c += getAtom(i)->numChars;
  38968. return c;
  38969. }
  38970. void setFont (const Font& newFont,
  38971. const tchar passwordCharacter) throw()
  38972. {
  38973. if (font != newFont)
  38974. {
  38975. font = newFont;
  38976. for (int i = atoms.size(); --i >= 0;)
  38977. {
  38978. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  38979. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  38980. }
  38981. }
  38982. }
  38983. juce_UseDebuggingNewOperator
  38984. Font font;
  38985. Colour colour;
  38986. private:
  38987. VoidArray atoms;
  38988. void initialiseAtoms (const String& textToParse,
  38989. const tchar passwordCharacter) throw()
  38990. {
  38991. int i = 0;
  38992. const int len = textToParse.length();
  38993. const tchar* const text = (const tchar*) textToParse;
  38994. while (i < len)
  38995. {
  38996. int start = i;
  38997. // create a whitespace atom unless it starts with non-ws
  38998. if (CharacterFunctions::isWhitespace (text[i])
  38999. && text[i] != T('\r')
  39000. && text[i] != T('\n'))
  39001. {
  39002. while (i < len
  39003. && CharacterFunctions::isWhitespace (text[i])
  39004. && text[i] != T('\r')
  39005. && text[i] != T('\n'))
  39006. {
  39007. ++i;
  39008. }
  39009. }
  39010. else
  39011. {
  39012. if (text[i] == T('\r'))
  39013. {
  39014. ++i;
  39015. if ((i < len) && (text[i] == T('\n')))
  39016. {
  39017. ++start;
  39018. ++i;
  39019. }
  39020. }
  39021. else if (text[i] == T('\n'))
  39022. {
  39023. ++i;
  39024. }
  39025. else
  39026. {
  39027. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  39028. ++i;
  39029. }
  39030. }
  39031. TextAtom* const atom = new TextAtom();
  39032. atom->atomText = String (text + start, i - start);
  39033. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  39034. atom->numChars = (uint16) (i - start);
  39035. atoms.add (atom);
  39036. }
  39037. }
  39038. const UniformTextSection& operator= (const UniformTextSection& other);
  39039. };
  39040. class TextEditorIterator
  39041. {
  39042. public:
  39043. TextEditorIterator (const VoidArray& sections_,
  39044. const float wordWrapWidth_,
  39045. const tchar passwordCharacter_) throw()
  39046. : indexInText (0),
  39047. lineY (0),
  39048. lineHeight (0),
  39049. maxDescent (0),
  39050. atomX (0),
  39051. atomRight (0),
  39052. atom (0),
  39053. currentSection (0),
  39054. sections (sections_),
  39055. sectionIndex (0),
  39056. atomIndex (0),
  39057. wordWrapWidth (wordWrapWidth_),
  39058. passwordCharacter (passwordCharacter_)
  39059. {
  39060. jassert (wordWrapWidth_ > 0);
  39061. if (sections.size() > 0)
  39062. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  39063. if (currentSection != 0)
  39064. {
  39065. lineHeight = currentSection->font.getHeight();
  39066. maxDescent = currentSection->font.getDescent();
  39067. }
  39068. }
  39069. TextEditorIterator (const TextEditorIterator& other) throw()
  39070. : indexInText (other.indexInText),
  39071. lineY (other.lineY),
  39072. lineHeight (other.lineHeight),
  39073. maxDescent (other.maxDescent),
  39074. atomX (other.atomX),
  39075. atomRight (other.atomRight),
  39076. atom (other.atom),
  39077. currentSection (other.currentSection),
  39078. sections (other.sections),
  39079. sectionIndex (other.sectionIndex),
  39080. atomIndex (other.atomIndex),
  39081. wordWrapWidth (other.wordWrapWidth),
  39082. passwordCharacter (other.passwordCharacter),
  39083. tempAtom (other.tempAtom)
  39084. {
  39085. }
  39086. ~TextEditorIterator() throw()
  39087. {
  39088. }
  39089. bool next() throw()
  39090. {
  39091. if (atom == &tempAtom)
  39092. {
  39093. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  39094. if (numRemaining > 0)
  39095. {
  39096. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  39097. atomX = 0;
  39098. if (tempAtom.numChars > 0)
  39099. lineY += lineHeight;
  39100. indexInText += tempAtom.numChars;
  39101. GlyphArrangement g;
  39102. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  39103. int split;
  39104. for (split = 0; split < g.getNumGlyphs(); ++split)
  39105. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  39106. break;
  39107. if (split > 0 && split <= numRemaining)
  39108. {
  39109. tempAtom.numChars = (uint16) split;
  39110. tempAtom.width = g.getGlyph (split - 1).getRight();
  39111. atomRight = atomX + tempAtom.width;
  39112. return true;
  39113. }
  39114. }
  39115. }
  39116. bool forceNewLine = false;
  39117. if (sectionIndex >= sections.size())
  39118. {
  39119. moveToEndOfLastAtom();
  39120. return false;
  39121. }
  39122. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  39123. {
  39124. if (atomIndex >= currentSection->getNumAtoms())
  39125. {
  39126. if (++sectionIndex >= sections.size())
  39127. {
  39128. moveToEndOfLastAtom();
  39129. return false;
  39130. }
  39131. atomIndex = 0;
  39132. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  39133. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39134. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39135. }
  39136. else
  39137. {
  39138. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  39139. if (! lastAtom->isWhitespace())
  39140. {
  39141. // handle the case where the last atom in a section is actually part of the same
  39142. // word as the first atom of the next section...
  39143. float right = atomRight + lastAtom->width;
  39144. float lineHeight2 = lineHeight;
  39145. float maxDescent2 = maxDescent;
  39146. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  39147. {
  39148. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  39149. if (s->getNumAtoms() == 0)
  39150. break;
  39151. const TextAtom* const nextAtom = s->getAtom (0);
  39152. if (nextAtom->isWhitespace())
  39153. break;
  39154. right += nextAtom->width;
  39155. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  39156. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  39157. if (SHOULD_WRAP (right, wordWrapWidth))
  39158. {
  39159. lineHeight = lineHeight2;
  39160. maxDescent = maxDescent2;
  39161. forceNewLine = true;
  39162. break;
  39163. }
  39164. if (s->getNumAtoms() > 1)
  39165. break;
  39166. }
  39167. }
  39168. }
  39169. }
  39170. if (atom != 0)
  39171. {
  39172. atomX = atomRight;
  39173. indexInText += atom->numChars;
  39174. if (atom->isNewLine())
  39175. {
  39176. atomX = 0;
  39177. lineY += lineHeight;
  39178. }
  39179. }
  39180. atom = currentSection->getAtom (atomIndex);
  39181. atomRight = atomX + atom->width;
  39182. ++atomIndex;
  39183. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  39184. {
  39185. if (atom->isWhitespace())
  39186. {
  39187. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  39188. atomRight = jmin (atomRight, wordWrapWidth);
  39189. }
  39190. else
  39191. {
  39192. return wrapCurrentAtom();
  39193. }
  39194. }
  39195. return true;
  39196. }
  39197. bool wrapCurrentAtom() throw()
  39198. {
  39199. atomRight = atom->width;
  39200. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  39201. {
  39202. tempAtom = *atom;
  39203. tempAtom.width = 0;
  39204. tempAtom.numChars = 0;
  39205. atom = &tempAtom;
  39206. if (atomX > 0)
  39207. {
  39208. atomX = 0;
  39209. lineY += lineHeight;
  39210. }
  39211. return next();
  39212. }
  39213. atomX = 0;
  39214. lineY += lineHeight;
  39215. return true;
  39216. }
  39217. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  39218. {
  39219. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39220. {
  39221. if (lastSection != currentSection)
  39222. {
  39223. lastSection = currentSection;
  39224. g.setColour (currentSection->colour);
  39225. g.setFont (currentSection->font);
  39226. }
  39227. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  39228. GlyphArrangement ga;
  39229. ga.addLineOfText (currentSection->font,
  39230. atom->getTrimmedText (passwordCharacter),
  39231. atomX,
  39232. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39233. ga.draw (g);
  39234. }
  39235. }
  39236. void drawSelection (Graphics& g,
  39237. const int selectionStart,
  39238. const int selectionEnd) const throw()
  39239. {
  39240. const int startX = roundFloatToInt (indexToX (selectionStart));
  39241. const int endX = roundFloatToInt (indexToX (selectionEnd));
  39242. const int y = roundFloatToInt (lineY);
  39243. const int nextY = roundFloatToInt (lineY + lineHeight);
  39244. g.fillRect (startX, y, endX - startX, nextY - y);
  39245. }
  39246. void drawSelectedText (Graphics& g,
  39247. const int selectionStart,
  39248. const int selectionEnd,
  39249. const Colour& selectedTextColour) const throw()
  39250. {
  39251. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39252. {
  39253. GlyphArrangement ga;
  39254. ga.addLineOfText (currentSection->font,
  39255. atom->getTrimmedText (passwordCharacter),
  39256. atomX,
  39257. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39258. if (selectionEnd < indexInText + atom->numChars)
  39259. {
  39260. GlyphArrangement ga2 (ga);
  39261. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  39262. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  39263. g.setColour (currentSection->colour);
  39264. ga2.draw (g);
  39265. }
  39266. if (selectionStart > indexInText)
  39267. {
  39268. GlyphArrangement ga2 (ga);
  39269. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  39270. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  39271. g.setColour (currentSection->colour);
  39272. ga2.draw (g);
  39273. }
  39274. g.setColour (selectedTextColour);
  39275. ga.draw (g);
  39276. }
  39277. }
  39278. float indexToX (const int indexToFind) const throw()
  39279. {
  39280. if (indexToFind <= indexInText)
  39281. return atomX;
  39282. if (indexToFind >= indexInText + atom->numChars)
  39283. return atomRight;
  39284. GlyphArrangement g;
  39285. g.addLineOfText (currentSection->font,
  39286. atom->getText (passwordCharacter),
  39287. atomX, 0.0f);
  39288. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  39289. }
  39290. int xToIndex (const float xToFind) const throw()
  39291. {
  39292. if (xToFind <= atomX || atom->isNewLine())
  39293. return indexInText;
  39294. if (xToFind >= atomRight)
  39295. return indexInText + atom->numChars;
  39296. GlyphArrangement g;
  39297. g.addLineOfText (currentSection->font,
  39298. atom->getText (passwordCharacter),
  39299. atomX, 0.0f);
  39300. int j;
  39301. for (j = 0; j < atom->numChars; ++j)
  39302. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  39303. break;
  39304. return indexInText + j;
  39305. }
  39306. void updateLineHeight() throw()
  39307. {
  39308. float x = atomRight;
  39309. int tempSectionIndex = sectionIndex;
  39310. int tempAtomIndex = atomIndex;
  39311. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39312. while (! SHOULD_WRAP (x, wordWrapWidth))
  39313. {
  39314. if (tempSectionIndex >= sections.size())
  39315. break;
  39316. bool checkSize = false;
  39317. if (tempAtomIndex >= currentSection->getNumAtoms())
  39318. {
  39319. if (++tempSectionIndex >= sections.size())
  39320. break;
  39321. tempAtomIndex = 0;
  39322. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39323. checkSize = true;
  39324. }
  39325. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  39326. if (atom == 0)
  39327. break;
  39328. x += atom->width;
  39329. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  39330. break;
  39331. if (checkSize)
  39332. {
  39333. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39334. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39335. }
  39336. ++tempAtomIndex;
  39337. }
  39338. }
  39339. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  39340. {
  39341. while (next())
  39342. {
  39343. if (indexInText + atom->numChars >= index)
  39344. {
  39345. updateLineHeight();
  39346. if (indexInText + atom->numChars > index)
  39347. {
  39348. cx = indexToX (index);
  39349. cy = lineY;
  39350. lineHeight_ = lineHeight;
  39351. return true;
  39352. }
  39353. }
  39354. }
  39355. cx = atomX;
  39356. cy = lineY;
  39357. lineHeight_ = lineHeight;
  39358. return false;
  39359. }
  39360. juce_UseDebuggingNewOperator
  39361. int indexInText;
  39362. float lineY, lineHeight, maxDescent;
  39363. float atomX, atomRight;
  39364. const TextAtom* atom;
  39365. const UniformTextSection* currentSection;
  39366. private:
  39367. const VoidArray& sections;
  39368. int sectionIndex, atomIndex;
  39369. const float wordWrapWidth;
  39370. const tchar passwordCharacter;
  39371. TextAtom tempAtom;
  39372. const TextEditorIterator& operator= (const TextEditorIterator&);
  39373. void moveToEndOfLastAtom() throw()
  39374. {
  39375. if (atom != 0)
  39376. {
  39377. atomX = atomRight;
  39378. if (atom->isNewLine())
  39379. {
  39380. atomX = 0.0f;
  39381. lineY += lineHeight;
  39382. }
  39383. }
  39384. }
  39385. };
  39386. class TextEditorInsertAction : public UndoableAction
  39387. {
  39388. TextEditor& owner;
  39389. const String text;
  39390. const int insertIndex, oldCaretPos, newCaretPos;
  39391. const Font font;
  39392. const Colour colour;
  39393. TextEditorInsertAction (const TextEditorInsertAction&);
  39394. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  39395. public:
  39396. TextEditorInsertAction (TextEditor& owner_,
  39397. const String& text_,
  39398. const int insertIndex_,
  39399. const Font& font_,
  39400. const Colour& colour_,
  39401. const int oldCaretPos_,
  39402. const int newCaretPos_) throw()
  39403. : owner (owner_),
  39404. text (text_),
  39405. insertIndex (insertIndex_),
  39406. oldCaretPos (oldCaretPos_),
  39407. newCaretPos (newCaretPos_),
  39408. font (font_),
  39409. colour (colour_)
  39410. {
  39411. }
  39412. ~TextEditorInsertAction()
  39413. {
  39414. }
  39415. bool perform()
  39416. {
  39417. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  39418. return true;
  39419. }
  39420. bool undo()
  39421. {
  39422. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  39423. return true;
  39424. }
  39425. int getSizeInUnits()
  39426. {
  39427. return text.length() + 16;
  39428. }
  39429. };
  39430. class TextEditorRemoveAction : public UndoableAction
  39431. {
  39432. TextEditor& owner;
  39433. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  39434. VoidArray removedSections;
  39435. TextEditorRemoveAction (const TextEditorRemoveAction&);
  39436. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  39437. public:
  39438. TextEditorRemoveAction (TextEditor& owner_,
  39439. const int startIndex_,
  39440. const int endIndex_,
  39441. const int oldCaretPos_,
  39442. const int newCaretPos_,
  39443. const VoidArray& removedSections_) throw()
  39444. : owner (owner_),
  39445. startIndex (startIndex_),
  39446. endIndex (endIndex_),
  39447. oldCaretPos (oldCaretPos_),
  39448. newCaretPos (newCaretPos_),
  39449. removedSections (removedSections_)
  39450. {
  39451. }
  39452. ~TextEditorRemoveAction()
  39453. {
  39454. for (int i = removedSections.size(); --i >= 0;)
  39455. {
  39456. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39457. section->clear();
  39458. delete section;
  39459. }
  39460. }
  39461. bool perform()
  39462. {
  39463. owner.remove (startIndex, endIndex, 0, newCaretPos);
  39464. return true;
  39465. }
  39466. bool undo()
  39467. {
  39468. owner.reinsert (startIndex, removedSections);
  39469. owner.moveCursorTo (oldCaretPos, false);
  39470. return true;
  39471. }
  39472. int getSizeInUnits()
  39473. {
  39474. int n = 0;
  39475. for (int i = removedSections.size(); --i >= 0;)
  39476. {
  39477. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39478. n += section->getTotalLength();
  39479. }
  39480. return n + 16;
  39481. }
  39482. };
  39483. class TextHolderComponent : public Component,
  39484. public Timer
  39485. {
  39486. TextEditor* const owner;
  39487. TextHolderComponent (const TextHolderComponent&);
  39488. const TextHolderComponent& operator= (const TextHolderComponent&);
  39489. public:
  39490. TextHolderComponent (TextEditor* const owner_)
  39491. : owner (owner_)
  39492. {
  39493. setWantsKeyboardFocus (false);
  39494. setInterceptsMouseClicks (false, true);
  39495. }
  39496. ~TextHolderComponent()
  39497. {
  39498. }
  39499. void paint (Graphics& g)
  39500. {
  39501. owner->drawContent (g);
  39502. }
  39503. void timerCallback()
  39504. {
  39505. owner->timerCallbackInt();
  39506. }
  39507. const MouseCursor getMouseCursor()
  39508. {
  39509. return owner->getMouseCursor();
  39510. }
  39511. };
  39512. class TextEditorViewport : public Viewport
  39513. {
  39514. TextEditor* const owner;
  39515. float lastWordWrapWidth;
  39516. TextEditorViewport (const TextEditorViewport&);
  39517. const TextEditorViewport& operator= (const TextEditorViewport&);
  39518. public:
  39519. TextEditorViewport (TextEditor* const owner_)
  39520. : owner (owner_),
  39521. lastWordWrapWidth (0)
  39522. {
  39523. }
  39524. ~TextEditorViewport()
  39525. {
  39526. }
  39527. void visibleAreaChanged (int, int, int, int)
  39528. {
  39529. const float wordWrapWidth = owner->getWordWrapWidth();
  39530. if (wordWrapWidth != lastWordWrapWidth)
  39531. {
  39532. lastWordWrapWidth = wordWrapWidth;
  39533. owner->updateTextHolderSize();
  39534. }
  39535. }
  39536. };
  39537. const int flashSpeedIntervalMs = 380;
  39538. const int textChangeMessageId = 0x10003001;
  39539. const int returnKeyMessageId = 0x10003002;
  39540. const int escapeKeyMessageId = 0x10003003;
  39541. const int focusLossMessageId = 0x10003004;
  39542. TextEditor::TextEditor (const String& name,
  39543. const tchar passwordCharacter_)
  39544. : Component (name),
  39545. borderSize (1, 1, 1, 3),
  39546. readOnly (false),
  39547. multiline (false),
  39548. wordWrap (false),
  39549. returnKeyStartsNewLine (false),
  39550. caretVisible (true),
  39551. popupMenuEnabled (true),
  39552. selectAllTextWhenFocused (false),
  39553. scrollbarVisible (true),
  39554. wasFocused (false),
  39555. caretFlashState (true),
  39556. keepCursorOnScreen (true),
  39557. tabKeyUsed (false),
  39558. menuActive (false),
  39559. cursorX (0),
  39560. cursorY (0),
  39561. cursorHeight (0),
  39562. maxTextLength (0),
  39563. selectionStart (0),
  39564. selectionEnd (0),
  39565. leftIndent (4),
  39566. topIndent (4),
  39567. lastTransactionTime (0),
  39568. currentFont (14.0f),
  39569. totalNumChars (0),
  39570. caretPosition (0),
  39571. sections (8),
  39572. passwordCharacter (passwordCharacter_),
  39573. dragType (notDragging),
  39574. listeners (2)
  39575. {
  39576. setOpaque (true);
  39577. addAndMakeVisible (viewport = new TextEditorViewport (this));
  39578. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  39579. viewport->setWantsKeyboardFocus (false);
  39580. viewport->setScrollBarsShown (false, false);
  39581. setMouseCursor (MouseCursor::IBeamCursor);
  39582. setWantsKeyboardFocus (true);
  39583. }
  39584. TextEditor::~TextEditor()
  39585. {
  39586. clearInternal (0);
  39587. delete viewport;
  39588. }
  39589. void TextEditor::newTransaction() throw()
  39590. {
  39591. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39592. undoManager.beginNewTransaction();
  39593. }
  39594. void TextEditor::doUndoRedo (const bool isRedo)
  39595. {
  39596. if (! isReadOnly())
  39597. {
  39598. if ((isRedo) ? undoManager.redo()
  39599. : undoManager.undo())
  39600. {
  39601. scrollToMakeSureCursorIsVisible();
  39602. repaint();
  39603. textChanged();
  39604. }
  39605. }
  39606. }
  39607. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  39608. const bool shouldWordWrap)
  39609. {
  39610. multiline = shouldBeMultiLine;
  39611. wordWrap = shouldWordWrap && shouldBeMultiLine;
  39612. setScrollbarsShown (scrollbarVisible);
  39613. viewport->setViewPosition (0, 0);
  39614. resized();
  39615. scrollToMakeSureCursorIsVisible();
  39616. }
  39617. bool TextEditor::isMultiLine() const throw()
  39618. {
  39619. return multiline;
  39620. }
  39621. void TextEditor::setScrollbarsShown (bool enabled) throw()
  39622. {
  39623. scrollbarVisible = enabled;
  39624. enabled = enabled && isMultiLine();
  39625. viewport->setScrollBarsShown (enabled, enabled);
  39626. }
  39627. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  39628. {
  39629. readOnly = shouldBeReadOnly;
  39630. enablementChanged();
  39631. }
  39632. bool TextEditor::isReadOnly() const throw()
  39633. {
  39634. return readOnly || ! isEnabled();
  39635. }
  39636. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  39637. {
  39638. returnKeyStartsNewLine = shouldStartNewLine;
  39639. }
  39640. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  39641. {
  39642. tabKeyUsed = shouldTabKeyBeUsed;
  39643. }
  39644. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  39645. {
  39646. popupMenuEnabled = b;
  39647. }
  39648. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  39649. {
  39650. selectAllTextWhenFocused = b;
  39651. }
  39652. const Font TextEditor::getFont() const throw()
  39653. {
  39654. return currentFont;
  39655. }
  39656. void TextEditor::setFont (const Font& newFont) throw()
  39657. {
  39658. currentFont = newFont;
  39659. scrollToMakeSureCursorIsVisible();
  39660. }
  39661. void TextEditor::applyFontToAllText (const Font& newFont)
  39662. {
  39663. currentFont = newFont;
  39664. const Colour overallColour (findColour (textColourId));
  39665. for (int i = sections.size(); --i >= 0;)
  39666. {
  39667. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  39668. uts->setFont (newFont, passwordCharacter);
  39669. uts->colour = overallColour;
  39670. }
  39671. coalesceSimilarSections();
  39672. updateTextHolderSize();
  39673. scrollToMakeSureCursorIsVisible();
  39674. repaint();
  39675. }
  39676. void TextEditor::colourChanged()
  39677. {
  39678. setOpaque (findColour (backgroundColourId).isOpaque());
  39679. repaint();
  39680. }
  39681. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  39682. {
  39683. caretVisible = shouldCaretBeVisible;
  39684. if (shouldCaretBeVisible)
  39685. textHolder->startTimer (flashSpeedIntervalMs);
  39686. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  39687. : MouseCursor::NormalCursor);
  39688. }
  39689. void TextEditor::setInputRestrictions (const int maxLen,
  39690. const String& chars) throw()
  39691. {
  39692. maxTextLength = jmax (0, maxLen);
  39693. allowedCharacters = chars;
  39694. }
  39695. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  39696. {
  39697. textToShowWhenEmpty = text;
  39698. colourForTextWhenEmpty = colourToUse;
  39699. }
  39700. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  39701. {
  39702. if (passwordCharacter != newPasswordCharacter)
  39703. {
  39704. passwordCharacter = newPasswordCharacter;
  39705. resized();
  39706. repaint();
  39707. }
  39708. }
  39709. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  39710. {
  39711. viewport->setScrollBarThickness (newThicknessPixels);
  39712. }
  39713. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  39714. {
  39715. viewport->setScrollBarButtonVisibility (buttonsVisible);
  39716. }
  39717. void TextEditor::clear()
  39718. {
  39719. clearInternal (0);
  39720. updateTextHolderSize();
  39721. undoManager.clearUndoHistory();
  39722. }
  39723. void TextEditor::setText (const String& newText,
  39724. const bool sendTextChangeMessage)
  39725. {
  39726. const int newLength = newText.length();
  39727. if (newLength != getTotalNumChars() || getText() != newText)
  39728. {
  39729. const int oldCursorPos = caretPosition;
  39730. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  39731. clearInternal (0);
  39732. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  39733. // if you're adding text with line-feeds to a single-line text editor, it
  39734. // ain't gonna look right!
  39735. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  39736. if (cursorWasAtEnd && ! isMultiLine())
  39737. moveCursorTo (getTotalNumChars(), false);
  39738. else
  39739. moveCursorTo (oldCursorPos, false);
  39740. if (sendTextChangeMessage)
  39741. textChanged();
  39742. repaint();
  39743. }
  39744. updateTextHolderSize();
  39745. scrollToMakeSureCursorIsVisible();
  39746. undoManager.clearUndoHistory();
  39747. }
  39748. void TextEditor::textChanged() throw()
  39749. {
  39750. updateTextHolderSize();
  39751. postCommandMessage (textChangeMessageId);
  39752. }
  39753. void TextEditor::returnPressed()
  39754. {
  39755. postCommandMessage (returnKeyMessageId);
  39756. }
  39757. void TextEditor::escapePressed()
  39758. {
  39759. postCommandMessage (escapeKeyMessageId);
  39760. }
  39761. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  39762. {
  39763. jassert (newListener != 0)
  39764. if (newListener != 0)
  39765. listeners.add (newListener);
  39766. }
  39767. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  39768. {
  39769. listeners.removeValue (listenerToRemove);
  39770. }
  39771. void TextEditor::timerCallbackInt()
  39772. {
  39773. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  39774. if (caretFlashState != newState)
  39775. {
  39776. caretFlashState = newState;
  39777. if (caretFlashState)
  39778. wasFocused = true;
  39779. if (caretVisible
  39780. && hasKeyboardFocus (false)
  39781. && ! isReadOnly())
  39782. {
  39783. repaintCaret();
  39784. }
  39785. }
  39786. const unsigned int now = Time::getApproximateMillisecondCounter();
  39787. if (now > lastTransactionTime + 200)
  39788. newTransaction();
  39789. }
  39790. void TextEditor::repaintCaret()
  39791. {
  39792. if (! findColour (caretColourId).isTransparent())
  39793. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  39794. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  39795. 4,
  39796. roundFloatToInt (cursorHeight) + 2);
  39797. }
  39798. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  39799. {
  39800. if (textStartIndex > textEndIndex && textEndIndex > 0)
  39801. swapVariables (textStartIndex, textEndIndex);
  39802. float x = 0, y = 0, lh = currentFont.getHeight();
  39803. const float wordWrapWidth = getWordWrapWidth();
  39804. if (wordWrapWidth > 0)
  39805. {
  39806. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39807. i.getCharPosition (textStartIndex, x, y, lh);
  39808. const int y1 = (int) y;
  39809. int y2;
  39810. if (textEndIndex >= 0)
  39811. {
  39812. i.getCharPosition (textEndIndex, x, y, lh);
  39813. y2 = (int) (y + lh * 2.0f);
  39814. }
  39815. else
  39816. {
  39817. y2 = textHolder->getHeight();
  39818. }
  39819. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  39820. }
  39821. }
  39822. void TextEditor::moveCaret (int newCaretPos) throw()
  39823. {
  39824. if (newCaretPos < 0)
  39825. newCaretPos = 0;
  39826. else if (newCaretPos > getTotalNumChars())
  39827. newCaretPos = getTotalNumChars();
  39828. if (newCaretPos != getCaretPosition())
  39829. {
  39830. repaintCaret();
  39831. caretFlashState = true;
  39832. caretPosition = newCaretPos;
  39833. textHolder->startTimer (flashSpeedIntervalMs);
  39834. scrollToMakeSureCursorIsVisible();
  39835. repaintCaret();
  39836. }
  39837. }
  39838. void TextEditor::setCaretPosition (const int newIndex) throw()
  39839. {
  39840. moveCursorTo (newIndex, false);
  39841. }
  39842. int TextEditor::getCaretPosition() const throw()
  39843. {
  39844. return caretPosition;
  39845. }
  39846. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  39847. const int desiredCaretY) throw()
  39848. {
  39849. updateCaretPosition();
  39850. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  39851. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  39852. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  39853. {
  39854. vx += desiredCaretX - proportionOfWidth (0.2f);
  39855. }
  39856. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39857. {
  39858. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39859. }
  39860. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  39861. if (! isMultiLine())
  39862. {
  39863. vy = viewport->getViewPositionY();
  39864. }
  39865. else
  39866. {
  39867. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  39868. const int curH = roundFloatToInt (cursorHeight);
  39869. if (desiredCaretY < 0)
  39870. {
  39871. vy = jmax (0, desiredCaretY + vy);
  39872. }
  39873. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39874. {
  39875. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39876. }
  39877. }
  39878. viewport->setViewPosition (vx, vy);
  39879. }
  39880. const Rectangle TextEditor::getCaretRectangle() throw()
  39881. {
  39882. updateCaretPosition();
  39883. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  39884. roundFloatToInt (cursorY) - viewport->getY(),
  39885. 1, roundFloatToInt (cursorHeight));
  39886. }
  39887. float TextEditor::getWordWrapWidth() const throw()
  39888. {
  39889. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  39890. : 1.0e10f;
  39891. }
  39892. void TextEditor::updateTextHolderSize() throw()
  39893. {
  39894. const float wordWrapWidth = getWordWrapWidth();
  39895. if (wordWrapWidth > 0)
  39896. {
  39897. float maxWidth = 0.0f;
  39898. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39899. while (i.next())
  39900. maxWidth = jmax (maxWidth, i.atomRight);
  39901. const int w = leftIndent + roundFloatToInt (maxWidth);
  39902. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  39903. currentFont.getHeight()));
  39904. textHolder->setSize (w + 1, h + 1);
  39905. }
  39906. }
  39907. int TextEditor::getTextWidth() const throw()
  39908. {
  39909. return textHolder->getWidth();
  39910. }
  39911. int TextEditor::getTextHeight() const throw()
  39912. {
  39913. return textHolder->getHeight();
  39914. }
  39915. void TextEditor::setIndents (const int newLeftIndent,
  39916. const int newTopIndent) throw()
  39917. {
  39918. leftIndent = newLeftIndent;
  39919. topIndent = newTopIndent;
  39920. }
  39921. void TextEditor::setBorder (const BorderSize& border) throw()
  39922. {
  39923. borderSize = border;
  39924. resized();
  39925. }
  39926. const BorderSize TextEditor::getBorder() const throw()
  39927. {
  39928. return borderSize;
  39929. }
  39930. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  39931. {
  39932. keepCursorOnScreen = shouldScrollToShowCursor;
  39933. }
  39934. void TextEditor::updateCaretPosition() throw()
  39935. {
  39936. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  39937. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  39938. }
  39939. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  39940. {
  39941. updateCaretPosition();
  39942. if (keepCursorOnScreen)
  39943. {
  39944. int x = viewport->getViewPositionX();
  39945. int y = viewport->getViewPositionY();
  39946. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  39947. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  39948. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  39949. {
  39950. x += relativeCursorX - proportionOfWidth (0.2f);
  39951. }
  39952. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39953. {
  39954. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39955. }
  39956. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  39957. if (! isMultiLine())
  39958. {
  39959. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  39960. }
  39961. else
  39962. {
  39963. const int curH = roundFloatToInt (cursorHeight);
  39964. if (relativeCursorY < 0)
  39965. {
  39966. y = jmax (0, relativeCursorY + y);
  39967. }
  39968. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39969. {
  39970. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39971. }
  39972. }
  39973. viewport->setViewPosition (x, y);
  39974. }
  39975. }
  39976. void TextEditor::moveCursorTo (const int newPosition,
  39977. const bool isSelecting) throw()
  39978. {
  39979. if (isSelecting)
  39980. {
  39981. moveCaret (newPosition);
  39982. const int oldSelStart = selectionStart;
  39983. const int oldSelEnd = selectionEnd;
  39984. if (dragType == notDragging)
  39985. {
  39986. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  39987. dragType = draggingSelectionStart;
  39988. else
  39989. dragType = draggingSelectionEnd;
  39990. }
  39991. if (dragType == draggingSelectionStart)
  39992. {
  39993. selectionStart = getCaretPosition();
  39994. if (selectionEnd < selectionStart)
  39995. {
  39996. swapVariables (selectionStart, selectionEnd);
  39997. dragType = draggingSelectionEnd;
  39998. }
  39999. }
  40000. else
  40001. {
  40002. selectionEnd = getCaretPosition();
  40003. if (selectionEnd < selectionStart)
  40004. {
  40005. swapVariables (selectionStart, selectionEnd);
  40006. dragType = draggingSelectionStart;
  40007. }
  40008. }
  40009. jassert (selectionStart <= selectionEnd);
  40010. jassert (oldSelStart <= oldSelEnd);
  40011. repaintText (jmin (oldSelStart, selectionStart),
  40012. jmax (oldSelEnd, selectionEnd));
  40013. }
  40014. else
  40015. {
  40016. dragType = notDragging;
  40017. if (selectionEnd > selectionStart)
  40018. repaintText (selectionStart, selectionEnd);
  40019. moveCaret (newPosition);
  40020. selectionStart = getCaretPosition();
  40021. selectionEnd = getCaretPosition();
  40022. }
  40023. }
  40024. int TextEditor::getTextIndexAt (const int x,
  40025. const int y) throw()
  40026. {
  40027. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  40028. (float) (y + viewport->getViewPositionY() - topIndent));
  40029. }
  40030. void TextEditor::insertTextAtCursor (String newText)
  40031. {
  40032. if (allowedCharacters.isNotEmpty())
  40033. newText = newText.retainCharacters (allowedCharacters);
  40034. if (! isMultiLine())
  40035. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  40036. else
  40037. newText = newText.replace (T("\r\n"), T("\n"));
  40038. const int newCaretPos = selectionStart + newText.length();
  40039. const int insertIndex = selectionStart;
  40040. remove (selectionStart, selectionEnd,
  40041. &undoManager,
  40042. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  40043. if (maxTextLength > 0)
  40044. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  40045. if (newText.isNotEmpty())
  40046. insert (newText,
  40047. insertIndex,
  40048. currentFont,
  40049. findColour (textColourId),
  40050. &undoManager,
  40051. newCaretPos);
  40052. textChanged();
  40053. }
  40054. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  40055. {
  40056. moveCursorTo (startPos, false);
  40057. moveCursorTo (startPos + numChars, true);
  40058. }
  40059. void TextEditor::copy()
  40060. {
  40061. if (passwordCharacter == 0)
  40062. {
  40063. const String selection (getTextSubstring (selectionStart, selectionEnd));
  40064. if (selection.isNotEmpty())
  40065. SystemClipboard::copyTextToClipboard (selection);
  40066. }
  40067. }
  40068. void TextEditor::paste()
  40069. {
  40070. if (! isReadOnly())
  40071. {
  40072. const String clip (SystemClipboard::getTextFromClipboard());
  40073. if (clip.isNotEmpty())
  40074. insertTextAtCursor (clip);
  40075. }
  40076. }
  40077. void TextEditor::cut()
  40078. {
  40079. if (! isReadOnly())
  40080. {
  40081. moveCaret (selectionEnd);
  40082. insertTextAtCursor (String::empty);
  40083. }
  40084. }
  40085. void TextEditor::drawContent (Graphics& g)
  40086. {
  40087. const float wordWrapWidth = getWordWrapWidth();
  40088. if (wordWrapWidth > 0)
  40089. {
  40090. g.setOrigin (leftIndent, topIndent);
  40091. const Rectangle clip (g.getClipBounds());
  40092. Colour selectedTextColour;
  40093. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40094. while (i.lineY + 200.0 < clip.getY() && i.next())
  40095. {}
  40096. if (selectionStart < selectionEnd)
  40097. {
  40098. g.setColour (findColour (highlightColourId)
  40099. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  40100. selectedTextColour = findColour (highlightedTextColourId);
  40101. TextEditorIterator i2 (i);
  40102. while (i2.next() && i2.lineY < clip.getBottom())
  40103. {
  40104. i2.updateLineHeight();
  40105. if (i2.lineY + i2.lineHeight >= clip.getY()
  40106. && selectionEnd >= i2.indexInText
  40107. && selectionStart <= i2.indexInText + i2.atom->numChars)
  40108. {
  40109. i2.drawSelection (g, selectionStart, selectionEnd);
  40110. }
  40111. }
  40112. }
  40113. const UniformTextSection* lastSection = 0;
  40114. while (i.next() && i.lineY < clip.getBottom())
  40115. {
  40116. i.updateLineHeight();
  40117. if (i.lineY + i.lineHeight >= clip.getY())
  40118. {
  40119. if (selectionEnd >= i.indexInText
  40120. && selectionStart <= i.indexInText + i.atom->numChars)
  40121. {
  40122. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  40123. lastSection = 0;
  40124. }
  40125. else
  40126. {
  40127. i.draw (g, lastSection);
  40128. }
  40129. }
  40130. }
  40131. }
  40132. }
  40133. void TextEditor::paint (Graphics& g)
  40134. {
  40135. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  40136. }
  40137. void TextEditor::paintOverChildren (Graphics& g)
  40138. {
  40139. if (caretFlashState
  40140. && hasKeyboardFocus (false)
  40141. && caretVisible
  40142. && ! isReadOnly())
  40143. {
  40144. g.setColour (findColour (caretColourId));
  40145. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  40146. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  40147. 2.0f, cursorHeight);
  40148. }
  40149. if (textToShowWhenEmpty.isNotEmpty()
  40150. && (! hasKeyboardFocus (false))
  40151. && getTotalNumChars() == 0)
  40152. {
  40153. g.setColour (colourForTextWhenEmpty);
  40154. g.setFont (getFont());
  40155. if (isMultiLine())
  40156. {
  40157. g.drawText (textToShowWhenEmpty,
  40158. 0, 0, getWidth(), getHeight(),
  40159. Justification::centred, true);
  40160. }
  40161. else
  40162. {
  40163. g.drawText (textToShowWhenEmpty,
  40164. leftIndent, topIndent,
  40165. viewport->getWidth() - leftIndent,
  40166. viewport->getHeight() - topIndent,
  40167. Justification::centredLeft, true);
  40168. }
  40169. }
  40170. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  40171. }
  40172. void TextEditor::mouseDown (const MouseEvent& e)
  40173. {
  40174. beginDragAutoRepeat (100);
  40175. newTransaction();
  40176. if (wasFocused || ! selectAllTextWhenFocused)
  40177. {
  40178. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40179. {
  40180. moveCursorTo (getTextIndexAt (e.x, e.y),
  40181. e.mods.isShiftDown());
  40182. }
  40183. else
  40184. {
  40185. PopupMenu m;
  40186. addPopupMenuItems (m, &e);
  40187. menuActive = true;
  40188. const int result = m.show();
  40189. menuActive = false;
  40190. if (result != 0)
  40191. performPopupMenuAction (result);
  40192. }
  40193. }
  40194. }
  40195. void TextEditor::mouseDrag (const MouseEvent& e)
  40196. {
  40197. if (wasFocused || ! selectAllTextWhenFocused)
  40198. {
  40199. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40200. {
  40201. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  40202. }
  40203. }
  40204. }
  40205. void TextEditor::mouseUp (const MouseEvent& e)
  40206. {
  40207. newTransaction();
  40208. textHolder->startTimer (flashSpeedIntervalMs);
  40209. if (wasFocused || ! selectAllTextWhenFocused)
  40210. {
  40211. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40212. {
  40213. moveCaret (getTextIndexAt (e.x, e.y));
  40214. }
  40215. }
  40216. wasFocused = true;
  40217. }
  40218. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  40219. {
  40220. int tokenEnd = getTextIndexAt (e.x, e.y);
  40221. int tokenStart = tokenEnd;
  40222. if (e.getNumberOfClicks() > 3)
  40223. {
  40224. tokenStart = 0;
  40225. tokenEnd = getTotalNumChars();
  40226. }
  40227. else
  40228. {
  40229. const String t (getText());
  40230. const int totalLength = getTotalNumChars();
  40231. while (tokenEnd < totalLength)
  40232. {
  40233. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  40234. ++tokenEnd;
  40235. else
  40236. break;
  40237. }
  40238. tokenStart = tokenEnd;
  40239. while (tokenStart > 0)
  40240. {
  40241. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  40242. --tokenStart;
  40243. else
  40244. break;
  40245. }
  40246. if (e.getNumberOfClicks() > 2)
  40247. {
  40248. while (tokenEnd < totalLength)
  40249. {
  40250. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  40251. ++tokenEnd;
  40252. else
  40253. break;
  40254. }
  40255. while (tokenStart > 0)
  40256. {
  40257. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  40258. --tokenStart;
  40259. else
  40260. break;
  40261. }
  40262. }
  40263. }
  40264. moveCursorTo (tokenEnd, false);
  40265. moveCursorTo (tokenStart, true);
  40266. }
  40267. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40268. {
  40269. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  40270. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40271. }
  40272. bool TextEditor::keyPressed (const KeyPress& key)
  40273. {
  40274. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  40275. return false;
  40276. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  40277. if (key.isKeyCode (KeyPress::leftKey)
  40278. || key.isKeyCode (KeyPress::upKey))
  40279. {
  40280. newTransaction();
  40281. int newPos;
  40282. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  40283. newPos = indexAtPosition (cursorX, cursorY - 1);
  40284. else if (moveInWholeWordSteps)
  40285. newPos = findWordBreakBefore (getCaretPosition());
  40286. else
  40287. newPos = getCaretPosition() - 1;
  40288. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40289. }
  40290. else if (key.isKeyCode (KeyPress::rightKey)
  40291. || key.isKeyCode (KeyPress::downKey))
  40292. {
  40293. newTransaction();
  40294. int newPos;
  40295. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  40296. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  40297. else if (moveInWholeWordSteps)
  40298. newPos = findWordBreakAfter (getCaretPosition());
  40299. else
  40300. newPos = getCaretPosition() + 1;
  40301. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40302. }
  40303. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  40304. {
  40305. newTransaction();
  40306. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  40307. key.getModifiers().isShiftDown());
  40308. }
  40309. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  40310. {
  40311. newTransaction();
  40312. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  40313. key.getModifiers().isShiftDown());
  40314. }
  40315. else if (key.isKeyCode (KeyPress::homeKey))
  40316. {
  40317. newTransaction();
  40318. if (isMultiLine() && ! moveInWholeWordSteps)
  40319. moveCursorTo (indexAtPosition (0.0f, cursorY),
  40320. key.getModifiers().isShiftDown());
  40321. else
  40322. moveCursorTo (0, key.getModifiers().isShiftDown());
  40323. }
  40324. else if (key.isKeyCode (KeyPress::endKey))
  40325. {
  40326. newTransaction();
  40327. if (isMultiLine() && ! moveInWholeWordSteps)
  40328. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  40329. key.getModifiers().isShiftDown());
  40330. else
  40331. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  40332. }
  40333. else if (key.isKeyCode (KeyPress::backspaceKey))
  40334. {
  40335. if (moveInWholeWordSteps)
  40336. {
  40337. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  40338. }
  40339. else
  40340. {
  40341. if (selectionStart == selectionEnd && selectionStart > 0)
  40342. --selectionStart;
  40343. }
  40344. cut();
  40345. }
  40346. else if (key.isKeyCode (KeyPress::deleteKey))
  40347. {
  40348. if (key.getModifiers().isShiftDown())
  40349. copy();
  40350. if (selectionStart == selectionEnd
  40351. && selectionEnd < getTotalNumChars())
  40352. {
  40353. ++selectionEnd;
  40354. }
  40355. cut();
  40356. }
  40357. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  40358. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  40359. {
  40360. newTransaction();
  40361. copy();
  40362. }
  40363. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  40364. {
  40365. newTransaction();
  40366. copy();
  40367. cut();
  40368. }
  40369. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  40370. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  40371. {
  40372. newTransaction();
  40373. paste();
  40374. }
  40375. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  40376. {
  40377. newTransaction();
  40378. doUndoRedo (false);
  40379. }
  40380. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  40381. {
  40382. newTransaction();
  40383. doUndoRedo (true);
  40384. }
  40385. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  40386. {
  40387. newTransaction();
  40388. moveCursorTo (getTotalNumChars(), false);
  40389. moveCursorTo (0, true);
  40390. }
  40391. else if (key == KeyPress::returnKey)
  40392. {
  40393. newTransaction();
  40394. if (returnKeyStartsNewLine)
  40395. insertTextAtCursor (T("\n"));
  40396. else
  40397. returnPressed();
  40398. }
  40399. else if (key.isKeyCode (KeyPress::escapeKey))
  40400. {
  40401. newTransaction();
  40402. moveCursorTo (getCaretPosition(), false);
  40403. escapePressed();
  40404. }
  40405. else if (key.getTextCharacter() >= ' '
  40406. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  40407. {
  40408. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  40409. lastTransactionTime = Time::getApproximateMillisecondCounter();
  40410. }
  40411. else
  40412. {
  40413. return false;
  40414. }
  40415. return true;
  40416. }
  40417. bool TextEditor::keyStateChanged (const bool isKeyDown)
  40418. {
  40419. if (! isKeyDown)
  40420. return false;
  40421. #if JUCE_WIN32
  40422. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  40423. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  40424. #endif
  40425. // (overridden to avoid forwarding key events to the parent)
  40426. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  40427. }
  40428. const int baseMenuItemID = 0x7fff0000;
  40429. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  40430. {
  40431. const bool writable = ! isReadOnly();
  40432. if (passwordCharacter == 0)
  40433. {
  40434. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  40435. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  40436. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  40437. }
  40438. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  40439. m.addSeparator();
  40440. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  40441. m.addSeparator();
  40442. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  40443. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  40444. }
  40445. void TextEditor::performPopupMenuAction (const int menuItemID)
  40446. {
  40447. switch (menuItemID)
  40448. {
  40449. case baseMenuItemID + 1:
  40450. copy();
  40451. cut();
  40452. break;
  40453. case baseMenuItemID + 2:
  40454. copy();
  40455. break;
  40456. case baseMenuItemID + 3:
  40457. paste();
  40458. break;
  40459. case baseMenuItemID + 4:
  40460. cut();
  40461. break;
  40462. case baseMenuItemID + 5:
  40463. moveCursorTo (getTotalNumChars(), false);
  40464. moveCursorTo (0, true);
  40465. break;
  40466. case baseMenuItemID + 6:
  40467. doUndoRedo (false);
  40468. break;
  40469. case baseMenuItemID + 7:
  40470. doUndoRedo (true);
  40471. break;
  40472. default:
  40473. break;
  40474. }
  40475. }
  40476. void TextEditor::focusGained (FocusChangeType)
  40477. {
  40478. newTransaction();
  40479. caretFlashState = true;
  40480. if (selectAllTextWhenFocused)
  40481. {
  40482. moveCursorTo (0, false);
  40483. moveCursorTo (getTotalNumChars(), true);
  40484. }
  40485. repaint();
  40486. if (caretVisible)
  40487. textHolder->startTimer (flashSpeedIntervalMs);
  40488. ComponentPeer* const peer = getPeer();
  40489. if (peer != 0 && ! isReadOnly())
  40490. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  40491. getScreenY() - peer->getScreenY());
  40492. }
  40493. void TextEditor::focusLost (FocusChangeType)
  40494. {
  40495. newTransaction();
  40496. wasFocused = false;
  40497. textHolder->stopTimer();
  40498. caretFlashState = false;
  40499. postCommandMessage (focusLossMessageId);
  40500. repaint();
  40501. }
  40502. void TextEditor::resized()
  40503. {
  40504. viewport->setBoundsInset (borderSize);
  40505. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  40506. updateTextHolderSize();
  40507. if (! isMultiLine())
  40508. {
  40509. scrollToMakeSureCursorIsVisible();
  40510. }
  40511. else
  40512. {
  40513. updateCaretPosition();
  40514. }
  40515. }
  40516. void TextEditor::handleCommandMessage (const int commandId)
  40517. {
  40518. const ComponentDeletionWatcher deletionChecker (this);
  40519. for (int i = listeners.size(); --i >= 0;)
  40520. {
  40521. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  40522. if (tl != 0)
  40523. {
  40524. switch (commandId)
  40525. {
  40526. case textChangeMessageId:
  40527. tl->textEditorTextChanged (*this);
  40528. break;
  40529. case returnKeyMessageId:
  40530. tl->textEditorReturnKeyPressed (*this);
  40531. break;
  40532. case escapeKeyMessageId:
  40533. tl->textEditorEscapeKeyPressed (*this);
  40534. break;
  40535. case focusLossMessageId:
  40536. tl->textEditorFocusLost (*this);
  40537. break;
  40538. default:
  40539. jassertfalse
  40540. break;
  40541. }
  40542. if (i > 0 && deletionChecker.hasBeenDeleted())
  40543. return;
  40544. }
  40545. }
  40546. }
  40547. void TextEditor::enablementChanged()
  40548. {
  40549. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  40550. : MouseCursor::IBeamCursor));
  40551. repaint();
  40552. }
  40553. void TextEditor::clearInternal (UndoManager* const um) throw()
  40554. {
  40555. remove (0, getTotalNumChars(), um, caretPosition);
  40556. }
  40557. void TextEditor::insert (const String& text,
  40558. const int insertIndex,
  40559. const Font& font,
  40560. const Colour& colour,
  40561. UndoManager* const um,
  40562. const int caretPositionToMoveTo) throw()
  40563. {
  40564. if (text.isNotEmpty())
  40565. {
  40566. if (um != 0)
  40567. {
  40568. um->perform (new TextEditorInsertAction (*this,
  40569. text,
  40570. insertIndex,
  40571. font,
  40572. colour,
  40573. caretPosition,
  40574. caretPositionToMoveTo));
  40575. }
  40576. else
  40577. {
  40578. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  40579. // a line gets moved due to word wrap
  40580. int index = 0;
  40581. int nextIndex = 0;
  40582. for (int i = 0; i < sections.size(); ++i)
  40583. {
  40584. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40585. if (insertIndex == index)
  40586. {
  40587. sections.insert (i, new UniformTextSection (text,
  40588. font, colour,
  40589. passwordCharacter));
  40590. break;
  40591. }
  40592. else if (insertIndex > index && insertIndex < nextIndex)
  40593. {
  40594. splitSection (i, insertIndex - index);
  40595. sections.insert (i + 1, new UniformTextSection (text,
  40596. font, colour,
  40597. passwordCharacter));
  40598. break;
  40599. }
  40600. index = nextIndex;
  40601. }
  40602. if (nextIndex == insertIndex)
  40603. sections.add (new UniformTextSection (text,
  40604. font, colour,
  40605. passwordCharacter));
  40606. coalesceSimilarSections();
  40607. totalNumChars = -1;
  40608. moveCursorTo (caretPositionToMoveTo, false);
  40609. repaintText (insertIndex, -1);
  40610. }
  40611. }
  40612. }
  40613. void TextEditor::reinsert (const int insertIndex,
  40614. const VoidArray& sectionsToInsert) throw()
  40615. {
  40616. int index = 0;
  40617. int nextIndex = 0;
  40618. for (int i = 0; i < sections.size(); ++i)
  40619. {
  40620. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40621. if (insertIndex == index)
  40622. {
  40623. for (int j = sectionsToInsert.size(); --j >= 0;)
  40624. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40625. break;
  40626. }
  40627. else if (insertIndex > index && insertIndex < nextIndex)
  40628. {
  40629. splitSection (i, insertIndex - index);
  40630. for (int j = sectionsToInsert.size(); --j >= 0;)
  40631. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40632. break;
  40633. }
  40634. index = nextIndex;
  40635. }
  40636. if (nextIndex == insertIndex)
  40637. {
  40638. for (int j = 0; j < sectionsToInsert.size(); ++j)
  40639. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40640. }
  40641. coalesceSimilarSections();
  40642. totalNumChars = -1;
  40643. }
  40644. void TextEditor::remove (const int startIndex,
  40645. int endIndex,
  40646. UndoManager* const um,
  40647. const int caretPositionToMoveTo) throw()
  40648. {
  40649. if (endIndex > startIndex)
  40650. {
  40651. int index = 0;
  40652. for (int i = 0; i < sections.size(); ++i)
  40653. {
  40654. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  40655. if (startIndex > index && startIndex < nextIndex)
  40656. {
  40657. splitSection (i, startIndex - index);
  40658. --i;
  40659. }
  40660. else if (endIndex > index && endIndex < nextIndex)
  40661. {
  40662. splitSection (i, endIndex - index);
  40663. --i;
  40664. }
  40665. else
  40666. {
  40667. index = nextIndex;
  40668. if (index > endIndex)
  40669. break;
  40670. }
  40671. }
  40672. index = 0;
  40673. if (um != 0)
  40674. {
  40675. VoidArray removedSections;
  40676. for (int i = 0; i < sections.size(); ++i)
  40677. {
  40678. if (endIndex <= startIndex)
  40679. break;
  40680. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40681. const int nextIndex = index + section->getTotalLength();
  40682. if (startIndex <= index && endIndex >= nextIndex)
  40683. removedSections.add (new UniformTextSection (*section));
  40684. index = nextIndex;
  40685. }
  40686. um->perform (new TextEditorRemoveAction (*this,
  40687. startIndex,
  40688. endIndex,
  40689. caretPosition,
  40690. caretPositionToMoveTo,
  40691. removedSections));
  40692. }
  40693. else
  40694. {
  40695. for (int i = 0; i < sections.size(); ++i)
  40696. {
  40697. if (endIndex <= startIndex)
  40698. break;
  40699. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40700. const int nextIndex = index + section->getTotalLength();
  40701. if (startIndex <= index && endIndex >= nextIndex)
  40702. {
  40703. sections.remove(i);
  40704. endIndex -= (nextIndex - index);
  40705. section->clear();
  40706. delete section;
  40707. --i;
  40708. }
  40709. else
  40710. {
  40711. index = nextIndex;
  40712. }
  40713. }
  40714. coalesceSimilarSections();
  40715. totalNumChars = -1;
  40716. moveCursorTo (caretPositionToMoveTo, false);
  40717. repaintText (startIndex, -1);
  40718. }
  40719. }
  40720. }
  40721. const String TextEditor::getText() const throw()
  40722. {
  40723. String t;
  40724. for (int i = 0; i < sections.size(); ++i)
  40725. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  40726. return t;
  40727. }
  40728. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  40729. {
  40730. String t;
  40731. int index = 0;
  40732. for (int i = 0; i < sections.size(); ++i)
  40733. {
  40734. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  40735. const int nextIndex = index + s->getTotalLength();
  40736. if (startCharacter < nextIndex)
  40737. {
  40738. if (endCharacter <= index)
  40739. break;
  40740. const int start = jmax (index, startCharacter);
  40741. t += s->getTextSubstring (start - index, endCharacter - index);
  40742. }
  40743. index = nextIndex;
  40744. }
  40745. return t;
  40746. }
  40747. const String TextEditor::getHighlightedText() const throw()
  40748. {
  40749. return getTextSubstring (getHighlightedRegionStart(),
  40750. getHighlightedRegionStart() + getHighlightedRegionLength());
  40751. }
  40752. int TextEditor::getTotalNumChars() throw()
  40753. {
  40754. if (totalNumChars < 0)
  40755. {
  40756. totalNumChars = 0;
  40757. for (int i = sections.size(); --i >= 0;)
  40758. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40759. }
  40760. return totalNumChars;
  40761. }
  40762. bool TextEditor::isEmpty() const throw()
  40763. {
  40764. if (totalNumChars != 0)
  40765. {
  40766. for (int i = sections.size(); --i >= 0;)
  40767. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  40768. return false;
  40769. }
  40770. return true;
  40771. }
  40772. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  40773. {
  40774. const float wordWrapWidth = getWordWrapWidth();
  40775. if (wordWrapWidth > 0 && sections.size() > 0)
  40776. {
  40777. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40778. i.getCharPosition (index, cx, cy, lineHeight);
  40779. }
  40780. else
  40781. {
  40782. cx = cy = 0;
  40783. lineHeight = currentFont.getHeight();
  40784. }
  40785. }
  40786. int TextEditor::indexAtPosition (const float x, const float y) throw()
  40787. {
  40788. const float wordWrapWidth = getWordWrapWidth();
  40789. if (wordWrapWidth > 0)
  40790. {
  40791. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40792. while (i.next())
  40793. {
  40794. if (i.lineY + getHeight() > y)
  40795. i.updateLineHeight();
  40796. if (i.lineY + i.lineHeight > y)
  40797. {
  40798. if (i.lineY > y)
  40799. return jmax (0, i.indexInText - 1);
  40800. if (i.atomX >= x)
  40801. return i.indexInText;
  40802. if (x < i.atomRight)
  40803. return i.xToIndex (x);
  40804. }
  40805. }
  40806. }
  40807. return getTotalNumChars();
  40808. }
  40809. static int getCharacterCategory (const tchar character) throw()
  40810. {
  40811. return CharacterFunctions::isLetterOrDigit (character)
  40812. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  40813. }
  40814. int TextEditor::findWordBreakAfter (const int position) const throw()
  40815. {
  40816. const String t (getTextSubstring (position, position + 512));
  40817. const int totalLength = t.length();
  40818. int i = 0;
  40819. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40820. ++i;
  40821. const int type = getCharacterCategory (t[i]);
  40822. while (i < totalLength && type == getCharacterCategory (t[i]))
  40823. ++i;
  40824. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40825. ++i;
  40826. return position + i;
  40827. }
  40828. int TextEditor::findWordBreakBefore (const int position) const throw()
  40829. {
  40830. if (position <= 0)
  40831. return 0;
  40832. const int startOfBuffer = jmax (0, position - 512);
  40833. const String t (getTextSubstring (startOfBuffer, position));
  40834. int i = position - startOfBuffer;
  40835. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  40836. --i;
  40837. if (i > 0)
  40838. {
  40839. const int type = getCharacterCategory (t [i - 1]);
  40840. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  40841. --i;
  40842. }
  40843. jassert (startOfBuffer + i >= 0);
  40844. return startOfBuffer + i;
  40845. }
  40846. void TextEditor::splitSection (const int sectionIndex,
  40847. const int charToSplitAt) throw()
  40848. {
  40849. jassert (sections[sectionIndex] != 0);
  40850. sections.insert (sectionIndex + 1,
  40851. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  40852. ->split (charToSplitAt, passwordCharacter));
  40853. }
  40854. void TextEditor::coalesceSimilarSections() throw()
  40855. {
  40856. for (int i = 0; i < sections.size() - 1; ++i)
  40857. {
  40858. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  40859. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  40860. if (s1->font == s2->font
  40861. && s1->colour == s2->colour)
  40862. {
  40863. s1->append (*s2, passwordCharacter);
  40864. sections.remove (i + 1);
  40865. delete s2;
  40866. --i;
  40867. }
  40868. }
  40869. }
  40870. END_JUCE_NAMESPACE
  40871. /********* End of inlined file: juce_TextEditor.cpp *********/
  40872. /********* Start of inlined file: juce_Toolbar.cpp *********/
  40873. BEGIN_JUCE_NAMESPACE
  40874. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  40875. class ToolbarSpacerComp : public ToolbarItemComponent
  40876. {
  40877. public:
  40878. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  40879. : ToolbarItemComponent (itemId, String::empty, false),
  40880. fixedSize (fixedSize_),
  40881. drawBar (drawBar_)
  40882. {
  40883. }
  40884. ~ToolbarSpacerComp()
  40885. {
  40886. }
  40887. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  40888. int& preferredSize, int& minSize, int& maxSize)
  40889. {
  40890. if (fixedSize <= 0)
  40891. {
  40892. preferredSize = toolbarThickness * 2;
  40893. minSize = 4;
  40894. maxSize = 32768;
  40895. }
  40896. else
  40897. {
  40898. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  40899. minSize = drawBar ? maxSize : jmin (4, maxSize);
  40900. preferredSize = maxSize;
  40901. if (getEditingMode() == editableOnPalette)
  40902. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  40903. }
  40904. return true;
  40905. }
  40906. void paintButtonArea (Graphics&, int, int, bool, bool)
  40907. {
  40908. }
  40909. void contentAreaChanged (const Rectangle&)
  40910. {
  40911. }
  40912. int getResizeOrder() const throw()
  40913. {
  40914. return fixedSize <= 0 ? 0 : 1;
  40915. }
  40916. void paint (Graphics& g)
  40917. {
  40918. const int w = getWidth();
  40919. const int h = getHeight();
  40920. if (drawBar)
  40921. {
  40922. g.setColour (findColour (Toolbar::separatorColourId, true));
  40923. const float thickness = 0.2f;
  40924. if (isToolbarVertical())
  40925. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  40926. else
  40927. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  40928. }
  40929. if (getEditingMode() != normalMode && ! drawBar)
  40930. {
  40931. g.setColour (findColour (Toolbar::separatorColourId, true));
  40932. const int indentX = jmin (2, (w - 3) / 2);
  40933. const int indentY = jmin (2, (h - 3) / 2);
  40934. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  40935. if (fixedSize <= 0)
  40936. {
  40937. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  40938. if (isToolbarVertical())
  40939. {
  40940. x1 = w * 0.5f;
  40941. y1 = h * 0.4f;
  40942. x2 = x1;
  40943. y2 = indentX * 2.0f;
  40944. x3 = x1;
  40945. y3 = h * 0.6f;
  40946. x4 = x1;
  40947. y4 = h - y2;
  40948. hw = w * 0.15f;
  40949. hl = w * 0.2f;
  40950. }
  40951. else
  40952. {
  40953. x1 = w * 0.4f;
  40954. y1 = h * 0.5f;
  40955. x2 = indentX * 2.0f;
  40956. y2 = y1;
  40957. x3 = w * 0.6f;
  40958. y3 = y1;
  40959. x4 = w - x2;
  40960. y4 = y1;
  40961. hw = h * 0.15f;
  40962. hl = h * 0.2f;
  40963. }
  40964. Path p;
  40965. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  40966. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  40967. g.fillPath (p);
  40968. }
  40969. }
  40970. }
  40971. juce_UseDebuggingNewOperator
  40972. private:
  40973. const float fixedSize;
  40974. const bool drawBar;
  40975. ToolbarSpacerComp (const ToolbarSpacerComp&);
  40976. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  40977. };
  40978. class MissingItemsComponent : public PopupMenuCustomComponent
  40979. {
  40980. public:
  40981. MissingItemsComponent (Toolbar& owner_, const int height_)
  40982. : PopupMenuCustomComponent (true),
  40983. owner (owner_),
  40984. height (height_)
  40985. {
  40986. for (int i = owner_.items.size(); --i >= 0;)
  40987. {
  40988. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  40989. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  40990. {
  40991. oldIndexes.insert (0, i);
  40992. addAndMakeVisible (tc, 0);
  40993. }
  40994. }
  40995. layout (400);
  40996. }
  40997. ~MissingItemsComponent()
  40998. {
  40999. // deleting the toolbar while its menu it open??
  41000. jassert (owner.isValidComponent());
  41001. for (int i = 0; i < getNumChildComponents(); ++i)
  41002. {
  41003. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  41004. if (tc != 0)
  41005. {
  41006. tc->setVisible (false);
  41007. const int index = oldIndexes.remove (i);
  41008. owner.addChildComponent (tc, index);
  41009. --i;
  41010. }
  41011. }
  41012. owner.resized();
  41013. }
  41014. void layout (const int preferredWidth)
  41015. {
  41016. const int indent = 8;
  41017. int x = indent;
  41018. int y = indent;
  41019. int maxX = 0;
  41020. for (int i = 0; i < getNumChildComponents(); ++i)
  41021. {
  41022. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  41023. if (tc != 0)
  41024. {
  41025. int preferredSize = 1, minSize = 1, maxSize = 1;
  41026. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41027. {
  41028. if (x + preferredSize > preferredWidth && x > indent)
  41029. {
  41030. x = indent;
  41031. y += height;
  41032. }
  41033. tc->setBounds (x, y, preferredSize, height);
  41034. x += preferredSize;
  41035. maxX = jmax (maxX, x);
  41036. }
  41037. }
  41038. }
  41039. setSize (maxX + 8, y + height + 8);
  41040. }
  41041. void getIdealSize (int& idealWidth, int& idealHeight)
  41042. {
  41043. idealWidth = getWidth();
  41044. idealHeight = getHeight();
  41045. }
  41046. juce_UseDebuggingNewOperator
  41047. private:
  41048. Toolbar& owner;
  41049. const int height;
  41050. Array <int> oldIndexes;
  41051. MissingItemsComponent (const MissingItemsComponent&);
  41052. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  41053. };
  41054. Toolbar::Toolbar()
  41055. : vertical (false),
  41056. isEditingActive (false),
  41057. toolbarStyle (Toolbar::iconsOnly)
  41058. {
  41059. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  41060. missingItemsButton->setAlwaysOnTop (true);
  41061. missingItemsButton->addButtonListener (this);
  41062. }
  41063. Toolbar::~Toolbar()
  41064. {
  41065. animator.cancelAllAnimations (true);
  41066. deleteAllChildren();
  41067. }
  41068. void Toolbar::setVertical (const bool shouldBeVertical)
  41069. {
  41070. if (vertical != shouldBeVertical)
  41071. {
  41072. vertical = shouldBeVertical;
  41073. resized();
  41074. }
  41075. }
  41076. void Toolbar::clear()
  41077. {
  41078. for (int i = items.size(); --i >= 0;)
  41079. {
  41080. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41081. items.remove (i);
  41082. delete tc;
  41083. }
  41084. resized();
  41085. }
  41086. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  41087. {
  41088. if (itemId == ToolbarItemFactory::separatorBarId)
  41089. return new ToolbarSpacerComp (itemId, 0.1f, true);
  41090. else if (itemId == ToolbarItemFactory::spacerId)
  41091. return new ToolbarSpacerComp (itemId, 0.5f, false);
  41092. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  41093. return new ToolbarSpacerComp (itemId, 0, false);
  41094. return factory.createItem (itemId);
  41095. }
  41096. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  41097. const int itemId,
  41098. const int insertIndex)
  41099. {
  41100. // An ID can't be zero - this might indicate a mistake somewhere?
  41101. jassert (itemId != 0);
  41102. ToolbarItemComponent* const tc = createItem (factory, itemId);
  41103. if (tc != 0)
  41104. {
  41105. #ifdef JUCE_DEBUG
  41106. Array <int> allowedIds;
  41107. factory.getAllToolbarItemIds (allowedIds);
  41108. // If your factory can create an item for a given ID, it must also return
  41109. // that ID from its getAllToolbarItemIds() method!
  41110. jassert (allowedIds.contains (itemId));
  41111. #endif
  41112. items.insert (insertIndex, tc);
  41113. addAndMakeVisible (tc, insertIndex);
  41114. }
  41115. }
  41116. void Toolbar::addItem (ToolbarItemFactory& factory,
  41117. const int itemId,
  41118. const int insertIndex)
  41119. {
  41120. addItemInternal (factory, itemId, insertIndex);
  41121. resized();
  41122. }
  41123. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  41124. {
  41125. Array <int> ids;
  41126. factoryToUse.getDefaultItemSet (ids);
  41127. clear();
  41128. for (int i = 0; i < ids.size(); ++i)
  41129. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  41130. resized();
  41131. }
  41132. void Toolbar::removeToolbarItem (const int itemIndex)
  41133. {
  41134. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41135. if (tc != 0)
  41136. {
  41137. items.removeValue (tc);
  41138. delete tc;
  41139. resized();
  41140. }
  41141. }
  41142. int Toolbar::getNumItems() const throw()
  41143. {
  41144. return items.size();
  41145. }
  41146. int Toolbar::getItemId (const int itemIndex) const throw()
  41147. {
  41148. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41149. return tc != 0 ? tc->getItemId() : 0;
  41150. }
  41151. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  41152. {
  41153. return items [itemIndex];
  41154. }
  41155. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  41156. {
  41157. for (;;)
  41158. {
  41159. index += delta;
  41160. ToolbarItemComponent* const tc = getItemComponent (index);
  41161. if (tc == 0)
  41162. break;
  41163. if (tc->isActive)
  41164. return tc;
  41165. }
  41166. return 0;
  41167. }
  41168. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  41169. {
  41170. if (toolbarStyle != newStyle)
  41171. {
  41172. toolbarStyle = newStyle;
  41173. updateAllItemPositions (false);
  41174. }
  41175. }
  41176. const String Toolbar::toString() const
  41177. {
  41178. String s (T("TB:"));
  41179. for (int i = 0; i < getNumItems(); ++i)
  41180. s << getItemId(i) << T(' ');
  41181. return s.trimEnd();
  41182. }
  41183. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  41184. const String& savedVersion)
  41185. {
  41186. if (! savedVersion.startsWith (T("TB:")))
  41187. return false;
  41188. StringArray tokens;
  41189. tokens.addTokens (savedVersion.substring (3), false);
  41190. clear();
  41191. for (int i = 0; i < tokens.size(); ++i)
  41192. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  41193. resized();
  41194. return true;
  41195. }
  41196. void Toolbar::paint (Graphics& g)
  41197. {
  41198. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  41199. }
  41200. int Toolbar::getThickness() const throw()
  41201. {
  41202. return vertical ? getWidth() : getHeight();
  41203. }
  41204. int Toolbar::getLength() const throw()
  41205. {
  41206. return vertical ? getHeight() : getWidth();
  41207. }
  41208. void Toolbar::setEditingActive (const bool active)
  41209. {
  41210. if (isEditingActive != active)
  41211. {
  41212. isEditingActive = active;
  41213. updateAllItemPositions (false);
  41214. }
  41215. }
  41216. void Toolbar::resized()
  41217. {
  41218. updateAllItemPositions (false);
  41219. }
  41220. void Toolbar::updateAllItemPositions (const bool animate)
  41221. {
  41222. if (getWidth() > 0 && getHeight() > 0)
  41223. {
  41224. StretchableObjectResizer resizer;
  41225. int i;
  41226. for (i = 0; i < items.size(); ++i)
  41227. {
  41228. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41229. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  41230. : ToolbarItemComponent::normalMode);
  41231. tc->setStyle (toolbarStyle);
  41232. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  41233. int preferredSize = 1, minSize = 1, maxSize = 1;
  41234. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  41235. preferredSize, minSize, maxSize))
  41236. {
  41237. tc->isActive = true;
  41238. resizer.addItem (preferredSize, minSize, maxSize,
  41239. spacer != 0 ? spacer->getResizeOrder() : 2);
  41240. }
  41241. else
  41242. {
  41243. tc->isActive = false;
  41244. tc->setVisible (false);
  41245. }
  41246. }
  41247. resizer.resizeToFit (getLength());
  41248. int totalLength = 0;
  41249. for (i = 0; i < resizer.getNumItems(); ++i)
  41250. totalLength += (int) resizer.getItemSize (i);
  41251. const bool itemsOffTheEnd = totalLength > getLength();
  41252. const int extrasButtonSize = getThickness() / 2;
  41253. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  41254. missingItemsButton->setVisible (itemsOffTheEnd);
  41255. missingItemsButton->setEnabled (! isEditingActive);
  41256. if (vertical)
  41257. missingItemsButton->setCentrePosition (getWidth() / 2,
  41258. getHeight() - 4 - extrasButtonSize / 2);
  41259. else
  41260. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  41261. getHeight() / 2);
  41262. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  41263. : missingItemsButton->getX()) - 4
  41264. : getLength();
  41265. int pos = 0, activeIndex = 0;
  41266. for (i = 0; i < items.size(); ++i)
  41267. {
  41268. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41269. if (tc->isActive)
  41270. {
  41271. const int size = (int) resizer.getItemSize (activeIndex++);
  41272. Rectangle newBounds;
  41273. if (vertical)
  41274. newBounds.setBounds (0, pos, getWidth(), size);
  41275. else
  41276. newBounds.setBounds (pos, 0, size, getHeight());
  41277. if (animate)
  41278. {
  41279. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  41280. }
  41281. else
  41282. {
  41283. animator.cancelAnimation (tc, false);
  41284. tc->setBounds (newBounds);
  41285. }
  41286. pos += size;
  41287. tc->setVisible (pos <= maxLength
  41288. && ((! tc->isBeingDragged)
  41289. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  41290. }
  41291. }
  41292. }
  41293. }
  41294. void Toolbar::buttonClicked (Button*)
  41295. {
  41296. jassert (missingItemsButton->isShowing());
  41297. if (missingItemsButton->isShowing())
  41298. {
  41299. PopupMenu m;
  41300. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  41301. m.showAt (missingItemsButton);
  41302. }
  41303. }
  41304. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  41305. Component* /*sourceComponent*/)
  41306. {
  41307. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  41308. }
  41309. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  41310. {
  41311. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41312. if (tc != 0)
  41313. {
  41314. if (getNumItems() == 0)
  41315. {
  41316. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41317. {
  41318. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41319. if (palette != 0)
  41320. palette->replaceComponent (tc);
  41321. }
  41322. else
  41323. {
  41324. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41325. }
  41326. items.add (tc);
  41327. addChildComponent (tc);
  41328. updateAllItemPositions (false);
  41329. }
  41330. else
  41331. {
  41332. for (int i = getNumItems(); --i >= 0;)
  41333. {
  41334. int currentIndex = getIndexOfChildComponent (tc);
  41335. if (currentIndex < 0)
  41336. {
  41337. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41338. {
  41339. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41340. if (palette != 0)
  41341. palette->replaceComponent (tc);
  41342. }
  41343. else
  41344. {
  41345. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41346. }
  41347. items.add (tc);
  41348. addChildComponent (tc);
  41349. currentIndex = getIndexOfChildComponent (tc);
  41350. updateAllItemPositions (true);
  41351. }
  41352. int newIndex = currentIndex;
  41353. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  41354. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  41355. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  41356. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  41357. if (prev != 0)
  41358. {
  41359. const Rectangle previousPos (animator.getComponentDestination (prev));
  41360. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  41361. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  41362. {
  41363. newIndex = getIndexOfChildComponent (prev);
  41364. }
  41365. }
  41366. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  41367. if (next != 0)
  41368. {
  41369. const Rectangle nextPos (animator.getComponentDestination (next));
  41370. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  41371. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  41372. {
  41373. newIndex = getIndexOfChildComponent (next) + 1;
  41374. }
  41375. }
  41376. if (newIndex != currentIndex)
  41377. {
  41378. items.removeValue (tc);
  41379. removeChildComponent (tc);
  41380. addChildComponent (tc, newIndex);
  41381. items.insert (newIndex, tc);
  41382. updateAllItemPositions (true);
  41383. }
  41384. else
  41385. {
  41386. break;
  41387. }
  41388. }
  41389. }
  41390. }
  41391. }
  41392. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  41393. {
  41394. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41395. if (tc != 0)
  41396. {
  41397. if (isParentOf (tc))
  41398. {
  41399. items.removeValue (tc);
  41400. removeChildComponent (tc);
  41401. updateAllItemPositions (true);
  41402. }
  41403. }
  41404. }
  41405. void Toolbar::itemDropped (const String&, Component*, int, int)
  41406. {
  41407. }
  41408. void Toolbar::mouseDown (const MouseEvent& e)
  41409. {
  41410. if (e.mods.isPopupMenu())
  41411. {
  41412. }
  41413. }
  41414. class ToolbarCustomisationDialog : public DialogWindow
  41415. {
  41416. public:
  41417. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  41418. Toolbar* const toolbar_,
  41419. const int optionFlags)
  41420. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  41421. toolbar (toolbar_)
  41422. {
  41423. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  41424. setResizable (true, true);
  41425. setResizeLimits (400, 300, 1500, 1000);
  41426. positionNearBar();
  41427. }
  41428. ~ToolbarCustomisationDialog()
  41429. {
  41430. setContentComponent (0, true);
  41431. }
  41432. void closeButtonPressed()
  41433. {
  41434. setVisible (false);
  41435. }
  41436. bool canModalEventBeSentToComponent (const Component* comp)
  41437. {
  41438. return toolbar->isParentOf (comp);
  41439. }
  41440. void positionNearBar()
  41441. {
  41442. const Rectangle screenSize (toolbar->getParentMonitorArea());
  41443. const int tbx = toolbar->getScreenX();
  41444. const int tby = toolbar->getScreenY();
  41445. const int gap = 8;
  41446. int x, y;
  41447. if (toolbar->isVertical())
  41448. {
  41449. y = tby;
  41450. if (tbx > screenSize.getCentreX())
  41451. x = tbx - getWidth() - gap;
  41452. else
  41453. x = tbx + toolbar->getWidth() + gap;
  41454. }
  41455. else
  41456. {
  41457. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  41458. if (tby > screenSize.getCentreY())
  41459. y = tby - getHeight() - gap;
  41460. else
  41461. y = tby + toolbar->getHeight() + gap;
  41462. }
  41463. setTopLeftPosition (x, y);
  41464. }
  41465. private:
  41466. Toolbar* const toolbar;
  41467. class CustomiserPanel : public Component,
  41468. private ComboBoxListener,
  41469. private ButtonListener
  41470. {
  41471. public:
  41472. CustomiserPanel (ToolbarItemFactory& factory_,
  41473. Toolbar* const toolbar_,
  41474. const int optionFlags)
  41475. : factory (factory_),
  41476. toolbar (toolbar_),
  41477. styleBox (0),
  41478. defaultButton (0)
  41479. {
  41480. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  41481. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  41482. | Toolbar::allowIconsWithTextChoice
  41483. | Toolbar::allowTextOnlyChoice)) != 0)
  41484. {
  41485. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  41486. styleBox->setEditableText (false);
  41487. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  41488. styleBox->addItem (TRANS("Show icons only"), 1);
  41489. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  41490. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  41491. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  41492. styleBox->addItem (TRANS("Show descriptions only"), 3);
  41493. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  41494. styleBox->setSelectedId (1);
  41495. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  41496. styleBox->setSelectedId (2);
  41497. else if (toolbar_->getStyle() == Toolbar::textOnly)
  41498. styleBox->setSelectedId (3);
  41499. styleBox->addListener (this);
  41500. }
  41501. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  41502. {
  41503. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  41504. defaultButton->addButtonListener (this);
  41505. }
  41506. addAndMakeVisible (instructions = new Label (String::empty,
  41507. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  41508. instructions->setFont (Font (13.0f));
  41509. setSize (500, 300);
  41510. }
  41511. ~CustomiserPanel()
  41512. {
  41513. deleteAllChildren();
  41514. }
  41515. void comboBoxChanged (ComboBox*)
  41516. {
  41517. if (styleBox->getSelectedId() == 1)
  41518. toolbar->setStyle (Toolbar::iconsOnly);
  41519. else if (styleBox->getSelectedId() == 2)
  41520. toolbar->setStyle (Toolbar::iconsWithText);
  41521. else if (styleBox->getSelectedId() == 3)
  41522. toolbar->setStyle (Toolbar::textOnly);
  41523. palette->resized(); // to make it update the styles
  41524. }
  41525. void buttonClicked (Button*)
  41526. {
  41527. toolbar->addDefaultItems (factory);
  41528. }
  41529. void paint (Graphics& g)
  41530. {
  41531. Colour background;
  41532. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  41533. if (dw != 0)
  41534. background = dw->getBackgroundColour();
  41535. g.setColour (background.contrasting().withAlpha (0.3f));
  41536. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  41537. }
  41538. void resized()
  41539. {
  41540. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  41541. if (styleBox != 0)
  41542. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  41543. if (defaultButton != 0)
  41544. {
  41545. defaultButton->changeWidthToFitText (22);
  41546. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  41547. }
  41548. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  41549. }
  41550. private:
  41551. ToolbarItemFactory& factory;
  41552. Toolbar* const toolbar;
  41553. Label* instructions;
  41554. ToolbarItemPalette* palette;
  41555. ComboBox* styleBox;
  41556. TextButton* defaultButton;
  41557. };
  41558. };
  41559. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  41560. {
  41561. setEditingActive (true);
  41562. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  41563. dw.runModalLoop();
  41564. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  41565. setEditingActive (false);
  41566. }
  41567. END_JUCE_NAMESPACE
  41568. /********* End of inlined file: juce_Toolbar.cpp *********/
  41569. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  41570. BEGIN_JUCE_NAMESPACE
  41571. ToolbarItemFactory::ToolbarItemFactory()
  41572. {
  41573. }
  41574. ToolbarItemFactory::~ToolbarItemFactory()
  41575. {
  41576. }
  41577. class ItemDragAndDropOverlayComponent : public Component
  41578. {
  41579. public:
  41580. ItemDragAndDropOverlayComponent()
  41581. : isDragging (false)
  41582. {
  41583. setAlwaysOnTop (true);
  41584. setRepaintsOnMouseActivity (true);
  41585. setMouseCursor (MouseCursor::DraggingHandCursor);
  41586. }
  41587. ~ItemDragAndDropOverlayComponent()
  41588. {
  41589. }
  41590. void paint (Graphics& g)
  41591. {
  41592. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41593. if (isMouseOverOrDragging()
  41594. && tc != 0
  41595. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41596. {
  41597. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  41598. g.drawRect (0, 0, getWidth(), getHeight(),
  41599. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  41600. }
  41601. }
  41602. void mouseDown (const MouseEvent& e)
  41603. {
  41604. isDragging = false;
  41605. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41606. if (tc != 0)
  41607. {
  41608. tc->dragOffsetX = e.x;
  41609. tc->dragOffsetY = e.y;
  41610. }
  41611. }
  41612. void mouseDrag (const MouseEvent& e)
  41613. {
  41614. if (! (isDragging || e.mouseWasClicked()))
  41615. {
  41616. isDragging = true;
  41617. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  41618. if (dnd != 0)
  41619. {
  41620. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  41621. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41622. if (tc != 0)
  41623. {
  41624. tc->isBeingDragged = true;
  41625. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41626. tc->setVisible (false);
  41627. }
  41628. }
  41629. }
  41630. }
  41631. void mouseUp (const MouseEvent&)
  41632. {
  41633. isDragging = false;
  41634. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41635. if (tc != 0)
  41636. {
  41637. tc->isBeingDragged = false;
  41638. Toolbar* const tb = tc->getToolbar();
  41639. if (tb != 0)
  41640. tb->updateAllItemPositions (true);
  41641. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41642. delete tc;
  41643. }
  41644. }
  41645. void parentSizeChanged()
  41646. {
  41647. setBounds (0, 0, getParentWidth(), getParentHeight());
  41648. }
  41649. juce_UseDebuggingNewOperator
  41650. private:
  41651. bool isDragging;
  41652. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  41653. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  41654. };
  41655. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  41656. const String& labelText,
  41657. const bool isBeingUsedAsAButton_)
  41658. : Button (labelText),
  41659. itemId (itemId_),
  41660. mode (normalMode),
  41661. toolbarStyle (Toolbar::iconsOnly),
  41662. overlayComp (0),
  41663. dragOffsetX (0),
  41664. dragOffsetY (0),
  41665. isActive (true),
  41666. isBeingDragged (false),
  41667. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  41668. {
  41669. // Your item ID can't be 0!
  41670. jassert (itemId_ != 0);
  41671. }
  41672. ToolbarItemComponent::~ToolbarItemComponent()
  41673. {
  41674. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41675. delete overlayComp;
  41676. }
  41677. Toolbar* ToolbarItemComponent::getToolbar() const
  41678. {
  41679. return dynamic_cast <Toolbar*> (getParentComponent());
  41680. }
  41681. bool ToolbarItemComponent::isToolbarVertical() const
  41682. {
  41683. const Toolbar* const t = getToolbar();
  41684. return t != 0 && t->isVertical();
  41685. }
  41686. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  41687. {
  41688. if (toolbarStyle != newStyle)
  41689. {
  41690. toolbarStyle = newStyle;
  41691. repaint();
  41692. resized();
  41693. }
  41694. }
  41695. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  41696. {
  41697. if (isBeingUsedAsAButton)
  41698. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  41699. isMouseOver, isMouseDown, *this);
  41700. if (toolbarStyle != Toolbar::iconsOnly)
  41701. {
  41702. const int indent = contentArea.getX();
  41703. int y = indent;
  41704. int h = getHeight() - indent * 2;
  41705. if (toolbarStyle == Toolbar::iconsWithText)
  41706. {
  41707. y = contentArea.getBottom() + indent / 2;
  41708. h -= contentArea.getHeight();
  41709. }
  41710. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  41711. getButtonText(), *this);
  41712. }
  41713. if (! contentArea.isEmpty())
  41714. {
  41715. g.saveState();
  41716. g.setOrigin (contentArea.getX(), contentArea.getY());
  41717. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  41718. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  41719. g.restoreState();
  41720. }
  41721. }
  41722. void ToolbarItemComponent::resized()
  41723. {
  41724. if (toolbarStyle != Toolbar::textOnly)
  41725. {
  41726. const int indent = jmin (proportionOfWidth (0.08f),
  41727. proportionOfHeight (0.08f));
  41728. contentArea = Rectangle (indent, indent,
  41729. getWidth() - indent * 2,
  41730. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  41731. : (getHeight() - indent * 2));
  41732. }
  41733. else
  41734. {
  41735. contentArea = Rectangle();
  41736. }
  41737. contentAreaChanged (contentArea);
  41738. }
  41739. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  41740. {
  41741. if (mode != newMode)
  41742. {
  41743. mode = newMode;
  41744. repaint();
  41745. if (mode == normalMode)
  41746. {
  41747. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41748. delete overlayComp;
  41749. overlayComp = 0;
  41750. }
  41751. else if (overlayComp == 0)
  41752. {
  41753. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  41754. overlayComp->parentSizeChanged();
  41755. }
  41756. resized();
  41757. }
  41758. }
  41759. END_JUCE_NAMESPACE
  41760. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  41761. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  41762. BEGIN_JUCE_NAMESPACE
  41763. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  41764. Toolbar* const toolbar_)
  41765. : factory (factory_),
  41766. toolbar (toolbar_)
  41767. {
  41768. Component* const itemHolder = new Component();
  41769. Array <int> allIds;
  41770. factory_.getAllToolbarItemIds (allIds);
  41771. for (int i = 0; i < allIds.size(); ++i)
  41772. {
  41773. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  41774. jassert (tc != 0);
  41775. if (tc != 0)
  41776. {
  41777. itemHolder->addAndMakeVisible (tc);
  41778. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  41779. }
  41780. }
  41781. viewport = new Viewport();
  41782. viewport->setViewedComponent (itemHolder);
  41783. addAndMakeVisible (viewport);
  41784. }
  41785. ToolbarItemPalette::~ToolbarItemPalette()
  41786. {
  41787. viewport->getViewedComponent()->deleteAllChildren();
  41788. deleteAllChildren();
  41789. }
  41790. void ToolbarItemPalette::resized()
  41791. {
  41792. viewport->setBoundsInset (BorderSize (1));
  41793. Component* const itemHolder = viewport->getViewedComponent();
  41794. const int indent = 8;
  41795. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  41796. const int height = toolbar->getThickness();
  41797. int x = indent;
  41798. int y = indent;
  41799. int maxX = 0;
  41800. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  41801. {
  41802. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  41803. if (tc != 0)
  41804. {
  41805. tc->setStyle (toolbar->getStyle());
  41806. int preferredSize = 1, minSize = 1, maxSize = 1;
  41807. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41808. {
  41809. if (x + preferredSize > preferredWidth && x > indent)
  41810. {
  41811. x = indent;
  41812. y += height;
  41813. }
  41814. tc->setBounds (x, y, preferredSize, height);
  41815. x += preferredSize + 8;
  41816. maxX = jmax (maxX, x);
  41817. }
  41818. }
  41819. }
  41820. itemHolder->setSize (maxX, y + height + 8);
  41821. }
  41822. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  41823. {
  41824. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  41825. jassert (tc != 0);
  41826. if (tc != 0)
  41827. {
  41828. tc->setBounds (comp->getBounds());
  41829. tc->setStyle (toolbar->getStyle());
  41830. tc->setEditingMode (comp->getEditingMode());
  41831. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  41832. }
  41833. }
  41834. END_JUCE_NAMESPACE
  41835. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  41836. /********* Start of inlined file: juce_TreeView.cpp *********/
  41837. BEGIN_JUCE_NAMESPACE
  41838. class TreeViewContentComponent : public Component,
  41839. public TooltipClient
  41840. {
  41841. public:
  41842. TreeViewContentComponent (TreeView* const owner_)
  41843. : owner (owner_),
  41844. buttonUnderMouse (0),
  41845. isDragging (false)
  41846. {
  41847. }
  41848. ~TreeViewContentComponent()
  41849. {
  41850. deleteAllChildren();
  41851. }
  41852. void mouseDown (const MouseEvent& e)
  41853. {
  41854. updateButtonUnderMouse (e);
  41855. isDragging = false;
  41856. needSelectionOnMouseUp = false;
  41857. Rectangle pos;
  41858. TreeViewItem* const item = findItemAt (e.y, pos);
  41859. if (item == 0)
  41860. return;
  41861. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  41862. // as selection clicks)
  41863. if (e.x < pos.getX() && owner->openCloseButtonsVisible)
  41864. {
  41865. if (e.x >= pos.getX() - owner->getIndentSize())
  41866. item->setOpen (! item->isOpen());
  41867. // (clicks to the left of an open/close button are ignored)
  41868. }
  41869. else
  41870. {
  41871. // mouse-down inside the body of the item..
  41872. if (! owner->isMultiSelectEnabled())
  41873. item->setSelected (true, true);
  41874. else if (item->isSelected())
  41875. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  41876. else
  41877. selectBasedOnModifiers (item, e.mods);
  41878. MouseEvent e2 (e);
  41879. e2.x -= pos.getX();
  41880. e2.y -= pos.getY();
  41881. if (e2.x >= 0)
  41882. item->itemClicked (e2);
  41883. }
  41884. }
  41885. void mouseUp (const MouseEvent& e)
  41886. {
  41887. updateButtonUnderMouse (e);
  41888. if (needSelectionOnMouseUp && e.mouseWasClicked())
  41889. {
  41890. Rectangle pos;
  41891. TreeViewItem* const item = findItemAt (e.y, pos);
  41892. if (item != 0)
  41893. selectBasedOnModifiers (item, e.mods);
  41894. }
  41895. }
  41896. void mouseDoubleClick (const MouseEvent& e)
  41897. {
  41898. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  41899. {
  41900. Rectangle pos;
  41901. TreeViewItem* const item = findItemAt (e.y, pos);
  41902. if (item != 0 && (e.x >= pos.getX() || ! owner->openCloseButtonsVisible))
  41903. {
  41904. MouseEvent e2 (e);
  41905. e2.x -= pos.getX();
  41906. e2.y -= pos.getY();
  41907. item->itemDoubleClicked (e2);
  41908. }
  41909. }
  41910. }
  41911. void mouseDrag (const MouseEvent& e)
  41912. {
  41913. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  41914. {
  41915. isDragging = true;
  41916. Rectangle pos;
  41917. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  41918. if (item != 0 && e.getMouseDownX() >= pos.getX())
  41919. {
  41920. const String dragDescription (item->getDragSourceDescription());
  41921. if (dragDescription.isNotEmpty())
  41922. {
  41923. DragAndDropContainer* const dragContainer
  41924. = DragAndDropContainer::findParentDragContainerFor (this);
  41925. if (dragContainer != 0)
  41926. {
  41927. pos.setSize (pos.getWidth(), item->itemHeight);
  41928. Image* dragImage = Component::createComponentSnapshot (pos, true);
  41929. dragImage->multiplyAllAlphas (0.6f);
  41930. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  41931. }
  41932. else
  41933. {
  41934. // to be able to do a drag-and-drop operation, the treeview needs to
  41935. // be inside a component which is also a DragAndDropContainer.
  41936. jassertfalse
  41937. }
  41938. }
  41939. }
  41940. }
  41941. }
  41942. void mouseMove (const MouseEvent& e)
  41943. {
  41944. updateButtonUnderMouse (e);
  41945. }
  41946. void mouseExit (const MouseEvent& e)
  41947. {
  41948. updateButtonUnderMouse (e);
  41949. }
  41950. void paint (Graphics& g);
  41951. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  41952. void updateComponents()
  41953. {
  41954. const int visibleTop = -getY();
  41955. const int visibleBottom = visibleTop + getParentHeight();
  41956. BitArray itemsToKeep;
  41957. TreeViewItem* item = owner->rootItem;
  41958. int y = (item != 0 && !owner->rootItemVisible) ? -item->itemHeight : 0;
  41959. while (item != 0 && y < visibleBottom)
  41960. {
  41961. y += item->itemHeight;
  41962. if (y >= visibleTop)
  41963. {
  41964. const int index = rowComponentIds.indexOf (item->uid);
  41965. if (index < 0)
  41966. {
  41967. Component* const comp = item->createItemComponent();
  41968. if (comp != 0)
  41969. {
  41970. addAndMakeVisible (comp);
  41971. itemsToKeep.setBit (rowComponentItems.size());
  41972. rowComponentItems.add (item);
  41973. rowComponentIds.add (item->uid);
  41974. rowComponents.add (comp);
  41975. }
  41976. }
  41977. else
  41978. {
  41979. itemsToKeep.setBit (index);
  41980. }
  41981. }
  41982. item = item->getNextVisibleItem (true);
  41983. }
  41984. for (int i = rowComponentItems.size(); --i >= 0;)
  41985. {
  41986. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  41987. bool keep = false;
  41988. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  41989. && isParentOf (comp))
  41990. {
  41991. if (itemsToKeep[i])
  41992. {
  41993. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  41994. Rectangle pos (item->getItemPosition (false));
  41995. pos.setSize (pos.getWidth(), item->itemHeight);
  41996. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  41997. {
  41998. keep = true;
  41999. comp->setBounds (pos);
  42000. }
  42001. }
  42002. else
  42003. {
  42004. comp->setSize (0, 0);
  42005. }
  42006. }
  42007. if (! keep)
  42008. {
  42009. delete comp;
  42010. rowComponents.remove (i);
  42011. rowComponentIds.remove (i);
  42012. rowComponentItems.remove (i);
  42013. }
  42014. }
  42015. }
  42016. void updateButtonUnderMouse (const MouseEvent& e)
  42017. {
  42018. TreeViewItem* newItem = 0;
  42019. if (owner->openCloseButtonsVisible)
  42020. {
  42021. Rectangle pos;
  42022. TreeViewItem* item = findItemAt (e.y, pos);
  42023. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner->getIndentSize())
  42024. {
  42025. newItem = item;
  42026. if (! newItem->mightContainSubItems())
  42027. newItem = 0;
  42028. }
  42029. }
  42030. if (buttonUnderMouse != newItem)
  42031. {
  42032. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  42033. {
  42034. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  42035. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  42036. }
  42037. buttonUnderMouse = newItem;
  42038. if (buttonUnderMouse != 0)
  42039. {
  42040. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  42041. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  42042. }
  42043. }
  42044. }
  42045. bool isMouseOverButton (TreeViewItem* item) const throw()
  42046. {
  42047. return item == buttonUnderMouse;
  42048. }
  42049. void resized()
  42050. {
  42051. owner->itemsChanged();
  42052. }
  42053. const String getTooltip()
  42054. {
  42055. int x, y;
  42056. getMouseXYRelative (x, y);
  42057. Rectangle pos;
  42058. TreeViewItem* const item = findItemAt (y, pos);
  42059. if (item != 0)
  42060. return item->getTooltip();
  42061. return owner->getTooltip();
  42062. }
  42063. juce_UseDebuggingNewOperator
  42064. private:
  42065. TreeView* const owner;
  42066. VoidArray rowComponentItems;
  42067. Array <int> rowComponentIds;
  42068. VoidArray rowComponents;
  42069. TreeViewItem* buttonUnderMouse;
  42070. bool isDragging, needSelectionOnMouseUp;
  42071. TreeViewContentComponent (const TreeViewContentComponent&);
  42072. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  42073. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  42074. {
  42075. TreeViewItem* firstSelected = 0;
  42076. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  42077. {
  42078. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  42079. jassert (lastSelected != 0);
  42080. int rowStart = firstSelected->getRowNumberInTree();
  42081. int rowEnd = lastSelected->getRowNumberInTree();
  42082. if (rowStart > rowEnd)
  42083. swapVariables (rowStart, rowEnd);
  42084. int ourRow = item->getRowNumberInTree();
  42085. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  42086. if (ourRow > otherEnd)
  42087. swapVariables (ourRow, otherEnd);
  42088. for (int i = ourRow; i <= otherEnd; ++i)
  42089. owner->getItemOnRow (i)->setSelected (true, false);
  42090. }
  42091. else
  42092. {
  42093. const bool cmd = modifiers.isCommandDown();
  42094. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  42095. }
  42096. }
  42097. bool containsItem (TreeViewItem* const item) const
  42098. {
  42099. for (int i = rowComponentItems.size(); --i >= 0;)
  42100. if ((TreeViewItem*) rowComponentItems.getUnchecked (i) == item)
  42101. return true;
  42102. return false;
  42103. }
  42104. };
  42105. class TreeViewport : public Viewport
  42106. {
  42107. public:
  42108. TreeViewport() throw() {}
  42109. ~TreeViewport() throw() {}
  42110. void updateComponents()
  42111. {
  42112. if (getViewedComponent() != 0)
  42113. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  42114. repaint();
  42115. }
  42116. void visibleAreaChanged (int, int, int, int)
  42117. {
  42118. updateComponents();
  42119. }
  42120. juce_UseDebuggingNewOperator
  42121. private:
  42122. TreeViewport (const TreeViewport&);
  42123. const TreeViewport& operator= (const TreeViewport&);
  42124. };
  42125. TreeView::TreeView (const String& componentName)
  42126. : Component (componentName),
  42127. rootItem (0),
  42128. indentSize (24),
  42129. defaultOpenness (false),
  42130. needsRecalculating (true),
  42131. rootItemVisible (true),
  42132. multiSelectEnabled (false),
  42133. openCloseButtonsVisible (true)
  42134. {
  42135. addAndMakeVisible (viewport = new TreeViewport());
  42136. viewport->setViewedComponent (new TreeViewContentComponent (this));
  42137. viewport->setWantsKeyboardFocus (false);
  42138. setWantsKeyboardFocus (true);
  42139. }
  42140. TreeView::~TreeView()
  42141. {
  42142. if (rootItem != 0)
  42143. rootItem->setOwnerView (0);
  42144. deleteAllChildren();
  42145. }
  42146. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  42147. {
  42148. if (rootItem != newRootItem)
  42149. {
  42150. if (newRootItem != 0)
  42151. {
  42152. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  42153. if (newRootItem->ownerView != 0)
  42154. newRootItem->ownerView->setRootItem (0);
  42155. }
  42156. if (rootItem != 0)
  42157. rootItem->setOwnerView (0);
  42158. rootItem = newRootItem;
  42159. if (newRootItem != 0)
  42160. newRootItem->setOwnerView (this);
  42161. needsRecalculating = true;
  42162. handleAsyncUpdate();
  42163. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42164. {
  42165. rootItem->setOpen (false); // force a re-open
  42166. rootItem->setOpen (true);
  42167. }
  42168. }
  42169. }
  42170. void TreeView::deleteRootItem()
  42171. {
  42172. TreeViewItem* const oldItem = rootItem;
  42173. setRootItem (0);
  42174. delete oldItem;
  42175. }
  42176. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  42177. {
  42178. rootItemVisible = shouldBeVisible;
  42179. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42180. {
  42181. rootItem->setOpen (false); // force a re-open
  42182. rootItem->setOpen (true);
  42183. }
  42184. itemsChanged();
  42185. }
  42186. void TreeView::colourChanged()
  42187. {
  42188. setOpaque (findColour (backgroundColourId).isOpaque());
  42189. repaint();
  42190. }
  42191. void TreeView::setIndentSize (const int newIndentSize)
  42192. {
  42193. if (indentSize != newIndentSize)
  42194. {
  42195. indentSize = newIndentSize;
  42196. resized();
  42197. }
  42198. }
  42199. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  42200. {
  42201. if (defaultOpenness != isOpenByDefault)
  42202. {
  42203. defaultOpenness = isOpenByDefault;
  42204. itemsChanged();
  42205. }
  42206. }
  42207. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  42208. {
  42209. multiSelectEnabled = canMultiSelect;
  42210. }
  42211. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  42212. {
  42213. if (openCloseButtonsVisible != shouldBeVisible)
  42214. {
  42215. openCloseButtonsVisible = shouldBeVisible;
  42216. itemsChanged();
  42217. }
  42218. }
  42219. void TreeView::clearSelectedItems()
  42220. {
  42221. if (rootItem != 0)
  42222. rootItem->deselectAllRecursively();
  42223. }
  42224. int TreeView::getNumSelectedItems() const throw()
  42225. {
  42226. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  42227. }
  42228. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  42229. {
  42230. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  42231. }
  42232. int TreeView::getNumRowsInTree() const
  42233. {
  42234. if (rootItem != 0)
  42235. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  42236. return 0;
  42237. }
  42238. TreeViewItem* TreeView::getItemOnRow (int index) const
  42239. {
  42240. if (! rootItemVisible)
  42241. ++index;
  42242. if (rootItem != 0 && index >= 0)
  42243. return rootItem->getItemOnRow (index);
  42244. return 0;
  42245. }
  42246. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  42247. {
  42248. XmlElement* e = 0;
  42249. if (rootItem != 0)
  42250. {
  42251. e = rootItem->createXmlOpenness();
  42252. if (e != 0 && alsoIncludeScrollPosition)
  42253. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  42254. }
  42255. return e;
  42256. }
  42257. void TreeView::restoreOpennessState (const XmlElement& newState)
  42258. {
  42259. if (rootItem != 0)
  42260. {
  42261. rootItem->restoreFromXml (newState);
  42262. if (newState.hasAttribute (T("scrollPos")))
  42263. viewport->setViewPosition (viewport->getViewPositionX(),
  42264. newState.getIntAttribute (T("scrollPos")));
  42265. }
  42266. }
  42267. void TreeView::paint (Graphics& g)
  42268. {
  42269. g.fillAll (findColour (backgroundColourId));
  42270. }
  42271. void TreeView::resized()
  42272. {
  42273. viewport->setBounds (0, 0, getWidth(), getHeight());
  42274. itemsChanged();
  42275. handleAsyncUpdate();
  42276. }
  42277. void TreeView::enablementChanged()
  42278. {
  42279. repaint();
  42280. }
  42281. void TreeView::moveSelectedRow (int delta)
  42282. {
  42283. if (delta == 0)
  42284. return;
  42285. int rowSelected = 0;
  42286. TreeViewItem* const firstSelected = getSelectedItem (0);
  42287. if (firstSelected != 0)
  42288. rowSelected = firstSelected->getRowNumberInTree();
  42289. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  42290. for (;;)
  42291. {
  42292. TreeViewItem* item = getItemOnRow (rowSelected);
  42293. if (item != 0)
  42294. {
  42295. if (! item->canBeSelected())
  42296. {
  42297. // if the row we want to highlight doesn't allow it, try skipping
  42298. // to the next item..
  42299. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  42300. rowSelected + (delta < 0 ? -1 : 1));
  42301. if (rowSelected != nextRowToTry)
  42302. {
  42303. rowSelected = nextRowToTry;
  42304. continue;
  42305. }
  42306. else
  42307. {
  42308. break;
  42309. }
  42310. }
  42311. item->setSelected (true, true);
  42312. scrollToKeepItemVisible (item);
  42313. }
  42314. break;
  42315. }
  42316. }
  42317. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  42318. {
  42319. if (item != 0 && item->ownerView == this)
  42320. {
  42321. handleAsyncUpdate();
  42322. item = item->getDeepestOpenParentItem();
  42323. int y = item->y;
  42324. int viewTop = viewport->getViewPositionY();
  42325. if (y < viewTop)
  42326. {
  42327. viewport->setViewPosition (viewport->getViewPositionX(), y);
  42328. }
  42329. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  42330. {
  42331. viewport->setViewPosition (viewport->getViewPositionX(),
  42332. (y + item->itemHeight) - viewport->getViewHeight());
  42333. }
  42334. }
  42335. }
  42336. bool TreeView::keyPressed (const KeyPress& key)
  42337. {
  42338. if (key.isKeyCode (KeyPress::upKey))
  42339. {
  42340. moveSelectedRow (-1);
  42341. }
  42342. else if (key.isKeyCode (KeyPress::downKey))
  42343. {
  42344. moveSelectedRow (1);
  42345. }
  42346. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  42347. {
  42348. if (rootItem != 0)
  42349. {
  42350. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  42351. if (key.isKeyCode (KeyPress::pageUpKey))
  42352. rowsOnScreen = -rowsOnScreen;
  42353. moveSelectedRow (rowsOnScreen);
  42354. }
  42355. }
  42356. else if (key.isKeyCode (KeyPress::homeKey))
  42357. {
  42358. moveSelectedRow (-0x3fffffff);
  42359. }
  42360. else if (key.isKeyCode (KeyPress::endKey))
  42361. {
  42362. moveSelectedRow (0x3fffffff);
  42363. }
  42364. else if (key.isKeyCode (KeyPress::returnKey))
  42365. {
  42366. TreeViewItem* const firstSelected = getSelectedItem (0);
  42367. if (firstSelected != 0)
  42368. firstSelected->setOpen (! firstSelected->isOpen());
  42369. }
  42370. else if (key.isKeyCode (KeyPress::leftKey))
  42371. {
  42372. TreeViewItem* const firstSelected = getSelectedItem (0);
  42373. if (firstSelected != 0)
  42374. {
  42375. if (firstSelected->isOpen())
  42376. {
  42377. firstSelected->setOpen (false);
  42378. }
  42379. else
  42380. {
  42381. TreeViewItem* parent = firstSelected->parentItem;
  42382. if ((! rootItemVisible) && parent == rootItem)
  42383. parent = 0;
  42384. if (parent != 0)
  42385. {
  42386. parent->setSelected (true, true);
  42387. scrollToKeepItemVisible (parent);
  42388. }
  42389. }
  42390. }
  42391. }
  42392. else if (key.isKeyCode (KeyPress::rightKey))
  42393. {
  42394. TreeViewItem* const firstSelected = getSelectedItem (0);
  42395. if (firstSelected != 0)
  42396. {
  42397. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  42398. moveSelectedRow (1);
  42399. else
  42400. firstSelected->setOpen (true);
  42401. }
  42402. }
  42403. else
  42404. {
  42405. return false;
  42406. }
  42407. return true;
  42408. }
  42409. void TreeView::itemsChanged() throw()
  42410. {
  42411. needsRecalculating = true;
  42412. repaint();
  42413. triggerAsyncUpdate();
  42414. }
  42415. void TreeView::handleAsyncUpdate()
  42416. {
  42417. if (needsRecalculating)
  42418. {
  42419. needsRecalculating = false;
  42420. const ScopedLock sl (nodeAlterationLock);
  42421. if (rootItem != 0)
  42422. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  42423. ((TreeViewport*) viewport)->updateComponents();
  42424. if (rootItem != 0)
  42425. {
  42426. viewport->getViewedComponent()
  42427. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  42428. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  42429. }
  42430. else
  42431. {
  42432. viewport->getViewedComponent()->setSize (0, 0);
  42433. }
  42434. }
  42435. }
  42436. void TreeViewContentComponent::paint (Graphics& g)
  42437. {
  42438. if (owner->rootItem != 0)
  42439. {
  42440. owner->handleAsyncUpdate();
  42441. if (! owner->rootItemVisible)
  42442. g.setOrigin (0, -owner->rootItem->itemHeight);
  42443. owner->rootItem->paintRecursively (g, getWidth());
  42444. }
  42445. }
  42446. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  42447. {
  42448. if (owner->rootItem != 0)
  42449. {
  42450. owner->handleAsyncUpdate();
  42451. if (! owner->rootItemVisible)
  42452. y += owner->rootItem->itemHeight;
  42453. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  42454. if (ti != 0)
  42455. itemPosition = ti->getItemPosition (false);
  42456. return ti;
  42457. }
  42458. return 0;
  42459. }
  42460. #define opennessDefault 0
  42461. #define opennessClosed 1
  42462. #define opennessOpen 2
  42463. TreeViewItem::TreeViewItem()
  42464. : ownerView (0),
  42465. parentItem (0),
  42466. subItems (8),
  42467. y (0),
  42468. itemHeight (0),
  42469. totalHeight (0),
  42470. selected (false),
  42471. redrawNeeded (true),
  42472. drawLinesInside (true),
  42473. drawsInLeftMargin (false),
  42474. openness (opennessDefault)
  42475. {
  42476. static int nextUID = 0;
  42477. uid = nextUID++;
  42478. }
  42479. TreeViewItem::~TreeViewItem()
  42480. {
  42481. }
  42482. const String TreeViewItem::getUniqueName() const
  42483. {
  42484. return String::empty;
  42485. }
  42486. void TreeViewItem::itemOpennessChanged (bool)
  42487. {
  42488. }
  42489. int TreeViewItem::getNumSubItems() const throw()
  42490. {
  42491. return subItems.size();
  42492. }
  42493. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  42494. {
  42495. return subItems [index];
  42496. }
  42497. void TreeViewItem::clearSubItems()
  42498. {
  42499. if (subItems.size() > 0)
  42500. {
  42501. if (ownerView != 0)
  42502. {
  42503. const ScopedLock sl (ownerView->nodeAlterationLock);
  42504. subItems.clear();
  42505. treeHasChanged();
  42506. }
  42507. else
  42508. {
  42509. subItems.clear();
  42510. }
  42511. }
  42512. }
  42513. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  42514. {
  42515. if (newItem != 0)
  42516. {
  42517. newItem->parentItem = this;
  42518. newItem->setOwnerView (ownerView);
  42519. newItem->y = 0;
  42520. newItem->itemHeight = newItem->getItemHeight();
  42521. newItem->totalHeight = 0;
  42522. newItem->itemWidth = newItem->getItemWidth();
  42523. newItem->totalWidth = 0;
  42524. if (ownerView != 0)
  42525. {
  42526. const ScopedLock sl (ownerView->nodeAlterationLock);
  42527. subItems.insert (insertPosition, newItem);
  42528. treeHasChanged();
  42529. if (newItem->isOpen())
  42530. newItem->itemOpennessChanged (true);
  42531. }
  42532. else
  42533. {
  42534. subItems.insert (insertPosition, newItem);
  42535. if (newItem->isOpen())
  42536. newItem->itemOpennessChanged (true);
  42537. }
  42538. }
  42539. }
  42540. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  42541. {
  42542. if (ownerView != 0)
  42543. ownerView->nodeAlterationLock.enter();
  42544. if (((unsigned int) index) < (unsigned int) subItems.size())
  42545. {
  42546. subItems.remove (index, deleteItem);
  42547. treeHasChanged();
  42548. }
  42549. if (ownerView != 0)
  42550. ownerView->nodeAlterationLock.exit();
  42551. }
  42552. bool TreeViewItem::isOpen() const throw()
  42553. {
  42554. if (openness == opennessDefault)
  42555. return ownerView != 0 && ownerView->defaultOpenness;
  42556. else
  42557. return openness == opennessOpen;
  42558. }
  42559. void TreeViewItem::setOpen (const bool shouldBeOpen)
  42560. {
  42561. if (isOpen() != shouldBeOpen)
  42562. {
  42563. openness = shouldBeOpen ? opennessOpen
  42564. : opennessClosed;
  42565. treeHasChanged();
  42566. itemOpennessChanged (isOpen());
  42567. }
  42568. }
  42569. bool TreeViewItem::isSelected() const throw()
  42570. {
  42571. return selected;
  42572. }
  42573. void TreeViewItem::deselectAllRecursively()
  42574. {
  42575. setSelected (false, false);
  42576. for (int i = 0; i < subItems.size(); ++i)
  42577. subItems.getUnchecked(i)->deselectAllRecursively();
  42578. }
  42579. void TreeViewItem::setSelected (const bool shouldBeSelected,
  42580. const bool deselectOtherItemsFirst)
  42581. {
  42582. if (shouldBeSelected && ! canBeSelected())
  42583. return;
  42584. if (deselectOtherItemsFirst)
  42585. getTopLevelItem()->deselectAllRecursively();
  42586. if (shouldBeSelected != selected)
  42587. {
  42588. selected = shouldBeSelected;
  42589. if (ownerView != 0)
  42590. ownerView->repaint();
  42591. itemSelectionChanged (shouldBeSelected);
  42592. }
  42593. }
  42594. void TreeViewItem::paintItem (Graphics&, int, int)
  42595. {
  42596. }
  42597. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  42598. {
  42599. ownerView->getLookAndFeel()
  42600. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  42601. }
  42602. void TreeViewItem::itemClicked (const MouseEvent&)
  42603. {
  42604. }
  42605. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  42606. {
  42607. if (mightContainSubItems())
  42608. setOpen (! isOpen());
  42609. }
  42610. void TreeViewItem::itemSelectionChanged (bool)
  42611. {
  42612. }
  42613. const String TreeViewItem::getTooltip()
  42614. {
  42615. return String::empty;
  42616. }
  42617. const String TreeViewItem::getDragSourceDescription()
  42618. {
  42619. return String::empty;
  42620. }
  42621. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  42622. {
  42623. const int indentX = getIndentX();
  42624. int width = itemWidth;
  42625. if (ownerView != 0 && width < 0)
  42626. width = ownerView->viewport->getViewWidth() - indentX;
  42627. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  42628. if (relativeToTreeViewTopLeft)
  42629. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  42630. r.getY() - ownerView->viewport->getViewPositionY());
  42631. return r;
  42632. }
  42633. void TreeViewItem::treeHasChanged() const throw()
  42634. {
  42635. if (ownerView != 0)
  42636. ownerView->itemsChanged();
  42637. }
  42638. void TreeViewItem::repaintItem() const
  42639. {
  42640. if (ownerView != 0 && areAllParentsOpen())
  42641. {
  42642. const Rectangle r (getItemPosition (true));
  42643. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  42644. }
  42645. }
  42646. bool TreeViewItem::areAllParentsOpen() const throw()
  42647. {
  42648. return parentItem == 0
  42649. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  42650. }
  42651. void TreeViewItem::updatePositions (int newY)
  42652. {
  42653. y = newY;
  42654. itemHeight = getItemHeight();
  42655. totalHeight = itemHeight;
  42656. itemWidth = getItemWidth();
  42657. totalWidth = jmax (itemWidth, 0) + getIndentX();
  42658. if (isOpen())
  42659. {
  42660. newY += totalHeight;
  42661. for (int i = 0; i < subItems.size(); ++i)
  42662. {
  42663. TreeViewItem* const ti = subItems.getUnchecked(i);
  42664. ti->updatePositions (newY);
  42665. newY += ti->totalHeight;
  42666. totalHeight += ti->totalHeight;
  42667. totalWidth = jmax (totalWidth, ti->totalWidth);
  42668. }
  42669. }
  42670. }
  42671. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  42672. {
  42673. TreeViewItem* result = this;
  42674. TreeViewItem* item = this;
  42675. while (item->parentItem != 0)
  42676. {
  42677. item = item->parentItem;
  42678. if (! item->isOpen())
  42679. result = item;
  42680. }
  42681. return result;
  42682. }
  42683. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  42684. {
  42685. ownerView = newOwner;
  42686. for (int i = subItems.size(); --i >= 0;)
  42687. subItems.getUnchecked(i)->setOwnerView (newOwner);
  42688. }
  42689. int TreeViewItem::getIndentX() const throw()
  42690. {
  42691. const int indentWidth = ownerView->getIndentSize();
  42692. int x = ownerView->rootItemVisible ? indentWidth : 0;
  42693. if (! ownerView->openCloseButtonsVisible)
  42694. x -= indentWidth;
  42695. TreeViewItem* p = parentItem;
  42696. while (p != 0)
  42697. {
  42698. x += indentWidth;
  42699. p = p->parentItem;
  42700. }
  42701. return x;
  42702. }
  42703. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  42704. {
  42705. drawsInLeftMargin = canDrawInLeftMargin;
  42706. }
  42707. void TreeViewItem::paintRecursively (Graphics& g, int width)
  42708. {
  42709. jassert (ownerView != 0);
  42710. if (ownerView == 0)
  42711. return;
  42712. const int indent = getIndentX();
  42713. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  42714. g.setColour (ownerView->findColour (TreeView::linesColourId));
  42715. const float halfH = itemHeight * 0.5f;
  42716. int depth = 0;
  42717. TreeViewItem* p = parentItem;
  42718. while (p != 0)
  42719. {
  42720. ++depth;
  42721. p = p->parentItem;
  42722. }
  42723. if (! ownerView->rootItemVisible)
  42724. --depth;
  42725. const int indentWidth = ownerView->getIndentSize();
  42726. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  42727. {
  42728. float x = (depth + 0.5f) * indentWidth;
  42729. if (depth >= 0)
  42730. {
  42731. if (parentItem != 0 && parentItem->drawLinesInside)
  42732. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  42733. if ((parentItem != 0 && parentItem->drawLinesInside)
  42734. || (parentItem == 0 && drawLinesInside))
  42735. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  42736. }
  42737. p = parentItem;
  42738. int d = depth;
  42739. while (p != 0 && --d >= 0)
  42740. {
  42741. x -= (float) indentWidth;
  42742. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  42743. && ! p->isLastOfSiblings())
  42744. {
  42745. g.drawLine (x, 0, x, (float) itemHeight);
  42746. }
  42747. p = p->parentItem;
  42748. }
  42749. if (mightContainSubItems())
  42750. {
  42751. g.saveState();
  42752. g.setOrigin (depth * indentWidth, 0);
  42753. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  42754. paintOpenCloseButton (g, indentWidth, itemHeight,
  42755. ((TreeViewContentComponent*) ownerView->viewport->getViewedComponent())
  42756. ->isMouseOverButton (this));
  42757. g.restoreState();
  42758. }
  42759. }
  42760. {
  42761. g.saveState();
  42762. g.setOrigin (indent, 0);
  42763. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  42764. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  42765. paintItem (g, itemW, itemHeight);
  42766. g.restoreState();
  42767. }
  42768. if (isOpen())
  42769. {
  42770. const Rectangle clip (g.getClipBounds());
  42771. for (int i = 0; i < subItems.size(); ++i)
  42772. {
  42773. TreeViewItem* const ti = subItems.getUnchecked(i);
  42774. const int relY = ti->y - y;
  42775. if (relY >= clip.getBottom())
  42776. break;
  42777. if (relY + ti->totalHeight >= clip.getY())
  42778. {
  42779. g.saveState();
  42780. g.setOrigin (0, relY);
  42781. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  42782. ti->paintRecursively (g, width);
  42783. g.restoreState();
  42784. }
  42785. }
  42786. }
  42787. }
  42788. bool TreeViewItem::isLastOfSiblings() const throw()
  42789. {
  42790. return parentItem == 0
  42791. || parentItem->subItems.getLast() == this;
  42792. }
  42793. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  42794. {
  42795. return (parentItem == 0) ? this
  42796. : parentItem->getTopLevelItem();
  42797. }
  42798. int TreeViewItem::getNumRows() const throw()
  42799. {
  42800. int num = 1;
  42801. if (isOpen())
  42802. {
  42803. for (int i = subItems.size(); --i >= 0;)
  42804. num += subItems.getUnchecked(i)->getNumRows();
  42805. }
  42806. return num;
  42807. }
  42808. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  42809. {
  42810. if (index == 0)
  42811. return this;
  42812. if (index > 0 && isOpen())
  42813. {
  42814. --index;
  42815. for (int i = 0; i < subItems.size(); ++i)
  42816. {
  42817. TreeViewItem* const item = subItems.getUnchecked(i);
  42818. if (index == 0)
  42819. return item;
  42820. const int numRows = item->getNumRows();
  42821. if (numRows > index)
  42822. return item->getItemOnRow (index);
  42823. index -= numRows;
  42824. }
  42825. }
  42826. return 0;
  42827. }
  42828. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  42829. {
  42830. if (((unsigned int) y) < (unsigned int) totalHeight)
  42831. {
  42832. const int h = itemHeight;
  42833. if (y < h)
  42834. return this;
  42835. if (isOpen())
  42836. {
  42837. y -= h;
  42838. for (int i = 0; i < subItems.size(); ++i)
  42839. {
  42840. TreeViewItem* const ti = subItems.getUnchecked(i);
  42841. if (ti->totalHeight >= y)
  42842. return ti->findItemRecursively (y);
  42843. y -= ti->totalHeight;
  42844. }
  42845. }
  42846. }
  42847. return 0;
  42848. }
  42849. int TreeViewItem::countSelectedItemsRecursively() const throw()
  42850. {
  42851. int total = 0;
  42852. if (isSelected())
  42853. ++total;
  42854. for (int i = subItems.size(); --i >= 0;)
  42855. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  42856. return total;
  42857. }
  42858. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  42859. {
  42860. if (isSelected())
  42861. {
  42862. if (index == 0)
  42863. return this;
  42864. --index;
  42865. }
  42866. if (index >= 0)
  42867. {
  42868. for (int i = 0; i < subItems.size(); ++i)
  42869. {
  42870. TreeViewItem* const item = subItems.getUnchecked(i);
  42871. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  42872. if (found != 0)
  42873. return found;
  42874. index -= item->countSelectedItemsRecursively();
  42875. }
  42876. }
  42877. return 0;
  42878. }
  42879. int TreeViewItem::getRowNumberInTree() const throw()
  42880. {
  42881. if (parentItem != 0 && ownerView != 0)
  42882. {
  42883. int n = 1 + parentItem->getRowNumberInTree();
  42884. int ourIndex = parentItem->subItems.indexOf (this);
  42885. jassert (ourIndex >= 0);
  42886. while (--ourIndex >= 0)
  42887. n += parentItem->subItems [ourIndex]->getNumRows();
  42888. if (parentItem->parentItem == 0
  42889. && ! ownerView->rootItemVisible)
  42890. --n;
  42891. return n;
  42892. }
  42893. else
  42894. {
  42895. return 0;
  42896. }
  42897. }
  42898. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  42899. {
  42900. drawLinesInside = drawLines;
  42901. }
  42902. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  42903. {
  42904. if (recurse && isOpen() && subItems.size() > 0)
  42905. return subItems [0];
  42906. if (parentItem != 0)
  42907. {
  42908. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  42909. if (nextIndex >= parentItem->subItems.size())
  42910. return parentItem->getNextVisibleItem (false);
  42911. return parentItem->subItems [nextIndex];
  42912. }
  42913. return 0;
  42914. }
  42915. void TreeViewItem::restoreFromXml (const XmlElement& e)
  42916. {
  42917. if (e.hasTagName (T("CLOSED")))
  42918. {
  42919. setOpen (false);
  42920. }
  42921. else if (e.hasTagName (T("OPEN")))
  42922. {
  42923. setOpen (true);
  42924. forEachXmlChildElement (e, n)
  42925. {
  42926. const String id (n->getStringAttribute (T("id")));
  42927. for (int i = 0; i < subItems.size(); ++i)
  42928. {
  42929. TreeViewItem* const ti = subItems.getUnchecked(i);
  42930. if (ti->getUniqueName() == id)
  42931. {
  42932. ti->restoreFromXml (*n);
  42933. break;
  42934. }
  42935. }
  42936. }
  42937. }
  42938. }
  42939. XmlElement* TreeViewItem::createXmlOpenness() const
  42940. {
  42941. if (openness != opennessDefault)
  42942. {
  42943. const String name (getUniqueName());
  42944. if (name.isNotEmpty())
  42945. {
  42946. XmlElement* e;
  42947. if (isOpen())
  42948. {
  42949. e = new XmlElement (T("OPEN"));
  42950. for (int i = 0; i < subItems.size(); ++i)
  42951. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  42952. }
  42953. else
  42954. {
  42955. e = new XmlElement (T("CLOSED"));
  42956. }
  42957. e->setAttribute (T("id"), name);
  42958. return e;
  42959. }
  42960. else
  42961. {
  42962. // trying to save the openness for an element that has no name - this won't
  42963. // work because it needs the names to identify what to open.
  42964. jassertfalse
  42965. }
  42966. }
  42967. return 0;
  42968. }
  42969. END_JUCE_NAMESPACE
  42970. /********* End of inlined file: juce_TreeView.cpp *********/
  42971. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42972. BEGIN_JUCE_NAMESPACE
  42973. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  42974. : fileList (listToShow),
  42975. listeners (2)
  42976. {
  42977. }
  42978. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  42979. {
  42980. }
  42981. FileBrowserListener::~FileBrowserListener()
  42982. {
  42983. }
  42984. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  42985. {
  42986. jassert (listener != 0);
  42987. if (listener != 0)
  42988. listeners.add (listener);
  42989. }
  42990. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  42991. {
  42992. listeners.removeValue (listener);
  42993. }
  42994. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  42995. {
  42996. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42997. for (int i = listeners.size(); --i >= 0;)
  42998. {
  42999. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43000. if (deletionWatcher.hasBeenDeleted())
  43001. return;
  43002. i = jmin (i, listeners.size() - 1);
  43003. }
  43004. }
  43005. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  43006. {
  43007. if (fileList.getDirectory().exists())
  43008. {
  43009. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  43010. for (int i = listeners.size(); --i >= 0;)
  43011. {
  43012. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  43013. if (deletionWatcher.hasBeenDeleted())
  43014. return;
  43015. i = jmin (i, listeners.size() - 1);
  43016. }
  43017. }
  43018. }
  43019. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  43020. {
  43021. if (fileList.getDirectory().exists())
  43022. {
  43023. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  43024. for (int i = listeners.size(); --i >= 0;)
  43025. {
  43026. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  43027. if (deletionWatcher.hasBeenDeleted())
  43028. return;
  43029. i = jmin (i, listeners.size() - 1);
  43030. }
  43031. }
  43032. }
  43033. END_JUCE_NAMESPACE
  43034. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  43035. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  43036. BEGIN_JUCE_NAMESPACE
  43037. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  43038. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  43039. Time* creationTime, bool* isReadOnly) throw();
  43040. bool juce_findFileNext (void* handle, String& resultFile,
  43041. bool* isDirectory, bool* isHidden, int64* fileSize,
  43042. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  43043. void juce_findFileClose (void* handle) throw();
  43044. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  43045. TimeSliceThread& thread_)
  43046. : fileFilter (fileFilter_),
  43047. thread (thread_),
  43048. includeDirectories (false),
  43049. includeFiles (false),
  43050. ignoreHiddenFiles (true),
  43051. fileFindHandle (0),
  43052. shouldStop (true)
  43053. {
  43054. }
  43055. DirectoryContentsList::~DirectoryContentsList()
  43056. {
  43057. clear();
  43058. }
  43059. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  43060. {
  43061. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  43062. }
  43063. const File& DirectoryContentsList::getDirectory() const throw()
  43064. {
  43065. return root;
  43066. }
  43067. void DirectoryContentsList::setDirectory (const File& directory,
  43068. const bool includeDirectories_,
  43069. const bool includeFiles_)
  43070. {
  43071. if (directory != root
  43072. || includeDirectories != includeDirectories_
  43073. || includeFiles != includeFiles_)
  43074. {
  43075. clear();
  43076. root = directory;
  43077. includeDirectories = includeDirectories_;
  43078. includeFiles = includeFiles_;
  43079. refresh();
  43080. }
  43081. }
  43082. void DirectoryContentsList::clear()
  43083. {
  43084. shouldStop = true;
  43085. thread.removeTimeSliceClient (this);
  43086. if (fileFindHandle != 0)
  43087. {
  43088. juce_findFileClose (fileFindHandle);
  43089. fileFindHandle = 0;
  43090. }
  43091. if (files.size() > 0)
  43092. {
  43093. files.clear();
  43094. changed();
  43095. }
  43096. }
  43097. void DirectoryContentsList::refresh()
  43098. {
  43099. clear();
  43100. if (root.isDirectory())
  43101. {
  43102. String fileFound;
  43103. bool fileFoundIsDir, isHidden, isReadOnly;
  43104. int64 fileSize;
  43105. Time modTime, creationTime;
  43106. String path (root.getFullPathName());
  43107. if (! path.endsWithChar (File::separator))
  43108. path += File::separator;
  43109. jassert (fileFindHandle == 0);
  43110. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  43111. &fileFoundIsDir,
  43112. &isHidden,
  43113. &fileSize,
  43114. &modTime,
  43115. &creationTime,
  43116. &isReadOnly);
  43117. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  43118. {
  43119. if (addFile (fileFound, fileFoundIsDir, isHidden,
  43120. fileSize, modTime, creationTime, isReadOnly))
  43121. {
  43122. changed();
  43123. }
  43124. }
  43125. shouldStop = false;
  43126. thread.addTimeSliceClient (this);
  43127. }
  43128. }
  43129. int DirectoryContentsList::getNumFiles() const
  43130. {
  43131. return files.size();
  43132. }
  43133. bool DirectoryContentsList::getFileInfo (const int index,
  43134. FileInfo& result) const
  43135. {
  43136. const ScopedLock sl (fileListLock);
  43137. const FileInfo* const info = files [index];
  43138. if (info != 0)
  43139. {
  43140. result = *info;
  43141. return true;
  43142. }
  43143. return false;
  43144. }
  43145. const File DirectoryContentsList::getFile (const int index) const
  43146. {
  43147. const ScopedLock sl (fileListLock);
  43148. const FileInfo* const info = files [index];
  43149. if (info != 0)
  43150. return root.getChildFile (info->filename);
  43151. return File::nonexistent;
  43152. }
  43153. bool DirectoryContentsList::isStillLoading() const
  43154. {
  43155. return fileFindHandle != 0;
  43156. }
  43157. void DirectoryContentsList::changed()
  43158. {
  43159. sendChangeMessage (this);
  43160. }
  43161. bool DirectoryContentsList::useTimeSlice()
  43162. {
  43163. const uint32 startTime = Time::getApproximateMillisecondCounter();
  43164. bool hasChanged = false;
  43165. for (int i = 100; --i >= 0;)
  43166. {
  43167. if (! checkNextFile (hasChanged))
  43168. {
  43169. if (hasChanged)
  43170. changed();
  43171. return false;
  43172. }
  43173. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  43174. break;
  43175. }
  43176. if (hasChanged)
  43177. changed();
  43178. return true;
  43179. }
  43180. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  43181. {
  43182. if (fileFindHandle != 0)
  43183. {
  43184. String fileFound;
  43185. bool fileFoundIsDir, isHidden, isReadOnly;
  43186. int64 fileSize;
  43187. Time modTime, creationTime;
  43188. if (juce_findFileNext (fileFindHandle, fileFound,
  43189. &fileFoundIsDir, &isHidden,
  43190. &fileSize,
  43191. &modTime,
  43192. &creationTime,
  43193. &isReadOnly))
  43194. {
  43195. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  43196. modTime, creationTime, isReadOnly))
  43197. {
  43198. hasChanged = true;
  43199. }
  43200. return true;
  43201. }
  43202. else
  43203. {
  43204. juce_findFileClose (fileFindHandle);
  43205. fileFindHandle = 0;
  43206. }
  43207. }
  43208. return false;
  43209. }
  43210. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  43211. const DirectoryContentsList::FileInfo* const second) throw()
  43212. {
  43213. #if JUCE_WINDOWS
  43214. if (first->isDirectory != second->isDirectory)
  43215. return first->isDirectory ? -1 : 1;
  43216. #endif
  43217. return first->filename.compareIgnoreCase (second->filename);
  43218. }
  43219. bool DirectoryContentsList::addFile (const String& filename,
  43220. const bool isDir,
  43221. const bool isHidden,
  43222. const int64 fileSize,
  43223. const Time& modTime,
  43224. const Time& creationTime,
  43225. const bool isReadOnly)
  43226. {
  43227. if (filename == T("..")
  43228. || filename == T(".")
  43229. || (ignoreHiddenFiles && isHidden))
  43230. return false;
  43231. const File file (root.getChildFile (filename));
  43232. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  43233. && (fileFilter == 0
  43234. || ((! isDir) && fileFilter->isFileSuitable (file))
  43235. || (isDir && fileFilter->isDirectorySuitable (file))))
  43236. {
  43237. FileInfo* const info = new FileInfo();
  43238. info->filename = filename;
  43239. info->fileSize = fileSize;
  43240. info->modificationTime = modTime;
  43241. info->creationTime = creationTime;
  43242. info->isDirectory = isDir;
  43243. info->isReadOnly = isReadOnly;
  43244. const ScopedLock sl (fileListLock);
  43245. for (int i = files.size(); --i >= 0;)
  43246. {
  43247. if (files.getUnchecked(i)->filename == info->filename)
  43248. {
  43249. delete info;
  43250. return false;
  43251. }
  43252. }
  43253. files.addSorted (*this, info);
  43254. return true;
  43255. }
  43256. return false;
  43257. }
  43258. END_JUCE_NAMESPACE
  43259. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  43260. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  43261. BEGIN_JUCE_NAMESPACE
  43262. class DirectoriesOnlyFilter : public FileFilter
  43263. {
  43264. public:
  43265. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  43266. bool isFileSuitable (const File&) const { return false; }
  43267. bool isDirectorySuitable (const File&) const { return true; }
  43268. };
  43269. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  43270. const File& initialFileOrDirectory,
  43271. const FileFilter* fileFilter,
  43272. FilePreviewComponent* previewComp_,
  43273. const bool useTreeView,
  43274. const bool filenameTextBoxIsReadOnly)
  43275. : directoriesOnlyFilter (0),
  43276. mode (mode_),
  43277. listeners (2),
  43278. previewComp (previewComp_),
  43279. thread ("Juce FileBrowser")
  43280. {
  43281. String filename;
  43282. if (initialFileOrDirectory == File::nonexistent)
  43283. {
  43284. currentRoot = File::getCurrentWorkingDirectory();
  43285. }
  43286. else if (initialFileOrDirectory.isDirectory())
  43287. {
  43288. currentRoot = initialFileOrDirectory;
  43289. }
  43290. else
  43291. {
  43292. currentRoot = initialFileOrDirectory.getParentDirectory();
  43293. filename = initialFileOrDirectory.getFileName();
  43294. }
  43295. if (mode_ == chooseDirectoryMode)
  43296. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  43297. fileList = new DirectoryContentsList (fileFilter, thread);
  43298. if (useTreeView)
  43299. {
  43300. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  43301. addAndMakeVisible (tree);
  43302. fileListComponent = tree;
  43303. }
  43304. else
  43305. {
  43306. FileListComponent* const list = new FileListComponent (*fileList);
  43307. list->setOutlineThickness (1);
  43308. addAndMakeVisible (list);
  43309. fileListComponent = list;
  43310. }
  43311. fileListComponent->addListener (this);
  43312. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  43313. currentPathBox->setEditableText (true);
  43314. StringArray rootNames, rootPaths;
  43315. const BitArray separators (getRoots (rootNames, rootPaths));
  43316. for (int i = 0; i < rootNames.size(); ++i)
  43317. {
  43318. if (separators [i])
  43319. currentPathBox->addSeparator();
  43320. currentPathBox->addItem (rootNames[i], i + 1);
  43321. }
  43322. currentPathBox->addSeparator();
  43323. currentPathBox->addListener (this);
  43324. addAndMakeVisible (filenameBox = new TextEditor());
  43325. filenameBox->setMultiLine (false);
  43326. filenameBox->setSelectAllWhenFocused (true);
  43327. filenameBox->setText (filename, false);
  43328. filenameBox->addListener (this);
  43329. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  43330. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  43331. : TRANS("file:"));
  43332. addAndMakeVisible (label);
  43333. label->attachToComponent (filenameBox, true);
  43334. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  43335. goUpButton->addButtonListener (this);
  43336. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  43337. if (previewComp != 0)
  43338. addAndMakeVisible (previewComp);
  43339. setRoot (currentRoot);
  43340. thread.startThread (4);
  43341. }
  43342. FileBrowserComponent::~FileBrowserComponent()
  43343. {
  43344. if (previewComp != 0)
  43345. removeChildComponent (previewComp);
  43346. deleteAllChildren();
  43347. deleteAndZero (fileList);
  43348. delete directoriesOnlyFilter;
  43349. thread.stopThread (10000);
  43350. }
  43351. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  43352. {
  43353. jassert (newListener != 0)
  43354. if (newListener != 0)
  43355. listeners.add (newListener);
  43356. }
  43357. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  43358. {
  43359. listeners.removeValue (listener);
  43360. }
  43361. const File FileBrowserComponent::getCurrentFile() const throw()
  43362. {
  43363. return currentRoot.getChildFile (filenameBox->getText());
  43364. }
  43365. bool FileBrowserComponent::currentFileIsValid() const
  43366. {
  43367. if (mode == saveFileMode)
  43368. return ! getCurrentFile().isDirectory();
  43369. else if (mode == loadFileMode)
  43370. return getCurrentFile().existsAsFile();
  43371. else if (mode == chooseDirectoryMode)
  43372. return getCurrentFile().isDirectory();
  43373. jassertfalse
  43374. return false;
  43375. }
  43376. const File FileBrowserComponent::getRoot() const
  43377. {
  43378. return currentRoot;
  43379. }
  43380. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  43381. {
  43382. if (currentRoot != newRootDirectory)
  43383. {
  43384. fileListComponent->scrollToTop();
  43385. if (mode == chooseDirectoryMode)
  43386. filenameBox->setText (String::empty, false);
  43387. String path (newRootDirectory.getFullPathName());
  43388. if (path.isEmpty())
  43389. path += File::separator;
  43390. StringArray rootNames, rootPaths;
  43391. getRoots (rootNames, rootPaths);
  43392. if (! rootPaths.contains (path, true))
  43393. {
  43394. bool alreadyListed = false;
  43395. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  43396. {
  43397. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  43398. {
  43399. alreadyListed = true;
  43400. break;
  43401. }
  43402. }
  43403. if (! alreadyListed)
  43404. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  43405. }
  43406. }
  43407. currentRoot = newRootDirectory;
  43408. fileList->setDirectory (currentRoot, true, true);
  43409. String currentRootName (currentRoot.getFullPathName());
  43410. if (currentRootName.isEmpty())
  43411. currentRootName += File::separator;
  43412. currentPathBox->setText (currentRootName, true);
  43413. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  43414. && currentRoot.getParentDirectory() != currentRoot);
  43415. }
  43416. void FileBrowserComponent::goUp()
  43417. {
  43418. setRoot (getRoot().getParentDirectory());
  43419. }
  43420. void FileBrowserComponent::refresh()
  43421. {
  43422. fileList->refresh();
  43423. }
  43424. const String FileBrowserComponent::getActionVerb() const
  43425. {
  43426. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  43427. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  43428. }
  43429. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  43430. {
  43431. return previewComp;
  43432. }
  43433. void FileBrowserComponent::resized()
  43434. {
  43435. getLookAndFeel()
  43436. .layoutFileBrowserComponent (*this, fileListComponent,
  43437. previewComp, currentPathBox,
  43438. filenameBox, goUpButton);
  43439. }
  43440. void FileBrowserComponent::sendListenerChangeMessage()
  43441. {
  43442. ComponentDeletionWatcher deletionWatcher (this);
  43443. if (previewComp != 0)
  43444. previewComp->selectedFileChanged (getCurrentFile());
  43445. jassert (! deletionWatcher.hasBeenDeleted());
  43446. for (int i = listeners.size(); --i >= 0;)
  43447. {
  43448. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43449. if (deletionWatcher.hasBeenDeleted())
  43450. return;
  43451. i = jmin (i, listeners.size() - 1);
  43452. }
  43453. }
  43454. void FileBrowserComponent::selectionChanged()
  43455. {
  43456. const File selected (fileListComponent->getSelectedFile());
  43457. if ((mode == chooseDirectoryMode && selected.isDirectory())
  43458. || selected.existsAsFile())
  43459. {
  43460. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  43461. }
  43462. sendListenerChangeMessage();
  43463. }
  43464. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  43465. {
  43466. ComponentDeletionWatcher deletionWatcher (this);
  43467. for (int i = listeners.size(); --i >= 0;)
  43468. {
  43469. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  43470. if (deletionWatcher.hasBeenDeleted())
  43471. return;
  43472. i = jmin (i, listeners.size() - 1);
  43473. }
  43474. }
  43475. void FileBrowserComponent::fileDoubleClicked (const File& f)
  43476. {
  43477. if (f.isDirectory())
  43478. {
  43479. setRoot (f);
  43480. }
  43481. else
  43482. {
  43483. ComponentDeletionWatcher deletionWatcher (this);
  43484. for (int i = listeners.size(); --i >= 0;)
  43485. {
  43486. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  43487. if (deletionWatcher.hasBeenDeleted())
  43488. return;
  43489. i = jmin (i, listeners.size() - 1);
  43490. }
  43491. }
  43492. }
  43493. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  43494. {
  43495. #if JUCE_LINUX || JUCE_WINDOWS
  43496. if (key.getModifiers().isCommandDown()
  43497. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  43498. {
  43499. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  43500. fileList->refresh();
  43501. return true;
  43502. }
  43503. #endif
  43504. return false;
  43505. }
  43506. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  43507. {
  43508. sendListenerChangeMessage();
  43509. }
  43510. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  43511. {
  43512. if (filenameBox->getText().containsChar (File::separator))
  43513. {
  43514. const File f (currentRoot.getChildFile (filenameBox->getText()));
  43515. if (f.isDirectory())
  43516. {
  43517. setRoot (f);
  43518. filenameBox->setText (String::empty);
  43519. }
  43520. else
  43521. {
  43522. setRoot (f.getParentDirectory());
  43523. filenameBox->setText (f.getFileName());
  43524. }
  43525. }
  43526. else
  43527. {
  43528. fileDoubleClicked (getCurrentFile());
  43529. }
  43530. }
  43531. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  43532. {
  43533. }
  43534. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  43535. {
  43536. if (mode != saveFileMode)
  43537. selectionChanged();
  43538. }
  43539. void FileBrowserComponent::buttonClicked (Button*)
  43540. {
  43541. goUp();
  43542. }
  43543. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  43544. {
  43545. const String newText (currentPathBox->getText().trim().unquoted());
  43546. if (newText.isNotEmpty())
  43547. {
  43548. const int index = currentPathBox->getSelectedId() - 1;
  43549. StringArray rootNames, rootPaths;
  43550. getRoots (rootNames, rootPaths);
  43551. if (rootPaths [index].isNotEmpty())
  43552. {
  43553. setRoot (File (rootPaths [index]));
  43554. }
  43555. else
  43556. {
  43557. File f (newText);
  43558. for (;;)
  43559. {
  43560. if (f.isDirectory())
  43561. {
  43562. setRoot (f);
  43563. break;
  43564. }
  43565. if (f.getParentDirectory() == f)
  43566. break;
  43567. f = f.getParentDirectory();
  43568. }
  43569. }
  43570. }
  43571. }
  43572. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  43573. {
  43574. BitArray separators;
  43575. #if JUCE_WINDOWS
  43576. OwnedArray<File> roots;
  43577. File::findFileSystemRoots (roots);
  43578. rootPaths.clear();
  43579. for (int i = 0; i < roots.size(); ++i)
  43580. {
  43581. const File* const drive = roots.getUnchecked(i);
  43582. String name (drive->getFullPathName());
  43583. rootPaths.add (name);
  43584. if (drive->isOnHardDisk())
  43585. {
  43586. String volume (drive->getVolumeLabel());
  43587. if (volume.isEmpty())
  43588. volume = TRANS("Hard Drive");
  43589. name << " [" << drive->getVolumeLabel() << ']';
  43590. }
  43591. else if (drive->isOnCDRomDrive())
  43592. {
  43593. name << TRANS(" [CD/DVD drive]");
  43594. }
  43595. rootNames.add (name);
  43596. }
  43597. separators.setBit (rootPaths.size());
  43598. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43599. rootNames.add ("Documents");
  43600. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43601. rootNames.add ("Desktop");
  43602. #endif
  43603. #if JUCE_MAC
  43604. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43605. rootNames.add ("Home folder");
  43606. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43607. rootNames.add ("Documents");
  43608. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43609. rootNames.add ("Desktop");
  43610. separators.setBit (rootPaths.size());
  43611. OwnedArray <File> volumes;
  43612. File vol ("/Volumes");
  43613. vol.findChildFiles (volumes, File::findDirectories, false);
  43614. for (int i = 0; i < volumes.size(); ++i)
  43615. {
  43616. const File* const volume = volumes.getUnchecked(i);
  43617. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  43618. {
  43619. rootPaths.add (volume->getFullPathName());
  43620. rootNames.add (volume->getFileName());
  43621. }
  43622. }
  43623. #endif
  43624. #if JUCE_LINUX
  43625. rootPaths.add ("/");
  43626. rootNames.add ("/");
  43627. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43628. rootNames.add ("Home folder");
  43629. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43630. rootNames.add ("Desktop");
  43631. #endif
  43632. return separators;
  43633. }
  43634. END_JUCE_NAMESPACE
  43635. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  43636. /********* Start of inlined file: juce_FileChooser.cpp *********/
  43637. BEGIN_JUCE_NAMESPACE
  43638. FileChooser::FileChooser (const String& chooserBoxTitle,
  43639. const File& currentFileOrDirectory,
  43640. const String& fileFilters,
  43641. const bool useNativeDialogBox_)
  43642. : title (chooserBoxTitle),
  43643. filters (fileFilters),
  43644. startingFile (currentFileOrDirectory),
  43645. useNativeDialogBox (useNativeDialogBox_)
  43646. {
  43647. #if JUCE_LINUX
  43648. useNativeDialogBox = false;
  43649. #endif
  43650. if (! fileFilters.containsNonWhitespaceChars())
  43651. filters = T("*");
  43652. }
  43653. FileChooser::~FileChooser()
  43654. {
  43655. }
  43656. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  43657. {
  43658. return showDialog (false, false, false, false, previewComponent);
  43659. }
  43660. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  43661. {
  43662. return showDialog (false, false, false, true, previewComponent);
  43663. }
  43664. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  43665. {
  43666. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  43667. }
  43668. bool FileChooser::browseForDirectory()
  43669. {
  43670. return showDialog (true, false, false, false, 0);
  43671. }
  43672. const File FileChooser::getResult() const
  43673. {
  43674. // if you've used a multiple-file select, you should use the getResults() method
  43675. // to retrieve all the files that were chosen.
  43676. jassert (results.size() <= 1);
  43677. const File* const f = results.getFirst();
  43678. if (f != 0)
  43679. return *f;
  43680. return File::nonexistent;
  43681. }
  43682. const OwnedArray <File>& FileChooser::getResults() const
  43683. {
  43684. return results;
  43685. }
  43686. bool FileChooser::showDialog (const bool isDirectory,
  43687. const bool isSave,
  43688. const bool warnAboutOverwritingExistingFiles,
  43689. const bool selectMultipleFiles,
  43690. FilePreviewComponent* const previewComponent)
  43691. {
  43692. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  43693. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  43694. if (currentlyFocused != 0)
  43695. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  43696. results.clear();
  43697. // the preview component needs to be the right size before you pass it in here..
  43698. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  43699. && previewComponent->getHeight() > 10));
  43700. #if JUCE_WINDOWS
  43701. if (useNativeDialogBox)
  43702. #else
  43703. if (useNativeDialogBox && (previewComponent == 0))
  43704. #endif
  43705. {
  43706. showPlatformDialog (results, title, startingFile, filters,
  43707. isDirectory, isSave,
  43708. warnAboutOverwritingExistingFiles,
  43709. selectMultipleFiles,
  43710. previewComponent);
  43711. }
  43712. else
  43713. {
  43714. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  43715. WildcardFileFilter wildcard (filters, String::empty);
  43716. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  43717. : (isSave ? FileBrowserComponent::saveFileMode
  43718. : FileBrowserComponent::loadFileMode),
  43719. startingFile, &wildcard, previewComponent);
  43720. FileChooserDialogBox box (title, String::empty,
  43721. browserComponent,
  43722. warnAboutOverwritingExistingFiles,
  43723. browserComponent.findColour (AlertWindow::backgroundColourId));
  43724. if (box.show())
  43725. results.add (new File (browserComponent.getCurrentFile()));
  43726. }
  43727. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  43728. currentlyFocused->grabKeyboardFocus();
  43729. delete currentlyFocusedChecker;
  43730. return results.size() > 0;
  43731. }
  43732. FilePreviewComponent::FilePreviewComponent()
  43733. {
  43734. }
  43735. FilePreviewComponent::~FilePreviewComponent()
  43736. {
  43737. }
  43738. END_JUCE_NAMESPACE
  43739. /********* End of inlined file: juce_FileChooser.cpp *********/
  43740. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  43741. BEGIN_JUCE_NAMESPACE
  43742. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  43743. const String& instructions,
  43744. FileBrowserComponent& chooserComponent,
  43745. const bool warnAboutOverwritingExistingFiles_,
  43746. const Colour& backgroundColour)
  43747. : ResizableWindow (name, backgroundColour, true),
  43748. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  43749. {
  43750. content = new ContentComponent();
  43751. content->setName (name);
  43752. content->instructions = instructions;
  43753. content->chooserComponent = &chooserComponent;
  43754. content->addAndMakeVisible (&chooserComponent);
  43755. content->okButton = new TextButton (chooserComponent.getActionVerb());
  43756. content->addAndMakeVisible (content->okButton);
  43757. content->okButton->addButtonListener (this);
  43758. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  43759. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  43760. content->cancelButton = new TextButton (TRANS("Cancel"));
  43761. content->addAndMakeVisible (content->cancelButton);
  43762. content->cancelButton->addButtonListener (this);
  43763. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  43764. setContentComponent (content);
  43765. setResizable (true, true);
  43766. setResizeLimits (300, 300, 1200, 1000);
  43767. content->chooserComponent->addListener (this);
  43768. }
  43769. FileChooserDialogBox::~FileChooserDialogBox()
  43770. {
  43771. content->chooserComponent->removeListener (this);
  43772. }
  43773. bool FileChooserDialogBox::show (int w, int h)
  43774. {
  43775. if (w <= 0)
  43776. {
  43777. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  43778. if (previewComp != 0)
  43779. w = 400 + previewComp->getWidth();
  43780. else
  43781. w = 600;
  43782. }
  43783. if (h <= 0)
  43784. h = 500;
  43785. centreWithSize (w, h);
  43786. const bool ok = (runModalLoop() != 0);
  43787. setVisible (false);
  43788. return ok;
  43789. }
  43790. void FileChooserDialogBox::buttonClicked (Button* button)
  43791. {
  43792. if (button == content->okButton)
  43793. {
  43794. if (warnAboutOverwritingExistingFiles
  43795. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  43796. && content->chooserComponent->getCurrentFile().exists())
  43797. {
  43798. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43799. TRANS("File already exists"),
  43800. TRANS("There's already a file called:\n\n")
  43801. + content->chooserComponent->getCurrentFile().getFullPathName()
  43802. + T("\n\nAre you sure you want to overwrite it?"),
  43803. TRANS("overwrite"),
  43804. TRANS("cancel")))
  43805. {
  43806. return;
  43807. }
  43808. }
  43809. exitModalState (1);
  43810. }
  43811. else if (button == content->cancelButton)
  43812. closeButtonPressed();
  43813. }
  43814. void FileChooserDialogBox::closeButtonPressed()
  43815. {
  43816. setVisible (false);
  43817. }
  43818. void FileChooserDialogBox::selectionChanged()
  43819. {
  43820. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  43821. }
  43822. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  43823. {
  43824. }
  43825. void FileChooserDialogBox::fileDoubleClicked (const File&)
  43826. {
  43827. selectionChanged();
  43828. content->okButton->triggerClick();
  43829. }
  43830. FileChooserDialogBox::ContentComponent::ContentComponent()
  43831. {
  43832. setInterceptsMouseClicks (false, true);
  43833. }
  43834. FileChooserDialogBox::ContentComponent::~ContentComponent()
  43835. {
  43836. delete okButton;
  43837. delete cancelButton;
  43838. }
  43839. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  43840. {
  43841. g.setColour (Colours::black);
  43842. text.draw (g);
  43843. }
  43844. void FileChooserDialogBox::ContentComponent::resized()
  43845. {
  43846. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  43847. float left, top, right, bottom;
  43848. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  43849. const int y = roundFloatToInt (bottom) + 10;
  43850. const int buttonHeight = 26;
  43851. const int buttonY = getHeight() - buttonHeight - 8;
  43852. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  43853. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  43854. proportionOfWidth (0.2f), buttonHeight);
  43855. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  43856. proportionOfWidth (0.2f), buttonHeight);
  43857. }
  43858. END_JUCE_NAMESPACE
  43859. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  43860. /********* Start of inlined file: juce_FileFilter.cpp *********/
  43861. BEGIN_JUCE_NAMESPACE
  43862. FileFilter::FileFilter (const String& filterDescription)
  43863. : description (filterDescription)
  43864. {
  43865. }
  43866. FileFilter::~FileFilter()
  43867. {
  43868. }
  43869. const String& FileFilter::getDescription() const throw()
  43870. {
  43871. return description;
  43872. }
  43873. END_JUCE_NAMESPACE
  43874. /********* End of inlined file: juce_FileFilter.cpp *********/
  43875. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  43876. BEGIN_JUCE_NAMESPACE
  43877. Image* juce_createIconForFile (const File& file);
  43878. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  43879. : ListBox (String::empty, 0),
  43880. DirectoryContentsDisplayComponent (listToShow)
  43881. {
  43882. setModel (this);
  43883. fileList.addChangeListener (this);
  43884. }
  43885. FileListComponent::~FileListComponent()
  43886. {
  43887. fileList.removeChangeListener (this);
  43888. deleteAllChildren();
  43889. }
  43890. const File FileListComponent::getSelectedFile() const
  43891. {
  43892. return fileList.getFile (getSelectedRow());
  43893. }
  43894. void FileListComponent::scrollToTop()
  43895. {
  43896. getVerticalScrollBar()->setCurrentRangeStart (0);
  43897. }
  43898. void FileListComponent::changeListenerCallback (void*)
  43899. {
  43900. updateContent();
  43901. if (lastDirectory != fileList.getDirectory())
  43902. {
  43903. lastDirectory = fileList.getDirectory();
  43904. deselectAllRows();
  43905. }
  43906. }
  43907. class FileListItemComponent : public Component,
  43908. public TimeSliceClient,
  43909. public AsyncUpdater
  43910. {
  43911. public:
  43912. FileListItemComponent (FileListComponent& owner_,
  43913. TimeSliceThread& thread_) throw()
  43914. : owner (owner_),
  43915. thread (thread_),
  43916. icon (0)
  43917. {
  43918. }
  43919. ~FileListItemComponent() throw()
  43920. {
  43921. thread.removeTimeSliceClient (this);
  43922. clearIcon();
  43923. }
  43924. void paint (Graphics& g)
  43925. {
  43926. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  43927. file.getFileName(),
  43928. icon,
  43929. fileSize, modTime,
  43930. isDirectory, highlighted,
  43931. index);
  43932. }
  43933. void mouseDown (const MouseEvent& e)
  43934. {
  43935. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  43936. owner.sendMouseClickMessage (file, e);
  43937. }
  43938. void mouseDoubleClick (const MouseEvent&)
  43939. {
  43940. owner.sendDoubleClickMessage (file);
  43941. }
  43942. void update (const File& root,
  43943. const DirectoryContentsList::FileInfo* const fileInfo,
  43944. const int index_,
  43945. const bool highlighted_) throw()
  43946. {
  43947. thread.removeTimeSliceClient (this);
  43948. if (highlighted_ != highlighted
  43949. || index_ != index)
  43950. {
  43951. index = index_;
  43952. highlighted = highlighted_;
  43953. repaint();
  43954. }
  43955. File newFile;
  43956. String newFileSize;
  43957. String newModTime;
  43958. if (fileInfo != 0)
  43959. {
  43960. newFile = root.getChildFile (fileInfo->filename);
  43961. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  43962. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  43963. }
  43964. if (newFile != file
  43965. || fileSize != newFileSize
  43966. || modTime != newModTime)
  43967. {
  43968. file = newFile;
  43969. fileSize = newFileSize;
  43970. modTime = newModTime;
  43971. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  43972. repaint();
  43973. clearIcon();
  43974. }
  43975. if (file != File::nonexistent
  43976. && icon == 0 && ! isDirectory)
  43977. {
  43978. updateIcon (true);
  43979. if (icon == 0)
  43980. thread.addTimeSliceClient (this);
  43981. }
  43982. }
  43983. bool useTimeSlice()
  43984. {
  43985. updateIcon (false);
  43986. return false;
  43987. }
  43988. void handleAsyncUpdate()
  43989. {
  43990. repaint();
  43991. }
  43992. juce_UseDebuggingNewOperator
  43993. private:
  43994. FileListComponent& owner;
  43995. TimeSliceThread& thread;
  43996. bool highlighted;
  43997. int index;
  43998. File file;
  43999. String fileSize;
  44000. String modTime;
  44001. Image* icon;
  44002. bool isDirectory;
  44003. void clearIcon() throw()
  44004. {
  44005. ImageCache::release (icon);
  44006. icon = 0;
  44007. }
  44008. void updateIcon (const bool onlyUpdateIfCached) throw()
  44009. {
  44010. if (icon == 0)
  44011. {
  44012. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44013. Image* im = ImageCache::getFromHashCode (hashCode);
  44014. if (im == 0 && ! onlyUpdateIfCached)
  44015. {
  44016. im = juce_createIconForFile (file);
  44017. if (im != 0)
  44018. ImageCache::addImageToCache (im, hashCode);
  44019. }
  44020. if (im != 0)
  44021. {
  44022. icon = im;
  44023. triggerAsyncUpdate();
  44024. }
  44025. }
  44026. }
  44027. };
  44028. int FileListComponent::getNumRows()
  44029. {
  44030. return fileList.getNumFiles();
  44031. }
  44032. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  44033. {
  44034. }
  44035. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  44036. {
  44037. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  44038. if (comp == 0)
  44039. {
  44040. delete existingComponentToUpdate;
  44041. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  44042. }
  44043. DirectoryContentsList::FileInfo fileInfo;
  44044. if (fileList.getFileInfo (row, fileInfo))
  44045. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  44046. else
  44047. comp->update (fileList.getDirectory(), 0, row, isSelected);
  44048. return comp;
  44049. }
  44050. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  44051. {
  44052. sendSelectionChangeMessage();
  44053. }
  44054. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  44055. {
  44056. }
  44057. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  44058. {
  44059. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  44060. }
  44061. END_JUCE_NAMESPACE
  44062. /********* End of inlined file: juce_FileListComponent.cpp *********/
  44063. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  44064. BEGIN_JUCE_NAMESPACE
  44065. FilenameComponent::FilenameComponent (const String& name,
  44066. const File& currentFile,
  44067. const bool canEditFilename,
  44068. const bool isDirectory,
  44069. const bool isForSaving,
  44070. const String& fileBrowserWildcard,
  44071. const String& enforcedSuffix_,
  44072. const String& textWhenNothingSelected)
  44073. : Component (name),
  44074. maxRecentFiles (30),
  44075. isDir (isDirectory),
  44076. isSaving (isForSaving),
  44077. isFileDragOver (false),
  44078. wildcard (fileBrowserWildcard),
  44079. enforcedSuffix (enforcedSuffix_)
  44080. {
  44081. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  44082. filenameBox->setEditableText (canEditFilename);
  44083. filenameBox->addListener (this);
  44084. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  44085. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  44086. browseButton = 0;
  44087. setBrowseButtonText (T("..."));
  44088. setCurrentFile (currentFile, true);
  44089. }
  44090. FilenameComponent::~FilenameComponent()
  44091. {
  44092. deleteAllChildren();
  44093. }
  44094. void FilenameComponent::paintOverChildren (Graphics& g)
  44095. {
  44096. if (isFileDragOver)
  44097. {
  44098. g.setColour (Colours::red.withAlpha (0.2f));
  44099. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  44100. }
  44101. }
  44102. void FilenameComponent::resized()
  44103. {
  44104. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  44105. }
  44106. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  44107. {
  44108. browseButtonText = newBrowseButtonText;
  44109. lookAndFeelChanged();
  44110. }
  44111. void FilenameComponent::lookAndFeelChanged()
  44112. {
  44113. deleteAndZero (browseButton);
  44114. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  44115. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  44116. resized();
  44117. browseButton->addButtonListener (this);
  44118. }
  44119. void FilenameComponent::setTooltip (const String& newTooltip)
  44120. {
  44121. SettableTooltipClient::setTooltip (newTooltip);
  44122. filenameBox->setTooltip (newTooltip);
  44123. }
  44124. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44125. {
  44126. defaultBrowseFile = newDefaultDirectory;
  44127. }
  44128. void FilenameComponent::buttonClicked (Button*)
  44129. {
  44130. FileChooser fc (TRANS("Choose a new file"),
  44131. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  44132. : getCurrentFile(),
  44133. wildcard);
  44134. if (isDir ? fc.browseForDirectory()
  44135. : (isSaving ? fc.browseForFileToSave (false)
  44136. : fc.browseForFileToOpen()))
  44137. {
  44138. setCurrentFile (fc.getResult(), true);
  44139. }
  44140. }
  44141. void FilenameComponent::comboBoxChanged (ComboBox*)
  44142. {
  44143. setCurrentFile (getCurrentFile(), true);
  44144. }
  44145. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  44146. {
  44147. return true;
  44148. }
  44149. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  44150. {
  44151. isFileDragOver = false;
  44152. repaint();
  44153. const File f (filenames[0]);
  44154. if (f.exists() && (f.isDirectory() == isDir))
  44155. setCurrentFile (f, true);
  44156. }
  44157. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  44158. {
  44159. isFileDragOver = true;
  44160. repaint();
  44161. }
  44162. void FilenameComponent::fileDragExit (const StringArray&)
  44163. {
  44164. isFileDragOver = false;
  44165. repaint();
  44166. }
  44167. const File FilenameComponent::getCurrentFile() const
  44168. {
  44169. File f (filenameBox->getText());
  44170. if (enforcedSuffix.isNotEmpty())
  44171. f = f.withFileExtension (enforcedSuffix);
  44172. return f;
  44173. }
  44174. void FilenameComponent::setCurrentFile (File newFile,
  44175. const bool addToRecentlyUsedList,
  44176. const bool sendChangeNotification)
  44177. {
  44178. if (enforcedSuffix.isNotEmpty())
  44179. newFile = newFile.withFileExtension (enforcedSuffix);
  44180. if (newFile.getFullPathName() != lastFilename)
  44181. {
  44182. lastFilename = newFile.getFullPathName();
  44183. if (addToRecentlyUsedList)
  44184. addRecentlyUsedFile (newFile);
  44185. filenameBox->setText (lastFilename, true);
  44186. if (sendChangeNotification)
  44187. triggerAsyncUpdate();
  44188. }
  44189. }
  44190. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  44191. {
  44192. filenameBox->setEditableText (shouldBeEditable);
  44193. }
  44194. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  44195. {
  44196. StringArray names;
  44197. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  44198. names.add (filenameBox->getItemText (i));
  44199. return names;
  44200. }
  44201. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  44202. {
  44203. if (filenames != getRecentlyUsedFilenames())
  44204. {
  44205. filenameBox->clear();
  44206. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  44207. filenameBox->addItem (filenames[i], i + 1);
  44208. }
  44209. }
  44210. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  44211. {
  44212. maxRecentFiles = jmax (1, newMaximum);
  44213. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  44214. }
  44215. void FilenameComponent::addRecentlyUsedFile (const File& file)
  44216. {
  44217. StringArray files (getRecentlyUsedFilenames());
  44218. if (file.getFullPathName().isNotEmpty())
  44219. {
  44220. files.removeString (file.getFullPathName(), true);
  44221. files.insert (0, file.getFullPathName());
  44222. setRecentlyUsedFilenames (files);
  44223. }
  44224. }
  44225. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  44226. {
  44227. jassert (listener != 0);
  44228. if (listener != 0)
  44229. listeners.add (listener);
  44230. }
  44231. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  44232. {
  44233. listeners.removeValue (listener);
  44234. }
  44235. void FilenameComponent::handleAsyncUpdate()
  44236. {
  44237. for (int i = listeners.size(); --i >= 0;)
  44238. {
  44239. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  44240. i = jmin (i, listeners.size());
  44241. }
  44242. }
  44243. END_JUCE_NAMESPACE
  44244. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  44245. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44246. BEGIN_JUCE_NAMESPACE
  44247. FileSearchPathListComponent::FileSearchPathListComponent()
  44248. {
  44249. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  44250. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  44251. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  44252. listBox->setOutlineThickness (1);
  44253. addAndMakeVisible (addButton = new TextButton ("+"));
  44254. addButton->addButtonListener (this);
  44255. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44256. addAndMakeVisible (removeButton = new TextButton ("-"));
  44257. removeButton->addButtonListener (this);
  44258. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44259. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  44260. changeButton->addButtonListener (this);
  44261. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44262. upButton->addButtonListener (this);
  44263. {
  44264. Path arrowPath;
  44265. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  44266. DrawablePath arrowImage;
  44267. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44268. arrowImage.setPath (arrowPath);
  44269. ((DrawableButton*) upButton)->setImages (&arrowImage);
  44270. }
  44271. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44272. downButton->addButtonListener (this);
  44273. {
  44274. Path arrowPath;
  44275. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  44276. DrawablePath arrowImage;
  44277. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44278. arrowImage.setPath (arrowPath);
  44279. ((DrawableButton*) downButton)->setImages (&arrowImage);
  44280. }
  44281. updateButtons();
  44282. }
  44283. FileSearchPathListComponent::~FileSearchPathListComponent()
  44284. {
  44285. deleteAllChildren();
  44286. }
  44287. void FileSearchPathListComponent::updateButtons() throw()
  44288. {
  44289. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  44290. removeButton->setEnabled (anythingSelected);
  44291. changeButton->setEnabled (anythingSelected);
  44292. upButton->setEnabled (anythingSelected);
  44293. downButton->setEnabled (anythingSelected);
  44294. }
  44295. void FileSearchPathListComponent::changed() throw()
  44296. {
  44297. listBox->updateContent();
  44298. listBox->repaint();
  44299. updateButtons();
  44300. }
  44301. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  44302. {
  44303. if (newPath.toString() != path.toString())
  44304. {
  44305. path = newPath;
  44306. changed();
  44307. }
  44308. }
  44309. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44310. {
  44311. defaultBrowseTarget = newDefaultDirectory;
  44312. }
  44313. int FileSearchPathListComponent::getNumRows()
  44314. {
  44315. return path.getNumPaths();
  44316. }
  44317. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  44318. {
  44319. if (rowIsSelected)
  44320. g.fillAll (findColour (TextEditor::highlightColourId));
  44321. g.setColour (findColour (ListBox::textColourId));
  44322. Font f (height * 0.7f);
  44323. f.setHorizontalScale (0.9f);
  44324. g.setFont (f);
  44325. g.drawText (path [rowNumber].getFullPathName(),
  44326. 4, 0, width - 6, height,
  44327. Justification::centredLeft, true);
  44328. }
  44329. void FileSearchPathListComponent::deleteKeyPressed (int row)
  44330. {
  44331. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  44332. {
  44333. path.remove (row);
  44334. changed();
  44335. }
  44336. }
  44337. void FileSearchPathListComponent::returnKeyPressed (int row)
  44338. {
  44339. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  44340. if (chooser.browseForDirectory())
  44341. {
  44342. path.remove (row);
  44343. path.add (chooser.getResult(), row);
  44344. changed();
  44345. }
  44346. }
  44347. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  44348. {
  44349. returnKeyPressed (row);
  44350. }
  44351. void FileSearchPathListComponent::selectedRowsChanged (int)
  44352. {
  44353. updateButtons();
  44354. }
  44355. void FileSearchPathListComponent::paint (Graphics& g)
  44356. {
  44357. g.fillAll (findColour (backgroundColourId));
  44358. }
  44359. void FileSearchPathListComponent::resized()
  44360. {
  44361. const int buttonH = 22;
  44362. const int buttonY = getHeight() - buttonH - 4;
  44363. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  44364. addButton->setBounds (2, buttonY, buttonH, buttonH);
  44365. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  44366. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  44367. downButton->setSize (buttonH * 2, buttonH);
  44368. upButton->setSize (buttonH * 2, buttonH);
  44369. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  44370. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  44371. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  44372. }
  44373. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  44374. {
  44375. return true;
  44376. }
  44377. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  44378. {
  44379. for (int i = filenames.size(); --i >= 0;)
  44380. {
  44381. const File f (filenames[i]);
  44382. if (f.isDirectory())
  44383. {
  44384. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  44385. path.add (f, row);
  44386. changed();
  44387. }
  44388. }
  44389. }
  44390. void FileSearchPathListComponent::buttonClicked (Button* button)
  44391. {
  44392. const int currentRow = listBox->getSelectedRow();
  44393. if (button == removeButton)
  44394. {
  44395. deleteKeyPressed (currentRow);
  44396. }
  44397. else if (button == addButton)
  44398. {
  44399. File start (defaultBrowseTarget);
  44400. if (start == File::nonexistent)
  44401. start = path [0];
  44402. if (start == File::nonexistent)
  44403. start = File::getCurrentWorkingDirectory();
  44404. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  44405. if (chooser.browseForDirectory())
  44406. {
  44407. path.add (chooser.getResult(), currentRow);
  44408. }
  44409. }
  44410. else if (button == changeButton)
  44411. {
  44412. returnKeyPressed (currentRow);
  44413. }
  44414. else if (button == upButton)
  44415. {
  44416. if (currentRow > 0 && currentRow < path.getNumPaths())
  44417. {
  44418. const File f (path[currentRow]);
  44419. path.remove (currentRow);
  44420. path.add (f, currentRow - 1);
  44421. listBox->selectRow (currentRow - 1);
  44422. }
  44423. }
  44424. else if (button == downButton)
  44425. {
  44426. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  44427. {
  44428. const File f (path[currentRow]);
  44429. path.remove (currentRow);
  44430. path.add (f, currentRow + 1);
  44431. listBox->selectRow (currentRow + 1);
  44432. }
  44433. }
  44434. changed();
  44435. }
  44436. END_JUCE_NAMESPACE
  44437. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44438. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  44439. BEGIN_JUCE_NAMESPACE
  44440. Image* juce_createIconForFile (const File& file);
  44441. class FileListTreeItem : public TreeViewItem,
  44442. public TimeSliceClient,
  44443. public AsyncUpdater,
  44444. public ChangeListener
  44445. {
  44446. public:
  44447. FileListTreeItem (FileTreeComponent& owner_,
  44448. DirectoryContentsList* const parentContentsList_,
  44449. const int indexInContentsList_,
  44450. const File& file_,
  44451. TimeSliceThread& thread_) throw()
  44452. : file (file_),
  44453. owner (owner_),
  44454. parentContentsList (parentContentsList_),
  44455. indexInContentsList (indexInContentsList_),
  44456. subContentsList (0),
  44457. canDeleteSubContentsList (false),
  44458. thread (thread_),
  44459. icon (0)
  44460. {
  44461. DirectoryContentsList::FileInfo fileInfo;
  44462. if (parentContentsList_ != 0
  44463. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  44464. {
  44465. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  44466. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  44467. isDirectory = fileInfo.isDirectory;
  44468. }
  44469. else
  44470. {
  44471. isDirectory = true;
  44472. }
  44473. }
  44474. ~FileListTreeItem() throw()
  44475. {
  44476. thread.removeTimeSliceClient (this);
  44477. clearSubItems();
  44478. ImageCache::release (icon);
  44479. if (canDeleteSubContentsList)
  44480. delete subContentsList;
  44481. }
  44482. bool mightContainSubItems() { return isDirectory; }
  44483. const String getUniqueName() const { return file.getFullPathName(); }
  44484. int getItemHeight() const { return 22; }
  44485. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  44486. void itemOpennessChanged (bool isNowOpen)
  44487. {
  44488. if (isNowOpen)
  44489. {
  44490. clearSubItems();
  44491. isDirectory = file.isDirectory();
  44492. if (isDirectory)
  44493. {
  44494. if (subContentsList == 0)
  44495. {
  44496. jassert (parentContentsList != 0);
  44497. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  44498. l->setDirectory (file, true, true);
  44499. setSubContentsList (l);
  44500. canDeleteSubContentsList = true;
  44501. }
  44502. changeListenerCallback (0);
  44503. }
  44504. }
  44505. }
  44506. void setSubContentsList (DirectoryContentsList* newList) throw()
  44507. {
  44508. jassert (subContentsList == 0);
  44509. subContentsList = newList;
  44510. newList->addChangeListener (this);
  44511. }
  44512. void changeListenerCallback (void*)
  44513. {
  44514. clearSubItems();
  44515. if (isOpen() && subContentsList != 0)
  44516. {
  44517. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  44518. {
  44519. FileListTreeItem* const item
  44520. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  44521. addSubItem (item);
  44522. }
  44523. }
  44524. }
  44525. void paintItem (Graphics& g, int width, int height)
  44526. {
  44527. if (file != File::nonexistent)
  44528. {
  44529. updateIcon (true);
  44530. if (icon == 0)
  44531. thread.addTimeSliceClient (this);
  44532. }
  44533. owner.getLookAndFeel()
  44534. .drawFileBrowserRow (g, width, height,
  44535. file.getFileName(),
  44536. icon,
  44537. fileSize, modTime,
  44538. isDirectory, isSelected(),
  44539. indexInContentsList);
  44540. }
  44541. void itemClicked (const MouseEvent& e)
  44542. {
  44543. owner.sendMouseClickMessage (file, e);
  44544. }
  44545. void itemDoubleClicked (const MouseEvent& e)
  44546. {
  44547. TreeViewItem::itemDoubleClicked (e);
  44548. owner.sendDoubleClickMessage (file);
  44549. }
  44550. void itemSelectionChanged (bool)
  44551. {
  44552. owner.sendSelectionChangeMessage();
  44553. }
  44554. bool useTimeSlice()
  44555. {
  44556. updateIcon (false);
  44557. thread.removeTimeSliceClient (this);
  44558. return false;
  44559. }
  44560. void handleAsyncUpdate()
  44561. {
  44562. owner.repaint();
  44563. }
  44564. const File file;
  44565. juce_UseDebuggingNewOperator
  44566. private:
  44567. FileTreeComponent& owner;
  44568. DirectoryContentsList* parentContentsList;
  44569. int indexInContentsList;
  44570. DirectoryContentsList* subContentsList;
  44571. bool isDirectory, canDeleteSubContentsList;
  44572. TimeSliceThread& thread;
  44573. Image* icon;
  44574. String fileSize;
  44575. String modTime;
  44576. void updateIcon (const bool onlyUpdateIfCached) throw()
  44577. {
  44578. if (icon == 0)
  44579. {
  44580. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44581. Image* im = ImageCache::getFromHashCode (hashCode);
  44582. if (im == 0 && ! onlyUpdateIfCached)
  44583. {
  44584. im = juce_createIconForFile (file);
  44585. if (im != 0)
  44586. ImageCache::addImageToCache (im, hashCode);
  44587. }
  44588. if (im != 0)
  44589. {
  44590. icon = im;
  44591. triggerAsyncUpdate();
  44592. }
  44593. }
  44594. }
  44595. };
  44596. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  44597. : DirectoryContentsDisplayComponent (listToShow)
  44598. {
  44599. FileListTreeItem* const root
  44600. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  44601. listToShow.getTimeSliceThread());
  44602. root->setSubContentsList (&listToShow);
  44603. setRootItemVisible (false);
  44604. setRootItem (root);
  44605. }
  44606. FileTreeComponent::~FileTreeComponent()
  44607. {
  44608. TreeViewItem* const root = getRootItem();
  44609. setRootItem (0);
  44610. delete root;
  44611. }
  44612. const File FileTreeComponent::getSelectedFile() const
  44613. {
  44614. return getSelectedFile (0);
  44615. }
  44616. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  44617. {
  44618. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  44619. if (item != 0)
  44620. return item->file;
  44621. return File::nonexistent;
  44622. }
  44623. void FileTreeComponent::scrollToTop()
  44624. {
  44625. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  44626. }
  44627. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  44628. {
  44629. dragAndDropDescription = description;
  44630. }
  44631. END_JUCE_NAMESPACE
  44632. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  44633. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  44634. BEGIN_JUCE_NAMESPACE
  44635. ImagePreviewComponent::ImagePreviewComponent()
  44636. : currentThumbnail (0)
  44637. {
  44638. }
  44639. ImagePreviewComponent::~ImagePreviewComponent()
  44640. {
  44641. delete currentThumbnail;
  44642. }
  44643. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  44644. {
  44645. const int availableW = proportionOfWidth (0.97f);
  44646. const int availableH = getHeight() - 13 * 4;
  44647. const double scale = jmin (1.0,
  44648. availableW / (double) w,
  44649. availableH / (double) h);
  44650. w = roundDoubleToInt (scale * w);
  44651. h = roundDoubleToInt (scale * h);
  44652. }
  44653. void ImagePreviewComponent::selectedFileChanged (const File& file)
  44654. {
  44655. if (fileToLoad != file)
  44656. {
  44657. fileToLoad = file;
  44658. startTimer (100);
  44659. }
  44660. }
  44661. void ImagePreviewComponent::timerCallback()
  44662. {
  44663. stopTimer();
  44664. deleteAndZero (currentThumbnail);
  44665. currentDetails = String::empty;
  44666. repaint();
  44667. FileInputStream* const in = fileToLoad.createInputStream();
  44668. if (in != 0)
  44669. {
  44670. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  44671. if (format != 0)
  44672. {
  44673. currentThumbnail = format->decodeImage (*in);
  44674. if (currentThumbnail != 0)
  44675. {
  44676. int w = currentThumbnail->getWidth();
  44677. int h = currentThumbnail->getHeight();
  44678. currentDetails
  44679. << fileToLoad.getFileName() << "\n"
  44680. << format->getFormatName() << "\n"
  44681. << w << " x " << h << " pixels\n"
  44682. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  44683. getThumbSize (w, h);
  44684. Image* const reduced = currentThumbnail->createCopy (w, h);
  44685. delete currentThumbnail;
  44686. currentThumbnail = reduced;
  44687. }
  44688. }
  44689. delete in;
  44690. }
  44691. }
  44692. void ImagePreviewComponent::paint (Graphics& g)
  44693. {
  44694. if (currentThumbnail != 0)
  44695. {
  44696. g.setFont (13.0f);
  44697. int w = currentThumbnail->getWidth();
  44698. int h = currentThumbnail->getHeight();
  44699. getThumbSize (w, h);
  44700. const int numLines = 4;
  44701. const int totalH = 13 * numLines + h + 4;
  44702. const int y = (getHeight() - totalH) / 2;
  44703. g.drawImageWithin (currentThumbnail,
  44704. (getWidth() - w) / 2, y, w, h,
  44705. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  44706. false);
  44707. g.drawFittedText (currentDetails,
  44708. 0, y + h + 4, getWidth(), 100,
  44709. Justification::centredTop, numLines);
  44710. }
  44711. }
  44712. END_JUCE_NAMESPACE
  44713. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  44714. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  44715. BEGIN_JUCE_NAMESPACE
  44716. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  44717. const String& description)
  44718. : FileFilter (description.isEmpty() ? wildcardPatterns
  44719. : (description + T(" (") + wildcardPatterns + T(")")))
  44720. {
  44721. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  44722. wildcards.trim();
  44723. wildcards.removeEmptyStrings();
  44724. // special case for *.*, because people use it to mean "any file", but it
  44725. // would actually ignore files with no extension.
  44726. for (int i = wildcards.size(); --i >= 0;)
  44727. if (wildcards[i] == T("*.*"))
  44728. wildcards.set (i, T("*"));
  44729. }
  44730. WildcardFileFilter::~WildcardFileFilter()
  44731. {
  44732. }
  44733. bool WildcardFileFilter::isFileSuitable (const File& file) const
  44734. {
  44735. const String filename (file.getFileName());
  44736. for (int i = wildcards.size(); --i >= 0;)
  44737. if (filename.matchesWildcard (wildcards[i], true))
  44738. return true;
  44739. return false;
  44740. }
  44741. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  44742. {
  44743. return true;
  44744. }
  44745. END_JUCE_NAMESPACE
  44746. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  44747. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44748. BEGIN_JUCE_NAMESPACE
  44749. KeyboardFocusTraverser::KeyboardFocusTraverser()
  44750. {
  44751. }
  44752. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  44753. {
  44754. }
  44755. // This will sort a set of components, so that they are ordered in terms of
  44756. // left-to-right and then top-to-bottom.
  44757. class ScreenPositionComparator
  44758. {
  44759. public:
  44760. ScreenPositionComparator() {}
  44761. static int compareElements (const Component* const first, const Component* const second) throw()
  44762. {
  44763. int explicitOrder1 = first->getExplicitFocusOrder();
  44764. if (explicitOrder1 <= 0)
  44765. explicitOrder1 = INT_MAX / 2;
  44766. int explicitOrder2 = second->getExplicitFocusOrder();
  44767. if (explicitOrder2 <= 0)
  44768. explicitOrder2 = INT_MAX / 2;
  44769. if (explicitOrder1 != explicitOrder2)
  44770. return explicitOrder1 - explicitOrder2;
  44771. const int diff = first->getY() - second->getY();
  44772. return (diff == 0) ? first->getX() - second->getX()
  44773. : diff;
  44774. }
  44775. };
  44776. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  44777. {
  44778. if (parent->getNumChildComponents() > 0)
  44779. {
  44780. Array <Component*> localComps;
  44781. ScreenPositionComparator comparator;
  44782. int i;
  44783. for (i = parent->getNumChildComponents(); --i >= 0;)
  44784. {
  44785. Component* const c = parent->getChildComponent (i);
  44786. if (c->isVisible() && c->isEnabled())
  44787. localComps.addSorted (comparator, c);
  44788. }
  44789. for (i = 0; i < localComps.size(); ++i)
  44790. {
  44791. Component* const c = localComps.getUnchecked (i);
  44792. if (c->getWantsKeyboardFocus())
  44793. comps.add (c);
  44794. if (! c->isFocusContainer())
  44795. findAllFocusableComponents (c, comps);
  44796. }
  44797. }
  44798. }
  44799. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  44800. {
  44801. Component* focusContainer = current->getParentComponent();
  44802. if (focusContainer != 0)
  44803. {
  44804. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  44805. focusContainer = focusContainer->getParentComponent();
  44806. if (focusContainer != 0)
  44807. {
  44808. Array <Component*> comps;
  44809. findAllFocusableComponents (focusContainer, comps);
  44810. if (comps.size() > 0)
  44811. {
  44812. const int index = comps.indexOf (current);
  44813. return comps [(index + comps.size() + delta) % comps.size()];
  44814. }
  44815. }
  44816. }
  44817. return 0;
  44818. }
  44819. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  44820. {
  44821. return getIncrementedComponent (current, 1);
  44822. }
  44823. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  44824. {
  44825. return getIncrementedComponent (current, -1);
  44826. }
  44827. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  44828. {
  44829. Array <Component*> comps;
  44830. if (parentComponent != 0)
  44831. findAllFocusableComponents (parentComponent, comps);
  44832. return comps.getFirst();
  44833. }
  44834. END_JUCE_NAMESPACE
  44835. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44836. /********* Start of inlined file: juce_KeyListener.cpp *********/
  44837. BEGIN_JUCE_NAMESPACE
  44838. bool KeyListener::keyStateChanged (const bool, Component*)
  44839. {
  44840. return false;
  44841. }
  44842. END_JUCE_NAMESPACE
  44843. /********* End of inlined file: juce_KeyListener.cpp *********/
  44844. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44845. BEGIN_JUCE_NAMESPACE
  44846. // N.B. these two includes are put here deliberately to avoid problems with
  44847. // old GCCs failing on long include paths
  44848. const int maxKeys = 3;
  44849. class KeyMappingChangeButton : public Button
  44850. {
  44851. public:
  44852. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  44853. const CommandID commandID_,
  44854. const String& keyName,
  44855. const int keyNum_)
  44856. : Button (keyName),
  44857. owner (owner_),
  44858. commandID (commandID_),
  44859. keyNum (keyNum_)
  44860. {
  44861. setWantsKeyboardFocus (false);
  44862. setTriggeredOnMouseDown (keyNum >= 0);
  44863. if (keyNum_ < 0)
  44864. setTooltip (TRANS("adds a new key-mapping"));
  44865. else
  44866. setTooltip (TRANS("click to change this key-mapping"));
  44867. }
  44868. ~KeyMappingChangeButton()
  44869. {
  44870. }
  44871. void paintButton (Graphics& g, bool isOver, bool isDown)
  44872. {
  44873. if (keyNum >= 0)
  44874. {
  44875. if (isEnabled())
  44876. {
  44877. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  44878. g.fillAll (owner->textColour.withAlpha (alpha));
  44879. g.setOpacity (0.3f);
  44880. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  44881. }
  44882. g.setColour (owner->textColour);
  44883. g.setFont (getHeight() * 0.6f);
  44884. g.drawFittedText (getName(),
  44885. 3, 0, getWidth() - 6, getHeight(),
  44886. Justification::centred, 1);
  44887. }
  44888. else
  44889. {
  44890. const float thickness = 7.0f;
  44891. const float indent = 22.0f;
  44892. Path p;
  44893. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  44894. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  44895. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  44896. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  44897. p.setUsingNonZeroWinding (false);
  44898. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  44899. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  44900. }
  44901. if (hasKeyboardFocus (false))
  44902. {
  44903. g.setColour (owner->textColour.withAlpha (0.4f));
  44904. g.drawRect (0, 0, getWidth(), getHeight());
  44905. }
  44906. }
  44907. void clicked()
  44908. {
  44909. if (keyNum >= 0)
  44910. {
  44911. // existing key clicked..
  44912. PopupMenu m;
  44913. m.addItem (1, TRANS("change this key-mapping"));
  44914. m.addSeparator();
  44915. m.addItem (2, TRANS("remove this key-mapping"));
  44916. const int res = m.show();
  44917. if (res == 1)
  44918. {
  44919. owner->assignNewKey (commandID, keyNum);
  44920. }
  44921. else if (res == 2)
  44922. {
  44923. owner->getMappings()->removeKeyPress (commandID, keyNum);
  44924. }
  44925. }
  44926. else
  44927. {
  44928. // + button pressed..
  44929. owner->assignNewKey (commandID, -1);
  44930. }
  44931. }
  44932. void fitToContent (const int h) throw()
  44933. {
  44934. if (keyNum < 0)
  44935. {
  44936. setSize (h, h);
  44937. }
  44938. else
  44939. {
  44940. Font f (h * 0.6f);
  44941. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  44942. }
  44943. }
  44944. juce_UseDebuggingNewOperator
  44945. private:
  44946. KeyMappingEditorComponent* const owner;
  44947. const CommandID commandID;
  44948. const int keyNum;
  44949. KeyMappingChangeButton (const KeyMappingChangeButton&);
  44950. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  44951. };
  44952. class KeyMappingItemComponent : public Component
  44953. {
  44954. public:
  44955. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  44956. const CommandID commandID_)
  44957. : owner (owner_),
  44958. commandID (commandID_)
  44959. {
  44960. setInterceptsMouseClicks (false, true);
  44961. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  44962. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  44963. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  44964. {
  44965. KeyMappingChangeButton* const kb
  44966. = new KeyMappingChangeButton (owner_, commandID,
  44967. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  44968. kb->setEnabled (! isReadOnly);
  44969. addAndMakeVisible (kb);
  44970. }
  44971. KeyMappingChangeButton* const kb
  44972. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  44973. addChildComponent (kb);
  44974. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  44975. }
  44976. ~KeyMappingItemComponent()
  44977. {
  44978. deleteAllChildren();
  44979. }
  44980. void paint (Graphics& g)
  44981. {
  44982. g.setFont (getHeight() * 0.7f);
  44983. g.setColour (owner->textColour);
  44984. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  44985. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  44986. Justification::centredLeft, true);
  44987. }
  44988. void resized()
  44989. {
  44990. int x = getWidth() - 4;
  44991. for (int i = getNumChildComponents(); --i >= 0;)
  44992. {
  44993. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  44994. kb->fitToContent (getHeight() - 2);
  44995. kb->setTopRightPosition (x, 1);
  44996. x -= kb->getWidth() + 5;
  44997. }
  44998. }
  44999. juce_UseDebuggingNewOperator
  45000. private:
  45001. KeyMappingEditorComponent* const owner;
  45002. const CommandID commandID;
  45003. KeyMappingItemComponent (const KeyMappingItemComponent&);
  45004. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  45005. };
  45006. class KeyMappingTreeViewItem : public TreeViewItem
  45007. {
  45008. public:
  45009. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  45010. const CommandID commandID_)
  45011. : owner (owner_),
  45012. commandID (commandID_)
  45013. {
  45014. }
  45015. ~KeyMappingTreeViewItem()
  45016. {
  45017. }
  45018. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  45019. bool mightContainSubItems() { return false; }
  45020. int getItemHeight() const { return 20; }
  45021. Component* createItemComponent()
  45022. {
  45023. return new KeyMappingItemComponent (owner, commandID);
  45024. }
  45025. juce_UseDebuggingNewOperator
  45026. private:
  45027. KeyMappingEditorComponent* const owner;
  45028. const CommandID commandID;
  45029. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  45030. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  45031. };
  45032. class KeyCategoryTreeViewItem : public TreeViewItem
  45033. {
  45034. public:
  45035. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  45036. const String& name)
  45037. : owner (owner_),
  45038. categoryName (name)
  45039. {
  45040. }
  45041. ~KeyCategoryTreeViewItem()
  45042. {
  45043. }
  45044. const String getUniqueName() const { return categoryName + "_cat"; }
  45045. bool mightContainSubItems() { return true; }
  45046. int getItemHeight() const { return 28; }
  45047. void paintItem (Graphics& g, int width, int height)
  45048. {
  45049. g.setFont (height * 0.6f, Font::bold);
  45050. g.setColour (owner->textColour);
  45051. g.drawText (categoryName,
  45052. 2, 0, width - 2, height,
  45053. Justification::centredLeft, true);
  45054. }
  45055. void itemOpennessChanged (bool isNowOpen)
  45056. {
  45057. if (isNowOpen)
  45058. {
  45059. if (getNumSubItems() == 0)
  45060. {
  45061. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  45062. for (int i = 0; i < commands.size(); ++i)
  45063. {
  45064. if (owner->shouldCommandBeIncluded (commands[i]))
  45065. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  45066. }
  45067. }
  45068. }
  45069. else
  45070. {
  45071. clearSubItems();
  45072. }
  45073. }
  45074. juce_UseDebuggingNewOperator
  45075. private:
  45076. KeyMappingEditorComponent* owner;
  45077. String categoryName;
  45078. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  45079. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  45080. };
  45081. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  45082. const bool showResetToDefaultButton)
  45083. : mappings (mappingManager),
  45084. textColour (Colours::black)
  45085. {
  45086. jassert (mappingManager != 0); // can't be null!
  45087. mappingManager->addChangeListener (this);
  45088. setLinesDrawnForSubItems (false);
  45089. resetButton = 0;
  45090. if (showResetToDefaultButton)
  45091. {
  45092. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  45093. resetButton->addButtonListener (this);
  45094. }
  45095. addAndMakeVisible (tree = new TreeView());
  45096. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  45097. tree->setRootItemVisible (false);
  45098. tree->setDefaultOpenness (true);
  45099. tree->setRootItem (this);
  45100. }
  45101. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  45102. {
  45103. mappings->removeChangeListener (this);
  45104. deleteAllChildren();
  45105. }
  45106. bool KeyMappingEditorComponent::mightContainSubItems()
  45107. {
  45108. return true;
  45109. }
  45110. const String KeyMappingEditorComponent::getUniqueName() const
  45111. {
  45112. return T("keys");
  45113. }
  45114. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  45115. const Colour& textColour_)
  45116. {
  45117. backgroundColour = mainBackground;
  45118. textColour = textColour_;
  45119. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  45120. }
  45121. void KeyMappingEditorComponent::parentHierarchyChanged()
  45122. {
  45123. changeListenerCallback (0);
  45124. }
  45125. void KeyMappingEditorComponent::resized()
  45126. {
  45127. int h = getHeight();
  45128. if (resetButton != 0)
  45129. {
  45130. const int buttonHeight = 20;
  45131. h -= buttonHeight + 8;
  45132. int x = getWidth() - 8;
  45133. const int y = h + 6;
  45134. resetButton->changeWidthToFitText (buttonHeight);
  45135. resetButton->setTopRightPosition (x, y);
  45136. }
  45137. tree->setBounds (0, 0, getWidth(), h);
  45138. }
  45139. void KeyMappingEditorComponent::buttonClicked (Button* button)
  45140. {
  45141. if (button == resetButton)
  45142. {
  45143. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  45144. TRANS("Reset to defaults"),
  45145. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  45146. TRANS("Reset")))
  45147. {
  45148. mappings->resetToDefaultMappings();
  45149. }
  45150. }
  45151. }
  45152. void KeyMappingEditorComponent::changeListenerCallback (void*)
  45153. {
  45154. XmlElement* openness = tree->getOpennessState (true);
  45155. clearSubItems();
  45156. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  45157. for (int i = 0; i < categories.size(); ++i)
  45158. {
  45159. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  45160. int count = 0;
  45161. for (int j = 0; j < commands.size(); ++j)
  45162. if (shouldCommandBeIncluded (commands[j]))
  45163. ++count;
  45164. if (count > 0)
  45165. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  45166. }
  45167. if (openness != 0)
  45168. {
  45169. tree->restoreOpennessState (*openness);
  45170. delete openness;
  45171. }
  45172. }
  45173. class KeyEntryWindow : public AlertWindow
  45174. {
  45175. public:
  45176. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  45177. : AlertWindow (TRANS("New key-mapping"),
  45178. TRANS("Please press a key combination now..."),
  45179. AlertWindow::NoIcon),
  45180. owner (owner_)
  45181. {
  45182. addButton (TRANS("ok"), 1);
  45183. addButton (TRANS("cancel"), 0);
  45184. // (avoid return + escape keys getting processed by the buttons..)
  45185. for (int i = getNumChildComponents(); --i >= 0;)
  45186. getChildComponent (i)->setWantsKeyboardFocus (false);
  45187. setWantsKeyboardFocus (true);
  45188. grabKeyboardFocus();
  45189. }
  45190. ~KeyEntryWindow()
  45191. {
  45192. }
  45193. bool keyPressed (const KeyPress& key)
  45194. {
  45195. lastPress = key;
  45196. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  45197. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  45198. if (previousCommand != 0)
  45199. {
  45200. message << "\n\n"
  45201. << TRANS("(Currently assigned to \"")
  45202. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  45203. << "\")";
  45204. }
  45205. setMessage (message);
  45206. return true;
  45207. }
  45208. bool keyStateChanged (const bool)
  45209. {
  45210. return true;
  45211. }
  45212. KeyPress lastPress;
  45213. juce_UseDebuggingNewOperator
  45214. private:
  45215. KeyMappingEditorComponent* owner;
  45216. KeyEntryWindow (const KeyEntryWindow&);
  45217. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  45218. };
  45219. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  45220. {
  45221. KeyEntryWindow entryWindow (this);
  45222. if (entryWindow.runModalLoop() != 0)
  45223. {
  45224. entryWindow.setVisible (false);
  45225. if (entryWindow.lastPress.isValid())
  45226. {
  45227. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  45228. if (previousCommand != 0)
  45229. {
  45230. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  45231. TRANS("Change key-mapping"),
  45232. TRANS("This key is already assigned to the command \"")
  45233. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  45234. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  45235. TRANS("re-assign"),
  45236. TRANS("cancel")))
  45237. {
  45238. return;
  45239. }
  45240. }
  45241. mappings->removeKeyPress (entryWindow.lastPress);
  45242. if (index >= 0)
  45243. mappings->removeKeyPress (commandID, index);
  45244. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  45245. }
  45246. }
  45247. }
  45248. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  45249. {
  45250. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45251. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  45252. }
  45253. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  45254. {
  45255. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45256. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  45257. }
  45258. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  45259. {
  45260. return key.getTextDescription();
  45261. }
  45262. END_JUCE_NAMESPACE
  45263. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  45264. /********* Start of inlined file: juce_KeyPress.cpp *********/
  45265. BEGIN_JUCE_NAMESPACE
  45266. KeyPress::KeyPress() throw()
  45267. : keyCode (0),
  45268. mods (0),
  45269. textCharacter (0)
  45270. {
  45271. }
  45272. KeyPress::KeyPress (const int keyCode_,
  45273. const ModifierKeys& mods_,
  45274. const juce_wchar textCharacter_) throw()
  45275. : keyCode (keyCode_),
  45276. mods (mods_),
  45277. textCharacter (textCharacter_)
  45278. {
  45279. }
  45280. KeyPress::KeyPress (const int keyCode_) throw()
  45281. : keyCode (keyCode_),
  45282. textCharacter (0)
  45283. {
  45284. }
  45285. KeyPress::KeyPress (const KeyPress& other) throw()
  45286. : keyCode (other.keyCode),
  45287. mods (other.mods),
  45288. textCharacter (other.textCharacter)
  45289. {
  45290. }
  45291. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  45292. {
  45293. keyCode = other.keyCode;
  45294. mods = other.mods;
  45295. textCharacter = other.textCharacter;
  45296. return *this;
  45297. }
  45298. bool KeyPress::operator== (const KeyPress& other) const throw()
  45299. {
  45300. return mods.getRawFlags() == other.mods.getRawFlags()
  45301. && (textCharacter == other.textCharacter
  45302. || textCharacter == 0
  45303. || other.textCharacter == 0)
  45304. && (keyCode == other.keyCode
  45305. || (keyCode < 256
  45306. && other.keyCode < 256
  45307. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  45308. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  45309. }
  45310. bool KeyPress::operator!= (const KeyPress& other) const throw()
  45311. {
  45312. return ! operator== (other);
  45313. }
  45314. bool KeyPress::isCurrentlyDown() const throw()
  45315. {
  45316. return isKeyCurrentlyDown (keyCode)
  45317. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  45318. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  45319. }
  45320. struct KeyNameAndCode
  45321. {
  45322. const char* name;
  45323. int code;
  45324. };
  45325. static const KeyNameAndCode keyNameTranslations[] =
  45326. {
  45327. { "spacebar", KeyPress::spaceKey },
  45328. { "return", KeyPress::returnKey },
  45329. { "escape", KeyPress::escapeKey },
  45330. { "backspace", KeyPress::backspaceKey },
  45331. { "cursor left", KeyPress::leftKey },
  45332. { "cursor right", KeyPress::rightKey },
  45333. { "cursor up", KeyPress::upKey },
  45334. { "cursor down", KeyPress::downKey },
  45335. { "page up", KeyPress::pageUpKey },
  45336. { "page down", KeyPress::pageDownKey },
  45337. { "home", KeyPress::homeKey },
  45338. { "end", KeyPress::endKey },
  45339. { "delete", KeyPress::deleteKey },
  45340. { "insert", KeyPress::insertKey },
  45341. { "tab", KeyPress::tabKey },
  45342. { "play", KeyPress::playKey },
  45343. { "stop", KeyPress::stopKey },
  45344. { "fast forward", KeyPress::fastForwardKey },
  45345. { "rewind", KeyPress::rewindKey }
  45346. };
  45347. static const tchar* const numberPadPrefix = T("numpad ");
  45348. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  45349. {
  45350. int modifiers = 0;
  45351. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  45352. || desc.containsWholeWordIgnoreCase (T("control"))
  45353. || desc.containsWholeWordIgnoreCase (T("ctl")))
  45354. modifiers |= ModifierKeys::ctrlModifier;
  45355. if (desc.containsWholeWordIgnoreCase (T("shift"))
  45356. || desc.containsWholeWordIgnoreCase (T("shft")))
  45357. modifiers |= ModifierKeys::shiftModifier;
  45358. if (desc.containsWholeWordIgnoreCase (T("alt"))
  45359. || desc.containsWholeWordIgnoreCase (T("option")))
  45360. modifiers |= ModifierKeys::altModifier;
  45361. if (desc.containsWholeWordIgnoreCase (T("command"))
  45362. || desc.containsWholeWordIgnoreCase (T("cmd")))
  45363. modifiers |= ModifierKeys::commandModifier;
  45364. int key = 0;
  45365. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45366. {
  45367. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  45368. {
  45369. key = keyNameTranslations[i].code;
  45370. break;
  45371. }
  45372. }
  45373. if (key == 0)
  45374. {
  45375. // see if it's a numpad key..
  45376. if (desc.containsIgnoreCase (numberPadPrefix))
  45377. {
  45378. const tchar lastChar = desc.trimEnd().getLastCharacter();
  45379. if (lastChar >= T('0') && lastChar <= T('9'))
  45380. key = numberPad0 + lastChar - T('0');
  45381. else if (lastChar == T('+'))
  45382. key = numberPadAdd;
  45383. else if (lastChar == T('-'))
  45384. key = numberPadSubtract;
  45385. else if (lastChar == T('*'))
  45386. key = numberPadMultiply;
  45387. else if (lastChar == T('/'))
  45388. key = numberPadDivide;
  45389. else if (lastChar == T('.'))
  45390. key = numberPadDecimalPoint;
  45391. else if (lastChar == T('='))
  45392. key = numberPadEquals;
  45393. else if (desc.endsWith (T("separator")))
  45394. key = numberPadSeparator;
  45395. else if (desc.endsWith (T("delete")))
  45396. key = numberPadDelete;
  45397. }
  45398. if (key == 0)
  45399. {
  45400. // see if it's a function key..
  45401. for (int i = 1; i <= 12; ++i)
  45402. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  45403. key = F1Key + i - 1;
  45404. if (key == 0)
  45405. {
  45406. // give up and use the hex code..
  45407. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  45408. .toLowerCase()
  45409. .retainCharacters (T("0123456789abcdef"))
  45410. .getHexValue32();
  45411. if (hexCode > 0)
  45412. key = hexCode;
  45413. else
  45414. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  45415. }
  45416. }
  45417. }
  45418. return KeyPress (key, ModifierKeys (modifiers), 0);
  45419. }
  45420. const String KeyPress::getTextDescription() const throw()
  45421. {
  45422. String desc;
  45423. if (keyCode > 0)
  45424. {
  45425. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  45426. // want to store it as being a slash, not shift+whatever.
  45427. if (textCharacter == T('/'))
  45428. return "/";
  45429. if (mods.isCtrlDown())
  45430. desc << "ctrl + ";
  45431. if (mods.isShiftDown())
  45432. desc << "shift + ";
  45433. #if JUCE_MAC
  45434. // only do this on the mac, because on Windows ctrl and command are the same,
  45435. // and this would get confusing
  45436. if (mods.isCommandDown())
  45437. desc << "command + ";
  45438. if (mods.isAltDown())
  45439. desc << "option + ";
  45440. #else
  45441. if (mods.isAltDown())
  45442. desc << "alt + ";
  45443. #endif
  45444. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45445. if (keyCode == keyNameTranslations[i].code)
  45446. return desc + keyNameTranslations[i].name;
  45447. if (keyCode >= F1Key && keyCode <= F16Key)
  45448. desc << 'F' << (1 + keyCode - F1Key);
  45449. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  45450. desc << numberPadPrefix << (keyCode - numberPad0);
  45451. else if (keyCode >= 33 && keyCode < 176)
  45452. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  45453. else if (keyCode == numberPadAdd)
  45454. desc << numberPadPrefix << '+';
  45455. else if (keyCode == numberPadSubtract)
  45456. desc << numberPadPrefix << '-';
  45457. else if (keyCode == numberPadMultiply)
  45458. desc << numberPadPrefix << '*';
  45459. else if (keyCode == numberPadDivide)
  45460. desc << numberPadPrefix << '/';
  45461. else if (keyCode == numberPadSeparator)
  45462. desc << numberPadPrefix << "separator";
  45463. else if (keyCode == numberPadDecimalPoint)
  45464. desc << numberPadPrefix << '.';
  45465. else if (keyCode == numberPadDelete)
  45466. desc << numberPadPrefix << "delete";
  45467. else
  45468. desc << '#' << String::toHexString (keyCode);
  45469. }
  45470. return desc;
  45471. }
  45472. END_JUCE_NAMESPACE
  45473. /********* End of inlined file: juce_KeyPress.cpp *********/
  45474. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  45475. BEGIN_JUCE_NAMESPACE
  45476. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  45477. : commandManager (commandManager_)
  45478. {
  45479. // A manager is needed to get the descriptions of commands, and will be called when
  45480. // a command is invoked. So you can't leave this null..
  45481. jassert (commandManager_ != 0);
  45482. Desktop::getInstance().addFocusChangeListener (this);
  45483. }
  45484. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  45485. : commandManager (other.commandManager)
  45486. {
  45487. Desktop::getInstance().addFocusChangeListener (this);
  45488. }
  45489. KeyPressMappingSet::~KeyPressMappingSet()
  45490. {
  45491. Desktop::getInstance().removeFocusChangeListener (this);
  45492. }
  45493. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  45494. {
  45495. for (int i = 0; i < mappings.size(); ++i)
  45496. if (mappings.getUnchecked(i)->commandID == commandID)
  45497. return mappings.getUnchecked (i)->keypresses;
  45498. return Array <KeyPress> ();
  45499. }
  45500. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  45501. const KeyPress& newKeyPress,
  45502. int insertIndex) throw()
  45503. {
  45504. if (findCommandForKeyPress (newKeyPress) != commandID)
  45505. {
  45506. removeKeyPress (newKeyPress);
  45507. if (newKeyPress.isValid())
  45508. {
  45509. for (int i = mappings.size(); --i >= 0;)
  45510. {
  45511. if (mappings.getUnchecked(i)->commandID == commandID)
  45512. {
  45513. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  45514. sendChangeMessage (this);
  45515. return;
  45516. }
  45517. }
  45518. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45519. if (ci != 0)
  45520. {
  45521. CommandMapping* const cm = new CommandMapping();
  45522. cm->commandID = commandID;
  45523. cm->keypresses.add (newKeyPress);
  45524. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  45525. mappings.add (cm);
  45526. sendChangeMessage (this);
  45527. }
  45528. }
  45529. }
  45530. }
  45531. void KeyPressMappingSet::resetToDefaultMappings() throw()
  45532. {
  45533. mappings.clear();
  45534. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  45535. {
  45536. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  45537. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45538. {
  45539. addKeyPress (ci->commandID,
  45540. ci->defaultKeypresses.getReference (j));
  45541. }
  45542. }
  45543. sendChangeMessage (this);
  45544. }
  45545. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  45546. {
  45547. clearAllKeyPresses (commandID);
  45548. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45549. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45550. {
  45551. addKeyPress (ci->commandID,
  45552. ci->defaultKeypresses.getReference (j));
  45553. }
  45554. }
  45555. void KeyPressMappingSet::clearAllKeyPresses() throw()
  45556. {
  45557. if (mappings.size() > 0)
  45558. {
  45559. sendChangeMessage (this);
  45560. mappings.clear();
  45561. }
  45562. }
  45563. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  45564. {
  45565. for (int i = mappings.size(); --i >= 0;)
  45566. {
  45567. if (mappings.getUnchecked(i)->commandID == commandID)
  45568. {
  45569. mappings.remove (i);
  45570. sendChangeMessage (this);
  45571. }
  45572. }
  45573. }
  45574. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  45575. {
  45576. if (keypress.isValid())
  45577. {
  45578. for (int i = mappings.size(); --i >= 0;)
  45579. {
  45580. CommandMapping* const cm = mappings.getUnchecked(i);
  45581. for (int j = cm->keypresses.size(); --j >= 0;)
  45582. {
  45583. if (keypress == cm->keypresses [j])
  45584. {
  45585. cm->keypresses.remove (j);
  45586. sendChangeMessage (this);
  45587. }
  45588. }
  45589. }
  45590. }
  45591. }
  45592. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  45593. const int keyPressIndex) throw()
  45594. {
  45595. for (int i = mappings.size(); --i >= 0;)
  45596. {
  45597. if (mappings.getUnchecked(i)->commandID == commandID)
  45598. {
  45599. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  45600. sendChangeMessage (this);
  45601. break;
  45602. }
  45603. }
  45604. }
  45605. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  45606. {
  45607. for (int i = 0; i < mappings.size(); ++i)
  45608. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  45609. return mappings.getUnchecked(i)->commandID;
  45610. return 0;
  45611. }
  45612. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  45613. const KeyPress& keyPress) const throw()
  45614. {
  45615. for (int i = mappings.size(); --i >= 0;)
  45616. if (mappings.getUnchecked(i)->commandID == commandID)
  45617. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  45618. return false;
  45619. }
  45620. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  45621. const KeyPress& key,
  45622. const bool isKeyDown,
  45623. const int millisecsSinceKeyPressed,
  45624. Component* const originatingComponent) const
  45625. {
  45626. ApplicationCommandTarget::InvocationInfo info (commandID);
  45627. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  45628. info.isKeyDown = isKeyDown;
  45629. info.keyPress = key;
  45630. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  45631. info.originatingComponent = originatingComponent;
  45632. commandManager->invoke (info, false);
  45633. }
  45634. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  45635. {
  45636. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  45637. {
  45638. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  45639. {
  45640. // if the XML was created as a set of differences from the default mappings,
  45641. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  45642. resetToDefaultMappings();
  45643. }
  45644. else
  45645. {
  45646. // if the XML was created calling createXml (false), then we need to clear all
  45647. // the keys and treat the xml as describing the entire set of mappings.
  45648. clearAllKeyPresses();
  45649. }
  45650. forEachXmlChildElement (xmlVersion, map)
  45651. {
  45652. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  45653. if (commandId != 0)
  45654. {
  45655. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  45656. if (map->hasTagName (T("MAPPING")))
  45657. {
  45658. addKeyPress (commandId, key);
  45659. }
  45660. else if (map->hasTagName (T("UNMAPPING")))
  45661. {
  45662. if (containsMapping (commandId, key))
  45663. removeKeyPress (key);
  45664. }
  45665. }
  45666. }
  45667. return true;
  45668. }
  45669. return false;
  45670. }
  45671. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  45672. {
  45673. KeyPressMappingSet* defaultSet = 0;
  45674. if (saveDifferencesFromDefaultSet)
  45675. {
  45676. defaultSet = new KeyPressMappingSet (commandManager);
  45677. defaultSet->resetToDefaultMappings();
  45678. }
  45679. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  45680. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  45681. int i;
  45682. for (i = 0; i < mappings.size(); ++i)
  45683. {
  45684. const CommandMapping* const cm = mappings.getUnchecked(i);
  45685. for (int j = 0; j < cm->keypresses.size(); ++j)
  45686. {
  45687. if (defaultSet == 0
  45688. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45689. {
  45690. XmlElement* const map = new XmlElement (T("MAPPING"));
  45691. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45692. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45693. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45694. doc->addChildElement (map);
  45695. }
  45696. }
  45697. }
  45698. if (defaultSet != 0)
  45699. {
  45700. for (i = 0; i < defaultSet->mappings.size(); ++i)
  45701. {
  45702. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  45703. for (int j = 0; j < cm->keypresses.size(); ++j)
  45704. {
  45705. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45706. {
  45707. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  45708. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45709. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45710. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45711. doc->addChildElement (map);
  45712. }
  45713. }
  45714. }
  45715. delete defaultSet;
  45716. }
  45717. return doc;
  45718. }
  45719. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  45720. Component* originatingComponent)
  45721. {
  45722. bool used = false;
  45723. const CommandID commandID = findCommandForKeyPress (key);
  45724. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45725. if (ci != 0
  45726. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  45727. {
  45728. ApplicationCommandInfo info (0);
  45729. if (commandManager->getTargetForCommand (commandID, info) != 0
  45730. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  45731. {
  45732. invokeCommand (commandID, key, true, 0, originatingComponent);
  45733. used = true;
  45734. }
  45735. else
  45736. {
  45737. if (originatingComponent != 0)
  45738. originatingComponent->getLookAndFeel().playAlertSound();
  45739. }
  45740. }
  45741. return used;
  45742. }
  45743. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  45744. {
  45745. bool used = false;
  45746. const uint32 now = Time::getMillisecondCounter();
  45747. for (int i = mappings.size(); --i >= 0;)
  45748. {
  45749. CommandMapping* const cm = mappings.getUnchecked(i);
  45750. if (cm->wantsKeyUpDownCallbacks)
  45751. {
  45752. for (int j = cm->keypresses.size(); --j >= 0;)
  45753. {
  45754. const KeyPress key (cm->keypresses.getReference (j));
  45755. const bool isDown = key.isCurrentlyDown();
  45756. int keyPressEntryIndex = 0;
  45757. bool wasDown = false;
  45758. for (int k = keysDown.size(); --k >= 0;)
  45759. {
  45760. if (key == keysDown.getUnchecked(k)->key)
  45761. {
  45762. keyPressEntryIndex = k;
  45763. wasDown = true;
  45764. used = true;
  45765. break;
  45766. }
  45767. }
  45768. if (isDown != wasDown)
  45769. {
  45770. int millisecs = 0;
  45771. if (isDown)
  45772. {
  45773. KeyPressTime* const k = new KeyPressTime();
  45774. k->key = key;
  45775. k->timeWhenPressed = now;
  45776. keysDown.add (k);
  45777. }
  45778. else
  45779. {
  45780. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  45781. if (now > pressTime)
  45782. millisecs = now - pressTime;
  45783. keysDown.remove (keyPressEntryIndex);
  45784. }
  45785. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  45786. used = true;
  45787. }
  45788. }
  45789. }
  45790. }
  45791. return used;
  45792. }
  45793. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  45794. {
  45795. if (focusedComponent != 0)
  45796. focusedComponent->keyStateChanged (false);
  45797. }
  45798. END_JUCE_NAMESPACE
  45799. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  45800. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  45801. BEGIN_JUCE_NAMESPACE
  45802. ModifierKeys::ModifierKeys (const int flags_) throw()
  45803. : flags (flags_)
  45804. {
  45805. }
  45806. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  45807. : flags (other.flags)
  45808. {
  45809. }
  45810. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  45811. {
  45812. flags = other.flags;
  45813. return *this;
  45814. }
  45815. int ModifierKeys::currentModifierFlags = 0;
  45816. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  45817. {
  45818. return ModifierKeys (currentModifierFlags);
  45819. }
  45820. END_JUCE_NAMESPACE
  45821. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  45822. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  45823. BEGIN_JUCE_NAMESPACE
  45824. struct AnimationTask
  45825. {
  45826. AnimationTask (Component* const comp)
  45827. : component (comp),
  45828. watcher (comp)
  45829. {
  45830. }
  45831. Component* component;
  45832. ComponentDeletionWatcher watcher;
  45833. Rectangle destination;
  45834. int msElapsed, msTotal;
  45835. double startSpeed, midSpeed, endSpeed, lastProgress;
  45836. double left, top, right, bottom;
  45837. bool useTimeslice (const int elapsed)
  45838. {
  45839. if (watcher.hasBeenDeleted())
  45840. return false;
  45841. msElapsed += elapsed;
  45842. double newProgress = msElapsed / (double) msTotal;
  45843. if (newProgress >= 0 && newProgress < 1.0)
  45844. {
  45845. newProgress = timeToDistance (newProgress);
  45846. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  45847. jassert (newProgress >= lastProgress);
  45848. lastProgress = newProgress;
  45849. left += (destination.getX() - left) * delta;
  45850. top += (destination.getY() - top) * delta;
  45851. right += (destination.getRight() - right) * delta;
  45852. bottom += (destination.getBottom() - bottom) * delta;
  45853. if (delta < 1.0)
  45854. {
  45855. const Rectangle newBounds (roundDoubleToInt (left),
  45856. roundDoubleToInt (top),
  45857. roundDoubleToInt (right - left),
  45858. roundDoubleToInt (bottom - top));
  45859. if (newBounds != destination)
  45860. {
  45861. component->setBounds (newBounds);
  45862. return true;
  45863. }
  45864. }
  45865. }
  45866. component->setBounds (destination);
  45867. return false;
  45868. }
  45869. void moveToFinalDestination()
  45870. {
  45871. if (! watcher.hasBeenDeleted())
  45872. component->setBounds (destination);
  45873. }
  45874. private:
  45875. inline double timeToDistance (const double time) const
  45876. {
  45877. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  45878. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  45879. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  45880. }
  45881. };
  45882. ComponentAnimator::ComponentAnimator()
  45883. : lastTime (0)
  45884. {
  45885. }
  45886. ComponentAnimator::~ComponentAnimator()
  45887. {
  45888. cancelAllAnimations (false);
  45889. jassert (tasks.size() == 0);
  45890. }
  45891. void* ComponentAnimator::findTaskFor (Component* const component) const
  45892. {
  45893. for (int i = tasks.size(); --i >= 0;)
  45894. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  45895. return tasks.getUnchecked(i);
  45896. return 0;
  45897. }
  45898. void ComponentAnimator::animateComponent (Component* const component,
  45899. const Rectangle& finalPosition,
  45900. const int millisecondsToSpendMoving,
  45901. const double startSpeed,
  45902. const double endSpeed)
  45903. {
  45904. if (component != 0)
  45905. {
  45906. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  45907. if (at == 0)
  45908. {
  45909. at = new AnimationTask (component);
  45910. tasks.add (at);
  45911. sendChangeMessage (this);
  45912. }
  45913. at->msElapsed = 0;
  45914. at->lastProgress = 0;
  45915. at->msTotal = jmax (1, millisecondsToSpendMoving);
  45916. at->destination = finalPosition;
  45917. // the speeds must be 0 or greater!
  45918. jassert (startSpeed >= 0 && endSpeed >= 0)
  45919. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  45920. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  45921. at->midSpeed = invTotalDistance;
  45922. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  45923. at->left = component->getX();
  45924. at->top = component->getY();
  45925. at->right = component->getRight();
  45926. at->bottom = component->getBottom();
  45927. if (! isTimerRunning())
  45928. {
  45929. lastTime = Time::getMillisecondCounter();
  45930. startTimer (1000 / 50);
  45931. }
  45932. }
  45933. }
  45934. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  45935. {
  45936. for (int i = tasks.size(); --i >= 0;)
  45937. {
  45938. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45939. if (moveComponentsToTheirFinalPositions)
  45940. at->moveToFinalDestination();
  45941. delete at;
  45942. tasks.remove (i);
  45943. sendChangeMessage (this);
  45944. }
  45945. }
  45946. void ComponentAnimator::cancelAnimation (Component* const component,
  45947. const bool moveComponentToItsFinalPosition)
  45948. {
  45949. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45950. if (at != 0)
  45951. {
  45952. if (moveComponentToItsFinalPosition)
  45953. at->moveToFinalDestination();
  45954. tasks.removeValue (at);
  45955. delete at;
  45956. sendChangeMessage (this);
  45957. }
  45958. }
  45959. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  45960. {
  45961. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45962. if (at != 0)
  45963. return at->destination;
  45964. else if (component != 0)
  45965. return component->getBounds();
  45966. return Rectangle();
  45967. }
  45968. bool ComponentAnimator::isAnimating (Component* component) const
  45969. {
  45970. return findTaskFor (component) != 0;
  45971. }
  45972. void ComponentAnimator::timerCallback()
  45973. {
  45974. const uint32 timeNow = Time::getMillisecondCounter();
  45975. if (lastTime == 0 || lastTime == timeNow)
  45976. lastTime = timeNow;
  45977. const int elapsed = timeNow - lastTime;
  45978. for (int i = tasks.size(); --i >= 0;)
  45979. {
  45980. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45981. if (! at->useTimeslice (elapsed))
  45982. {
  45983. tasks.remove (i);
  45984. delete at;
  45985. sendChangeMessage (this);
  45986. }
  45987. }
  45988. lastTime = timeNow;
  45989. if (tasks.size() == 0)
  45990. stopTimer();
  45991. }
  45992. END_JUCE_NAMESPACE
  45993. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  45994. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  45995. BEGIN_JUCE_NAMESPACE
  45996. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  45997. : minW (0),
  45998. maxW (0x3fffffff),
  45999. minH (0),
  46000. maxH (0x3fffffff),
  46001. minOffTop (0),
  46002. minOffLeft (0),
  46003. minOffBottom (0),
  46004. minOffRight (0),
  46005. aspectRatio (0.0)
  46006. {
  46007. }
  46008. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  46009. {
  46010. }
  46011. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  46012. {
  46013. minW = minimumWidth;
  46014. }
  46015. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  46016. {
  46017. maxW = maximumWidth;
  46018. }
  46019. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  46020. {
  46021. minH = minimumHeight;
  46022. }
  46023. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  46024. {
  46025. maxH = maximumHeight;
  46026. }
  46027. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  46028. {
  46029. jassert (maxW >= minimumWidth);
  46030. jassert (maxH >= minimumHeight);
  46031. jassert (minimumWidth > 0 && minimumHeight > 0);
  46032. minW = minimumWidth;
  46033. minH = minimumHeight;
  46034. if (minW > maxW)
  46035. maxW = minW;
  46036. if (minH > maxH)
  46037. maxH = minH;
  46038. }
  46039. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  46040. {
  46041. jassert (maximumWidth >= minW);
  46042. jassert (maximumHeight >= minH);
  46043. jassert (maximumWidth > 0 && maximumHeight > 0);
  46044. maxW = jmax (minW, maximumWidth);
  46045. maxH = jmax (minH, maximumHeight);
  46046. }
  46047. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  46048. const int minimumHeight,
  46049. const int maximumWidth,
  46050. const int maximumHeight) throw()
  46051. {
  46052. jassert (maximumWidth >= minimumWidth);
  46053. jassert (maximumHeight >= minimumHeight);
  46054. jassert (maximumWidth > 0 && maximumHeight > 0);
  46055. jassert (minimumWidth > 0 && minimumHeight > 0);
  46056. minW = jmax (0, minimumWidth);
  46057. minH = jmax (0, minimumHeight);
  46058. maxW = jmax (minW, maximumWidth);
  46059. maxH = jmax (minH, maximumHeight);
  46060. }
  46061. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  46062. const int minimumWhenOffTheLeft,
  46063. const int minimumWhenOffTheBottom,
  46064. const int minimumWhenOffTheRight) throw()
  46065. {
  46066. minOffTop = minimumWhenOffTheTop;
  46067. minOffLeft = minimumWhenOffTheLeft;
  46068. minOffBottom = minimumWhenOffTheBottom;
  46069. minOffRight = minimumWhenOffTheRight;
  46070. }
  46071. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  46072. {
  46073. aspectRatio = jmax (0.0, widthOverHeight);
  46074. }
  46075. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  46076. {
  46077. return aspectRatio;
  46078. }
  46079. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  46080. int x, int y, int w, int h,
  46081. const bool isStretchingTop,
  46082. const bool isStretchingLeft,
  46083. const bool isStretchingBottom,
  46084. const bool isStretchingRight)
  46085. {
  46086. jassert (component != 0);
  46087. Rectangle limits;
  46088. Component* const p = component->getParentComponent();
  46089. if (p == 0)
  46090. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  46091. else
  46092. limits.setSize (p->getWidth(), p->getHeight());
  46093. if (component->isOnDesktop())
  46094. {
  46095. ComponentPeer* const peer = component->getPeer();
  46096. const BorderSize border (peer->getFrameSize());
  46097. x -= border.getLeft();
  46098. y -= border.getTop();
  46099. w += border.getLeftAndRight();
  46100. h += border.getTopAndBottom();
  46101. checkBounds (x, y, w, h,
  46102. border.addedTo (component->getBounds()), limits,
  46103. isStretchingTop, isStretchingLeft,
  46104. isStretchingBottom, isStretchingRight);
  46105. x += border.getLeft();
  46106. y += border.getTop();
  46107. w -= border.getLeftAndRight();
  46108. h -= border.getTopAndBottom();
  46109. }
  46110. else
  46111. {
  46112. checkBounds (x, y, w, h,
  46113. component->getBounds(), limits,
  46114. isStretchingTop, isStretchingLeft,
  46115. isStretchingBottom, isStretchingRight);
  46116. }
  46117. applyBoundsToComponent (component, x, y, w, h);
  46118. }
  46119. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  46120. {
  46121. setBoundsForComponent (component,
  46122. component->getX(), component->getY(),
  46123. component->getWidth(), component->getHeight(),
  46124. false, false, false, false);
  46125. }
  46126. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  46127. int x, int y, int w, int h)
  46128. {
  46129. component->setBounds (x, y, w, h);
  46130. }
  46131. void ComponentBoundsConstrainer::resizeStart()
  46132. {
  46133. }
  46134. void ComponentBoundsConstrainer::resizeEnd()
  46135. {
  46136. }
  46137. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  46138. const Rectangle& old,
  46139. const Rectangle& limits,
  46140. const bool isStretchingTop,
  46141. const bool isStretchingLeft,
  46142. const bool isStretchingBottom,
  46143. const bool isStretchingRight)
  46144. {
  46145. // constrain the size if it's being stretched..
  46146. if (isStretchingLeft)
  46147. {
  46148. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  46149. w = old.getRight() - x;
  46150. }
  46151. if (isStretchingRight)
  46152. {
  46153. w = jlimit (minW, maxW, w);
  46154. }
  46155. if (isStretchingTop)
  46156. {
  46157. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  46158. h = old.getBottom() - y;
  46159. }
  46160. if (isStretchingBottom)
  46161. {
  46162. h = jlimit (minH, maxH, h);
  46163. }
  46164. // constrain the aspect ratio if one has been specified..
  46165. if (aspectRatio > 0.0 && w > 0 && h > 0)
  46166. {
  46167. bool adjustWidth;
  46168. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46169. {
  46170. adjustWidth = true;
  46171. }
  46172. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46173. {
  46174. adjustWidth = false;
  46175. }
  46176. else
  46177. {
  46178. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  46179. const double newRatio = fabs (w / (double) h);
  46180. adjustWidth = (oldRatio > newRatio);
  46181. }
  46182. if (adjustWidth)
  46183. {
  46184. w = roundDoubleToInt (h * aspectRatio);
  46185. if (w > maxW || w < minW)
  46186. {
  46187. w = jlimit (minW, maxW, w);
  46188. h = roundDoubleToInt (w / aspectRatio);
  46189. }
  46190. }
  46191. else
  46192. {
  46193. h = roundDoubleToInt (w / aspectRatio);
  46194. if (h > maxH || h < minH)
  46195. {
  46196. h = jlimit (minH, maxH, h);
  46197. w = roundDoubleToInt (h * aspectRatio);
  46198. }
  46199. }
  46200. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46201. {
  46202. x = old.getX() + (old.getWidth() - w) / 2;
  46203. }
  46204. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46205. {
  46206. y = old.getY() + (old.getHeight() - h) / 2;
  46207. }
  46208. else
  46209. {
  46210. if (isStretchingLeft)
  46211. x = old.getRight() - w;
  46212. if (isStretchingTop)
  46213. y = old.getBottom() - h;
  46214. }
  46215. }
  46216. // ...and constrain the position if limits have been set for that.
  46217. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  46218. {
  46219. if (minOffTop > 0)
  46220. {
  46221. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  46222. if (y < limit)
  46223. {
  46224. if (isStretchingTop)
  46225. h -= (limit - y);
  46226. y = limit;
  46227. }
  46228. }
  46229. if (minOffLeft > 0)
  46230. {
  46231. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  46232. if (x < limit)
  46233. {
  46234. if (isStretchingLeft)
  46235. w -= (limit - x);
  46236. x = limit;
  46237. }
  46238. }
  46239. if (minOffBottom > 0)
  46240. {
  46241. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  46242. if (y > limit)
  46243. {
  46244. if (isStretchingBottom)
  46245. h += (limit - y);
  46246. else
  46247. y = limit;
  46248. }
  46249. }
  46250. if (minOffRight > 0)
  46251. {
  46252. const int limit = limits.getRight() - jmin (minOffRight, w);
  46253. if (x > limit)
  46254. {
  46255. if (isStretchingRight)
  46256. w += (limit - x);
  46257. else
  46258. x = limit;
  46259. }
  46260. }
  46261. }
  46262. jassert (w >= 0 && h >= 0);
  46263. }
  46264. END_JUCE_NAMESPACE
  46265. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  46266. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46267. BEGIN_JUCE_NAMESPACE
  46268. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  46269. : component (component_),
  46270. lastPeer (0),
  46271. registeredParentComps (4),
  46272. reentrant (false)
  46273. {
  46274. jassert (component != 0); // can't use this with a null pointer..
  46275. #ifdef JUCE_DEBUG
  46276. deletionWatcher = new ComponentDeletionWatcher (component_);
  46277. #endif
  46278. component->addComponentListener (this);
  46279. registerWithParentComps();
  46280. }
  46281. ComponentMovementWatcher::~ComponentMovementWatcher()
  46282. {
  46283. component->removeComponentListener (this);
  46284. unregister();
  46285. #ifdef JUCE_DEBUG
  46286. delete deletionWatcher;
  46287. #endif
  46288. }
  46289. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  46290. {
  46291. #ifdef JUCE_DEBUG
  46292. // agh! don't delete the target component without deleting this object first!
  46293. jassert (! deletionWatcher->hasBeenDeleted());
  46294. #endif
  46295. if (! reentrant)
  46296. {
  46297. reentrant = true;
  46298. ComponentPeer* const peer = component->getPeer();
  46299. if (peer != lastPeer)
  46300. {
  46301. ComponentDeletionWatcher watcher (component);
  46302. componentPeerChanged();
  46303. if (watcher.hasBeenDeleted())
  46304. return;
  46305. lastPeer = peer;
  46306. }
  46307. unregister();
  46308. registerWithParentComps();
  46309. reentrant = false;
  46310. componentMovedOrResized (*component, true, true);
  46311. }
  46312. }
  46313. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  46314. {
  46315. #ifdef JUCE_DEBUG
  46316. // agh! don't delete the target component without deleting this object first!
  46317. jassert (! deletionWatcher->hasBeenDeleted());
  46318. #endif
  46319. if (wasMoved)
  46320. {
  46321. int x = 0, y = 0;
  46322. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  46323. wasMoved = (lastX != x || lastY != y);
  46324. lastX = x;
  46325. lastY = y;
  46326. }
  46327. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  46328. lastWidth = component->getWidth();
  46329. lastHeight = component->getHeight();
  46330. if (wasMoved || wasResized)
  46331. componentMovedOrResized (wasMoved, wasResized);
  46332. }
  46333. void ComponentMovementWatcher::registerWithParentComps() throw()
  46334. {
  46335. Component* p = component->getParentComponent();
  46336. while (p != 0)
  46337. {
  46338. p->addComponentListener (this);
  46339. registeredParentComps.add (p);
  46340. p = p->getParentComponent();
  46341. }
  46342. }
  46343. void ComponentMovementWatcher::unregister() throw()
  46344. {
  46345. for (int i = registeredParentComps.size(); --i >= 0;)
  46346. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  46347. registeredParentComps.clear();
  46348. }
  46349. END_JUCE_NAMESPACE
  46350. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46351. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  46352. BEGIN_JUCE_NAMESPACE
  46353. GroupComponent::GroupComponent (const String& componentName,
  46354. const String& labelText)
  46355. : Component (componentName),
  46356. text (labelText),
  46357. justification (Justification::left)
  46358. {
  46359. setInterceptsMouseClicks (false, true);
  46360. }
  46361. GroupComponent::~GroupComponent()
  46362. {
  46363. }
  46364. void GroupComponent::setText (const String& newText) throw()
  46365. {
  46366. if (text != newText)
  46367. {
  46368. text = newText;
  46369. repaint();
  46370. }
  46371. }
  46372. const String GroupComponent::getText() const throw()
  46373. {
  46374. return text;
  46375. }
  46376. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  46377. {
  46378. if (justification.getFlags() != newJustification.getFlags())
  46379. {
  46380. justification = newJustification;
  46381. repaint();
  46382. }
  46383. }
  46384. void GroupComponent::paint (Graphics& g)
  46385. {
  46386. getLookAndFeel()
  46387. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  46388. text, justification,
  46389. *this);
  46390. }
  46391. void GroupComponent::enablementChanged()
  46392. {
  46393. repaint();
  46394. }
  46395. void GroupComponent::colourChanged()
  46396. {
  46397. repaint();
  46398. }
  46399. END_JUCE_NAMESPACE
  46400. /********* End of inlined file: juce_GroupComponent.cpp *********/
  46401. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  46402. BEGIN_JUCE_NAMESPACE
  46403. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  46404. : DocumentWindow (String::empty, backgroundColour,
  46405. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  46406. {
  46407. }
  46408. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  46409. {
  46410. }
  46411. void MultiDocumentPanelWindow::maximiseButtonPressed()
  46412. {
  46413. MultiDocumentPanel* const owner = getOwner();
  46414. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46415. if (owner != 0)
  46416. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  46417. }
  46418. void MultiDocumentPanelWindow::closeButtonPressed()
  46419. {
  46420. MultiDocumentPanel* const owner = getOwner();
  46421. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46422. if (owner != 0)
  46423. owner->closeDocument (getContentComponent(), true);
  46424. }
  46425. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  46426. {
  46427. DocumentWindow::activeWindowStatusChanged();
  46428. updateOrder();
  46429. }
  46430. void MultiDocumentPanelWindow::broughtToFront()
  46431. {
  46432. DocumentWindow::broughtToFront();
  46433. updateOrder();
  46434. }
  46435. void MultiDocumentPanelWindow::updateOrder()
  46436. {
  46437. MultiDocumentPanel* const owner = getOwner();
  46438. if (owner != 0)
  46439. owner->updateOrder();
  46440. }
  46441. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  46442. {
  46443. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46444. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46445. }
  46446. class MDITabbedComponentInternal : public TabbedComponent
  46447. {
  46448. public:
  46449. MDITabbedComponentInternal()
  46450. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  46451. {
  46452. }
  46453. ~MDITabbedComponentInternal()
  46454. {
  46455. }
  46456. void currentTabChanged (const int, const String&)
  46457. {
  46458. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46459. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46460. if (owner != 0)
  46461. owner->updateOrder();
  46462. }
  46463. };
  46464. MultiDocumentPanel::MultiDocumentPanel()
  46465. : mode (MaximisedWindowsWithTabs),
  46466. tabComponent (0),
  46467. backgroundColour (Colours::lightblue),
  46468. maximumNumDocuments (0),
  46469. numDocsBeforeTabsUsed (0)
  46470. {
  46471. setOpaque (true);
  46472. }
  46473. MultiDocumentPanel::~MultiDocumentPanel()
  46474. {
  46475. closeAllDocuments (false);
  46476. }
  46477. static bool shouldDeleteComp (Component* const c)
  46478. {
  46479. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  46480. }
  46481. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  46482. {
  46483. while (components.size() > 0)
  46484. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  46485. return false;
  46486. return true;
  46487. }
  46488. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  46489. {
  46490. return new MultiDocumentPanelWindow (backgroundColour);
  46491. }
  46492. void MultiDocumentPanel::addWindow (Component* component)
  46493. {
  46494. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  46495. dw->setResizable (true, false);
  46496. dw->setContentComponent (component, false, true);
  46497. dw->setName (component->getName());
  46498. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  46499. int x = 4;
  46500. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  46501. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  46502. x += 16;
  46503. dw->setTopLeftPosition (x, x);
  46504. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  46505. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  46506. addAndMakeVisible (dw);
  46507. dw->toFront (true);
  46508. }
  46509. bool MultiDocumentPanel::addDocument (Component* const component,
  46510. const Colour& docColour,
  46511. const bool deleteWhenRemoved)
  46512. {
  46513. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  46514. // with a frame-within-a-frame! Just pass in the bare content component.
  46515. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  46516. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  46517. return false;
  46518. components.add (component);
  46519. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  46520. component->setComponentProperty (T("mdiDocumentBkg_"), docColour);
  46521. component->addComponentListener (this);
  46522. if (mode == FloatingWindows)
  46523. {
  46524. if (isFullscreenWhenOneDocument())
  46525. {
  46526. if (components.size() == 1)
  46527. {
  46528. addAndMakeVisible (component);
  46529. }
  46530. else
  46531. {
  46532. if (components.size() == 2)
  46533. addWindow (components.getFirst());
  46534. addWindow (component);
  46535. }
  46536. }
  46537. else
  46538. {
  46539. addWindow (component);
  46540. }
  46541. }
  46542. else
  46543. {
  46544. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  46545. {
  46546. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  46547. Array <Component*> temp (components);
  46548. for (int i = 0; i < temp.size(); ++i)
  46549. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  46550. resized();
  46551. }
  46552. else
  46553. {
  46554. if (tabComponent != 0)
  46555. tabComponent->addTab (component->getName(), docColour, component, false);
  46556. else
  46557. addAndMakeVisible (component);
  46558. }
  46559. setActiveDocument (component);
  46560. }
  46561. resized();
  46562. activeDocumentChanged();
  46563. return true;
  46564. }
  46565. bool MultiDocumentPanel::closeDocument (Component* component,
  46566. const bool checkItsOkToCloseFirst)
  46567. {
  46568. if (components.contains (component))
  46569. {
  46570. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  46571. return false;
  46572. component->removeComponentListener (this);
  46573. const bool shouldDelete = shouldDeleteComp (component);
  46574. component->removeComponentProperty (T("mdiDocumentDelete_"));
  46575. component->removeComponentProperty (T("mdiDocumentBkg_"));
  46576. if (mode == FloatingWindows)
  46577. {
  46578. for (int i = getNumChildComponents(); --i >= 0;)
  46579. {
  46580. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46581. if (dw != 0 && dw->getContentComponent() == component)
  46582. {
  46583. dw->setContentComponent (0, false);
  46584. delete dw;
  46585. break;
  46586. }
  46587. }
  46588. if (shouldDelete)
  46589. delete component;
  46590. components.removeValue (component);
  46591. if (isFullscreenWhenOneDocument() && components.size() == 1)
  46592. {
  46593. for (int i = getNumChildComponents(); --i >= 0;)
  46594. {
  46595. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46596. if (dw != 0)
  46597. {
  46598. dw->setContentComponent (0, false);
  46599. delete dw;
  46600. }
  46601. }
  46602. addAndMakeVisible (components.getFirst());
  46603. }
  46604. }
  46605. else
  46606. {
  46607. jassert (components.indexOf (component) >= 0);
  46608. if (tabComponent != 0)
  46609. {
  46610. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46611. if (tabComponent->getTabContentComponent (i) == component)
  46612. tabComponent->removeTab (i);
  46613. }
  46614. else
  46615. {
  46616. removeChildComponent (component);
  46617. }
  46618. if (shouldDelete)
  46619. delete component;
  46620. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  46621. deleteAndZero (tabComponent);
  46622. components.removeValue (component);
  46623. if (components.size() > 0 && tabComponent == 0)
  46624. addAndMakeVisible (components.getFirst());
  46625. }
  46626. resized();
  46627. activeDocumentChanged();
  46628. }
  46629. else
  46630. {
  46631. jassertfalse
  46632. }
  46633. return true;
  46634. }
  46635. int MultiDocumentPanel::getNumDocuments() const throw()
  46636. {
  46637. return components.size();
  46638. }
  46639. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  46640. {
  46641. return components [index];
  46642. }
  46643. Component* MultiDocumentPanel::getActiveDocument() const throw()
  46644. {
  46645. if (mode == FloatingWindows)
  46646. {
  46647. for (int i = getNumChildComponents(); --i >= 0;)
  46648. {
  46649. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46650. if (dw != 0 && dw->isActiveWindow())
  46651. return dw->getContentComponent();
  46652. }
  46653. }
  46654. return components.getLast();
  46655. }
  46656. void MultiDocumentPanel::setActiveDocument (Component* component)
  46657. {
  46658. if (mode == FloatingWindows)
  46659. {
  46660. component = getContainerComp (component);
  46661. if (component != 0)
  46662. component->toFront (true);
  46663. }
  46664. else if (tabComponent != 0)
  46665. {
  46666. jassert (components.indexOf (component) >= 0);
  46667. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46668. {
  46669. if (tabComponent->getTabContentComponent (i) == component)
  46670. {
  46671. tabComponent->setCurrentTabIndex (i);
  46672. break;
  46673. }
  46674. }
  46675. }
  46676. else
  46677. {
  46678. component->grabKeyboardFocus();
  46679. }
  46680. }
  46681. void MultiDocumentPanel::activeDocumentChanged()
  46682. {
  46683. }
  46684. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  46685. {
  46686. maximumNumDocuments = newNumber;
  46687. }
  46688. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  46689. {
  46690. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  46691. }
  46692. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  46693. {
  46694. return numDocsBeforeTabsUsed != 0;
  46695. }
  46696. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  46697. {
  46698. if (mode != newLayoutMode)
  46699. {
  46700. mode = newLayoutMode;
  46701. if (mode == FloatingWindows)
  46702. {
  46703. deleteAndZero (tabComponent);
  46704. }
  46705. else
  46706. {
  46707. for (int i = getNumChildComponents(); --i >= 0;)
  46708. {
  46709. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46710. if (dw != 0)
  46711. {
  46712. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  46713. dw->setContentComponent (0, false);
  46714. delete dw;
  46715. }
  46716. }
  46717. }
  46718. resized();
  46719. const Array <Component*> tempComps (components);
  46720. components.clear();
  46721. for (int i = 0; i < tempComps.size(); ++i)
  46722. {
  46723. Component* const c = tempComps.getUnchecked(i);
  46724. addDocument (c,
  46725. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  46726. shouldDeleteComp (c));
  46727. }
  46728. }
  46729. }
  46730. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  46731. {
  46732. if (backgroundColour != newBackgroundColour)
  46733. {
  46734. backgroundColour = newBackgroundColour;
  46735. setOpaque (newBackgroundColour.isOpaque());
  46736. repaint();
  46737. }
  46738. }
  46739. void MultiDocumentPanel::paint (Graphics& g)
  46740. {
  46741. g.fillAll (backgroundColour);
  46742. }
  46743. void MultiDocumentPanel::resized()
  46744. {
  46745. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  46746. {
  46747. for (int i = getNumChildComponents(); --i >= 0;)
  46748. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  46749. }
  46750. setWantsKeyboardFocus (components.size() == 0);
  46751. }
  46752. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  46753. {
  46754. if (mode == FloatingWindows)
  46755. {
  46756. for (int i = 0; i < getNumChildComponents(); ++i)
  46757. {
  46758. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46759. if (dw != 0 && dw->getContentComponent() == c)
  46760. {
  46761. c = dw;
  46762. break;
  46763. }
  46764. }
  46765. }
  46766. return c;
  46767. }
  46768. void MultiDocumentPanel::componentNameChanged (Component&)
  46769. {
  46770. if (mode == FloatingWindows)
  46771. {
  46772. for (int i = 0; i < getNumChildComponents(); ++i)
  46773. {
  46774. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46775. if (dw != 0)
  46776. dw->setName (dw->getContentComponent()->getName());
  46777. }
  46778. }
  46779. else if (tabComponent != 0)
  46780. {
  46781. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46782. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  46783. }
  46784. }
  46785. void MultiDocumentPanel::updateOrder()
  46786. {
  46787. const Array <Component*> oldList (components);
  46788. if (mode == FloatingWindows)
  46789. {
  46790. components.clear();
  46791. for (int i = 0; i < getNumChildComponents(); ++i)
  46792. {
  46793. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46794. if (dw != 0)
  46795. components.add (dw->getContentComponent());
  46796. }
  46797. }
  46798. else
  46799. {
  46800. if (tabComponent != 0)
  46801. {
  46802. Component* const current = tabComponent->getCurrentContentComponent();
  46803. if (current != 0)
  46804. {
  46805. components.removeValue (current);
  46806. components.add (current);
  46807. }
  46808. }
  46809. }
  46810. if (components != oldList)
  46811. activeDocumentChanged();
  46812. }
  46813. END_JUCE_NAMESPACE
  46814. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  46815. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  46816. BEGIN_JUCE_NAMESPACE
  46817. const int zoneL = 1;
  46818. const int zoneR = 2;
  46819. const int zoneT = 4;
  46820. const int zoneB = 8;
  46821. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  46822. ComponentBoundsConstrainer* const constrainer_)
  46823. : component (componentToResize),
  46824. constrainer (constrainer_),
  46825. borderSize (5),
  46826. mouseZone (0)
  46827. {
  46828. }
  46829. ResizableBorderComponent::~ResizableBorderComponent()
  46830. {
  46831. }
  46832. void ResizableBorderComponent::paint (Graphics& g)
  46833. {
  46834. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  46835. }
  46836. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  46837. {
  46838. updateMouseZone (e);
  46839. }
  46840. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  46841. {
  46842. updateMouseZone (e);
  46843. }
  46844. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  46845. {
  46846. if (component->isValidComponent())
  46847. {
  46848. updateMouseZone (e);
  46849. originalX = component->getX();
  46850. originalY = component->getY();
  46851. originalW = component->getWidth();
  46852. originalH = component->getHeight();
  46853. if (constrainer != 0)
  46854. constrainer->resizeStart();
  46855. }
  46856. else
  46857. {
  46858. jassertfalse
  46859. }
  46860. }
  46861. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  46862. {
  46863. if (! component->isValidComponent())
  46864. {
  46865. jassertfalse
  46866. return;
  46867. }
  46868. int x = originalX;
  46869. int y = originalY;
  46870. int w = originalW;
  46871. int h = originalH;
  46872. const int dx = e.getDistanceFromDragStartX();
  46873. const int dy = e.getDistanceFromDragStartY();
  46874. if ((mouseZone & zoneL) != 0)
  46875. {
  46876. x += dx;
  46877. w -= dx;
  46878. }
  46879. if ((mouseZone & zoneT) != 0)
  46880. {
  46881. y += dy;
  46882. h -= dy;
  46883. }
  46884. if ((mouseZone & zoneR) != 0)
  46885. w += dx;
  46886. if ((mouseZone & zoneB) != 0)
  46887. h += dy;
  46888. if (constrainer != 0)
  46889. constrainer->setBoundsForComponent (component,
  46890. x, y, w, h,
  46891. (mouseZone & zoneT) != 0,
  46892. (mouseZone & zoneL) != 0,
  46893. (mouseZone & zoneB) != 0,
  46894. (mouseZone & zoneR) != 0);
  46895. else
  46896. component->setBounds (x, y, w, h);
  46897. }
  46898. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  46899. {
  46900. if (constrainer != 0)
  46901. constrainer->resizeEnd();
  46902. }
  46903. bool ResizableBorderComponent::hitTest (int x, int y)
  46904. {
  46905. return x < borderSize.getLeft()
  46906. || x >= getWidth() - borderSize.getRight()
  46907. || y < borderSize.getTop()
  46908. || y >= getHeight() - borderSize.getBottom();
  46909. }
  46910. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  46911. {
  46912. if (borderSize != newBorderSize)
  46913. {
  46914. borderSize = newBorderSize;
  46915. repaint();
  46916. }
  46917. }
  46918. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  46919. {
  46920. return borderSize;
  46921. }
  46922. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  46923. {
  46924. int newZone = 0;
  46925. if (ResizableBorderComponent::hitTest (e.x, e.y))
  46926. {
  46927. if (e.x < jmax (borderSize.getLeft(),
  46928. proportionOfWidth (0.1f),
  46929. jmin (10, proportionOfWidth (0.33f))))
  46930. newZone |= zoneL;
  46931. else if (e.x >= jmin (getWidth() - borderSize.getRight(),
  46932. proportionOfWidth (0.9f),
  46933. getWidth() - jmin (10, proportionOfWidth (0.33f))))
  46934. newZone |= zoneR;
  46935. if (e.y < jmax (borderSize.getTop(),
  46936. proportionOfHeight (0.1f),
  46937. jmin (10, proportionOfHeight (0.33f))))
  46938. newZone |= zoneT;
  46939. else if (e.y >= jmin (getHeight() - borderSize.getBottom(),
  46940. proportionOfHeight (0.9f),
  46941. getHeight() - jmin (10, proportionOfHeight (0.33f))))
  46942. newZone |= zoneB;
  46943. }
  46944. if (mouseZone != newZone)
  46945. {
  46946. mouseZone = newZone;
  46947. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  46948. switch (newZone)
  46949. {
  46950. case (zoneL | zoneT):
  46951. mc = MouseCursor::TopLeftCornerResizeCursor;
  46952. break;
  46953. case zoneT:
  46954. mc = MouseCursor::TopEdgeResizeCursor;
  46955. break;
  46956. case (zoneR | zoneT):
  46957. mc = MouseCursor::TopRightCornerResizeCursor;
  46958. break;
  46959. case zoneL:
  46960. mc = MouseCursor::LeftEdgeResizeCursor;
  46961. break;
  46962. case zoneR:
  46963. mc = MouseCursor::RightEdgeResizeCursor;
  46964. break;
  46965. case (zoneL | zoneB):
  46966. mc = MouseCursor::BottomLeftCornerResizeCursor;
  46967. break;
  46968. case zoneB:
  46969. mc = MouseCursor::BottomEdgeResizeCursor;
  46970. break;
  46971. case (zoneR | zoneB):
  46972. mc = MouseCursor::BottomRightCornerResizeCursor;
  46973. break;
  46974. default:
  46975. break;
  46976. }
  46977. setMouseCursor (mc);
  46978. }
  46979. }
  46980. END_JUCE_NAMESPACE
  46981. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  46982. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  46983. BEGIN_JUCE_NAMESPACE
  46984. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  46985. ComponentBoundsConstrainer* const constrainer_)
  46986. : component (componentToResize),
  46987. constrainer (constrainer_)
  46988. {
  46989. setRepaintsOnMouseActivity (true);
  46990. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  46991. }
  46992. ResizableCornerComponent::~ResizableCornerComponent()
  46993. {
  46994. }
  46995. void ResizableCornerComponent::paint (Graphics& g)
  46996. {
  46997. getLookAndFeel()
  46998. .drawCornerResizer (g, getWidth(), getHeight(),
  46999. isMouseOverOrDragging(),
  47000. isMouseButtonDown());
  47001. }
  47002. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  47003. {
  47004. if (component->isValidComponent())
  47005. {
  47006. originalX = component->getX();
  47007. originalY = component->getY();
  47008. originalW = component->getWidth();
  47009. originalH = component->getHeight();
  47010. if (constrainer != 0)
  47011. constrainer->resizeStart();
  47012. }
  47013. else
  47014. {
  47015. jassertfalse
  47016. }
  47017. }
  47018. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  47019. {
  47020. if (! component->isValidComponent())
  47021. {
  47022. jassertfalse
  47023. return;
  47024. }
  47025. int x = originalX;
  47026. int y = originalY;
  47027. int w = originalW + e.getDistanceFromDragStartX();
  47028. int h = originalH + e.getDistanceFromDragStartY();
  47029. if (constrainer != 0)
  47030. constrainer->setBoundsForComponent (component, x, y, w, h,
  47031. false, false, true, true);
  47032. else
  47033. component->setBounds (x, y, w, h);
  47034. }
  47035. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  47036. {
  47037. if (constrainer != 0)
  47038. constrainer->resizeStart();
  47039. }
  47040. bool ResizableCornerComponent::hitTest (int x, int y)
  47041. {
  47042. if (getWidth() <= 0)
  47043. return false;
  47044. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  47045. return y >= yAtX - getHeight() / 4;
  47046. }
  47047. END_JUCE_NAMESPACE
  47048. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  47049. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  47050. BEGIN_JUCE_NAMESPACE
  47051. class ScrollbarButton : public Button
  47052. {
  47053. public:
  47054. int direction;
  47055. ScrollbarButton (const int direction_,
  47056. ScrollBar& owner_) throw()
  47057. : Button (String::empty),
  47058. direction (direction_),
  47059. owner (owner_)
  47060. {
  47061. setWantsKeyboardFocus (false);
  47062. }
  47063. ~ScrollbarButton()
  47064. {
  47065. }
  47066. void paintButton (Graphics& g,
  47067. bool isMouseOver,
  47068. bool isMouseDown)
  47069. {
  47070. getLookAndFeel()
  47071. .drawScrollbarButton (g, owner,
  47072. getWidth(), getHeight(),
  47073. direction,
  47074. owner.isVertical(),
  47075. isMouseOver, isMouseDown);
  47076. }
  47077. void clicked()
  47078. {
  47079. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  47080. }
  47081. juce_UseDebuggingNewOperator
  47082. private:
  47083. ScrollBar& owner;
  47084. ScrollbarButton (const ScrollbarButton&);
  47085. const ScrollbarButton& operator= (const ScrollbarButton&);
  47086. };
  47087. ScrollBar::ScrollBar (const bool vertical_,
  47088. const bool buttonsAreVisible)
  47089. : minimum (0.0),
  47090. maximum (1.0),
  47091. rangeStart (0.0),
  47092. rangeSize (0.1),
  47093. singleStepSize (0.1),
  47094. thumbAreaStart (0),
  47095. thumbAreaSize (0),
  47096. thumbStart (0),
  47097. thumbSize (0),
  47098. initialDelayInMillisecs (100),
  47099. repeatDelayInMillisecs (50),
  47100. minimumDelayInMillisecs (10),
  47101. vertical (vertical_),
  47102. isDraggingThumb (false),
  47103. alwaysVisible (false),
  47104. upButton (0),
  47105. downButton (0),
  47106. listeners (2)
  47107. {
  47108. setButtonVisibility (buttonsAreVisible);
  47109. setRepaintsOnMouseActivity (true);
  47110. setFocusContainer (true);
  47111. }
  47112. ScrollBar::~ScrollBar()
  47113. {
  47114. deleteAllChildren();
  47115. }
  47116. void ScrollBar::setRangeLimits (const double newMinimum,
  47117. const double newMaximum) throw()
  47118. {
  47119. minimum = newMinimum;
  47120. maximum = newMaximum;
  47121. jassert (maximum >= minimum); // these can't be the wrong way round!
  47122. setCurrentRangeStart (rangeStart);
  47123. updateThumbPosition();
  47124. }
  47125. void ScrollBar::setCurrentRange (double newStart,
  47126. double newSize) throw()
  47127. {
  47128. newSize = jlimit (0.0, maximum - minimum, newSize);
  47129. newStart = jlimit (minimum, maximum - newSize, newStart);
  47130. if (rangeStart != newStart
  47131. || rangeSize != newSize)
  47132. {
  47133. rangeStart = newStart;
  47134. rangeSize = newSize;
  47135. updateThumbPosition();
  47136. triggerAsyncUpdate();
  47137. }
  47138. }
  47139. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  47140. {
  47141. setCurrentRange (newStart, rangeSize);
  47142. }
  47143. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  47144. {
  47145. singleStepSize = newSingleStepSize;
  47146. }
  47147. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  47148. {
  47149. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  47150. }
  47151. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  47152. {
  47153. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  47154. }
  47155. void ScrollBar::scrollToTop() throw()
  47156. {
  47157. setCurrentRangeStart (minimum);
  47158. }
  47159. void ScrollBar::scrollToBottom() throw()
  47160. {
  47161. setCurrentRangeStart (maximum - rangeSize);
  47162. }
  47163. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  47164. const int repeatDelayInMillisecs_,
  47165. const int minimumDelayInMillisecs_) throw()
  47166. {
  47167. initialDelayInMillisecs = initialDelayInMillisecs_;
  47168. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  47169. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  47170. if (upButton != 0)
  47171. {
  47172. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47173. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47174. }
  47175. }
  47176. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  47177. {
  47178. jassert (listener != 0);
  47179. if (listener != 0)
  47180. listeners.add (listener);
  47181. }
  47182. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  47183. {
  47184. listeners.removeValue (listener);
  47185. }
  47186. void ScrollBar::handleAsyncUpdate()
  47187. {
  47188. const double value = getCurrentRangeStart();
  47189. for (int i = listeners.size(); --i >= 0;)
  47190. {
  47191. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  47192. i = jmin (i, listeners.size());
  47193. }
  47194. }
  47195. void ScrollBar::updateThumbPosition() throw()
  47196. {
  47197. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  47198. : thumbAreaSize);
  47199. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47200. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  47201. if (newThumbSize > thumbAreaSize)
  47202. newThumbSize = thumbAreaSize;
  47203. int newThumbStart = thumbAreaStart;
  47204. if (maximum - minimum > rangeSize)
  47205. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  47206. / ((maximum - minimum) - rangeSize));
  47207. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  47208. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  47209. {
  47210. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  47211. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  47212. if (vertical)
  47213. repaint (0, repaintStart, getWidth(), repaintSize);
  47214. else
  47215. repaint (repaintStart, 0, repaintSize, getHeight());
  47216. thumbStart = newThumbStart;
  47217. thumbSize = newThumbSize;
  47218. }
  47219. }
  47220. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  47221. {
  47222. if (vertical != shouldBeVertical)
  47223. {
  47224. vertical = shouldBeVertical;
  47225. if (upButton != 0)
  47226. {
  47227. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  47228. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  47229. }
  47230. updateThumbPosition();
  47231. }
  47232. }
  47233. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  47234. {
  47235. deleteAndZero (upButton);
  47236. deleteAndZero (downButton);
  47237. if (buttonsAreVisible)
  47238. {
  47239. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  47240. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  47241. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47242. }
  47243. updateThumbPosition();
  47244. }
  47245. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  47246. {
  47247. alwaysVisible = ! shouldHideWhenFullRange;
  47248. updateThumbPosition();
  47249. }
  47250. void ScrollBar::paint (Graphics& g)
  47251. {
  47252. if (thumbAreaSize > 0)
  47253. {
  47254. LookAndFeel& lf = getLookAndFeel();
  47255. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  47256. ? thumbSize : 0;
  47257. if (vertical)
  47258. {
  47259. lf.drawScrollbar (g, *this,
  47260. 0, thumbAreaStart,
  47261. getWidth(), thumbAreaSize,
  47262. vertical,
  47263. thumbStart, thumb,
  47264. isMouseOver(), isMouseButtonDown());
  47265. }
  47266. else
  47267. {
  47268. lf.drawScrollbar (g, *this,
  47269. thumbAreaStart, 0,
  47270. thumbAreaSize, getHeight(),
  47271. vertical,
  47272. thumbStart, thumb,
  47273. isMouseOver(), isMouseButtonDown());
  47274. }
  47275. }
  47276. }
  47277. void ScrollBar::lookAndFeelChanged()
  47278. {
  47279. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  47280. }
  47281. void ScrollBar::resized()
  47282. {
  47283. const int length = ((vertical) ? getHeight() : getWidth());
  47284. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  47285. : 0;
  47286. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47287. {
  47288. thumbAreaStart = length >> 1;
  47289. thumbAreaSize = 0;
  47290. }
  47291. else
  47292. {
  47293. thumbAreaStart = buttonSize;
  47294. thumbAreaSize = length - (buttonSize << 1);
  47295. }
  47296. if (upButton != 0)
  47297. {
  47298. if (vertical)
  47299. {
  47300. upButton->setBounds (0, 0, getWidth(), buttonSize);
  47301. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  47302. }
  47303. else
  47304. {
  47305. upButton->setBounds (0, 0, buttonSize, getHeight());
  47306. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  47307. }
  47308. }
  47309. updateThumbPosition();
  47310. }
  47311. void ScrollBar::mouseDown (const MouseEvent& e)
  47312. {
  47313. isDraggingThumb = false;
  47314. lastMousePos = vertical ? e.y : e.x;
  47315. dragStartMousePos = lastMousePos;
  47316. dragStartRange = rangeStart;
  47317. if (dragStartMousePos < thumbStart)
  47318. {
  47319. moveScrollbarInPages (-1);
  47320. startTimer (400);
  47321. }
  47322. else if (dragStartMousePos >= thumbStart + thumbSize)
  47323. {
  47324. moveScrollbarInPages (1);
  47325. startTimer (400);
  47326. }
  47327. else
  47328. {
  47329. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47330. && (thumbAreaSize > thumbSize);
  47331. }
  47332. }
  47333. void ScrollBar::mouseDrag (const MouseEvent& e)
  47334. {
  47335. if (isDraggingThumb)
  47336. {
  47337. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  47338. setCurrentRangeStart (dragStartRange
  47339. + deltaPixels * ((maximum - minimum) - rangeSize)
  47340. / (thumbAreaSize - thumbSize));
  47341. }
  47342. else
  47343. {
  47344. lastMousePos = (vertical) ? e.y : e.x;
  47345. }
  47346. }
  47347. void ScrollBar::mouseUp (const MouseEvent&)
  47348. {
  47349. isDraggingThumb = false;
  47350. stopTimer();
  47351. repaint();
  47352. }
  47353. void ScrollBar::mouseWheelMove (const MouseEvent&,
  47354. float wheelIncrementX,
  47355. float wheelIncrementY)
  47356. {
  47357. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  47358. if (increment < 0)
  47359. increment = jmin (increment * 10.0f, -1.0f);
  47360. else if (increment > 0)
  47361. increment = jmax (increment * 10.0f, 1.0f);
  47362. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  47363. }
  47364. void ScrollBar::timerCallback()
  47365. {
  47366. if (isMouseButtonDown())
  47367. {
  47368. startTimer (40);
  47369. if (lastMousePos < thumbStart)
  47370. setCurrentRangeStart (rangeStart - rangeSize);
  47371. else if (lastMousePos > thumbStart + thumbSize)
  47372. setCurrentRangeStart (rangeStart + rangeSize);
  47373. }
  47374. else
  47375. {
  47376. stopTimer();
  47377. }
  47378. }
  47379. bool ScrollBar::keyPressed (const KeyPress& key)
  47380. {
  47381. if (! isVisible())
  47382. return false;
  47383. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  47384. moveScrollbarInSteps (-1);
  47385. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  47386. moveScrollbarInSteps (1);
  47387. else if (key.isKeyCode (KeyPress::pageUpKey))
  47388. moveScrollbarInPages (-1);
  47389. else if (key.isKeyCode (KeyPress::pageDownKey))
  47390. moveScrollbarInPages (1);
  47391. else if (key.isKeyCode (KeyPress::homeKey))
  47392. scrollToTop();
  47393. else if (key.isKeyCode (KeyPress::endKey))
  47394. scrollToBottom();
  47395. else
  47396. return false;
  47397. return true;
  47398. }
  47399. END_JUCE_NAMESPACE
  47400. /********* End of inlined file: juce_ScrollBar.cpp *********/
  47401. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  47402. BEGIN_JUCE_NAMESPACE
  47403. StretchableLayoutManager::StretchableLayoutManager()
  47404. : totalSize (0)
  47405. {
  47406. }
  47407. StretchableLayoutManager::~StretchableLayoutManager()
  47408. {
  47409. }
  47410. void StretchableLayoutManager::clearAllItems()
  47411. {
  47412. items.clear();
  47413. totalSize = 0;
  47414. }
  47415. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  47416. const double minimumSize,
  47417. const double maximumSize,
  47418. const double preferredSize)
  47419. {
  47420. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  47421. if (layout == 0)
  47422. {
  47423. layout = new ItemLayoutProperties();
  47424. layout->itemIndex = itemIndex;
  47425. int i;
  47426. for (i = 0; i < items.size(); ++i)
  47427. if (items.getUnchecked (i)->itemIndex > itemIndex)
  47428. break;
  47429. items.insert (i, layout);
  47430. }
  47431. layout->minSize = minimumSize;
  47432. layout->maxSize = maximumSize;
  47433. layout->preferredSize = preferredSize;
  47434. layout->currentSize = 0;
  47435. }
  47436. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  47437. double& minimumSize,
  47438. double& maximumSize,
  47439. double& preferredSize) const
  47440. {
  47441. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47442. if (layout != 0)
  47443. {
  47444. minimumSize = layout->minSize;
  47445. maximumSize = layout->maxSize;
  47446. preferredSize = layout->preferredSize;
  47447. return true;
  47448. }
  47449. return false;
  47450. }
  47451. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  47452. {
  47453. totalSize = newTotalSize;
  47454. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  47455. }
  47456. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  47457. {
  47458. int pos = 0;
  47459. for (int i = 0; i < itemIndex; ++i)
  47460. {
  47461. const ItemLayoutProperties* const layout = getInfoFor (i);
  47462. if (layout != 0)
  47463. pos += layout->currentSize;
  47464. }
  47465. return pos;
  47466. }
  47467. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  47468. {
  47469. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47470. if (layout != 0)
  47471. return layout->currentSize;
  47472. return 0;
  47473. }
  47474. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  47475. {
  47476. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47477. if (layout != 0)
  47478. return -layout->currentSize / (double) totalSize;
  47479. return 0;
  47480. }
  47481. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  47482. int newPosition)
  47483. {
  47484. for (int i = items.size(); --i >= 0;)
  47485. {
  47486. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  47487. if (layout->itemIndex == itemIndex)
  47488. {
  47489. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  47490. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  47491. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  47492. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  47493. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  47494. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  47495. endPos += layout->currentSize;
  47496. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  47497. updatePrefSizesToMatchCurrentPositions();
  47498. break;
  47499. }
  47500. }
  47501. }
  47502. void StretchableLayoutManager::layOutComponents (Component** const components,
  47503. int numComponents,
  47504. int x, int y, int w, int h,
  47505. const bool vertically,
  47506. const bool resizeOtherDimension)
  47507. {
  47508. setTotalSize (vertically ? h : w);
  47509. int pos = vertically ? y : x;
  47510. for (int i = 0; i < numComponents; ++i)
  47511. {
  47512. const ItemLayoutProperties* const layout = getInfoFor (i);
  47513. if (layout != 0)
  47514. {
  47515. Component* const c = components[i];
  47516. if (c != 0)
  47517. {
  47518. if (i == numComponents - 1)
  47519. {
  47520. // if it's the last item, crop it to exactly fit the available space..
  47521. if (resizeOtherDimension)
  47522. {
  47523. if (vertically)
  47524. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  47525. else
  47526. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  47527. }
  47528. else
  47529. {
  47530. if (vertically)
  47531. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  47532. else
  47533. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  47534. }
  47535. }
  47536. else
  47537. {
  47538. if (resizeOtherDimension)
  47539. {
  47540. if (vertically)
  47541. c->setBounds (x, pos, w, layout->currentSize);
  47542. else
  47543. c->setBounds (pos, y, layout->currentSize, h);
  47544. }
  47545. else
  47546. {
  47547. if (vertically)
  47548. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  47549. else
  47550. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  47551. }
  47552. }
  47553. }
  47554. pos += layout->currentSize;
  47555. }
  47556. }
  47557. }
  47558. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  47559. {
  47560. for (int i = items.size(); --i >= 0;)
  47561. if (items.getUnchecked(i)->itemIndex == itemIndex)
  47562. return items.getUnchecked(i);
  47563. return 0;
  47564. }
  47565. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  47566. const int endIndex,
  47567. const int availableSpace,
  47568. int startPos)
  47569. {
  47570. // calculate the total sizes
  47571. int i;
  47572. double totalIdealSize = 0.0;
  47573. int totalMinimums = 0;
  47574. for (i = startIndex; i < endIndex; ++i)
  47575. {
  47576. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47577. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  47578. totalMinimums += layout->currentSize;
  47579. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  47580. }
  47581. if (totalIdealSize <= 0)
  47582. totalIdealSize = 1.0;
  47583. // now calc the best sizes..
  47584. int extraSpace = availableSpace - totalMinimums;
  47585. while (extraSpace > 0)
  47586. {
  47587. int numWantingMoreSpace = 0;
  47588. int numHavingTakenExtraSpace = 0;
  47589. // first figure out how many comps want a slice of the extra space..
  47590. for (i = startIndex; i < endIndex; ++i)
  47591. {
  47592. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47593. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47594. const int bestSize = jlimit (layout->currentSize,
  47595. jmax (layout->currentSize,
  47596. sizeToRealSize (layout->maxSize, totalSize)),
  47597. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47598. if (bestSize > layout->currentSize)
  47599. ++numWantingMoreSpace;
  47600. }
  47601. // ..share out the extra space..
  47602. for (i = startIndex; i < endIndex; ++i)
  47603. {
  47604. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47605. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47606. int bestSize = jlimit (layout->currentSize,
  47607. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  47608. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47609. const int extraWanted = bestSize - layout->currentSize;
  47610. if (extraWanted > 0)
  47611. {
  47612. const int extraAllowed = jmin (extraWanted,
  47613. extraSpace / jmax (1, numWantingMoreSpace));
  47614. if (extraAllowed > 0)
  47615. {
  47616. ++numHavingTakenExtraSpace;
  47617. --numWantingMoreSpace;
  47618. layout->currentSize += extraAllowed;
  47619. extraSpace -= extraAllowed;
  47620. }
  47621. }
  47622. }
  47623. if (numHavingTakenExtraSpace <= 0)
  47624. break;
  47625. }
  47626. // ..and calculate the end position
  47627. for (i = startIndex; i < endIndex; ++i)
  47628. {
  47629. ItemLayoutProperties* const layout = items.getUnchecked(i);
  47630. startPos += layout->currentSize;
  47631. }
  47632. return startPos;
  47633. }
  47634. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  47635. const int endIndex) const
  47636. {
  47637. int totalMinimums = 0;
  47638. for (int i = startIndex; i < endIndex; ++i)
  47639. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  47640. return totalMinimums;
  47641. }
  47642. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  47643. {
  47644. int totalMaximums = 0;
  47645. for (int i = startIndex; i < endIndex; ++i)
  47646. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  47647. return totalMaximums;
  47648. }
  47649. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  47650. {
  47651. for (int i = 0; i < items.size(); ++i)
  47652. {
  47653. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47654. layout->preferredSize
  47655. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  47656. : getItemCurrentAbsoluteSize (i);
  47657. }
  47658. }
  47659. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  47660. {
  47661. if (size < 0)
  47662. size *= -totalSpace;
  47663. return roundDoubleToInt (size);
  47664. }
  47665. END_JUCE_NAMESPACE
  47666. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  47667. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47668. BEGIN_JUCE_NAMESPACE
  47669. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  47670. const int itemIndex_,
  47671. const bool isVertical_)
  47672. : layout (layout_),
  47673. itemIndex (itemIndex_),
  47674. isVertical (isVertical_)
  47675. {
  47676. setRepaintsOnMouseActivity (true);
  47677. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  47678. : MouseCursor::UpDownResizeCursor));
  47679. }
  47680. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  47681. {
  47682. }
  47683. void StretchableLayoutResizerBar::paint (Graphics& g)
  47684. {
  47685. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  47686. getWidth(), getHeight(),
  47687. isVertical,
  47688. isMouseOver(),
  47689. isMouseButtonDown());
  47690. }
  47691. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  47692. {
  47693. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  47694. }
  47695. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  47696. {
  47697. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  47698. : e.getDistanceFromDragStartY());
  47699. layout->setItemPosition (itemIndex, desiredPos);
  47700. hasBeenMoved();
  47701. }
  47702. void StretchableLayoutResizerBar::hasBeenMoved()
  47703. {
  47704. if (getParentComponent() != 0)
  47705. getParentComponent()->resized();
  47706. }
  47707. END_JUCE_NAMESPACE
  47708. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47709. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  47710. BEGIN_JUCE_NAMESPACE
  47711. StretchableObjectResizer::StretchableObjectResizer()
  47712. {
  47713. }
  47714. StretchableObjectResizer::~StretchableObjectResizer()
  47715. {
  47716. }
  47717. void StretchableObjectResizer::addItem (const double size,
  47718. const double minSize, const double maxSize,
  47719. const int order)
  47720. {
  47721. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  47722. Item* const item = new Item();
  47723. item->size = size;
  47724. item->minSize = minSize;
  47725. item->maxSize = maxSize;
  47726. item->order = order;
  47727. items.add (item);
  47728. }
  47729. double StretchableObjectResizer::getItemSize (const int index) const throw()
  47730. {
  47731. const Item* const it = items [index];
  47732. return it != 0 ? it->size : 0;
  47733. }
  47734. void StretchableObjectResizer::resizeToFit (const double targetSize)
  47735. {
  47736. int order = 0;
  47737. for (;;)
  47738. {
  47739. double currentSize = 0;
  47740. double minSize = 0;
  47741. double maxSize = 0;
  47742. int nextHighestOrder = INT_MAX;
  47743. for (int i = 0; i < items.size(); ++i)
  47744. {
  47745. const Item* const it = items.getUnchecked(i);
  47746. currentSize += it->size;
  47747. if (it->order <= order)
  47748. {
  47749. minSize += it->minSize;
  47750. maxSize += it->maxSize;
  47751. }
  47752. else
  47753. {
  47754. minSize += it->size;
  47755. maxSize += it->size;
  47756. nextHighestOrder = jmin (nextHighestOrder, it->order);
  47757. }
  47758. }
  47759. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  47760. if (thisIterationTarget >= currentSize)
  47761. {
  47762. const double availableExtraSpace = maxSize - currentSize;
  47763. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  47764. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  47765. for (int i = 0; i < items.size(); ++i)
  47766. {
  47767. Item* const it = items.getUnchecked(i);
  47768. if (it->order <= order)
  47769. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  47770. }
  47771. }
  47772. else
  47773. {
  47774. const double amountOfSlack = currentSize - minSize;
  47775. const double targetAmountOfSlack = thisIterationTarget - minSize;
  47776. const double scale = targetAmountOfSlack / amountOfSlack;
  47777. for (int i = 0; i < items.size(); ++i)
  47778. {
  47779. Item* const it = items.getUnchecked(i);
  47780. if (it->order <= order)
  47781. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  47782. }
  47783. }
  47784. if (nextHighestOrder < INT_MAX)
  47785. order = nextHighestOrder;
  47786. else
  47787. break;
  47788. }
  47789. }
  47790. END_JUCE_NAMESPACE
  47791. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  47792. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  47793. BEGIN_JUCE_NAMESPACE
  47794. TabBarButton::TabBarButton (const String& name,
  47795. TabbedButtonBar* const owner_,
  47796. const int index)
  47797. : Button (name),
  47798. owner (owner_),
  47799. tabIndex (index),
  47800. overlapPixels (0)
  47801. {
  47802. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  47803. setComponentEffect (&shadow);
  47804. setWantsKeyboardFocus (false);
  47805. }
  47806. TabBarButton::~TabBarButton()
  47807. {
  47808. }
  47809. void TabBarButton::paintButton (Graphics& g,
  47810. bool isMouseOverButton,
  47811. bool isButtonDown)
  47812. {
  47813. int x, y, w, h;
  47814. getActiveArea (x, y, w, h);
  47815. g.setOrigin (x, y);
  47816. getLookAndFeel()
  47817. .drawTabButton (g, w, h,
  47818. owner->getTabBackgroundColour (tabIndex),
  47819. tabIndex, getButtonText(), *this,
  47820. owner->getOrientation(),
  47821. isMouseOverButton, isButtonDown,
  47822. getToggleState());
  47823. }
  47824. void TabBarButton::clicked (const ModifierKeys& mods)
  47825. {
  47826. if (mods.isPopupMenu())
  47827. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  47828. else
  47829. owner->setCurrentTabIndex (tabIndex);
  47830. }
  47831. bool TabBarButton::hitTest (int mx, int my)
  47832. {
  47833. int x, y, w, h;
  47834. getActiveArea (x, y, w, h);
  47835. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  47836. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  47837. {
  47838. if (((unsigned int) mx) < (unsigned int) getWidth()
  47839. && my >= y + overlapPixels
  47840. && my < y + h - overlapPixels)
  47841. return true;
  47842. }
  47843. else
  47844. {
  47845. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  47846. && ((unsigned int) my) < (unsigned int) getHeight())
  47847. return true;
  47848. }
  47849. Path p;
  47850. getLookAndFeel()
  47851. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  47852. owner->getOrientation(),
  47853. false, false, getToggleState());
  47854. return p.contains ((float) (mx - x),
  47855. (float) (my - y));
  47856. }
  47857. int TabBarButton::getBestTabLength (const int depth)
  47858. {
  47859. return jlimit (depth * 2,
  47860. depth * 7,
  47861. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  47862. }
  47863. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  47864. {
  47865. x = 0;
  47866. y = 0;
  47867. int r = getWidth();
  47868. int b = getHeight();
  47869. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  47870. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  47871. r -= spaceAroundImage;
  47872. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  47873. x += spaceAroundImage;
  47874. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  47875. y += spaceAroundImage;
  47876. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  47877. b -= spaceAroundImage;
  47878. w = r - x;
  47879. h = b - y;
  47880. }
  47881. class TabAreaBehindFrontButtonComponent : public Component
  47882. {
  47883. public:
  47884. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  47885. : owner (owner_)
  47886. {
  47887. setInterceptsMouseClicks (false, false);
  47888. }
  47889. ~TabAreaBehindFrontButtonComponent()
  47890. {
  47891. }
  47892. void paint (Graphics& g)
  47893. {
  47894. getLookAndFeel()
  47895. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  47896. *owner, owner->getOrientation());
  47897. }
  47898. void enablementChanged()
  47899. {
  47900. repaint();
  47901. }
  47902. private:
  47903. TabbedButtonBar* const owner;
  47904. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  47905. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  47906. };
  47907. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  47908. : orientation (orientation_),
  47909. currentTabIndex (-1),
  47910. extraTabsButton (0)
  47911. {
  47912. setInterceptsMouseClicks (false, true);
  47913. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  47914. setFocusContainer (true);
  47915. }
  47916. TabbedButtonBar::~TabbedButtonBar()
  47917. {
  47918. deleteAllChildren();
  47919. }
  47920. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  47921. {
  47922. orientation = newOrientation;
  47923. for (int i = getNumChildComponents(); --i >= 0;)
  47924. getChildComponent (i)->resized();
  47925. resized();
  47926. }
  47927. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  47928. {
  47929. return new TabBarButton (name, this, index);
  47930. }
  47931. void TabbedButtonBar::clearTabs()
  47932. {
  47933. tabs.clear();
  47934. tabColours.clear();
  47935. currentTabIndex = -1;
  47936. deleteAndZero (extraTabsButton);
  47937. removeChildComponent (behindFrontTab);
  47938. deleteAllChildren();
  47939. addChildComponent (behindFrontTab);
  47940. setCurrentTabIndex (-1);
  47941. }
  47942. void TabbedButtonBar::addTab (const String& tabName,
  47943. const Colour& tabBackgroundColour,
  47944. int insertIndex)
  47945. {
  47946. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  47947. if (tabName.isNotEmpty())
  47948. {
  47949. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  47950. insertIndex = tabs.size();
  47951. for (int i = tabs.size(); --i >= insertIndex;)
  47952. {
  47953. TabBarButton* const tb = getTabButton (i);
  47954. if (tb != 0)
  47955. tb->tabIndex++;
  47956. }
  47957. tabs.insert (insertIndex, tabName);
  47958. tabColours.insert (insertIndex, tabBackgroundColour);
  47959. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  47960. jassert (tb != 0); // your createTabButton() mustn't return zero!
  47961. addAndMakeVisible (tb, insertIndex);
  47962. resized();
  47963. if (currentTabIndex < 0)
  47964. setCurrentTabIndex (0);
  47965. }
  47966. }
  47967. void TabbedButtonBar::setTabName (const int tabIndex,
  47968. const String& newName)
  47969. {
  47970. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  47971. && tabs[tabIndex] != newName)
  47972. {
  47973. tabs.set (tabIndex, newName);
  47974. TabBarButton* const tb = getTabButton (tabIndex);
  47975. if (tb != 0)
  47976. tb->setButtonText (newName);
  47977. resized();
  47978. }
  47979. }
  47980. void TabbedButtonBar::removeTab (const int tabIndex)
  47981. {
  47982. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  47983. {
  47984. const int oldTabIndex = currentTabIndex;
  47985. if (currentTabIndex == tabIndex)
  47986. currentTabIndex = -1;
  47987. tabs.remove (tabIndex);
  47988. tabColours.remove (tabIndex);
  47989. TabBarButton* const tb = getTabButton (tabIndex);
  47990. if (tb != 0)
  47991. delete tb;
  47992. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  47993. {
  47994. TabBarButton* const tb = getTabButton (i);
  47995. if (tb != 0)
  47996. tb->tabIndex--;
  47997. }
  47998. resized();
  47999. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  48000. }
  48001. }
  48002. void TabbedButtonBar::moveTab (const int currentIndex,
  48003. const int newIndex)
  48004. {
  48005. tabs.move (currentIndex, newIndex);
  48006. tabColours.move (currentIndex, newIndex);
  48007. resized();
  48008. }
  48009. int TabbedButtonBar::getNumTabs() const
  48010. {
  48011. return tabs.size();
  48012. }
  48013. const StringArray TabbedButtonBar::getTabNames() const
  48014. {
  48015. return tabs;
  48016. }
  48017. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  48018. {
  48019. if (currentTabIndex != newIndex)
  48020. {
  48021. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  48022. newIndex = -1;
  48023. currentTabIndex = newIndex;
  48024. for (int i = 0; i < getNumChildComponents(); ++i)
  48025. {
  48026. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  48027. if (tb != 0)
  48028. tb->setToggleState (tb->tabIndex == newIndex, false);
  48029. }
  48030. resized();
  48031. if (sendChangeMessage_)
  48032. sendChangeMessage (this);
  48033. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  48034. }
  48035. }
  48036. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  48037. {
  48038. for (int i = getNumChildComponents(); --i >= 0;)
  48039. {
  48040. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  48041. if (tb != 0 && tb->tabIndex == index)
  48042. return tb;
  48043. }
  48044. return 0;
  48045. }
  48046. void TabbedButtonBar::lookAndFeelChanged()
  48047. {
  48048. deleteAndZero (extraTabsButton);
  48049. resized();
  48050. }
  48051. void TabbedButtonBar::resized()
  48052. {
  48053. const double minimumScale = 0.7;
  48054. int depth = getWidth();
  48055. int length = getHeight();
  48056. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  48057. swapVariables (depth, length);
  48058. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  48059. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  48060. int i, totalLength = overlap;
  48061. int numVisibleButtons = tabs.size();
  48062. for (i = 0; i < getNumChildComponents(); ++i)
  48063. {
  48064. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  48065. if (tb != 0)
  48066. {
  48067. totalLength += tb->getBestTabLength (depth) - overlap;
  48068. tb->overlapPixels = overlap / 2;
  48069. }
  48070. }
  48071. double scale = 1.0;
  48072. if (totalLength > length)
  48073. scale = jmax (minimumScale, length / (double) totalLength);
  48074. const bool isTooBig = totalLength * scale > length;
  48075. int tabsButtonPos = 0;
  48076. if (isTooBig)
  48077. {
  48078. if (extraTabsButton == 0)
  48079. {
  48080. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  48081. extraTabsButton->addButtonListener (this);
  48082. extraTabsButton->setAlwaysOnTop (true);
  48083. extraTabsButton->setTriggeredOnMouseDown (true);
  48084. }
  48085. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  48086. extraTabsButton->setSize (buttonSize, buttonSize);
  48087. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  48088. {
  48089. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  48090. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  48091. }
  48092. else
  48093. {
  48094. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  48095. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  48096. }
  48097. totalLength = 0;
  48098. for (i = 0; i < tabs.size(); ++i)
  48099. {
  48100. TabBarButton* const tb = getTabButton (i);
  48101. if (tb != 0)
  48102. {
  48103. const int newLength = totalLength + tb->getBestTabLength (depth);
  48104. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  48105. {
  48106. totalLength += overlap;
  48107. break;
  48108. }
  48109. numVisibleButtons = i + 1;
  48110. totalLength = newLength - overlap;
  48111. }
  48112. }
  48113. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  48114. }
  48115. else
  48116. {
  48117. deleteAndZero (extraTabsButton);
  48118. }
  48119. int pos = 0;
  48120. TabBarButton* frontTab = 0;
  48121. for (i = 0; i < tabs.size(); ++i)
  48122. {
  48123. TabBarButton* const tb = getTabButton (i);
  48124. if (tb != 0)
  48125. {
  48126. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  48127. if (i < numVisibleButtons)
  48128. {
  48129. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  48130. tb->setBounds (pos, 0, bestLength, getHeight());
  48131. else
  48132. tb->setBounds (0, pos, getWidth(), bestLength);
  48133. tb->toBack();
  48134. if (tb->tabIndex == currentTabIndex)
  48135. frontTab = tb;
  48136. tb->setVisible (true);
  48137. }
  48138. else
  48139. {
  48140. tb->setVisible (false);
  48141. }
  48142. pos += bestLength - overlap;
  48143. }
  48144. }
  48145. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  48146. if (frontTab != 0)
  48147. {
  48148. frontTab->toFront (false);
  48149. behindFrontTab->toBehind (frontTab);
  48150. }
  48151. }
  48152. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  48153. {
  48154. return tabColours [tabIndex];
  48155. }
  48156. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48157. {
  48158. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  48159. && tabColours [tabIndex] != newColour)
  48160. {
  48161. tabColours.set (tabIndex, newColour);
  48162. repaint();
  48163. }
  48164. }
  48165. void TabbedButtonBar::buttonClicked (Button* button)
  48166. {
  48167. if (extraTabsButton == button)
  48168. {
  48169. PopupMenu m;
  48170. for (int i = 0; i < tabs.size(); ++i)
  48171. {
  48172. TabBarButton* const tb = getTabButton (i);
  48173. if (tb != 0 && ! tb->isVisible())
  48174. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  48175. }
  48176. const int res = m.showAt (extraTabsButton);
  48177. if (res != 0)
  48178. setCurrentTabIndex (res - 1);
  48179. }
  48180. }
  48181. void TabbedButtonBar::currentTabChanged (const int, const String&)
  48182. {
  48183. }
  48184. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  48185. {
  48186. }
  48187. END_JUCE_NAMESPACE
  48188. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  48189. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  48190. BEGIN_JUCE_NAMESPACE
  48191. class TabCompButtonBar : public TabbedButtonBar
  48192. {
  48193. public:
  48194. TabCompButtonBar (TabbedComponent* const owner_,
  48195. const TabbedButtonBar::Orientation orientation)
  48196. : TabbedButtonBar (orientation),
  48197. owner (owner_)
  48198. {
  48199. }
  48200. ~TabCompButtonBar()
  48201. {
  48202. }
  48203. void currentTabChanged (const int newCurrentTabIndex,
  48204. const String& newTabName)
  48205. {
  48206. owner->changeCallback (newCurrentTabIndex, newTabName);
  48207. }
  48208. void popupMenuClickOnTab (const int tabIndex,
  48209. const String& tabName)
  48210. {
  48211. owner->popupMenuClickOnTab (tabIndex, tabName);
  48212. }
  48213. const Colour getTabBackgroundColour (const int tabIndex)
  48214. {
  48215. return owner->tabs->getTabBackgroundColour (tabIndex);
  48216. }
  48217. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  48218. {
  48219. return owner->createTabButton (tabName, tabIndex);
  48220. }
  48221. juce_UseDebuggingNewOperator
  48222. private:
  48223. TabbedComponent* const owner;
  48224. TabCompButtonBar (const TabCompButtonBar&);
  48225. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  48226. };
  48227. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  48228. : panelComponent (0),
  48229. tabDepth (30),
  48230. outlineThickness (1),
  48231. edgeIndent (0)
  48232. {
  48233. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  48234. }
  48235. TabbedComponent::~TabbedComponent()
  48236. {
  48237. clearTabs();
  48238. delete tabs;
  48239. }
  48240. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  48241. {
  48242. tabs->setOrientation (orientation);
  48243. resized();
  48244. }
  48245. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  48246. {
  48247. return tabs->getOrientation();
  48248. }
  48249. void TabbedComponent::setTabBarDepth (const int newDepth)
  48250. {
  48251. if (tabDepth != newDepth)
  48252. {
  48253. tabDepth = newDepth;
  48254. resized();
  48255. }
  48256. }
  48257. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  48258. {
  48259. return new TabBarButton (tabName, tabs, tabIndex);
  48260. }
  48261. void TabbedComponent::clearTabs()
  48262. {
  48263. if (panelComponent != 0)
  48264. {
  48265. panelComponent->setVisible (false);
  48266. removeChildComponent (panelComponent);
  48267. panelComponent = 0;
  48268. }
  48269. tabs->clearTabs();
  48270. for (int i = contentComponents.size(); --i >= 0;)
  48271. {
  48272. Component* const c = contentComponents.getUnchecked(i);
  48273. // be careful not to delete these components until they've been removed from the tab component
  48274. jassert (c == 0 || c->isValidComponent());
  48275. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48276. delete c;
  48277. }
  48278. contentComponents.clear();
  48279. }
  48280. void TabbedComponent::addTab (const String& tabName,
  48281. const Colour& tabBackgroundColour,
  48282. Component* const contentComponent,
  48283. const bool deleteComponentWhenNotNeeded,
  48284. const int insertIndex)
  48285. {
  48286. contentComponents.insert (insertIndex, contentComponent);
  48287. if (contentComponent != 0)
  48288. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  48289. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  48290. }
  48291. void TabbedComponent::setTabName (const int tabIndex,
  48292. const String& newName)
  48293. {
  48294. tabs->setTabName (tabIndex, newName);
  48295. }
  48296. void TabbedComponent::removeTab (const int tabIndex)
  48297. {
  48298. Component* const c = contentComponents [tabIndex];
  48299. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48300. {
  48301. if (c == panelComponent)
  48302. panelComponent = 0;
  48303. delete c;
  48304. }
  48305. contentComponents.remove (tabIndex);
  48306. tabs->removeTab (tabIndex);
  48307. }
  48308. int TabbedComponent::getNumTabs() const
  48309. {
  48310. return tabs->getNumTabs();
  48311. }
  48312. const StringArray TabbedComponent::getTabNames() const
  48313. {
  48314. return tabs->getTabNames();
  48315. }
  48316. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  48317. {
  48318. return contentComponents [tabIndex];
  48319. }
  48320. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  48321. {
  48322. return tabs->getTabBackgroundColour (tabIndex);
  48323. }
  48324. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48325. {
  48326. tabs->setTabBackgroundColour (tabIndex, newColour);
  48327. if (getCurrentTabIndex() == tabIndex)
  48328. repaint();
  48329. }
  48330. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  48331. {
  48332. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  48333. }
  48334. int TabbedComponent::getCurrentTabIndex() const
  48335. {
  48336. return tabs->getCurrentTabIndex();
  48337. }
  48338. const String& TabbedComponent::getCurrentTabName() const
  48339. {
  48340. return tabs->getCurrentTabName();
  48341. }
  48342. void TabbedComponent::setOutline (int thickness)
  48343. {
  48344. outlineThickness = thickness;
  48345. repaint();
  48346. }
  48347. void TabbedComponent::setIndent (const int indentThickness)
  48348. {
  48349. edgeIndent = indentThickness;
  48350. }
  48351. void TabbedComponent::paint (Graphics& g)
  48352. {
  48353. g.fillAll (findColour (backgroundColourId));
  48354. const TabbedButtonBar::Orientation o = getOrientation();
  48355. int x = 0;
  48356. int y = 0;
  48357. int r = getWidth();
  48358. int b = getHeight();
  48359. if (o == TabbedButtonBar::TabsAtTop)
  48360. y += tabDepth;
  48361. else if (o == TabbedButtonBar::TabsAtBottom)
  48362. b -= tabDepth;
  48363. else if (o == TabbedButtonBar::TabsAtLeft)
  48364. x += tabDepth;
  48365. else if (o == TabbedButtonBar::TabsAtRight)
  48366. r -= tabDepth;
  48367. g.reduceClipRegion (x, y, r - x, b - y);
  48368. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  48369. if (outlineThickness > 0)
  48370. {
  48371. if (o == TabbedButtonBar::TabsAtTop)
  48372. --y;
  48373. else if (o == TabbedButtonBar::TabsAtBottom)
  48374. ++b;
  48375. else if (o == TabbedButtonBar::TabsAtLeft)
  48376. --x;
  48377. else if (o == TabbedButtonBar::TabsAtRight)
  48378. ++r;
  48379. g.setColour (findColour (outlineColourId));
  48380. g.drawRect (x, y, r - x, b - y, outlineThickness);
  48381. }
  48382. }
  48383. void TabbedComponent::resized()
  48384. {
  48385. const TabbedButtonBar::Orientation o = getOrientation();
  48386. const int indent = edgeIndent + outlineThickness;
  48387. BorderSize indents (indent);
  48388. if (o == TabbedButtonBar::TabsAtTop)
  48389. {
  48390. tabs->setBounds (0, 0, getWidth(), tabDepth);
  48391. indents.setTop (tabDepth + edgeIndent);
  48392. }
  48393. else if (o == TabbedButtonBar::TabsAtBottom)
  48394. {
  48395. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  48396. indents.setBottom (tabDepth + edgeIndent);
  48397. }
  48398. else if (o == TabbedButtonBar::TabsAtLeft)
  48399. {
  48400. tabs->setBounds (0, 0, tabDepth, getHeight());
  48401. indents.setLeft (tabDepth + edgeIndent);
  48402. }
  48403. else if (o == TabbedButtonBar::TabsAtRight)
  48404. {
  48405. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  48406. indents.setRight (tabDepth + edgeIndent);
  48407. }
  48408. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  48409. for (int i = contentComponents.size(); --i >= 0;)
  48410. if (contentComponents.getUnchecked (i) != 0)
  48411. contentComponents.getUnchecked (i)->setBounds (bounds);
  48412. }
  48413. void TabbedComponent::lookAndFeelChanged()
  48414. {
  48415. for (int i = contentComponents.size(); --i >= 0;)
  48416. if (contentComponents.getUnchecked (i) != 0)
  48417. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  48418. }
  48419. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  48420. const String& newTabName)
  48421. {
  48422. if (panelComponent != 0)
  48423. {
  48424. panelComponent->setVisible (false);
  48425. removeChildComponent (panelComponent);
  48426. panelComponent = 0;
  48427. }
  48428. if (getCurrentTabIndex() >= 0)
  48429. {
  48430. panelComponent = contentComponents [getCurrentTabIndex()];
  48431. if (panelComponent != 0)
  48432. {
  48433. // do these ops as two stages instead of addAndMakeVisible() so that the
  48434. // component has always got a parent when it gets the visibilityChanged() callback
  48435. addChildComponent (panelComponent);
  48436. panelComponent->setVisible (true);
  48437. panelComponent->toFront (true);
  48438. }
  48439. repaint();
  48440. }
  48441. resized();
  48442. currentTabChanged (newCurrentTabIndex, newTabName);
  48443. }
  48444. void TabbedComponent::currentTabChanged (const int, const String&)
  48445. {
  48446. }
  48447. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  48448. {
  48449. }
  48450. END_JUCE_NAMESPACE
  48451. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  48452. /********* Start of inlined file: juce_Viewport.cpp *********/
  48453. BEGIN_JUCE_NAMESPACE
  48454. Viewport::Viewport (const String& componentName)
  48455. : Component (componentName),
  48456. contentComp (0),
  48457. lastVX (0),
  48458. lastVY (0),
  48459. lastVW (0),
  48460. lastVH (0),
  48461. scrollBarThickness (0),
  48462. singleStepX (16),
  48463. singleStepY (16),
  48464. showHScrollbar (true),
  48465. showVScrollbar (true)
  48466. {
  48467. // content holder is used to clip the contents so they don't overlap the scrollbars
  48468. addAndMakeVisible (contentHolder = new Component());
  48469. contentHolder->setInterceptsMouseClicks (false, true);
  48470. verticalScrollBar = new ScrollBar (true);
  48471. horizontalScrollBar = new ScrollBar (false);
  48472. addChildComponent (verticalScrollBar);
  48473. addChildComponent (horizontalScrollBar);
  48474. verticalScrollBar->addListener (this);
  48475. horizontalScrollBar->addListener (this);
  48476. setInterceptsMouseClicks (false, true);
  48477. setWantsKeyboardFocus (true);
  48478. }
  48479. Viewport::~Viewport()
  48480. {
  48481. contentHolder->deleteAllChildren();
  48482. deleteAllChildren();
  48483. }
  48484. void Viewport::visibleAreaChanged (int, int, int, int)
  48485. {
  48486. }
  48487. void Viewport::setViewedComponent (Component* const newViewedComponent)
  48488. {
  48489. if (contentComp != newViewedComponent)
  48490. {
  48491. if (contentComp->isValidComponent())
  48492. {
  48493. Component* const oldComp = contentComp;
  48494. contentComp = 0;
  48495. delete oldComp;
  48496. }
  48497. contentComp = newViewedComponent;
  48498. if (contentComp != 0)
  48499. {
  48500. contentComp->setTopLeftPosition (0, 0);
  48501. contentHolder->addAndMakeVisible (contentComp);
  48502. contentComp->addComponentListener (this);
  48503. }
  48504. updateVisibleRegion();
  48505. }
  48506. }
  48507. int Viewport::getMaximumVisibleWidth() const throw()
  48508. {
  48509. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48510. }
  48511. int Viewport::getMaximumVisibleHeight() const throw()
  48512. {
  48513. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48514. }
  48515. void Viewport::setViewPosition (const int xPixelsOffset,
  48516. const int yPixelsOffset)
  48517. {
  48518. if (contentComp != 0)
  48519. contentComp->setTopLeftPosition (-xPixelsOffset,
  48520. -yPixelsOffset);
  48521. }
  48522. void Viewport::setViewPositionProportionately (const double x,
  48523. const double y)
  48524. {
  48525. if (contentComp != 0)
  48526. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  48527. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  48528. }
  48529. void Viewport::componentMovedOrResized (Component&, bool, bool)
  48530. {
  48531. updateVisibleRegion();
  48532. }
  48533. void Viewport::resized()
  48534. {
  48535. updateVisibleRegion();
  48536. }
  48537. void Viewport::updateVisibleRegion()
  48538. {
  48539. if (contentComp != 0)
  48540. {
  48541. const int newVX = -contentComp->getX();
  48542. const int newVY = -contentComp->getY();
  48543. if (newVX == 0 && newVY == 0
  48544. && contentComp->getWidth() <= getWidth()
  48545. && contentComp->getHeight() <= getHeight())
  48546. {
  48547. horizontalScrollBar->setVisible (false);
  48548. verticalScrollBar->setVisible (false);
  48549. }
  48550. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  48551. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48552. horizontalScrollBar->setSingleStepSize (singleStepX);
  48553. if (! (contentComp->getWidth() > 0 && showHScrollbar && getHeight() > getScrollBarThickness()))
  48554. horizontalScrollBar->setVisible (false);
  48555. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  48556. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48557. verticalScrollBar->setSingleStepSize (singleStepY);
  48558. if (! (contentComp->getHeight() > 0 && showVScrollbar && getWidth() > getScrollBarThickness()))
  48559. verticalScrollBar->setVisible (false);
  48560. if (verticalScrollBar->isVisible())
  48561. {
  48562. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48563. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48564. verticalScrollBar
  48565. ->setBounds (getMaximumVisibleWidth(), 0,
  48566. getScrollBarThickness(), getMaximumVisibleHeight());
  48567. }
  48568. if (horizontalScrollBar->isVisible())
  48569. {
  48570. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48571. horizontalScrollBar
  48572. ->setBounds (0, getMaximumVisibleHeight(),
  48573. getMaximumVisibleWidth(), getScrollBarThickness());
  48574. }
  48575. contentHolder->setSize (getMaximumVisibleWidth(),
  48576. getMaximumVisibleHeight());
  48577. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  48578. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  48579. if (newVX != lastVX
  48580. || newVY != lastVY
  48581. || newVW != lastVW
  48582. || newVH != lastVH)
  48583. {
  48584. lastVX = newVX;
  48585. lastVY = newVY;
  48586. lastVW = newVW;
  48587. lastVH = newVH;
  48588. visibleAreaChanged (newVX, newVY, newVW, newVH);
  48589. }
  48590. horizontalScrollBar->handleUpdateNowIfNeeded();
  48591. verticalScrollBar->handleUpdateNowIfNeeded();
  48592. }
  48593. else
  48594. {
  48595. horizontalScrollBar->setVisible (false);
  48596. verticalScrollBar->setVisible (false);
  48597. }
  48598. }
  48599. void Viewport::setSingleStepSizes (const int stepX,
  48600. const int stepY)
  48601. {
  48602. singleStepX = stepX;
  48603. singleStepY = stepY;
  48604. updateVisibleRegion();
  48605. }
  48606. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  48607. const bool showHorizontalScrollbarIfNeeded)
  48608. {
  48609. showVScrollbar = showVerticalScrollbarIfNeeded;
  48610. showHScrollbar = showHorizontalScrollbarIfNeeded;
  48611. updateVisibleRegion();
  48612. }
  48613. void Viewport::setScrollBarThickness (const int thickness)
  48614. {
  48615. scrollBarThickness = thickness;
  48616. updateVisibleRegion();
  48617. }
  48618. int Viewport::getScrollBarThickness() const throw()
  48619. {
  48620. return (scrollBarThickness > 0) ? scrollBarThickness
  48621. : getLookAndFeel().getDefaultScrollbarWidth();
  48622. }
  48623. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  48624. {
  48625. verticalScrollBar->setButtonVisibility (buttonsVisible);
  48626. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  48627. }
  48628. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  48629. {
  48630. if (scrollBarThatHasMoved == horizontalScrollBar)
  48631. {
  48632. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  48633. }
  48634. else if (scrollBarThatHasMoved == verticalScrollBar)
  48635. {
  48636. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  48637. }
  48638. }
  48639. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48640. {
  48641. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  48642. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  48643. }
  48644. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48645. {
  48646. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  48647. {
  48648. const bool hasVertBar = verticalScrollBar->isVisible();
  48649. const bool hasHorzBar = horizontalScrollBar->isVisible();
  48650. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  48651. {
  48652. if (wheelIncrementX == 0 && ! hasVertBar)
  48653. wheelIncrementX = wheelIncrementY;
  48654. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  48655. wheelIncrementX, wheelIncrementY);
  48656. return true;
  48657. }
  48658. else if (hasVertBar && wheelIncrementY != 0)
  48659. {
  48660. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  48661. wheelIncrementX, wheelIncrementY);
  48662. return true;
  48663. }
  48664. }
  48665. return false;
  48666. }
  48667. bool Viewport::keyPressed (const KeyPress& key)
  48668. {
  48669. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  48670. || key.isKeyCode (KeyPress::downKey)
  48671. || key.isKeyCode (KeyPress::pageUpKey)
  48672. || key.isKeyCode (KeyPress::pageDownKey)
  48673. || key.isKeyCode (KeyPress::homeKey)
  48674. || key.isKeyCode (KeyPress::endKey);
  48675. if (verticalScrollBar->isVisible() && isUpDownKey)
  48676. return verticalScrollBar->keyPressed (key);
  48677. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  48678. || key.isKeyCode (KeyPress::rightKey);
  48679. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  48680. return horizontalScrollBar->keyPressed (key);
  48681. return false;
  48682. }
  48683. END_JUCE_NAMESPACE
  48684. /********* End of inlined file: juce_Viewport.cpp *********/
  48685. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  48686. BEGIN_JUCE_NAMESPACE
  48687. static const Colour createBaseColour (const Colour& buttonColour,
  48688. const bool hasKeyboardFocus,
  48689. const bool isMouseOverButton,
  48690. const bool isButtonDown) throw()
  48691. {
  48692. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  48693. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  48694. if (isButtonDown)
  48695. return baseColour.contrasting (0.2f);
  48696. else if (isMouseOverButton)
  48697. return baseColour.contrasting (0.1f);
  48698. return baseColour;
  48699. }
  48700. static String defaultSansName, defaultSerifName, defaultFixedName;
  48701. void clearUpDefaultFontNames() throw()
  48702. {
  48703. defaultSansName = String::empty;
  48704. defaultSerifName = String::empty;
  48705. defaultFixedName = String::empty;
  48706. }
  48707. LookAndFeel::LookAndFeel()
  48708. {
  48709. /* if this fails it means you're trying to create a LookAndFeel object before
  48710. the static Colours have been initialised. That ain't gonna work. It probably
  48711. means that you're using a static LookAndFeel object and that your compiler has
  48712. decided to intialise it before the Colours class.
  48713. */
  48714. jassert (Colours::white == Colour (0xffffffff));
  48715. // set up the standard set of colours..
  48716. #define textButtonColour 0xffbbbbff
  48717. #define textHighlightColour 0x401111ee
  48718. #define standardOutlineColour 0xb2808080
  48719. static const int standardColours[] =
  48720. {
  48721. TextButton::buttonColourId, textButtonColour,
  48722. TextButton::buttonOnColourId, 0xff4444ff,
  48723. TextButton::textColourId, 0xff000000,
  48724. ComboBox::buttonColourId, 0xffbbbbff,
  48725. ComboBox::outlineColourId, standardOutlineColour,
  48726. ToggleButton::textColourId, 0xff000000,
  48727. TextEditor::backgroundColourId, 0xffffffff,
  48728. TextEditor::textColourId, 0xff000000,
  48729. TextEditor::highlightColourId, textHighlightColour,
  48730. TextEditor::highlightedTextColourId, 0xff000000,
  48731. TextEditor::caretColourId, 0xff000000,
  48732. TextEditor::outlineColourId, 0x00000000,
  48733. TextEditor::focusedOutlineColourId, textButtonColour,
  48734. TextEditor::shadowColourId, 0x38000000,
  48735. Label::backgroundColourId, 0x00000000,
  48736. Label::textColourId, 0xff000000,
  48737. Label::outlineColourId, 0x00000000,
  48738. ScrollBar::backgroundColourId, 0x00000000,
  48739. ScrollBar::thumbColourId, 0xffffffff,
  48740. ScrollBar::trackColourId, 0xffffffff,
  48741. TreeView::linesColourId, 0x4c000000,
  48742. TreeView::backgroundColourId, 0x00000000,
  48743. PopupMenu::backgroundColourId, 0xffffffff,
  48744. PopupMenu::textColourId, 0xff000000,
  48745. PopupMenu::headerTextColourId, 0xff000000,
  48746. PopupMenu::highlightedTextColourId, 0xffffffff,
  48747. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  48748. ComboBox::textColourId, 0xff000000,
  48749. ComboBox::backgroundColourId, 0xffffffff,
  48750. ComboBox::arrowColourId, 0x99000000,
  48751. ListBox::backgroundColourId, 0xffffffff,
  48752. ListBox::outlineColourId, standardOutlineColour,
  48753. ListBox::textColourId, 0xff000000,
  48754. Slider::backgroundColourId, 0x00000000,
  48755. Slider::thumbColourId, textButtonColour,
  48756. Slider::trackColourId, 0x7fffffff,
  48757. Slider::rotarySliderFillColourId, 0x7f0000ff,
  48758. Slider::rotarySliderOutlineColourId, 0x66000000,
  48759. Slider::textBoxTextColourId, 0xff000000,
  48760. Slider::textBoxBackgroundColourId, 0xffffffff,
  48761. Slider::textBoxHighlightColourId, textHighlightColour,
  48762. Slider::textBoxOutlineColourId, standardOutlineColour,
  48763. ResizableWindow::backgroundColourId, 0xff777777,
  48764. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  48765. AlertWindow::backgroundColourId, 0xffededed,
  48766. AlertWindow::textColourId, 0xff000000,
  48767. AlertWindow::outlineColourId, 0xff666666,
  48768. ProgressBar::backgroundColourId, 0xffeeeeee,
  48769. ProgressBar::foregroundColourId, 0xffaaaaee,
  48770. TooltipWindow::backgroundColourId, 0xffeeeebb,
  48771. TooltipWindow::textColourId, 0xff000000,
  48772. TooltipWindow::outlineColourId, 0x4c000000,
  48773. TabbedComponent::backgroundColourId, 0x00000000,
  48774. TabbedComponent::outlineColourId, 0xff777777,
  48775. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  48776. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  48777. Toolbar::backgroundColourId, 0xfff6f8f9,
  48778. Toolbar::separatorColourId, 0x4c000000,
  48779. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  48780. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  48781. Toolbar::labelTextColourId, 0xff000000,
  48782. Toolbar::editingModeOutlineColourId, 0xffff0000,
  48783. HyperlinkButton::textColourId, 0xcc1111ee,
  48784. GroupComponent::outlineColourId, 0x66000000,
  48785. GroupComponent::textColourId, 0xff000000,
  48786. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  48787. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  48788. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  48789. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  48790. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  48791. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  48792. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  48793. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  48794. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  48795. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  48796. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  48797. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  48798. ColourSelector::backgroundColourId, 0xffe5e5e5,
  48799. ColourSelector::labelTextColourId, 0xff000000,
  48800. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  48801. };
  48802. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  48803. setColour (standardColours [i], Colour (standardColours [i + 1]));
  48804. if (defaultSansName.isEmpty())
  48805. Typeface::getDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  48806. defaultSans = defaultSansName;
  48807. defaultSerif = defaultSerifName;
  48808. defaultFixed = defaultFixedName;
  48809. }
  48810. LookAndFeel::~LookAndFeel()
  48811. {
  48812. }
  48813. const Colour LookAndFeel::findColour (const int colourId) const throw()
  48814. {
  48815. const int index = colourIds.indexOf (colourId);
  48816. if (index >= 0)
  48817. return colours [index];
  48818. jassertfalse
  48819. return Colours::black;
  48820. }
  48821. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  48822. {
  48823. const int index = colourIds.indexOf (colourId);
  48824. if (index >= 0)
  48825. colours.set (index, colour);
  48826. colourIds.add (colourId);
  48827. colours.add (colour);
  48828. }
  48829. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  48830. {
  48831. return colourIds.contains (colourId);
  48832. }
  48833. static LookAndFeel* defaultLF = 0;
  48834. static LookAndFeel* currentDefaultLF = 0;
  48835. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  48836. {
  48837. // if this happens, your app hasn't initialised itself properly.. if you're
  48838. // trying to hack your own main() function, have a look at
  48839. // JUCEApplication::initialiseForGUI()
  48840. jassert (currentDefaultLF != 0);
  48841. return *currentDefaultLF;
  48842. }
  48843. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  48844. {
  48845. if (newDefaultLookAndFeel == 0)
  48846. {
  48847. if (defaultLF == 0)
  48848. defaultLF = new LookAndFeel();
  48849. newDefaultLookAndFeel = defaultLF;
  48850. }
  48851. currentDefaultLF = newDefaultLookAndFeel;
  48852. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  48853. {
  48854. Component* const c = Desktop::getInstance().getComponent (i);
  48855. if (c != 0)
  48856. c->sendLookAndFeelChange();
  48857. }
  48858. }
  48859. void LookAndFeel::clearDefaultLookAndFeel() throw()
  48860. {
  48861. if (currentDefaultLF == defaultLF)
  48862. currentDefaultLF = 0;
  48863. deleteAndZero (defaultLF);
  48864. }
  48865. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  48866. {
  48867. String faceName (font.getTypefaceName());
  48868. if (faceName == Typeface::defaultTypefaceNameSans)
  48869. faceName = defaultSans;
  48870. else if (faceName == Typeface::defaultTypefaceNameSerif)
  48871. faceName = defaultSerif;
  48872. else if (faceName == Typeface::defaultTypefaceNameMono)
  48873. faceName = defaultFixed;
  48874. return new Typeface (faceName, font.isBold(), font.isItalic());
  48875. }
  48876. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  48877. {
  48878. defaultSans = newName;
  48879. }
  48880. void LookAndFeel::drawButtonBackground (Graphics& g,
  48881. Button& button,
  48882. const Colour& backgroundColour,
  48883. bool isMouseOverButton,
  48884. bool isButtonDown)
  48885. {
  48886. const int width = button.getWidth();
  48887. const int height = button.getHeight();
  48888. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  48889. const float halfThickness = outlineThickness * 0.5f;
  48890. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  48891. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  48892. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  48893. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  48894. const Colour baseColour (createBaseColour (backgroundColour,
  48895. button.hasKeyboardFocus (true),
  48896. isMouseOverButton, isButtonDown)
  48897. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48898. drawGlassLozenge (g,
  48899. indentL,
  48900. indentT,
  48901. width - indentL - indentR,
  48902. height - indentT - indentB,
  48903. baseColour, outlineThickness, -1.0f,
  48904. button.isConnectedOnLeft(),
  48905. button.isConnectedOnRight(),
  48906. button.isConnectedOnTop(),
  48907. button.isConnectedOnBottom());
  48908. }
  48909. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  48910. {
  48911. return button.getFont();
  48912. }
  48913. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  48914. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  48915. {
  48916. g.setFont (getFontForTextButton (button));
  48917. g.setColour (button.findColour (TextButton::textColourId)
  48918. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48919. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  48920. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  48921. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  48922. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  48923. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  48924. g.drawFittedText (button.getButtonText(),
  48925. leftIndent,
  48926. yIndent,
  48927. button.getWidth() - leftIndent - rightIndent,
  48928. button.getHeight() - yIndent * 2,
  48929. Justification::centred, 2);
  48930. }
  48931. void LookAndFeel::drawTickBox (Graphics& g,
  48932. Component& component,
  48933. int x, int y, int w, int h,
  48934. const bool ticked,
  48935. const bool isEnabled,
  48936. const bool isMouseOverButton,
  48937. const bool isButtonDown)
  48938. {
  48939. const float boxSize = w * 0.7f;
  48940. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  48941. createBaseColour (component.findColour (TextButton::buttonColourId)
  48942. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  48943. true,
  48944. isMouseOverButton,
  48945. isButtonDown),
  48946. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  48947. if (ticked)
  48948. {
  48949. Path tick;
  48950. tick.startNewSubPath (1.5f, 3.0f);
  48951. tick.lineTo (3.0f, 6.0f);
  48952. tick.lineTo (6.0f, 0.0f);
  48953. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48954. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48955. .translated ((float) x, (float) y));
  48956. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48957. }
  48958. }
  48959. void LookAndFeel::drawToggleButton (Graphics& g,
  48960. ToggleButton& button,
  48961. bool isMouseOverButton,
  48962. bool isButtonDown)
  48963. {
  48964. if (button.hasKeyboardFocus (true))
  48965. {
  48966. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48967. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48968. }
  48969. const int tickWidth = jmin (20, button.getHeight() - 4);
  48970. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48971. tickWidth, tickWidth,
  48972. button.getToggleState(),
  48973. button.isEnabled(),
  48974. isMouseOverButton,
  48975. isButtonDown);
  48976. g.setColour (button.findColour (ToggleButton::textColourId));
  48977. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48978. if (! button.isEnabled())
  48979. g.setOpacity (0.5f);
  48980. const int textX = tickWidth + 5;
  48981. g.drawFittedText (button.getButtonText(),
  48982. textX, 4,
  48983. button.getWidth() - textX - 2, button.getHeight() - 8,
  48984. Justification::centredLeft, 10);
  48985. }
  48986. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  48987. {
  48988. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  48989. const int tickWidth = jmin (24, button.getHeight());
  48990. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  48991. button.getHeight());
  48992. }
  48993. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  48994. const String& message,
  48995. const String& button1,
  48996. const String& button2,
  48997. const String& button3,
  48998. AlertWindow::AlertIconType iconType,
  48999. int numButtons,
  49000. Component* associatedComponent)
  49001. {
  49002. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  49003. if (numButtons == 1)
  49004. {
  49005. aw->addButton (button1, 0,
  49006. KeyPress (KeyPress::escapeKey, 0, 0),
  49007. KeyPress (KeyPress::returnKey, 0, 0));
  49008. }
  49009. else
  49010. {
  49011. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  49012. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  49013. if (button1ShortCut == button2ShortCut)
  49014. button2ShortCut = KeyPress();
  49015. if (numButtons == 2)
  49016. {
  49017. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  49018. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  49019. }
  49020. else if (numButtons == 3)
  49021. {
  49022. aw->addButton (button1, 1, button1ShortCut);
  49023. aw->addButton (button2, 2, button2ShortCut);
  49024. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  49025. }
  49026. }
  49027. return aw;
  49028. }
  49029. void LookAndFeel::drawAlertBox (Graphics& g,
  49030. AlertWindow& alert,
  49031. const Rectangle& textArea,
  49032. TextLayout& textLayout)
  49033. {
  49034. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  49035. int iconSpaceUsed = 0;
  49036. Justification alignment (Justification::horizontallyCentred);
  49037. const int iconWidth = 80;
  49038. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  49039. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  49040. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  49041. const Rectangle iconRect (iconSize / -10, iconSize / -10,
  49042. iconSize, iconSize);
  49043. if (alert.getAlertType() != AlertWindow::NoIcon)
  49044. {
  49045. Path icon;
  49046. uint32 colour;
  49047. char character;
  49048. if (alert.getAlertType() == AlertWindow::WarningIcon)
  49049. {
  49050. colour = 0x55ff5555;
  49051. character = '!';
  49052. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  49053. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  49054. (float) iconRect.getX(), (float) iconRect.getBottom());
  49055. icon = icon.createPathWithRoundedCorners (5.0f);
  49056. }
  49057. else
  49058. {
  49059. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  49060. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  49061. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  49062. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  49063. }
  49064. GlyphArrangement ga;
  49065. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  49066. String::charToString (character),
  49067. (float) iconRect.getX(), (float) iconRect.getY(),
  49068. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  49069. Justification::centred, false);
  49070. ga.createPath (icon);
  49071. icon.setUsingNonZeroWinding (false);
  49072. g.setColour (Colour (colour));
  49073. g.fillPath (icon);
  49074. iconSpaceUsed = iconWidth;
  49075. alignment = Justification::left;
  49076. }
  49077. g.setColour (alert.findColour (AlertWindow::textColourId));
  49078. textLayout.drawWithin (g,
  49079. textArea.getX() + iconSpaceUsed, textArea.getY(),
  49080. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  49081. alignment.getFlags() | Justification::top);
  49082. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  49083. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  49084. }
  49085. int LookAndFeel::getAlertBoxWindowFlags()
  49086. {
  49087. return ComponentPeer::windowAppearsOnTaskbar
  49088. | ComponentPeer::windowHasDropShadow;
  49089. }
  49090. int LookAndFeel::getAlertWindowButtonHeight()
  49091. {
  49092. return 28;
  49093. }
  49094. const Font LookAndFeel::getAlertWindowFont()
  49095. {
  49096. return Font (12.0f);
  49097. }
  49098. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  49099. int width, int height,
  49100. double progress, const String& textToShow)
  49101. {
  49102. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  49103. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  49104. g.fillAll (background);
  49105. if (progress >= 0.0f && progress < 1.0f)
  49106. {
  49107. drawGlassLozenge (g, 1.0f, 1.0f,
  49108. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  49109. (float) (height - 2),
  49110. foreground,
  49111. 0.5f, 0.0f,
  49112. true, true, true, true);
  49113. }
  49114. else
  49115. {
  49116. // spinning bar..
  49117. g.setColour (foreground);
  49118. const int stripeWidth = height * 2;
  49119. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  49120. Path p;
  49121. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  49122. p.addQuadrilateral (x, 0.0f,
  49123. x + stripeWidth * 0.5f, 0.0f,
  49124. x, (float) height,
  49125. x - stripeWidth * 0.5f, (float) height);
  49126. Image im (Image::ARGB, width, height, true);
  49127. {
  49128. Graphics g (im);
  49129. drawGlassLozenge (g, 1.0f, 1.0f,
  49130. (float) (width - 2),
  49131. (float) (height - 2),
  49132. foreground,
  49133. 0.5f, 0.0f,
  49134. true, true, true, true);
  49135. }
  49136. ImageBrush ib (&im, 0, 0, 0.85f);
  49137. g.setBrush (&ib);
  49138. g.fillPath (p);
  49139. }
  49140. if (textToShow.isNotEmpty())
  49141. {
  49142. g.setColour (Colour::contrasting (background, foreground));
  49143. g.setFont (height * 0.6f);
  49144. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  49145. }
  49146. }
  49147. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h)
  49148. {
  49149. const float radius = jmin (w, h) * 0.4f;
  49150. const float thickness = radius * 0.15f;
  49151. Path p;
  49152. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  49153. radius * 0.6f, thickness,
  49154. thickness * 0.5f);
  49155. const float cx = x + w * 0.5f;
  49156. const float cy = y + h * 0.5f;
  49157. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  49158. const Colour col (g.getCurrentColour());
  49159. for (int i = 0; i < 12; ++i)
  49160. {
  49161. const int n = (i + 12 - animationIndex) % 12;
  49162. g.setColour (col.withMultipliedAlpha ((n + 1) / 12.0f));
  49163. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  49164. .translated (cx, cy));
  49165. }
  49166. }
  49167. void LookAndFeel::drawScrollbarButton (Graphics& g,
  49168. ScrollBar& scrollbar,
  49169. int width, int height,
  49170. int buttonDirection,
  49171. bool /*isScrollbarVertical*/,
  49172. bool /*isMouseOverButton*/,
  49173. bool isButtonDown)
  49174. {
  49175. Path p;
  49176. if (buttonDirection == 0)
  49177. p.addTriangle (width * 0.5f, height * 0.2f,
  49178. width * 0.1f, height * 0.7f,
  49179. width * 0.9f, height * 0.7f);
  49180. else if (buttonDirection == 1)
  49181. p.addTriangle (width * 0.8f, height * 0.5f,
  49182. width * 0.3f, height * 0.1f,
  49183. width * 0.3f, height * 0.9f);
  49184. else if (buttonDirection == 2)
  49185. p.addTriangle (width * 0.5f, height * 0.8f,
  49186. width * 0.1f, height * 0.3f,
  49187. width * 0.9f, height * 0.3f);
  49188. else if (buttonDirection == 3)
  49189. p.addTriangle (width * 0.2f, height * 0.5f,
  49190. width * 0.7f, height * 0.1f,
  49191. width * 0.7f, height * 0.9f);
  49192. if (isButtonDown)
  49193. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  49194. else
  49195. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  49196. g.fillPath (p);
  49197. g.setColour (Colour (0x80000000));
  49198. g.strokePath (p, PathStrokeType (0.5f));
  49199. }
  49200. void LookAndFeel::drawScrollbar (Graphics& g,
  49201. ScrollBar& scrollbar,
  49202. int x, int y,
  49203. int width, int height,
  49204. bool isScrollbarVertical,
  49205. int thumbStartPosition,
  49206. int thumbSize,
  49207. bool /*isMouseOver*/,
  49208. bool /*isMouseDown*/)
  49209. {
  49210. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  49211. Path slotPath, thumbPath;
  49212. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  49213. const float slotIndentx2 = slotIndent * 2.0f;
  49214. const float thumbIndent = slotIndent + 1.0f;
  49215. const float thumbIndentx2 = thumbIndent * 2.0f;
  49216. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  49217. if (isScrollbarVertical)
  49218. {
  49219. slotPath.addRoundedRectangle (x + slotIndent,
  49220. y + slotIndent,
  49221. width - slotIndentx2,
  49222. height - slotIndentx2,
  49223. (width - slotIndentx2) * 0.5f);
  49224. if (thumbSize > 0)
  49225. thumbPath.addRoundedRectangle (x + thumbIndent,
  49226. thumbStartPosition + thumbIndent,
  49227. width - thumbIndentx2,
  49228. thumbSize - thumbIndentx2,
  49229. (width - thumbIndentx2) * 0.5f);
  49230. gx1 = (float) x;
  49231. gx2 = x + width * 0.7f;
  49232. }
  49233. else
  49234. {
  49235. slotPath.addRoundedRectangle (x + slotIndent,
  49236. y + slotIndent,
  49237. width - slotIndentx2,
  49238. height - slotIndentx2,
  49239. (height - slotIndentx2) * 0.5f);
  49240. if (thumbSize > 0)
  49241. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  49242. y + thumbIndent,
  49243. thumbSize - thumbIndentx2,
  49244. height - thumbIndentx2,
  49245. (height - thumbIndentx2) * 0.5f);
  49246. gy1 = (float) y;
  49247. gy2 = y + height * 0.7f;
  49248. }
  49249. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  49250. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  49251. gx1, gy1,
  49252. thumbColour.overlaidWith (Colour (0x19000000)),
  49253. gx2, gy2, false);
  49254. g.setBrush (&gb);
  49255. g.fillPath (slotPath);
  49256. if (isScrollbarVertical)
  49257. {
  49258. gx1 = x + width * 0.6f;
  49259. gx2 = (float) x + width;
  49260. }
  49261. else
  49262. {
  49263. gy1 = y + height * 0.6f;
  49264. gy2 = (float) y + height;
  49265. }
  49266. GradientBrush gb2 (Colours::transparentBlack,
  49267. gx1, gy1,
  49268. Colour (0x19000000),
  49269. gx2, gy2, false);
  49270. g.setBrush (&gb2);
  49271. g.fillPath (slotPath);
  49272. g.setColour (thumbColour);
  49273. g.fillPath (thumbPath);
  49274. GradientBrush gb3 (Colour (0x10000000),
  49275. gx1, gy1,
  49276. Colours::transparentBlack,
  49277. gx2, gy2, false);
  49278. g.saveState();
  49279. g.setBrush (&gb3);
  49280. if (isScrollbarVertical)
  49281. g.reduceClipRegion (x + width / 2, y, width, height);
  49282. else
  49283. g.reduceClipRegion (x, y + height / 2, width, height);
  49284. g.fillPath (thumbPath);
  49285. g.restoreState();
  49286. g.setColour (Colour (0x4c000000));
  49287. g.strokePath (thumbPath, PathStrokeType (0.4f));
  49288. }
  49289. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  49290. {
  49291. return 0;
  49292. }
  49293. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  49294. {
  49295. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  49296. }
  49297. int LookAndFeel::getDefaultScrollbarWidth()
  49298. {
  49299. return 18;
  49300. }
  49301. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  49302. {
  49303. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  49304. : scrollbar.getHeight());
  49305. }
  49306. const Path LookAndFeel::getTickShape (const float height)
  49307. {
  49308. static const unsigned char tickShapeData[] =
  49309. {
  49310. 109,0,224,168,68,0,0,119,67,108,0,224,172,68,0,128,146,67,113,0,192,148,68,0,0,219,67,0,96,110,68,0,224,56,68,113,0,64,51,68,0,32,130,68,0,64,20,68,0,224,
  49311. 162,68,108,0,128,3,68,0,128,168,68,113,0,128,221,67,0,192,175,68,0,0,207,67,0,32,179,68,113,0,0,201,67,0,224,173,68,0,0,181,67,0,224,161,68,108,0,128,168,67,
  49312. 0,128,154,68,113,0,128,141,67,0,192,138,68,0,128,108,67,0,64,131,68,113,0,0,62,67,0,128,119,68,0,0,5,67,0,128,114,68,113,0,0,102,67,0,192,88,68,0,128,155,
  49313. 67,0,192,88,68,113,0,0,190,67,0,192,88,68,0,128,232,67,0,224,131,68,108,0,128,246,67,0,192,139,68,113,0,64,33,68,0,128,87,68,0,0,93,68,0,224,26,68,113,0,
  49314. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  49315. };
  49316. Path p;
  49317. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  49318. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49319. return p;
  49320. }
  49321. const Path LookAndFeel::getCrossShape (const float height)
  49322. {
  49323. static const unsigned char crossShapeData[] =
  49324. {
  49325. 109,0,0,17,68,0,96,145,68,108,0,192,13,68,0,192,147,68,113,0,0,213,67,0,64,174,68,0,0,168,67,0,64,174,68,113,0,0,104,67,0,64,174,68,0,0,5,67,0,64,
  49326. 153,68,113,0,0,18,67,0,64,153,68,0,0,24,67,0,64,153,68,113,0,0,135,67,0,64,153,68,0,128,207,67,0,224,130,68,108,0,0,220,67,0,0,126,68,108,0,0,204,67,
  49327. 0,128,117,68,113,0,0,138,67,0,64,82,68,0,0,138,67,0,192,57,68,113,0,0,138,67,0,192,37,68,0,128,210,67,0,64,10,68,113,0,128,220,67,0,64,45,68,0,0,8,
  49328. 68,0,128,78,68,108,0,192,14,68,0,0,87,68,108,0,64,20,68,0,0,80,68,113,0,192,57,68,0,0,32,68,0,128,88,68,0,0,32,68,113,0,64,112,68,0,0,32,68,0,
  49329. 128,124,68,0,64,68,68,113,0,0,121,68,0,192,67,68,0,128,119,68,0,192,67,68,113,0,192,108,68,0,192,67,68,0,32,89,68,0,96,82,68,113,0,128,69,68,0,0,97,68,
  49330. 0,0,56,68,0,64,115,68,108,0,64,49,68,0,128,124,68,108,0,192,55,68,0,96,129,68,113,0,0,92,68,0,224,146,68,0,192,129,68,0,224,146,68,113,0,64,110,68,0,64,
  49331. 168,68,0,64,87,68,0,64,168,68,113,0,128,66,68,0,64,168,68,0,64,27,68,0,32,150,68,99,101
  49332. };
  49333. Path p;
  49334. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  49335. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49336. return p;
  49337. }
  49338. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  49339. {
  49340. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  49341. x += (w - boxSize) >> 1;
  49342. y += (h - boxSize) >> 1;
  49343. w = boxSize;
  49344. h = boxSize;
  49345. g.setColour (Colour (0xe5ffffff));
  49346. g.fillRect (x, y, w, h);
  49347. g.setColour (Colour (0x80000000));
  49348. g.drawRect (x, y, w, h);
  49349. const float size = boxSize / 2 + 1.0f;
  49350. const float centre = (float) (boxSize / 2);
  49351. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  49352. if (isPlus)
  49353. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  49354. }
  49355. void LookAndFeel::drawBubble (Graphics& g,
  49356. float tipX, float tipY,
  49357. float boxX, float boxY,
  49358. float boxW, float boxH)
  49359. {
  49360. int side = 0;
  49361. if (tipX < boxX)
  49362. side = 1;
  49363. else if (tipX > boxX + boxW)
  49364. side = 3;
  49365. else if (tipY > boxY + boxH)
  49366. side = 2;
  49367. const float indent = 2.0f;
  49368. Path p;
  49369. p.addBubble (boxX + indent,
  49370. boxY + indent,
  49371. boxW - indent * 2.0f,
  49372. boxH - indent * 2.0f,
  49373. 5.0f,
  49374. tipX, tipY,
  49375. side,
  49376. 0.5f,
  49377. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  49378. //xxx need to take comp as param for colour
  49379. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  49380. g.fillPath (p);
  49381. //xxx as above
  49382. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  49383. g.strokePath (p, PathStrokeType (1.33f));
  49384. }
  49385. const Font LookAndFeel::getPopupMenuFont()
  49386. {
  49387. return Font (17.0f);
  49388. }
  49389. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  49390. const bool isSeparator,
  49391. int standardMenuItemHeight,
  49392. int& idealWidth,
  49393. int& idealHeight)
  49394. {
  49395. if (isSeparator)
  49396. {
  49397. idealWidth = 50;
  49398. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  49399. }
  49400. else
  49401. {
  49402. Font font (getPopupMenuFont());
  49403. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  49404. font.setHeight (standardMenuItemHeight / 1.3f);
  49405. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  49406. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  49407. }
  49408. }
  49409. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49410. {
  49411. const Colour background (findColour (PopupMenu::backgroundColourId));
  49412. g.fillAll (background);
  49413. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  49414. for (int i = 0; i < height; i += 3)
  49415. g.fillRect (0, i, width, 1);
  49416. #if ! JUCE_MAC
  49417. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  49418. g.drawRect (0, 0, width, height);
  49419. #endif
  49420. }
  49421. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  49422. int width, int height,
  49423. bool isScrollUpArrow)
  49424. {
  49425. const Colour background (findColour (PopupMenu::backgroundColourId));
  49426. GradientBrush gb (background,
  49427. 0.0f, height * 0.5f,
  49428. background.withAlpha (0.0f),
  49429. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  49430. false);
  49431. g.setBrush (&gb);
  49432. g.fillRect (1, 1, width - 2, height - 2);
  49433. const float hw = width * 0.5f;
  49434. const float arrowW = height * 0.3f;
  49435. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  49436. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  49437. Path p;
  49438. p.addTriangle (hw - arrowW, y1,
  49439. hw + arrowW, y1,
  49440. hw, y2);
  49441. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  49442. g.fillPath (p);
  49443. }
  49444. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  49445. int width, int height,
  49446. const bool isSeparator,
  49447. const bool isActive,
  49448. const bool isHighlighted,
  49449. const bool isTicked,
  49450. const bool hasSubMenu,
  49451. const String& text,
  49452. const String& shortcutKeyText,
  49453. Image* image,
  49454. const Colour* const textColourToUse)
  49455. {
  49456. const float halfH = height * 0.5f;
  49457. if (isSeparator)
  49458. {
  49459. const float separatorIndent = 5.5f;
  49460. g.setColour (Colour (0x33000000));
  49461. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  49462. g.setColour (Colour (0x66ffffff));
  49463. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  49464. }
  49465. else
  49466. {
  49467. Colour textColour (findColour (PopupMenu::textColourId));
  49468. if (textColourToUse != 0)
  49469. textColour = *textColourToUse;
  49470. if (isHighlighted)
  49471. {
  49472. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  49473. g.fillRect (1, 1, width - 2, height - 2);
  49474. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  49475. }
  49476. else
  49477. {
  49478. g.setColour (textColour);
  49479. }
  49480. if (! isActive)
  49481. g.setOpacity (0.3f);
  49482. Font font (getPopupMenuFont());
  49483. if (font.getHeight() > height / 1.3f)
  49484. font.setHeight (height / 1.3f);
  49485. g.setFont (font);
  49486. const int leftBorder = (height * 5) / 4;
  49487. const int rightBorder = 4;
  49488. if (image != 0)
  49489. {
  49490. g.drawImageWithin (image,
  49491. 2, 1, leftBorder - 4, height - 2,
  49492. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  49493. }
  49494. else if (isTicked)
  49495. {
  49496. const Path tick (getTickShape (1.0f));
  49497. const float th = font.getAscent();
  49498. const float ty = halfH - th * 0.5f;
  49499. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  49500. th, true));
  49501. }
  49502. g.drawFittedText (text,
  49503. leftBorder, 0,
  49504. width - (leftBorder + rightBorder), height,
  49505. Justification::centredLeft, 1);
  49506. if (shortcutKeyText.isNotEmpty())
  49507. {
  49508. Font f2 (g.getCurrentFont());
  49509. f2.setHeight (f2.getHeight() * 0.75f);
  49510. f2.setHorizontalScale (0.95f);
  49511. g.setFont (f2);
  49512. g.drawText (shortcutKeyText,
  49513. leftBorder,
  49514. 0,
  49515. width - (leftBorder + rightBorder + 4),
  49516. height,
  49517. Justification::centredRight,
  49518. true);
  49519. }
  49520. if (hasSubMenu)
  49521. {
  49522. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  49523. const float x = width - height * 0.6f;
  49524. Path p;
  49525. p.addTriangle (x, halfH - arrowH * 0.5f,
  49526. x, halfH + arrowH * 0.5f,
  49527. x + arrowH * 0.6f, halfH);
  49528. g.fillPath (p);
  49529. }
  49530. }
  49531. }
  49532. int LookAndFeel::getMenuWindowFlags()
  49533. {
  49534. return ComponentPeer::windowHasDropShadow;
  49535. }
  49536. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  49537. bool, MenuBarComponent& menuBar)
  49538. {
  49539. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  49540. if (menuBar.isEnabled())
  49541. {
  49542. drawShinyButtonShape (g,
  49543. -4.0f, 0.0f,
  49544. width + 8.0f, (float) height,
  49545. 0.0f,
  49546. baseColour,
  49547. 0.4f,
  49548. true, true, true, true);
  49549. }
  49550. else
  49551. {
  49552. g.fillAll (baseColour);
  49553. }
  49554. }
  49555. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  49556. {
  49557. return Font (menuBar.getHeight() * 0.7f);
  49558. }
  49559. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  49560. {
  49561. return getMenuBarFont (menuBar, itemIndex, itemText)
  49562. .getStringWidth (itemText) + menuBar.getHeight();
  49563. }
  49564. void LookAndFeel::drawMenuBarItem (Graphics& g,
  49565. int width, int height,
  49566. int itemIndex,
  49567. const String& itemText,
  49568. bool isMouseOverItem,
  49569. bool isMenuOpen,
  49570. bool /*isMouseOverBar*/,
  49571. MenuBarComponent& menuBar)
  49572. {
  49573. if (! menuBar.isEnabled())
  49574. {
  49575. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  49576. .withMultipliedAlpha (0.5f));
  49577. }
  49578. else if (isMenuOpen || isMouseOverItem)
  49579. {
  49580. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  49581. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  49582. }
  49583. else
  49584. {
  49585. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  49586. }
  49587. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  49588. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  49589. }
  49590. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  49591. TextEditor& textEditor)
  49592. {
  49593. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  49594. }
  49595. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49596. {
  49597. if (textEditor.isEnabled())
  49598. {
  49599. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  49600. {
  49601. const int border = 2;
  49602. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  49603. g.drawRect (0, 0, width, height, border);
  49604. g.setOpacity (1.0f);
  49605. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  49606. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  49607. }
  49608. else
  49609. {
  49610. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49611. g.drawRect (0, 0, width, height);
  49612. g.setOpacity (1.0f);
  49613. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  49614. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  49615. }
  49616. }
  49617. }
  49618. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49619. const bool isButtonDown,
  49620. int buttonX, int buttonY,
  49621. int buttonW, int buttonH,
  49622. ComboBox& box)
  49623. {
  49624. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49625. if (box.isEnabled() && box.hasKeyboardFocus (false))
  49626. {
  49627. g.setColour (box.findColour (TextButton::buttonColourId));
  49628. g.drawRect (0, 0, width, height, 2);
  49629. }
  49630. else
  49631. {
  49632. g.setColour (box.findColour (ComboBox::outlineColourId));
  49633. g.drawRect (0, 0, width, height);
  49634. }
  49635. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  49636. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  49637. box.hasKeyboardFocus (true),
  49638. false, isButtonDown)
  49639. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  49640. drawGlassLozenge (g,
  49641. buttonX + outlineThickness, buttonY + outlineThickness,
  49642. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  49643. baseColour, outlineThickness, -1.0f,
  49644. true, true, true, true);
  49645. if (box.isEnabled())
  49646. {
  49647. const float arrowX = 0.3f;
  49648. const float arrowH = 0.2f;
  49649. Path p;
  49650. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49651. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49652. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49653. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49654. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49655. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49656. g.setColour (box.findColour (ComboBox::arrowColourId));
  49657. g.fillPath (p);
  49658. }
  49659. }
  49660. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  49661. {
  49662. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  49663. }
  49664. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  49665. {
  49666. return new Label (String::empty, String::empty);
  49667. }
  49668. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  49669. {
  49670. label.setBounds (1, 1,
  49671. box.getWidth() + 3 - box.getHeight(),
  49672. box.getHeight() - 2);
  49673. label.setFont (getComboBoxFont (box));
  49674. }
  49675. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  49676. {
  49677. g.fillAll (label.findColour (Label::backgroundColourId));
  49678. if (! label.isBeingEdited())
  49679. {
  49680. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  49681. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  49682. g.setFont (label.getFont());
  49683. g.drawFittedText (label.getText(),
  49684. label.getHorizontalBorderSize(),
  49685. label.getVerticalBorderSize(),
  49686. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  49687. label.getHeight() - 2 * label.getVerticalBorderSize(),
  49688. label.getJustificationType(),
  49689. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  49690. label.getMinimumHorizontalScale());
  49691. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  49692. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49693. }
  49694. else if (label.isEnabled())
  49695. {
  49696. g.setColour (label.findColour (Label::outlineColourId));
  49697. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49698. }
  49699. }
  49700. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  49701. int x, int y,
  49702. int width, int height,
  49703. float /*sliderPos*/,
  49704. float /*minSliderPos*/,
  49705. float /*maxSliderPos*/,
  49706. const Slider::SliderStyle /*style*/,
  49707. Slider& slider)
  49708. {
  49709. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49710. const Colour trackColour (slider.findColour (Slider::trackColourId));
  49711. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  49712. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  49713. Path indent;
  49714. if (slider.isHorizontal())
  49715. {
  49716. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  49717. const float ih = sliderRadius;
  49718. GradientBrush gb (gradCol1, 0.0f, iy,
  49719. gradCol2, 0.0f, iy + ih, false);
  49720. g.setBrush (&gb);
  49721. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  49722. width + sliderRadius, ih,
  49723. 5.0f);
  49724. g.fillPath (indent);
  49725. }
  49726. else
  49727. {
  49728. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  49729. const float iw = sliderRadius;
  49730. GradientBrush gb (gradCol1, ix, 0.0f,
  49731. gradCol2, ix + iw, 0.0f, false);
  49732. g.setBrush (&gb);
  49733. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  49734. iw, height + sliderRadius,
  49735. 5.0f);
  49736. g.fillPath (indent);
  49737. }
  49738. g.setColour (Colour (0x4c000000));
  49739. g.strokePath (indent, PathStrokeType (0.5f));
  49740. }
  49741. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  49742. int x, int y,
  49743. int width, int height,
  49744. float sliderPos,
  49745. float minSliderPos,
  49746. float maxSliderPos,
  49747. const Slider::SliderStyle style,
  49748. Slider& slider)
  49749. {
  49750. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49751. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  49752. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  49753. slider.isMouseOverOrDragging() && slider.isEnabled(),
  49754. slider.isMouseButtonDown() && slider.isEnabled()));
  49755. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  49756. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  49757. {
  49758. float kx, ky;
  49759. if (style == Slider::LinearVertical)
  49760. {
  49761. kx = x + width * 0.5f;
  49762. ky = sliderPos;
  49763. }
  49764. else
  49765. {
  49766. kx = sliderPos;
  49767. ky = y + height * 0.5f;
  49768. }
  49769. drawGlassSphere (g,
  49770. kx - sliderRadius,
  49771. ky - sliderRadius,
  49772. sliderRadius * 2.0f,
  49773. knobColour, outlineThickness);
  49774. }
  49775. else
  49776. {
  49777. if (style == Slider::ThreeValueVertical)
  49778. {
  49779. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  49780. sliderPos - sliderRadius,
  49781. sliderRadius * 2.0f,
  49782. knobColour, outlineThickness);
  49783. }
  49784. else if (style == Slider::ThreeValueHorizontal)
  49785. {
  49786. drawGlassSphere (g,sliderPos - sliderRadius,
  49787. y + height * 0.5f - sliderRadius,
  49788. sliderRadius * 2.0f,
  49789. knobColour, outlineThickness);
  49790. }
  49791. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  49792. {
  49793. const float sr = jmin (sliderRadius, width * 0.4f);
  49794. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  49795. minSliderPos - sliderRadius,
  49796. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  49797. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  49798. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  49799. }
  49800. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  49801. {
  49802. const float sr = jmin (sliderRadius, height * 0.4f);
  49803. drawGlassPointer (g, minSliderPos - sr,
  49804. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  49805. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  49806. drawGlassPointer (g, maxSliderPos - sliderRadius,
  49807. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  49808. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  49809. }
  49810. }
  49811. }
  49812. void LookAndFeel::drawLinearSlider (Graphics& g,
  49813. int x, int y,
  49814. int width, int height,
  49815. float sliderPos,
  49816. float minSliderPos,
  49817. float maxSliderPos,
  49818. const Slider::SliderStyle style,
  49819. Slider& slider)
  49820. {
  49821. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49822. if (style == Slider::LinearBar)
  49823. {
  49824. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49825. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  49826. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  49827. false,
  49828. isMouseOver,
  49829. isMouseOver || slider.isMouseButtonDown()));
  49830. drawShinyButtonShape (g,
  49831. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  49832. baseColour,
  49833. slider.isEnabled() ? 0.9f : 0.3f,
  49834. true, true, true, true);
  49835. }
  49836. else
  49837. {
  49838. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49839. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49840. }
  49841. }
  49842. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  49843. {
  49844. return jmin (7,
  49845. slider.getHeight() / 2,
  49846. slider.getWidth() / 2) + 2;
  49847. }
  49848. void LookAndFeel::drawRotarySlider (Graphics& g,
  49849. int x, int y,
  49850. int width, int height,
  49851. float sliderPos,
  49852. const float rotaryStartAngle,
  49853. const float rotaryEndAngle,
  49854. Slider& slider)
  49855. {
  49856. const float radius = jmin (width / 2, height / 2) - 2.0f;
  49857. const float centreX = x + width * 0.5f;
  49858. const float centreY = y + height * 0.5f;
  49859. const float rx = centreX - radius;
  49860. const float ry = centreY - radius;
  49861. const float rw = radius * 2.0f;
  49862. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  49863. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49864. if (radius > 12.0f)
  49865. {
  49866. if (slider.isEnabled())
  49867. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49868. else
  49869. g.setColour (Colour (0x80808080));
  49870. const float thickness = 0.7f;
  49871. {
  49872. Path filledArc;
  49873. filledArc.addPieSegment (rx, ry, rw, rw,
  49874. rotaryStartAngle,
  49875. angle,
  49876. thickness);
  49877. g.fillPath (filledArc);
  49878. }
  49879. if (thickness > 0)
  49880. {
  49881. const float innerRadius = radius * 0.2f;
  49882. Path p;
  49883. p.addTriangle (-innerRadius, 0.0f,
  49884. 0.0f, -radius * thickness * 1.1f,
  49885. innerRadius, 0.0f);
  49886. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  49887. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49888. }
  49889. if (slider.isEnabled())
  49890. {
  49891. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  49892. Path outlineArc;
  49893. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  49894. outlineArc.closeSubPath();
  49895. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  49896. }
  49897. }
  49898. else
  49899. {
  49900. if (slider.isEnabled())
  49901. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49902. else
  49903. g.setColour (Colour (0x80808080));
  49904. Path p;
  49905. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  49906. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  49907. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  49908. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49909. }
  49910. }
  49911. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  49912. {
  49913. return new TextButton (isIncrement ? "+" : "-", String::empty);
  49914. }
  49915. class SliderLabelComp : public Label
  49916. {
  49917. public:
  49918. SliderLabelComp() : Label (String::empty, String::empty) {}
  49919. ~SliderLabelComp() {}
  49920. void mouseWheelMove (const MouseEvent&, float, float) {}
  49921. };
  49922. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  49923. {
  49924. Label* const l = new SliderLabelComp();
  49925. l->setJustificationType (Justification::centred);
  49926. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49927. l->setColour (Label::backgroundColourId,
  49928. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  49929. : slider.findColour (Slider::textBoxBackgroundColourId));
  49930. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49931. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49932. l->setColour (TextEditor::backgroundColourId,
  49933. slider.findColour (Slider::textBoxBackgroundColourId)
  49934. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  49935. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49936. return l;
  49937. }
  49938. ImageEffectFilter* LookAndFeel::getSliderEffect()
  49939. {
  49940. return 0;
  49941. }
  49942. static const TextLayout layoutTooltipText (const String& text) throw()
  49943. {
  49944. const float tooltipFontSize = 12.0f;
  49945. const int maxToolTipWidth = 400;
  49946. const Font f (tooltipFontSize, Font::bold);
  49947. TextLayout tl (text, f);
  49948. tl.layout (maxToolTipWidth, Justification::left, true);
  49949. return tl;
  49950. }
  49951. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  49952. {
  49953. const TextLayout tl (layoutTooltipText (tipText));
  49954. width = tl.getWidth() + 14;
  49955. height = tl.getHeight() + 6;
  49956. }
  49957. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  49958. {
  49959. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  49960. const Colour textCol (findColour (TooltipWindow::textColourId));
  49961. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  49962. g.setColour (findColour (TooltipWindow::outlineColourId));
  49963. g.drawRect (0, 0, width, height, 1);
  49964. #endif
  49965. const TextLayout tl (layoutTooltipText (text));
  49966. g.setColour (findColour (TooltipWindow::textColourId));
  49967. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  49968. }
  49969. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  49970. {
  49971. return new TextButton (text, TRANS("click to browse for a different file"));
  49972. }
  49973. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  49974. ComboBox* filenameBox,
  49975. Button* browseButton)
  49976. {
  49977. browseButton->setSize (80, filenameComp.getHeight());
  49978. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  49979. if (tb != 0)
  49980. tb->changeWidthToFitText();
  49981. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  49982. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  49983. }
  49984. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  49985. int imageX, int imageY, int imageW, int imageH,
  49986. const Colour& overlayColour,
  49987. float imageOpacity,
  49988. ImageButton& button)
  49989. {
  49990. if (! button.isEnabled())
  49991. imageOpacity *= 0.3f;
  49992. if (! overlayColour.isOpaque())
  49993. {
  49994. g.setOpacity (imageOpacity);
  49995. g.drawImage (image, imageX, imageY, imageW, imageH,
  49996. 0, 0, image->getWidth(), image->getHeight(), false);
  49997. }
  49998. if (! overlayColour.isTransparent())
  49999. {
  50000. g.setColour (overlayColour);
  50001. g.drawImage (image, imageX, imageY, imageW, imageH,
  50002. 0, 0, image->getWidth(), image->getHeight(), true);
  50003. }
  50004. }
  50005. void LookAndFeel::drawCornerResizer (Graphics& g,
  50006. int w, int h,
  50007. bool /*isMouseOver*/,
  50008. bool /*isMouseDragging*/)
  50009. {
  50010. const float lineThickness = jmin (w, h) * 0.075f;
  50011. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  50012. {
  50013. g.setColour (Colours::lightgrey);
  50014. g.drawLine (w * i,
  50015. h + 1.0f,
  50016. w + 1.0f,
  50017. h * i,
  50018. lineThickness);
  50019. g.setColour (Colours::darkgrey);
  50020. g.drawLine (w * i + lineThickness,
  50021. h + 1.0f,
  50022. w + 1.0f,
  50023. h * i + lineThickness,
  50024. lineThickness);
  50025. }
  50026. }
  50027. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  50028. const BorderSize& /*borders*/)
  50029. {
  50030. }
  50031. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  50032. const BorderSize& /*border*/, ResizableWindow& window)
  50033. {
  50034. g.fillAll (window.getBackgroundColour());
  50035. }
  50036. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  50037. const BorderSize& border, ResizableWindow&)
  50038. {
  50039. g.setColour (Colour (0x80000000));
  50040. g.drawRect (0, 0, w, h);
  50041. g.setColour (Colour (0x19000000));
  50042. g.drawRect (border.getLeft() - 1,
  50043. border.getTop() - 1,
  50044. w + 2 - border.getLeftAndRight(),
  50045. h + 2 - border.getTopAndBottom());
  50046. }
  50047. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  50048. Graphics& g, int w, int h,
  50049. int titleSpaceX, int titleSpaceW,
  50050. const Image* icon,
  50051. bool drawTitleTextOnLeft)
  50052. {
  50053. const bool isActive = window.isActiveWindow();
  50054. GradientBrush gb (window.getBackgroundColour(),
  50055. 0.0f, 0.0f,
  50056. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  50057. 0.0f, (float) h, false);
  50058. g.setBrush (&gb);
  50059. g.fillAll();
  50060. g.setFont (h * 0.65f, Font::bold);
  50061. int textW = g.getCurrentFont().getStringWidth (window.getName());
  50062. int iconW = 0;
  50063. int iconH = 0;
  50064. if (icon != 0)
  50065. {
  50066. iconH = (int) g.getCurrentFont().getHeight();
  50067. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  50068. }
  50069. textW = jmin (titleSpaceW, textW + iconW);
  50070. int textX = drawTitleTextOnLeft ? titleSpaceX
  50071. : jmax (titleSpaceX, (w - textW) / 2);
  50072. if (textX + textW > titleSpaceX + titleSpaceW)
  50073. textX = titleSpaceX + titleSpaceW - textW;
  50074. if (icon != 0)
  50075. {
  50076. g.setOpacity (isActive ? 1.0f : 0.6f);
  50077. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  50078. RectanglePlacement::centred, false);
  50079. textX += iconW;
  50080. textW -= iconW;
  50081. }
  50082. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  50083. g.setColour (findColour (DocumentWindow::textColourId));
  50084. else
  50085. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  50086. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  50087. }
  50088. class GlassWindowButton : public Button
  50089. {
  50090. public:
  50091. GlassWindowButton (const String& name, const Colour& col,
  50092. const Path& normalShape_,
  50093. const Path& toggledShape_) throw()
  50094. : Button (name),
  50095. colour (col),
  50096. normalShape (normalShape_),
  50097. toggledShape (toggledShape_)
  50098. {
  50099. }
  50100. ~GlassWindowButton()
  50101. {
  50102. }
  50103. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  50104. {
  50105. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  50106. if (! isEnabled())
  50107. alpha *= 0.5f;
  50108. float x = 0, y = 0, diam;
  50109. if (getWidth() < getHeight())
  50110. {
  50111. diam = (float) getWidth();
  50112. y = (getHeight() - getWidth()) * 0.5f;
  50113. }
  50114. else
  50115. {
  50116. diam = (float) getHeight();
  50117. y = (getWidth() - getHeight()) * 0.5f;
  50118. }
  50119. x += diam * 0.05f;
  50120. y += diam * 0.05f;
  50121. diam *= 0.9f;
  50122. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  50123. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  50124. g.setBrush (&gb1);
  50125. g.fillEllipse (x, y, diam, diam);
  50126. x += 2.0f;
  50127. y += 2.0f;
  50128. diam -= 4.0f;
  50129. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  50130. Path& p = getToggleState() ? toggledShape : normalShape;
  50131. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  50132. diam * 0.4f, diam * 0.4f, true));
  50133. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  50134. g.fillPath (p, t);
  50135. }
  50136. juce_UseDebuggingNewOperator
  50137. private:
  50138. Colour colour;
  50139. Path normalShape, toggledShape;
  50140. GlassWindowButton (const GlassWindowButton&);
  50141. const GlassWindowButton& operator= (const GlassWindowButton&);
  50142. };
  50143. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  50144. {
  50145. Path shape;
  50146. const float crossThickness = 0.25f;
  50147. if (buttonType == DocumentWindow::closeButton)
  50148. {
  50149. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  50150. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  50151. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  50152. }
  50153. else if (buttonType == DocumentWindow::minimiseButton)
  50154. {
  50155. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50156. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  50157. }
  50158. else if (buttonType == DocumentWindow::maximiseButton)
  50159. {
  50160. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  50161. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50162. Path fullscreenShape;
  50163. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  50164. fullscreenShape.lineTo (0.0f, 100.0f);
  50165. fullscreenShape.lineTo (0.0f, 0.0f);
  50166. fullscreenShape.lineTo (100.0f, 0.0f);
  50167. fullscreenShape.lineTo (100.0f, 45.0f);
  50168. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  50169. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  50170. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  50171. }
  50172. jassertfalse
  50173. return 0;
  50174. }
  50175. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  50176. int titleBarX,
  50177. int titleBarY,
  50178. int titleBarW,
  50179. int titleBarH,
  50180. Button* minimiseButton,
  50181. Button* maximiseButton,
  50182. Button* closeButton,
  50183. bool positionTitleBarButtonsOnLeft)
  50184. {
  50185. const int buttonW = titleBarH - titleBarH / 8;
  50186. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  50187. : titleBarX + titleBarW - buttonW - buttonW / 4;
  50188. if (closeButton != 0)
  50189. {
  50190. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50191. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  50192. }
  50193. if (positionTitleBarButtonsOnLeft)
  50194. swapVariables (minimiseButton, maximiseButton);
  50195. if (maximiseButton != 0)
  50196. {
  50197. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50198. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  50199. }
  50200. if (minimiseButton != 0)
  50201. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50202. }
  50203. int LookAndFeel::getDefaultMenuBarHeight()
  50204. {
  50205. return 24;
  50206. }
  50207. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  50208. {
  50209. return new DropShadower (0.4f, 1, 5, 10);
  50210. }
  50211. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  50212. int w, int h,
  50213. bool /*isVerticalBar*/,
  50214. bool isMouseOver,
  50215. bool isMouseDragging)
  50216. {
  50217. float alpha = 0.5f;
  50218. if (isMouseOver || isMouseDragging)
  50219. {
  50220. g.fillAll (Colour (0x190000ff));
  50221. alpha = 1.0f;
  50222. }
  50223. const float cx = w * 0.5f;
  50224. const float cy = h * 0.5f;
  50225. const float cr = jmin (w, h) * 0.4f;
  50226. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  50227. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  50228. true);
  50229. g.setBrush (&gb);
  50230. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  50231. }
  50232. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  50233. const String& text,
  50234. const Justification& position,
  50235. GroupComponent& group)
  50236. {
  50237. const float textH = 15.0f;
  50238. const float indent = 3.0f;
  50239. const float textEdgeGap = 4.0f;
  50240. float cs = 5.0f;
  50241. Font f (textH);
  50242. Path p;
  50243. float x = indent;
  50244. float y = f.getAscent() - 3.0f;
  50245. float w = jmax (0.0f, width - x * 2.0f);
  50246. float h = jmax (0.0f, height - y - indent);
  50247. cs = jmin (cs, w * 0.5f, h * 0.5f);
  50248. const float cs2 = 2.0f * cs;
  50249. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  50250. float textX = cs + textEdgeGap;
  50251. if (position.testFlags (Justification::horizontallyCentred))
  50252. textX = cs + (w - cs2 - textW) * 0.5f;
  50253. else if (position.testFlags (Justification::right))
  50254. textX = w - cs - textW - textEdgeGap;
  50255. p.startNewSubPath (x + textX + textW, y);
  50256. p.lineTo (x + w - cs, y);
  50257. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  50258. p.lineTo (x + w, y + h - cs);
  50259. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50260. p.lineTo (x + cs, y + h);
  50261. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50262. p.lineTo (x, y + cs);
  50263. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50264. p.lineTo (x + textX, y);
  50265. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  50266. g.setColour (group.findColour (GroupComponent::outlineColourId)
  50267. .withMultipliedAlpha (alpha));
  50268. g.strokePath (p, PathStrokeType (2.0f));
  50269. g.setColour (group.findColour (GroupComponent::textColourId)
  50270. .withMultipliedAlpha (alpha));
  50271. g.setFont (f);
  50272. g.drawText (text,
  50273. roundFloatToInt (x + textX), 0,
  50274. roundFloatToInt (textW),
  50275. roundFloatToInt (textH),
  50276. Justification::centred, true);
  50277. }
  50278. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  50279. {
  50280. return 1 + tabDepth / 3;
  50281. }
  50282. int LookAndFeel::getTabButtonSpaceAroundImage()
  50283. {
  50284. return 4;
  50285. }
  50286. void LookAndFeel::createTabButtonShape (Path& p,
  50287. int width, int height,
  50288. int /*tabIndex*/,
  50289. const String& /*text*/,
  50290. Button& /*button*/,
  50291. TabbedButtonBar::Orientation orientation,
  50292. const bool /*isMouseOver*/,
  50293. const bool /*isMouseDown*/,
  50294. const bool /*isFrontTab*/)
  50295. {
  50296. const float w = (float) width;
  50297. const float h = (float) height;
  50298. float length = w;
  50299. float depth = h;
  50300. if (orientation == TabbedButtonBar::TabsAtLeft
  50301. || orientation == TabbedButtonBar::TabsAtRight)
  50302. {
  50303. swapVariables (length, depth);
  50304. }
  50305. const float indent = (float) getTabButtonOverlap ((int) depth);
  50306. const float overhang = 4.0f;
  50307. if (orientation == TabbedButtonBar::TabsAtLeft)
  50308. {
  50309. p.startNewSubPath (w, 0.0f);
  50310. p.lineTo (0.0f, indent);
  50311. p.lineTo (0.0f, h - indent);
  50312. p.lineTo (w, h);
  50313. p.lineTo (w + overhang, h + overhang);
  50314. p.lineTo (w + overhang, -overhang);
  50315. }
  50316. else if (orientation == TabbedButtonBar::TabsAtRight)
  50317. {
  50318. p.startNewSubPath (0.0f, 0.0f);
  50319. p.lineTo (w, indent);
  50320. p.lineTo (w, h - indent);
  50321. p.lineTo (0.0f, h);
  50322. p.lineTo (-overhang, h + overhang);
  50323. p.lineTo (-overhang, -overhang);
  50324. }
  50325. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50326. {
  50327. p.startNewSubPath (0.0f, 0.0f);
  50328. p.lineTo (indent, h);
  50329. p.lineTo (w - indent, h);
  50330. p.lineTo (w, 0.0f);
  50331. p.lineTo (w + overhang, -overhang);
  50332. p.lineTo (-overhang, -overhang);
  50333. }
  50334. else
  50335. {
  50336. p.startNewSubPath (0.0f, h);
  50337. p.lineTo (indent, 0.0f);
  50338. p.lineTo (w - indent, 0.0f);
  50339. p.lineTo (w, h);
  50340. p.lineTo (w + overhang, h + overhang);
  50341. p.lineTo (-overhang, h + overhang);
  50342. }
  50343. p.closeSubPath();
  50344. p = p.createPathWithRoundedCorners (3.0f);
  50345. }
  50346. void LookAndFeel::fillTabButtonShape (Graphics& g,
  50347. const Path& path,
  50348. const Colour& preferredColour,
  50349. int /*tabIndex*/,
  50350. const String& /*text*/,
  50351. Button& button,
  50352. TabbedButtonBar::Orientation /*orientation*/,
  50353. const bool /*isMouseOver*/,
  50354. const bool /*isMouseDown*/,
  50355. const bool isFrontTab)
  50356. {
  50357. g.setColour (isFrontTab ? preferredColour
  50358. : preferredColour.withMultipliedAlpha (0.9f));
  50359. g.fillPath (path);
  50360. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  50361. : TabbedButtonBar::tabOutlineColourId, false)
  50362. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  50363. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  50364. }
  50365. void LookAndFeel::drawTabButtonText (Graphics& g,
  50366. int x, int y, int w, int h,
  50367. const Colour& preferredBackgroundColour,
  50368. int /*tabIndex*/,
  50369. const String& text,
  50370. Button& button,
  50371. TabbedButtonBar::Orientation orientation,
  50372. const bool isMouseOver,
  50373. const bool isMouseDown,
  50374. const bool isFrontTab)
  50375. {
  50376. int length = w;
  50377. int depth = h;
  50378. if (orientation == TabbedButtonBar::TabsAtLeft
  50379. || orientation == TabbedButtonBar::TabsAtRight)
  50380. {
  50381. swapVariables (length, depth);
  50382. }
  50383. Font font (depth * 0.6f);
  50384. font.setUnderline (button.hasKeyboardFocus (false));
  50385. GlyphArrangement textLayout;
  50386. textLayout.addFittedText (font, text.trim(),
  50387. 0.0f, 0.0f, (float) length, (float) depth,
  50388. Justification::centred,
  50389. jmax (1, depth / 12));
  50390. AffineTransform transform;
  50391. if (orientation == TabbedButtonBar::TabsAtLeft)
  50392. {
  50393. transform = transform.rotated (float_Pi * -0.5f)
  50394. .translated ((float) x, (float) (y + h));
  50395. }
  50396. else if (orientation == TabbedButtonBar::TabsAtRight)
  50397. {
  50398. transform = transform.rotated (float_Pi * 0.5f)
  50399. .translated ((float) (x + w), (float) y);
  50400. }
  50401. else
  50402. {
  50403. transform = transform.translated ((float) x, (float) y);
  50404. }
  50405. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  50406. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  50407. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  50408. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  50409. else
  50410. g.setColour (preferredBackgroundColour.contrasting());
  50411. if (! (isMouseOver || isMouseDown))
  50412. g.setOpacity (0.8f);
  50413. if (! button.isEnabled())
  50414. g.setOpacity (0.3f);
  50415. textLayout.draw (g, transform);
  50416. }
  50417. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  50418. const String& text,
  50419. int tabDepth,
  50420. Button&)
  50421. {
  50422. Font f (tabDepth * 0.6f);
  50423. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  50424. }
  50425. void LookAndFeel::drawTabButton (Graphics& g,
  50426. int w, int h,
  50427. const Colour& preferredColour,
  50428. int tabIndex,
  50429. const String& text,
  50430. Button& button,
  50431. TabbedButtonBar::Orientation orientation,
  50432. const bool isMouseOver,
  50433. const bool isMouseDown,
  50434. const bool isFrontTab)
  50435. {
  50436. int length = w;
  50437. int depth = h;
  50438. if (orientation == TabbedButtonBar::TabsAtLeft
  50439. || orientation == TabbedButtonBar::TabsAtRight)
  50440. {
  50441. swapVariables (length, depth);
  50442. }
  50443. Path tabShape;
  50444. createTabButtonShape (tabShape, w, h,
  50445. tabIndex, text, button, orientation,
  50446. isMouseOver, isMouseDown, isFrontTab);
  50447. fillTabButtonShape (g, tabShape, preferredColour,
  50448. tabIndex, text, button, orientation,
  50449. isMouseOver, isMouseDown, isFrontTab);
  50450. const int indent = getTabButtonOverlap (depth);
  50451. int x = 0, y = 0;
  50452. if (orientation == TabbedButtonBar::TabsAtLeft
  50453. || orientation == TabbedButtonBar::TabsAtRight)
  50454. {
  50455. y += indent;
  50456. h -= indent * 2;
  50457. }
  50458. else
  50459. {
  50460. x += indent;
  50461. w -= indent * 2;
  50462. }
  50463. drawTabButtonText (g, x, y, w, h, preferredColour,
  50464. tabIndex, text, button, orientation,
  50465. isMouseOver, isMouseDown, isFrontTab);
  50466. }
  50467. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  50468. int w, int h,
  50469. TabbedButtonBar& tabBar,
  50470. TabbedButtonBar::Orientation orientation)
  50471. {
  50472. const float shadowSize = 0.2f;
  50473. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  50474. Rectangle shadowRect;
  50475. if (orientation == TabbedButtonBar::TabsAtLeft)
  50476. {
  50477. x1 = (float) w;
  50478. x2 = w * (1.0f - shadowSize);
  50479. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  50480. }
  50481. else if (orientation == TabbedButtonBar::TabsAtRight)
  50482. {
  50483. x2 = w * shadowSize;
  50484. shadowRect.setBounds (0, 0, (int) x2, h);
  50485. }
  50486. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50487. {
  50488. y2 = h * shadowSize;
  50489. shadowRect.setBounds (0, 0, w, (int) y2);
  50490. }
  50491. else
  50492. {
  50493. y1 = (float) h;
  50494. y2 = h * (1.0f - shadowSize);
  50495. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  50496. }
  50497. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  50498. Colours::transparentBlack, x2, y2,
  50499. false);
  50500. g.setBrush (&gb);
  50501. shadowRect.expand (2, 2);
  50502. g.fillRect (shadowRect);
  50503. g.setColour (Colour (0x80000000));
  50504. if (orientation == TabbedButtonBar::TabsAtLeft)
  50505. {
  50506. g.fillRect (w - 1, 0, 1, h);
  50507. }
  50508. else if (orientation == TabbedButtonBar::TabsAtRight)
  50509. {
  50510. g.fillRect (0, 0, 1, h);
  50511. }
  50512. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50513. {
  50514. g.fillRect (0, 0, w, 1);
  50515. }
  50516. else
  50517. {
  50518. g.fillRect (0, h - 1, w, 1);
  50519. }
  50520. }
  50521. Button* LookAndFeel::createTabBarExtrasButton()
  50522. {
  50523. const float thickness = 7.0f;
  50524. const float indent = 22.0f;
  50525. Path p;
  50526. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  50527. DrawablePath ellipse;
  50528. ellipse.setPath (p);
  50529. ellipse.setSolidFill (Colour (0x99ffffff));
  50530. p.clear();
  50531. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  50532. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  50533. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  50534. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  50535. p.setUsingNonZeroWinding (false);
  50536. DrawablePath dp;
  50537. dp.setPath (p);
  50538. dp.setSolidFill (Colour (0x59000000));
  50539. DrawableComposite normalImage;
  50540. normalImage.insertDrawable (ellipse);
  50541. normalImage.insertDrawable (dp);
  50542. dp.setSolidFill (Colour (0xcc000000));
  50543. DrawableComposite overImage;
  50544. overImage.insertDrawable (ellipse);
  50545. overImage.insertDrawable (dp);
  50546. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  50547. db->setImages (&normalImage, &overImage, 0);
  50548. return db;
  50549. }
  50550. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  50551. {
  50552. g.fillAll (Colours::white);
  50553. const int w = header.getWidth();
  50554. const int h = header.getHeight();
  50555. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  50556. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  50557. false);
  50558. g.setBrush (&gb);
  50559. g.fillRect (0, h / 2, w, h);
  50560. g.setColour (Colour (0x33000000));
  50561. g.fillRect (0, h - 1, w, 1);
  50562. for (int i = header.getNumColumns (true); --i >= 0;)
  50563. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  50564. }
  50565. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  50566. int width, int height,
  50567. bool isMouseOver, bool isMouseDown,
  50568. int columnFlags)
  50569. {
  50570. if (isMouseDown)
  50571. g.fillAll (Colour (0x8899aadd));
  50572. else if (isMouseOver)
  50573. g.fillAll (Colour (0x5599aadd));
  50574. int rightOfText = width - 4;
  50575. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  50576. {
  50577. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  50578. const float bottom = height - top;
  50579. const float w = height * 0.5f;
  50580. const float x = rightOfText - (w * 1.25f);
  50581. rightOfText = (int) x;
  50582. Path sortArrow;
  50583. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  50584. g.setColour (Colour (0x99000000));
  50585. g.fillPath (sortArrow);
  50586. }
  50587. g.setColour (Colours::black);
  50588. g.setFont (height * 0.5f, Font::bold);
  50589. const int textX = 4;
  50590. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  50591. }
  50592. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  50593. {
  50594. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  50595. GradientBrush gb (background, 0.0f, 0.0f,
  50596. background.darker (0.1f),
  50597. toolbar.isVertical() ? w - 1.0f : 0.0f,
  50598. toolbar.isVertical() ? 0.0f : h - 1.0f,
  50599. false);
  50600. g.setBrush (&gb);
  50601. g.fillAll();
  50602. }
  50603. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  50604. {
  50605. return createTabBarExtrasButton();
  50606. }
  50607. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  50608. bool isMouseOver, bool isMouseDown,
  50609. ToolbarItemComponent& component)
  50610. {
  50611. if (isMouseDown)
  50612. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  50613. else if (isMouseOver)
  50614. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  50615. }
  50616. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  50617. const String& text, ToolbarItemComponent& component)
  50618. {
  50619. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  50620. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  50621. const float fontHeight = jmin (14.0f, height * 0.85f);
  50622. g.setFont (fontHeight);
  50623. g.drawFittedText (text,
  50624. x, y, width, height,
  50625. Justification::centred,
  50626. jmax (1, height / (int) fontHeight));
  50627. }
  50628. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  50629. bool isOpen, int width, int height)
  50630. {
  50631. const int buttonSize = (height * 3) / 4;
  50632. const int buttonIndent = (height - buttonSize) / 2;
  50633. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  50634. const int textX = buttonIndent * 2 + buttonSize + 2;
  50635. g.setColour (Colours::black);
  50636. g.setFont (height * 0.7f, Font::bold);
  50637. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  50638. }
  50639. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  50640. PropertyComponent&)
  50641. {
  50642. g.setColour (Colour (0x66ffffff));
  50643. g.fillRect (0, 0, width, height - 1);
  50644. }
  50645. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  50646. PropertyComponent& component)
  50647. {
  50648. g.setColour (Colours::black);
  50649. if (! component.isEnabled())
  50650. g.setOpacity (g.getCurrentColour().getFloatAlpha() * 0.6f);
  50651. g.setFont (jmin (height, 24) * 0.65f);
  50652. const Rectangle r (getPropertyComponentContentPosition (component));
  50653. g.drawFittedText (component.getName(),
  50654. 3, r.getY(), r.getX() - 5, r.getHeight(),
  50655. Justification::centredLeft, 2);
  50656. }
  50657. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  50658. {
  50659. return Rectangle (component.getWidth() / 3, 1,
  50660. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  50661. }
  50662. void LookAndFeel::createFileChooserHeaderText (const String& title,
  50663. const String& instructions,
  50664. GlyphArrangement& text,
  50665. int width)
  50666. {
  50667. text.clear();
  50668. text.addJustifiedText (Font (17.0f, Font::bold), title,
  50669. 8.0f, 22.0f, width - 16.0f,
  50670. Justification::centred);
  50671. text.addJustifiedText (Font (14.0f), instructions,
  50672. 8.0f, 24.0f + 16.0f, width - 16.0f,
  50673. Justification::centred);
  50674. }
  50675. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  50676. const String& filename, Image* icon,
  50677. const String& fileSizeDescription,
  50678. const String& fileTimeDescription,
  50679. const bool isDirectory,
  50680. const bool isItemSelected,
  50681. const int /*itemIndex*/)
  50682. {
  50683. if (isItemSelected)
  50684. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  50685. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  50686. g.setFont (height * 0.7f);
  50687. Image* im = icon;
  50688. Image* toRelease = 0;
  50689. if (im == 0)
  50690. {
  50691. toRelease = im = (isDirectory ? getDefaultFolderImage()
  50692. : getDefaultDocumentFileImage());
  50693. }
  50694. const int x = 32;
  50695. if (im != 0)
  50696. {
  50697. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  50698. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  50699. false);
  50700. ImageCache::release (toRelease);
  50701. }
  50702. if (width > 450 && ! isDirectory)
  50703. {
  50704. const int sizeX = roundFloatToInt (width * 0.7f);
  50705. const int dateX = roundFloatToInt (width * 0.8f);
  50706. g.drawFittedText (filename,
  50707. x, 0, sizeX - x, height,
  50708. Justification::centredLeft, 1);
  50709. g.setFont (height * 0.5f);
  50710. g.setColour (Colours::darkgrey);
  50711. if (! isDirectory)
  50712. {
  50713. g.drawFittedText (fileSizeDescription,
  50714. sizeX, 0, dateX - sizeX - 8, height,
  50715. Justification::centredRight, 1);
  50716. g.drawFittedText (fileTimeDescription,
  50717. dateX, 0, width - 8 - dateX, height,
  50718. Justification::centredRight, 1);
  50719. }
  50720. }
  50721. else
  50722. {
  50723. g.drawFittedText (filename,
  50724. x, 0, width - x, height,
  50725. Justification::centredLeft, 1);
  50726. }
  50727. }
  50728. Button* LookAndFeel::createFileBrowserGoUpButton()
  50729. {
  50730. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  50731. Path arrowPath;
  50732. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  50733. DrawablePath arrowImage;
  50734. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  50735. arrowImage.setPath (arrowPath);
  50736. goUpButton->setImages (&arrowImage);
  50737. return goUpButton;
  50738. }
  50739. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  50740. DirectoryContentsDisplayComponent* fileListComponent,
  50741. FilePreviewComponent* previewComp,
  50742. ComboBox* currentPathBox,
  50743. TextEditor* filenameBox,
  50744. Button* goUpButton)
  50745. {
  50746. const int x = 8;
  50747. int w = browserComp.getWidth() - x - x;
  50748. if (previewComp != 0)
  50749. {
  50750. const int previewWidth = w / 3;
  50751. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  50752. w -= previewWidth + 4;
  50753. }
  50754. int y = 4;
  50755. const int controlsHeight = 22;
  50756. const int bottomSectionHeight = controlsHeight + 8;
  50757. const int upButtonWidth = 50;
  50758. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  50759. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  50760. y += controlsHeight + 4;
  50761. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  50762. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  50763. y = listAsComp->getBottom() + 4;
  50764. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  50765. }
  50766. Image* LookAndFeel::getDefaultFolderImage()
  50767. {
  50768. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  50769. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  50770. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  50771. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  50772. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  50773. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  50774. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  50775. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  50776. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  50777. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  50778. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  50779. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  50780. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  50781. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  50782. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  50783. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  50784. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  50785. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  50786. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  50787. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  50788. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  50789. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  50790. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  50791. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  50792. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  50793. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  50794. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  50795. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  50796. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  50797. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  50798. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  50799. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  50800. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  50801. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  50802. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  50803. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  50804. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  50805. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  50806. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  50807. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  50808. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  50809. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  50810. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  50811. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  50812. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  50813. }
  50814. Image* LookAndFeel::getDefaultDocumentFileImage()
  50815. {
  50816. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  50817. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  50818. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  50819. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  50820. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  50821. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  50822. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  50823. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  50824. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  50825. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  50826. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  50827. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  50828. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  50829. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  50830. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  50831. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  50832. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  50833. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  50834. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  50835. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  50836. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  50837. 174,66,96,130,0,0};
  50838. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  50839. }
  50840. void LookAndFeel::playAlertSound()
  50841. {
  50842. PlatformUtilities::beep();
  50843. }
  50844. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  50845. {
  50846. g.setColour (Colours::white.withAlpha (0.7f));
  50847. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  50848. g.setColour (Colours::black.withAlpha (0.2f));
  50849. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  50850. const int totalBlocks = 7;
  50851. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  50852. const float w = (width - 6.0f) / (float) totalBlocks;
  50853. for (int i = 0; i < totalBlocks; ++i)
  50854. {
  50855. if (i >= numBlocks)
  50856. g.setColour (Colours::lightblue.withAlpha (0.6f));
  50857. else
  50858. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  50859. : Colours::red);
  50860. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  50861. }
  50862. }
  50863. static void createRoundedPath (Path& p,
  50864. const float x, const float y,
  50865. const float w, const float h,
  50866. const float cs,
  50867. const bool curveTopLeft, const bool curveTopRight,
  50868. const bool curveBottomLeft, const bool curveBottomRight) throw()
  50869. {
  50870. const float cs2 = 2.0f * cs;
  50871. if (curveTopLeft)
  50872. {
  50873. p.startNewSubPath (x, y + cs);
  50874. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50875. }
  50876. else
  50877. {
  50878. p.startNewSubPath (x, y);
  50879. }
  50880. if (curveTopRight)
  50881. {
  50882. p.lineTo (x + w - cs, y);
  50883. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  50884. }
  50885. else
  50886. {
  50887. p.lineTo (x + w, y);
  50888. }
  50889. if (curveBottomRight)
  50890. {
  50891. p.lineTo (x + w, y + h - cs);
  50892. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50893. }
  50894. else
  50895. {
  50896. p.lineTo (x + w, y + h);
  50897. }
  50898. if (curveBottomLeft)
  50899. {
  50900. p.lineTo (x + cs, y + h);
  50901. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50902. }
  50903. else
  50904. {
  50905. p.lineTo (x, y + h);
  50906. }
  50907. p.closeSubPath();
  50908. }
  50909. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  50910. float x, float y, float w, float h,
  50911. float maxCornerSize,
  50912. const Colour& baseColour,
  50913. const float strokeWidth,
  50914. const bool flatOnLeft,
  50915. const bool flatOnRight,
  50916. const bool flatOnTop,
  50917. const bool flatOnBottom) throw()
  50918. {
  50919. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  50920. return;
  50921. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  50922. Path outline;
  50923. createRoundedPath (outline, x, y, w, h, cs,
  50924. ! (flatOnLeft || flatOnTop),
  50925. ! (flatOnRight || flatOnTop),
  50926. ! (flatOnLeft || flatOnBottom),
  50927. ! (flatOnRight || flatOnBottom));
  50928. ColourGradient cg (baseColour, 0.0f, y,
  50929. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  50930. false);
  50931. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  50932. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  50933. GradientBrush gb (cg);
  50934. g.setBrush (&gb);
  50935. g.fillPath (outline);
  50936. g.setColour (Colour (0x80000000));
  50937. g.strokePath (outline, PathStrokeType (strokeWidth));
  50938. }
  50939. void LookAndFeel::drawGlassSphere (Graphics& g,
  50940. const float x, const float y,
  50941. const float diameter,
  50942. const Colour& colour,
  50943. const float outlineThickness) throw()
  50944. {
  50945. if (diameter <= outlineThickness)
  50946. return;
  50947. Path p;
  50948. p.addEllipse (x, y, diameter, diameter);
  50949. {
  50950. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50951. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50952. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50953. GradientBrush gb (cg);
  50954. g.setBrush (&gb);
  50955. g.fillPath (p);
  50956. }
  50957. {
  50958. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  50959. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  50960. g.setBrush (&gb);
  50961. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  50962. }
  50963. {
  50964. ColourGradient cg (Colours::transparentBlack,
  50965. x + diameter * 0.5f, y + diameter * 0.5f,
  50966. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50967. x, y + diameter * 0.5f, true);
  50968. cg.addColour (0.7, Colours::transparentBlack);
  50969. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  50970. GradientBrush gb (cg);
  50971. g.setBrush (&gb);
  50972. g.fillPath (p);
  50973. }
  50974. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50975. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  50976. }
  50977. void LookAndFeel::drawGlassPointer (Graphics& g,
  50978. const float x, const float y,
  50979. const float diameter,
  50980. const Colour& colour, const float outlineThickness,
  50981. const int direction) throw()
  50982. {
  50983. if (diameter <= outlineThickness)
  50984. return;
  50985. Path p;
  50986. p.startNewSubPath (x + diameter * 0.5f, y);
  50987. p.lineTo (x + diameter, y + diameter * 0.6f);
  50988. p.lineTo (x + diameter, y + diameter);
  50989. p.lineTo (x, y + diameter);
  50990. p.lineTo (x, y + diameter * 0.6f);
  50991. p.closeSubPath();
  50992. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  50993. {
  50994. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50995. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50996. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50997. GradientBrush gb (cg);
  50998. g.setBrush (&gb);
  50999. g.fillPath (p);
  51000. }
  51001. {
  51002. ColourGradient cg (Colours::transparentBlack,
  51003. x + diameter * 0.5f, y + diameter * 0.5f,
  51004. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  51005. x - diameter * 0.2f, y + diameter * 0.5f, true);
  51006. cg.addColour (0.5, Colours::transparentBlack);
  51007. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  51008. GradientBrush gb (cg);
  51009. g.setBrush (&gb);
  51010. g.fillPath (p);
  51011. }
  51012. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  51013. g.strokePath (p, PathStrokeType (outlineThickness));
  51014. }
  51015. void LookAndFeel::drawGlassLozenge (Graphics& g,
  51016. const float x, const float y,
  51017. const float width, const float height,
  51018. const Colour& colour,
  51019. const float outlineThickness,
  51020. const float cornerSize,
  51021. const bool flatOnLeft,
  51022. const bool flatOnRight,
  51023. const bool flatOnTop,
  51024. const bool flatOnBottom) throw()
  51025. {
  51026. if (width <= outlineThickness || height <= outlineThickness)
  51027. return;
  51028. const int intX = (int) x;
  51029. const int intY = (int) y;
  51030. const int intW = (int) width;
  51031. const int intH = (int) height;
  51032. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  51033. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  51034. const int intEdge = (int) edgeBlurRadius;
  51035. Path outline;
  51036. createRoundedPath (outline, x, y, width, height, cs,
  51037. ! (flatOnLeft || flatOnTop),
  51038. ! (flatOnRight || flatOnTop),
  51039. ! (flatOnLeft || flatOnBottom),
  51040. ! (flatOnRight || flatOnBottom));
  51041. {
  51042. ColourGradient cg (colour.darker (0.2f), 0, y,
  51043. colour.darker (0.2f), 0, y + height, false);
  51044. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  51045. cg.addColour (0.4, colour);
  51046. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  51047. GradientBrush gb (cg);
  51048. g.setBrush (&gb);
  51049. g.fillPath (outline);
  51050. }
  51051. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  51052. colour.darker (0.2f), x, y + height * 0.5f, true);
  51053. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  51054. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  51055. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  51056. {
  51057. GradientBrush gb (cg);
  51058. g.saveState();
  51059. g.setBrush (&gb);
  51060. g.reduceClipRegion (intX, intY, intEdge, intH);
  51061. g.fillPath (outline);
  51062. g.restoreState();
  51063. }
  51064. if (! (flatOnRight || flatOnTop || flatOnBottom))
  51065. {
  51066. cg.x1 = x + width - edgeBlurRadius;
  51067. cg.x2 = x + width;
  51068. GradientBrush gb (cg);
  51069. g.saveState();
  51070. g.setBrush (&gb);
  51071. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  51072. g.fillPath (outline);
  51073. g.restoreState();
  51074. }
  51075. {
  51076. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  51077. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  51078. Path highlight;
  51079. createRoundedPath (highlight,
  51080. x + leftIndent,
  51081. y + cs * 0.1f,
  51082. width - (leftIndent + rightIndent),
  51083. height * 0.4f, cs * 0.4f,
  51084. ! (flatOnLeft || flatOnTop),
  51085. ! (flatOnRight || flatOnTop),
  51086. ! (flatOnLeft || flatOnBottom),
  51087. ! (flatOnRight || flatOnBottom));
  51088. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  51089. Colours::transparentWhite, 0, y + height * 0.4f, false);
  51090. g.setBrush (&gb);
  51091. g.fillPath (highlight);
  51092. }
  51093. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  51094. g.strokePath (outline, PathStrokeType (outlineThickness));
  51095. }
  51096. END_JUCE_NAMESPACE
  51097. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  51098. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51099. BEGIN_JUCE_NAMESPACE
  51100. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  51101. {
  51102. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  51103. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  51104. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  51105. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  51106. setColour (Slider::thumbColourId, Colours::white);
  51107. setColour (Slider::trackColourId, Colour (0x7f000000));
  51108. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  51109. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  51110. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  51111. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  51112. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  51113. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  51114. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  51115. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  51116. }
  51117. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  51118. {
  51119. }
  51120. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  51121. Button& button,
  51122. const Colour& backgroundColour,
  51123. bool isMouseOverButton,
  51124. bool isButtonDown)
  51125. {
  51126. const int width = button.getWidth();
  51127. const int height = button.getHeight();
  51128. const float indent = 2.0f;
  51129. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  51130. roundFloatToInt (height * 0.4f));
  51131. Path p;
  51132. p.addRoundedRectangle (indent, indent,
  51133. width - indent * 2.0f,
  51134. height - indent * 2.0f,
  51135. (float) cornerSize);
  51136. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  51137. if (isMouseOverButton)
  51138. {
  51139. if (isButtonDown)
  51140. bc = bc.brighter();
  51141. else if (bc.getBrightness() > 0.5f)
  51142. bc = bc.darker (0.1f);
  51143. else
  51144. bc = bc.brighter (0.1f);
  51145. }
  51146. g.setColour (bc);
  51147. g.fillPath (p);
  51148. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  51149. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  51150. }
  51151. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  51152. Component& /*component*/,
  51153. int x, int y, int w, int h,
  51154. const bool ticked,
  51155. const bool isEnabled,
  51156. const bool /*isMouseOverButton*/,
  51157. const bool isButtonDown)
  51158. {
  51159. Path box;
  51160. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  51161. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  51162. : Colours::lightgrey.withAlpha (0.1f));
  51163. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51164. .translated ((float) x, (float) y));
  51165. g.fillPath (box, trans);
  51166. g.setColour (Colours::black.withAlpha (0.6f));
  51167. g.strokePath (box, PathStrokeType (0.9f), trans);
  51168. if (ticked)
  51169. {
  51170. Path tick;
  51171. tick.startNewSubPath (1.5f, 3.0f);
  51172. tick.lineTo (3.0f, 6.0f);
  51173. tick.lineTo (6.0f, 0.0f);
  51174. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51175. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51176. }
  51177. }
  51178. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  51179. ToggleButton& button,
  51180. bool isMouseOverButton,
  51181. bool isButtonDown)
  51182. {
  51183. if (button.hasKeyboardFocus (true))
  51184. {
  51185. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51186. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51187. }
  51188. const int tickWidth = jmin (20, button.getHeight() - 4);
  51189. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  51190. tickWidth, tickWidth,
  51191. button.getToggleState(),
  51192. button.isEnabled(),
  51193. isMouseOverButton,
  51194. isButtonDown);
  51195. g.setColour (button.findColour (ToggleButton::textColourId));
  51196. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  51197. if (! button.isEnabled())
  51198. g.setOpacity (0.5f);
  51199. const int textX = tickWidth + 5;
  51200. g.drawFittedText (button.getButtonText(),
  51201. textX, 4,
  51202. button.getWidth() - textX - 2, button.getHeight() - 8,
  51203. Justification::centredLeft, 10);
  51204. }
  51205. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51206. int width, int height,
  51207. double progress, const String& textToShow)
  51208. {
  51209. if (progress < 0 || progress >= 1.0)
  51210. {
  51211. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  51212. }
  51213. else
  51214. {
  51215. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51216. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51217. g.fillAll (background);
  51218. g.setColour (foreground);
  51219. g.fillRect (1, 1,
  51220. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  51221. height - 2);
  51222. if (textToShow.isNotEmpty())
  51223. {
  51224. g.setColour (Colour::contrasting (background, foreground));
  51225. g.setFont (height * 0.6f);
  51226. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51227. }
  51228. }
  51229. }
  51230. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  51231. ScrollBar& bar,
  51232. int width, int height,
  51233. int buttonDirection,
  51234. bool isScrollbarVertical,
  51235. bool isMouseOverButton,
  51236. bool isButtonDown)
  51237. {
  51238. if (isScrollbarVertical)
  51239. width -= 2;
  51240. else
  51241. height -= 2;
  51242. Path p;
  51243. if (buttonDirection == 0)
  51244. p.addTriangle (width * 0.5f, height * 0.2f,
  51245. width * 0.1f, height * 0.7f,
  51246. width * 0.9f, height * 0.7f);
  51247. else if (buttonDirection == 1)
  51248. p.addTriangle (width * 0.8f, height * 0.5f,
  51249. width * 0.3f, height * 0.1f,
  51250. width * 0.3f, height * 0.9f);
  51251. else if (buttonDirection == 2)
  51252. p.addTriangle (width * 0.5f, height * 0.8f,
  51253. width * 0.1f, height * 0.3f,
  51254. width * 0.9f, height * 0.3f);
  51255. else if (buttonDirection == 3)
  51256. p.addTriangle (width * 0.2f, height * 0.5f,
  51257. width * 0.7f, height * 0.1f,
  51258. width * 0.7f, height * 0.9f);
  51259. if (isButtonDown)
  51260. g.setColour (Colours::white);
  51261. else if (isMouseOverButton)
  51262. g.setColour (Colours::white.withAlpha (0.7f));
  51263. else
  51264. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  51265. g.fillPath (p);
  51266. g.setColour (Colours::black.withAlpha (0.5f));
  51267. g.strokePath (p, PathStrokeType (0.5f));
  51268. }
  51269. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  51270. ScrollBar& bar,
  51271. int x, int y,
  51272. int width, int height,
  51273. bool isScrollbarVertical,
  51274. int thumbStartPosition,
  51275. int thumbSize,
  51276. bool isMouseOver,
  51277. bool isMouseDown)
  51278. {
  51279. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  51280. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51281. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  51282. if (thumbSize > 0.0f)
  51283. {
  51284. Rectangle thumb;
  51285. if (isScrollbarVertical)
  51286. {
  51287. width -= 2;
  51288. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  51289. roundFloatToInt (width * 0.3f), height);
  51290. thumb.setBounds (x + 1, thumbStartPosition,
  51291. width - 2, thumbSize);
  51292. }
  51293. else
  51294. {
  51295. height -= 2;
  51296. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  51297. width, roundFloatToInt (height * 0.3f));
  51298. thumb.setBounds (thumbStartPosition, y + 1,
  51299. thumbSize, height - 2);
  51300. }
  51301. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51302. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  51303. g.fillRect (thumb);
  51304. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  51305. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  51306. if (thumbSize > 16)
  51307. {
  51308. for (int i = 3; --i >= 0;)
  51309. {
  51310. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  51311. g.setColour (Colours::black.withAlpha (0.15f));
  51312. if (isScrollbarVertical)
  51313. {
  51314. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  51315. g.setColour (Colours::white.withAlpha (0.15f));
  51316. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  51317. }
  51318. else
  51319. {
  51320. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  51321. g.setColour (Colours::white.withAlpha (0.15f));
  51322. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  51323. }
  51324. }
  51325. }
  51326. }
  51327. }
  51328. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  51329. {
  51330. return &scrollbarShadow;
  51331. }
  51332. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51333. {
  51334. g.fillAll (findColour (PopupMenu::backgroundColourId));
  51335. g.setColour (Colours::black.withAlpha (0.6f));
  51336. g.drawRect (0, 0, width, height);
  51337. }
  51338. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  51339. bool, MenuBarComponent& menuBar)
  51340. {
  51341. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  51342. }
  51343. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  51344. {
  51345. if (textEditor.isEnabled())
  51346. {
  51347. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  51348. g.drawRect (0, 0, width, height);
  51349. }
  51350. }
  51351. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  51352. const bool isButtonDown,
  51353. int buttonX, int buttonY,
  51354. int buttonW, int buttonH,
  51355. ComboBox& box)
  51356. {
  51357. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  51358. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  51359. : ComboBox::backgroundColourId));
  51360. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  51361. g.setColour (box.findColour (ComboBox::outlineColourId));
  51362. g.drawRect (0, 0, width, height);
  51363. const float arrowX = 0.2f;
  51364. const float arrowH = 0.3f;
  51365. if (box.isEnabled())
  51366. {
  51367. Path p;
  51368. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  51369. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  51370. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  51371. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  51372. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  51373. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  51374. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  51375. : ComboBox::buttonColourId));
  51376. g.fillPath (p);
  51377. }
  51378. }
  51379. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  51380. {
  51381. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  51382. f.setHorizontalScale (0.9f);
  51383. return f;
  51384. }
  51385. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  51386. {
  51387. Path p;
  51388. p.addTriangle (x1, y1, x2, y2, x3, y3);
  51389. g.setColour (fill);
  51390. g.fillPath (p);
  51391. g.setColour (outline);
  51392. g.strokePath (p, PathStrokeType (0.3f));
  51393. }
  51394. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  51395. int x, int y,
  51396. int w, int h,
  51397. float sliderPos,
  51398. float minSliderPos,
  51399. float maxSliderPos,
  51400. const Slider::SliderStyle style,
  51401. Slider& slider)
  51402. {
  51403. g.fillAll (slider.findColour (Slider::backgroundColourId));
  51404. if (style == Slider::LinearBar)
  51405. {
  51406. g.setColour (slider.findColour (Slider::thumbColourId));
  51407. g.fillRect (x, y, (int) sliderPos - x, h);
  51408. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  51409. g.drawRect (x, y, (int) sliderPos - x, h);
  51410. }
  51411. else
  51412. {
  51413. g.setColour (slider.findColour (Slider::trackColourId)
  51414. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  51415. if (slider.isHorizontal())
  51416. {
  51417. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  51418. w, roundFloatToInt (h * 0.2f));
  51419. }
  51420. else
  51421. {
  51422. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  51423. jmin (4, roundFloatToInt (w * 0.2f)), h);
  51424. }
  51425. float alpha = 0.35f;
  51426. if (slider.isEnabled())
  51427. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  51428. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  51429. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  51430. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  51431. {
  51432. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  51433. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  51434. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  51435. fill, outline);
  51436. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  51437. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  51438. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  51439. fill, outline);
  51440. }
  51441. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  51442. {
  51443. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51444. minSliderPos - 7.0f, y + h * 0.9f ,
  51445. minSliderPos, y + h * 0.9f,
  51446. fill, outline);
  51447. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51448. maxSliderPos, y + h * 0.9f,
  51449. maxSliderPos + 7.0f, y + h * 0.9f,
  51450. fill, outline);
  51451. }
  51452. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  51453. {
  51454. drawTriangle (g, sliderPos, y + h * 0.9f,
  51455. sliderPos - 7.0f, y + h * 0.2f,
  51456. sliderPos + 7.0f, y + h * 0.2f,
  51457. fill, outline);
  51458. }
  51459. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  51460. {
  51461. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  51462. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  51463. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  51464. fill, outline);
  51465. }
  51466. }
  51467. }
  51468. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  51469. {
  51470. if (isIncrement)
  51471. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  51472. else
  51473. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  51474. }
  51475. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  51476. {
  51477. return &scrollbarShadow;
  51478. }
  51479. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  51480. {
  51481. return 8;
  51482. }
  51483. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  51484. int w, int h,
  51485. bool isMouseOver,
  51486. bool isMouseDragging)
  51487. {
  51488. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  51489. : Colours::darkgrey);
  51490. const float lineThickness = jmin (w, h) * 0.1f;
  51491. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  51492. {
  51493. g.drawLine (w * i,
  51494. h + 1.0f,
  51495. w + 1.0f,
  51496. h * i,
  51497. lineThickness);
  51498. }
  51499. }
  51500. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  51501. {
  51502. Path shape;
  51503. if (buttonType == DocumentWindow::closeButton)
  51504. {
  51505. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  51506. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  51507. ShapeButton* const b = new ShapeButton ("close",
  51508. Colour (0x7fff3333),
  51509. Colour (0xd7ff3333),
  51510. Colour (0xf7ff3333));
  51511. b->setShape (shape, true, true, true);
  51512. return b;
  51513. }
  51514. else if (buttonType == DocumentWindow::minimiseButton)
  51515. {
  51516. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51517. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  51518. DrawablePath dp;
  51519. dp.setPath (shape);
  51520. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51521. b->setImages (&dp);
  51522. return b;
  51523. }
  51524. else if (buttonType == DocumentWindow::maximiseButton)
  51525. {
  51526. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  51527. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51528. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  51529. DrawablePath dp;
  51530. dp.setPath (shape);
  51531. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51532. b->setImages (&dp);
  51533. return b;
  51534. }
  51535. jassertfalse
  51536. return 0;
  51537. }
  51538. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  51539. int titleBarX,
  51540. int titleBarY,
  51541. int titleBarW,
  51542. int titleBarH,
  51543. Button* minimiseButton,
  51544. Button* maximiseButton,
  51545. Button* closeButton,
  51546. bool positionTitleBarButtonsOnLeft)
  51547. {
  51548. titleBarY += titleBarH / 8;
  51549. titleBarH -= titleBarH / 4;
  51550. const int buttonW = titleBarH;
  51551. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  51552. : titleBarX + titleBarW - buttonW - 4;
  51553. if (closeButton != 0)
  51554. {
  51555. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  51556. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  51557. : -(buttonW + buttonW / 5);
  51558. }
  51559. if (positionTitleBarButtonsOnLeft)
  51560. swapVariables (minimiseButton, maximiseButton);
  51561. if (maximiseButton != 0)
  51562. {
  51563. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51564. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  51565. }
  51566. if (minimiseButton != 0)
  51567. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51568. }
  51569. END_JUCE_NAMESPACE
  51570. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51571. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  51572. BEGIN_JUCE_NAMESPACE
  51573. class DummyMenuComponent : public Component
  51574. {
  51575. DummyMenuComponent (const DummyMenuComponent&);
  51576. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  51577. public:
  51578. DummyMenuComponent() {}
  51579. ~DummyMenuComponent() {}
  51580. void inputAttemptWhenModal()
  51581. {
  51582. exitModalState (0);
  51583. }
  51584. };
  51585. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  51586. : model (0),
  51587. itemUnderMouse (-1),
  51588. currentPopupIndex (-1),
  51589. indexToShowAgain (-1),
  51590. lastMouseX (0),
  51591. lastMouseY (0),
  51592. inModalState (false),
  51593. currentPopup (0)
  51594. {
  51595. setRepaintsOnMouseActivity (true);
  51596. setWantsKeyboardFocus (false);
  51597. setMouseClickGrabsKeyboardFocus (false);
  51598. setModel (model_);
  51599. }
  51600. MenuBarComponent::~MenuBarComponent()
  51601. {
  51602. setModel (0);
  51603. Desktop::getInstance().removeGlobalMouseListener (this);
  51604. deleteAndZero (currentPopup);
  51605. }
  51606. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  51607. {
  51608. if (model != newModel)
  51609. {
  51610. if (model != 0)
  51611. model->removeListener (this);
  51612. model = newModel;
  51613. if (model != 0)
  51614. model->addListener (this);
  51615. repaint();
  51616. menuBarItemsChanged (0);
  51617. }
  51618. }
  51619. void MenuBarComponent::paint (Graphics& g)
  51620. {
  51621. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  51622. getLookAndFeel().drawMenuBarBackground (g,
  51623. getWidth(),
  51624. getHeight(),
  51625. isMouseOverBar,
  51626. *this);
  51627. if (model != 0)
  51628. {
  51629. for (int i = 0; i < menuNames.size(); ++i)
  51630. {
  51631. g.saveState();
  51632. g.setOrigin (xPositions [i], 0);
  51633. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  51634. getLookAndFeel().drawMenuBarItem (g,
  51635. xPositions[i + 1] - xPositions[i],
  51636. getHeight(),
  51637. i,
  51638. menuNames[i],
  51639. i == itemUnderMouse,
  51640. i == currentPopupIndex,
  51641. isMouseOverBar,
  51642. *this);
  51643. g.restoreState();
  51644. }
  51645. }
  51646. }
  51647. void MenuBarComponent::resized()
  51648. {
  51649. xPositions.clear();
  51650. int x = 2;
  51651. xPositions.add (x);
  51652. for (int i = 0; i < menuNames.size(); ++i)
  51653. {
  51654. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  51655. xPositions.add (x);
  51656. }
  51657. }
  51658. int MenuBarComponent::getItemAt (const int x, const int y)
  51659. {
  51660. for (int i = 0; i < xPositions.size(); ++i)
  51661. if (x >= xPositions[i] && x < xPositions[i + 1])
  51662. return reallyContains (x, y, true) ? i : -1;
  51663. return -1;
  51664. }
  51665. void MenuBarComponent::repaintMenuItem (int index)
  51666. {
  51667. if (((unsigned int) index) < (unsigned int) xPositions.size())
  51668. {
  51669. const int x1 = xPositions [index];
  51670. const int x2 = xPositions [index + 1];
  51671. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  51672. }
  51673. }
  51674. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  51675. {
  51676. const int newItem = getItemAt (x, y);
  51677. if (itemUnderMouse != newItem)
  51678. {
  51679. repaintMenuItem (itemUnderMouse);
  51680. itemUnderMouse = newItem;
  51681. repaintMenuItem (itemUnderMouse);
  51682. }
  51683. }
  51684. void MenuBarComponent::hideCurrentMenu()
  51685. {
  51686. deleteAndZero (currentPopup);
  51687. repaint();
  51688. }
  51689. void MenuBarComponent::showMenu (int index)
  51690. {
  51691. if (index != currentPopupIndex)
  51692. {
  51693. if (inModalState)
  51694. {
  51695. hideCurrentMenu();
  51696. indexToShowAgain = index;
  51697. return;
  51698. }
  51699. indexToShowAgain = -1;
  51700. currentPopupIndex = -1;
  51701. itemUnderMouse = index;
  51702. deleteAndZero (currentPopup);
  51703. menuBarItemsChanged (0);
  51704. Component* const prevFocused = getCurrentlyFocusedComponent();
  51705. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  51706. if (prevFocused != 0)
  51707. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  51708. ComponentDeletionWatcher deletionChecker (this);
  51709. enterModalState (false);
  51710. inModalState = true;
  51711. int result = 0;
  51712. ApplicationCommandManager* managerOfChosenCommand = 0;
  51713. Desktop::getInstance().addGlobalMouseListener (this);
  51714. for (;;)
  51715. {
  51716. const int x = getScreenX() + xPositions [itemUnderMouse];
  51717. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  51718. currentPopupIndex = itemUnderMouse;
  51719. indexToShowAgain = -1;
  51720. repaint();
  51721. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  51722. {
  51723. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  51724. menuNames [itemUnderMouse]));
  51725. currentPopup = m.createMenuComponent (x, getScreenY(),
  51726. w, getHeight(),
  51727. 0, w, 0, 0,
  51728. true, this,
  51729. &managerOfChosenCommand,
  51730. this);
  51731. }
  51732. if (currentPopup == 0)
  51733. {
  51734. currentPopup = new DummyMenuComponent();
  51735. addAndMakeVisible (currentPopup);
  51736. }
  51737. currentPopup->enterModalState (false);
  51738. currentPopup->toFront (false); // need to do this after making it modal, or it could
  51739. // be stuck behind other comps that are already modal..
  51740. result = currentPopup->runModalLoop();
  51741. if (deletionChecker.hasBeenDeleted())
  51742. {
  51743. delete prevCompDeletionChecker;
  51744. return;
  51745. }
  51746. const int lastPopupIndex = currentPopupIndex;
  51747. deleteAndZero (currentPopup);
  51748. currentPopupIndex = -1;
  51749. if (result != 0)
  51750. {
  51751. topLevelIndexClicked = lastPopupIndex;
  51752. break;
  51753. }
  51754. else if (indexToShowAgain >= 0)
  51755. {
  51756. menuBarItemsChanged (0);
  51757. repaint();
  51758. itemUnderMouse = indexToShowAgain;
  51759. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  51760. break;
  51761. }
  51762. else
  51763. {
  51764. break;
  51765. }
  51766. }
  51767. Desktop::getInstance().removeGlobalMouseListener (this);
  51768. inModalState = false;
  51769. exitModalState (0);
  51770. if (prevCompDeletionChecker != 0)
  51771. {
  51772. if (! prevCompDeletionChecker->hasBeenDeleted())
  51773. prevFocused->grabKeyboardFocus();
  51774. delete prevCompDeletionChecker;
  51775. }
  51776. int mx, my;
  51777. getMouseXYRelative (mx, my);
  51778. updateItemUnderMouse (mx, my);
  51779. repaint();
  51780. if (result != 0)
  51781. {
  51782. if (managerOfChosenCommand != 0)
  51783. {
  51784. ApplicationCommandTarget::InvocationInfo info (result);
  51785. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51786. managerOfChosenCommand->invoke (info, true);
  51787. }
  51788. postCommandMessage (result);
  51789. }
  51790. }
  51791. }
  51792. void MenuBarComponent::handleCommandMessage (int commandId)
  51793. {
  51794. if (model != 0)
  51795. model->menuItemSelected (commandId, topLevelIndexClicked);
  51796. }
  51797. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  51798. {
  51799. if (e.eventComponent == this)
  51800. updateItemUnderMouse (e.x, e.y);
  51801. }
  51802. void MenuBarComponent::mouseExit (const MouseEvent& e)
  51803. {
  51804. if (e.eventComponent == this)
  51805. updateItemUnderMouse (e.x, e.y);
  51806. }
  51807. void MenuBarComponent::mouseDown (const MouseEvent& e)
  51808. {
  51809. const MouseEvent e2 (e.getEventRelativeTo (this));
  51810. if (currentPopupIndex < 0)
  51811. {
  51812. updateItemUnderMouse (e2.x, e2.y);
  51813. currentPopupIndex = -2;
  51814. showMenu (itemUnderMouse);
  51815. }
  51816. }
  51817. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  51818. {
  51819. const MouseEvent e2 (e.getEventRelativeTo (this));
  51820. const int item = getItemAt (e2.x, e2.y);
  51821. if (item >= 0)
  51822. showMenu (item);
  51823. }
  51824. void MenuBarComponent::mouseUp (const MouseEvent& e)
  51825. {
  51826. const MouseEvent e2 (e.getEventRelativeTo (this));
  51827. updateItemUnderMouse (e2.x, e2.y);
  51828. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  51829. hideCurrentMenu();
  51830. }
  51831. void MenuBarComponent::mouseMove (const MouseEvent& e)
  51832. {
  51833. const MouseEvent e2 (e.getEventRelativeTo (this));
  51834. if (lastMouseX != e2.x || lastMouseY != e2.y)
  51835. {
  51836. if (currentPopupIndex >= 0)
  51837. {
  51838. const int item = getItemAt (e2.x, e2.y);
  51839. if (item >= 0)
  51840. showMenu (item);
  51841. }
  51842. else
  51843. {
  51844. updateItemUnderMouse (e2.x, e2.y);
  51845. }
  51846. lastMouseX = e2.x;
  51847. lastMouseY = e2.y;
  51848. }
  51849. }
  51850. bool MenuBarComponent::keyPressed (const KeyPress& key)
  51851. {
  51852. bool used = false;
  51853. const int numMenus = menuNames.size();
  51854. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  51855. if (key.isKeyCode (KeyPress::leftKey))
  51856. {
  51857. showMenu ((currentIndex + numMenus - 1) % numMenus);
  51858. used = true;
  51859. }
  51860. else if (key.isKeyCode (KeyPress::rightKey))
  51861. {
  51862. showMenu ((currentIndex + 1) % numMenus);
  51863. used = true;
  51864. }
  51865. return used;
  51866. }
  51867. void MenuBarComponent::inputAttemptWhenModal()
  51868. {
  51869. hideCurrentMenu();
  51870. }
  51871. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  51872. {
  51873. StringArray newNames;
  51874. if (model != 0)
  51875. newNames = model->getMenuBarNames();
  51876. if (newNames != menuNames)
  51877. {
  51878. menuNames = newNames;
  51879. repaint();
  51880. resized();
  51881. }
  51882. }
  51883. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  51884. const ApplicationCommandTarget::InvocationInfo& info)
  51885. {
  51886. if (model == 0
  51887. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  51888. return;
  51889. for (int i = 0; i < menuNames.size(); ++i)
  51890. {
  51891. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  51892. if (menu.containsCommandItem (info.commandID))
  51893. {
  51894. itemUnderMouse = i;
  51895. repaintMenuItem (i);
  51896. startTimer (200);
  51897. break;
  51898. }
  51899. }
  51900. }
  51901. void MenuBarComponent::timerCallback()
  51902. {
  51903. stopTimer();
  51904. int mx, my;
  51905. getMouseXYRelative (mx, my);
  51906. updateItemUnderMouse (mx, my);
  51907. }
  51908. END_JUCE_NAMESPACE
  51909. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  51910. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  51911. BEGIN_JUCE_NAMESPACE
  51912. MenuBarModel::MenuBarModel() throw()
  51913. : manager (0)
  51914. {
  51915. }
  51916. MenuBarModel::~MenuBarModel()
  51917. {
  51918. setApplicationCommandManagerToWatch (0);
  51919. }
  51920. void MenuBarModel::menuItemsChanged()
  51921. {
  51922. triggerAsyncUpdate();
  51923. }
  51924. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  51925. {
  51926. if (manager != newManager)
  51927. {
  51928. if (manager != 0)
  51929. manager->removeListener (this);
  51930. manager = newManager;
  51931. if (manager != 0)
  51932. manager->addListener (this);
  51933. }
  51934. }
  51935. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  51936. {
  51937. jassert (newListener != 0);
  51938. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  51939. if (newListener != 0)
  51940. listeners.add (newListener);
  51941. }
  51942. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  51943. {
  51944. // Trying to remove a listener that isn't on the list!
  51945. // If this assertion happens because this object is a dangling pointer, make sure you've not
  51946. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  51947. jassert (listeners.contains (listenerToRemove));
  51948. listeners.removeValue (listenerToRemove);
  51949. }
  51950. void MenuBarModel::handleAsyncUpdate()
  51951. {
  51952. for (int i = listeners.size(); --i >= 0;)
  51953. {
  51954. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  51955. i = jmin (i, listeners.size());
  51956. }
  51957. }
  51958. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  51959. {
  51960. for (int i = listeners.size(); --i >= 0;)
  51961. {
  51962. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  51963. i = jmin (i, listeners.size());
  51964. }
  51965. }
  51966. void MenuBarModel::applicationCommandListChanged()
  51967. {
  51968. menuItemsChanged();
  51969. }
  51970. END_JUCE_NAMESPACE
  51971. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  51972. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  51973. BEGIN_JUCE_NAMESPACE
  51974. static VoidArray activeMenuWindows;
  51975. class MenuItemInfo
  51976. {
  51977. public:
  51978. const int itemId;
  51979. String text;
  51980. const Colour textColour;
  51981. const bool active, isSeparator, isTicked, usesColour;
  51982. Image* image;
  51983. PopupMenuCustomComponent* const customComp;
  51984. PopupMenu* subMenu;
  51985. ApplicationCommandManager* const commandManager;
  51986. MenuItemInfo() throw()
  51987. : itemId (0),
  51988. active (true),
  51989. isSeparator (true),
  51990. isTicked (false),
  51991. usesColour (false),
  51992. image (0),
  51993. customComp (0),
  51994. subMenu (0),
  51995. commandManager (0)
  51996. {
  51997. }
  51998. MenuItemInfo (const int itemId_,
  51999. const String& text_,
  52000. const bool active_,
  52001. const bool isTicked_,
  52002. const Image* im,
  52003. const Colour& textColour_,
  52004. const bool usesColour_,
  52005. PopupMenuCustomComponent* const customComp_,
  52006. const PopupMenu* const subMenu_,
  52007. ApplicationCommandManager* const commandManager_) throw()
  52008. : itemId (itemId_),
  52009. text (text_),
  52010. textColour (textColour_),
  52011. active (active_),
  52012. isSeparator (false),
  52013. isTicked (isTicked_),
  52014. usesColour (usesColour_),
  52015. image (0),
  52016. customComp (customComp_),
  52017. commandManager (commandManager_)
  52018. {
  52019. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  52020. if (customComp != 0)
  52021. customComp->refCount_++;
  52022. if (im != 0)
  52023. image = im->createCopy();
  52024. if (commandManager_ != 0 && itemId_ != 0)
  52025. {
  52026. String shortcutKey;
  52027. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  52028. ->getKeyPressesAssignedToCommand (itemId_));
  52029. for (int i = 0; i < keyPresses.size(); ++i)
  52030. {
  52031. const String key (keyPresses.getReference(i).getTextDescription());
  52032. if (shortcutKey.isNotEmpty())
  52033. shortcutKey << ", ";
  52034. if (key.length() == 1)
  52035. shortcutKey << "shortcut: '" << key << '\'';
  52036. else
  52037. shortcutKey << key;
  52038. }
  52039. shortcutKey = shortcutKey.trim();
  52040. if (shortcutKey.isNotEmpty())
  52041. text << "<end>" << shortcutKey;
  52042. }
  52043. }
  52044. MenuItemInfo (const MenuItemInfo& other) throw()
  52045. : itemId (other.itemId),
  52046. text (other.text),
  52047. textColour (other.textColour),
  52048. active (other.active),
  52049. isSeparator (other.isSeparator),
  52050. isTicked (other.isTicked),
  52051. usesColour (other.usesColour),
  52052. customComp (other.customComp),
  52053. commandManager (other.commandManager)
  52054. {
  52055. if (other.subMenu != 0)
  52056. subMenu = new PopupMenu (*(other.subMenu));
  52057. else
  52058. subMenu = 0;
  52059. if (other.image != 0)
  52060. image = other.image->createCopy();
  52061. else
  52062. image = 0;
  52063. if (customComp != 0)
  52064. customComp->refCount_++;
  52065. }
  52066. ~MenuItemInfo() throw()
  52067. {
  52068. delete subMenu;
  52069. delete image;
  52070. if (customComp != 0 && --(customComp->refCount_) == 0)
  52071. delete customComp;
  52072. }
  52073. bool canBeTriggered() const throw()
  52074. {
  52075. return active && ! (isSeparator || (subMenu != 0));
  52076. }
  52077. bool hasActiveSubMenu() const throw()
  52078. {
  52079. return active && (subMenu != 0);
  52080. }
  52081. juce_UseDebuggingNewOperator
  52082. private:
  52083. const MenuItemInfo& operator= (const MenuItemInfo&);
  52084. };
  52085. class MenuItemComponent : public Component
  52086. {
  52087. bool isHighlighted;
  52088. public:
  52089. MenuItemInfo itemInfo;
  52090. MenuItemComponent (const MenuItemInfo& itemInfo_)
  52091. : isHighlighted (false),
  52092. itemInfo (itemInfo_)
  52093. {
  52094. if (itemInfo.customComp != 0)
  52095. addAndMakeVisible (itemInfo.customComp);
  52096. }
  52097. ~MenuItemComponent()
  52098. {
  52099. if (itemInfo.customComp != 0)
  52100. removeChildComponent (itemInfo.customComp);
  52101. }
  52102. void getIdealSize (int& idealWidth,
  52103. int& idealHeight,
  52104. const int standardItemHeight)
  52105. {
  52106. if (itemInfo.customComp != 0)
  52107. {
  52108. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  52109. }
  52110. else
  52111. {
  52112. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  52113. itemInfo.isSeparator,
  52114. standardItemHeight,
  52115. idealWidth,
  52116. idealHeight);
  52117. }
  52118. }
  52119. void paint (Graphics& g)
  52120. {
  52121. if (itemInfo.customComp == 0)
  52122. {
  52123. String mainText (itemInfo.text);
  52124. String endText;
  52125. const int endIndex = mainText.indexOf (T("<end>"));
  52126. if (endIndex >= 0)
  52127. {
  52128. endText = mainText.substring (endIndex + 5).trim();
  52129. mainText = mainText.substring (0, endIndex);
  52130. }
  52131. getLookAndFeel()
  52132. .drawPopupMenuItem (g, getWidth(), getHeight(),
  52133. itemInfo.isSeparator,
  52134. itemInfo.active,
  52135. isHighlighted,
  52136. itemInfo.isTicked,
  52137. itemInfo.subMenu != 0,
  52138. mainText, endText,
  52139. itemInfo.image,
  52140. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  52141. }
  52142. }
  52143. void resized()
  52144. {
  52145. if (getNumChildComponents() > 0)
  52146. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  52147. }
  52148. void setHighlighted (bool shouldBeHighlighted)
  52149. {
  52150. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  52151. if (isHighlighted != shouldBeHighlighted)
  52152. {
  52153. isHighlighted = shouldBeHighlighted;
  52154. if (itemInfo.customComp != 0)
  52155. {
  52156. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  52157. itemInfo.customComp->repaint();
  52158. }
  52159. repaint();
  52160. }
  52161. }
  52162. private:
  52163. MenuItemComponent (const MenuItemComponent&);
  52164. const MenuItemComponent& operator= (const MenuItemComponent&);
  52165. };
  52166. static const int scrollZone = 24;
  52167. static const int borderSize = 2;
  52168. static const int timerInterval = 50;
  52169. static const int dismissCommandId = 0x6287345f;
  52170. static bool wasHiddenBecauseOfAppChange = false;
  52171. class PopupMenuWindow : public Component,
  52172. private Timer
  52173. {
  52174. public:
  52175. PopupMenuWindow() throw()
  52176. : Component (T("menu")),
  52177. owner (0),
  52178. currentChild (0),
  52179. activeSubMenu (0),
  52180. menuBarComponent (0),
  52181. managerOfChosenCommand (0),
  52182. componentAttachedTo (0),
  52183. attachedCompWatcher (0),
  52184. lastMouseX (0),
  52185. lastMouseY (0),
  52186. minimumWidth (0),
  52187. maximumNumColumns (7),
  52188. standardItemHeight (0),
  52189. isOver (false),
  52190. hasBeenOver (false),
  52191. isDown (false),
  52192. needsToScroll (false),
  52193. hideOnExit (false),
  52194. disableMouseMoves (false),
  52195. hasAnyJuceCompHadFocus (false),
  52196. numColumns (0),
  52197. contentHeight (0),
  52198. childYOffset (0),
  52199. timeEnteredCurrentChildComp (0),
  52200. scrollAcceleration (1.0)
  52201. {
  52202. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  52203. setWantsKeyboardFocus (true);
  52204. setMouseClickGrabsKeyboardFocus (false);
  52205. setOpaque (true);
  52206. setAlwaysOnTop (true);
  52207. Desktop::getInstance().addGlobalMouseListener (this);
  52208. activeMenuWindows.add (this);
  52209. }
  52210. ~PopupMenuWindow()
  52211. {
  52212. activeMenuWindows.removeValue (this);
  52213. Desktop::getInstance().removeGlobalMouseListener (this);
  52214. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52215. delete activeSubMenu;
  52216. deleteAllChildren();
  52217. delete attachedCompWatcher;
  52218. }
  52219. static PopupMenuWindow* create (const PopupMenu& menu,
  52220. const bool dismissOnMouseUp,
  52221. PopupMenuWindow* const owner_,
  52222. const int minX, const int maxX,
  52223. const int minY, const int maxY,
  52224. const int minimumWidth,
  52225. const int maximumNumColumns,
  52226. const int standardItemHeight,
  52227. const bool alignToRectangle,
  52228. const int itemIdThatMustBeVisible,
  52229. Component* const menuBarComponent,
  52230. ApplicationCommandManager** managerOfChosenCommand,
  52231. Component* const componentAttachedTo) throw()
  52232. {
  52233. if (menu.items.size() > 0)
  52234. {
  52235. int totalItems = 0;
  52236. PopupMenuWindow* const mw = new PopupMenuWindow();
  52237. mw->setLookAndFeel (menu.lookAndFeel);
  52238. mw->setWantsKeyboardFocus (false);
  52239. mw->minimumWidth = minimumWidth;
  52240. mw->maximumNumColumns = maximumNumColumns;
  52241. mw->standardItemHeight = standardItemHeight;
  52242. mw->dismissOnMouseUp = dismissOnMouseUp;
  52243. for (int i = 0; i < menu.items.size(); ++i)
  52244. {
  52245. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  52246. mw->addItem (*item);
  52247. ++totalItems;
  52248. }
  52249. if (totalItems == 0)
  52250. {
  52251. delete mw;
  52252. }
  52253. else
  52254. {
  52255. mw->owner = owner_;
  52256. mw->menuBarComponent = menuBarComponent;
  52257. mw->managerOfChosenCommand = managerOfChosenCommand;
  52258. mw->componentAttachedTo = componentAttachedTo;
  52259. delete mw->attachedCompWatcher;
  52260. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  52261. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  52262. mw->setTopLeftPosition (mw->windowPos.getX(),
  52263. mw->windowPos.getY());
  52264. mw->updateYPositions();
  52265. if (itemIdThatMustBeVisible != 0)
  52266. {
  52267. const int y = minY - mw->windowPos.getY();
  52268. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  52269. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  52270. }
  52271. mw->resizeToBestWindowPos();
  52272. mw->addToDesktop (ComponentPeer::windowIsTemporary
  52273. | mw->getLookAndFeel().getMenuWindowFlags());
  52274. return mw;
  52275. }
  52276. }
  52277. return 0;
  52278. }
  52279. void paint (Graphics& g)
  52280. {
  52281. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  52282. }
  52283. void paintOverChildren (Graphics& g)
  52284. {
  52285. if (isScrolling())
  52286. {
  52287. LookAndFeel& lf = getLookAndFeel();
  52288. if (isScrollZoneActive (false))
  52289. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  52290. if (isScrollZoneActive (true))
  52291. {
  52292. g.setOrigin (0, getHeight() - scrollZone);
  52293. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  52294. }
  52295. }
  52296. }
  52297. bool isScrollZoneActive (bool bottomOne) const
  52298. {
  52299. return isScrolling()
  52300. && (bottomOne
  52301. ? childYOffset < contentHeight - windowPos.getHeight()
  52302. : childYOffset > 0);
  52303. }
  52304. void addItem (const MenuItemInfo& item) throw()
  52305. {
  52306. MenuItemComponent* const mic = new MenuItemComponent (item);
  52307. addAndMakeVisible (mic);
  52308. int itemW = 80;
  52309. int itemH = 16;
  52310. mic->getIdealSize (itemW, itemH, standardItemHeight);
  52311. mic->setSize (itemW, jlimit (2, 600, itemH));
  52312. mic->addMouseListener (this, false);
  52313. }
  52314. // hide this and all sub-comps
  52315. void hide (const MenuItemInfo* const item) throw()
  52316. {
  52317. if (isVisible())
  52318. {
  52319. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52320. deleteAndZero (activeSubMenu);
  52321. currentChild = 0;
  52322. exitModalState (item != 0 ? item->itemId : 0);
  52323. setVisible (false);
  52324. if (item != 0
  52325. && item->commandManager != 0
  52326. && item->itemId != 0)
  52327. {
  52328. *managerOfChosenCommand = item->commandManager;
  52329. }
  52330. }
  52331. }
  52332. void dismissMenu (const MenuItemInfo* const item) throw()
  52333. {
  52334. if (owner != 0)
  52335. {
  52336. owner->dismissMenu (item);
  52337. }
  52338. else
  52339. {
  52340. if (item != 0)
  52341. {
  52342. // need a copy of this on the stack as the one passed in will get deleted during this call
  52343. const MenuItemInfo mi (*item);
  52344. hide (&mi);
  52345. }
  52346. else
  52347. {
  52348. hide (0);
  52349. }
  52350. }
  52351. }
  52352. void mouseMove (const MouseEvent&)
  52353. {
  52354. timerCallback();
  52355. }
  52356. void mouseDown (const MouseEvent&)
  52357. {
  52358. timerCallback();
  52359. }
  52360. void mouseDrag (const MouseEvent&)
  52361. {
  52362. timerCallback();
  52363. }
  52364. void mouseUp (const MouseEvent&)
  52365. {
  52366. timerCallback();
  52367. }
  52368. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  52369. {
  52370. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  52371. lastMouseX = -1;
  52372. }
  52373. bool keyPressed (const KeyPress& key)
  52374. {
  52375. if (key.isKeyCode (KeyPress::downKey))
  52376. {
  52377. selectNextItem (1);
  52378. }
  52379. else if (key.isKeyCode (KeyPress::upKey))
  52380. {
  52381. selectNextItem (-1);
  52382. }
  52383. else if (key.isKeyCode (KeyPress::leftKey))
  52384. {
  52385. PopupMenuWindow* parentWindow = owner;
  52386. if (parentWindow != 0)
  52387. {
  52388. MenuItemComponent* currentChildOfParent
  52389. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  52390. hide (0);
  52391. if (parentWindow->isValidComponent())
  52392. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  52393. disableTimerUntilMouseMoves();
  52394. }
  52395. else if (menuBarComponent != 0)
  52396. {
  52397. menuBarComponent->keyPressed (key);
  52398. }
  52399. }
  52400. else if (key.isKeyCode (KeyPress::rightKey))
  52401. {
  52402. disableTimerUntilMouseMoves();
  52403. if (showSubMenuFor (currentChild))
  52404. {
  52405. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52406. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  52407. activeSubMenu->selectNextItem (1);
  52408. }
  52409. else if (menuBarComponent != 0)
  52410. {
  52411. menuBarComponent->keyPressed (key);
  52412. }
  52413. }
  52414. else if (key.isKeyCode (KeyPress::returnKey))
  52415. {
  52416. triggerCurrentlyHighlightedItem();
  52417. }
  52418. else if (key.isKeyCode (KeyPress::escapeKey))
  52419. {
  52420. dismissMenu (0);
  52421. }
  52422. else
  52423. {
  52424. return false;
  52425. }
  52426. return true;
  52427. }
  52428. void inputAttemptWhenModal()
  52429. {
  52430. timerCallback();
  52431. if (! isOverAnyMenu())
  52432. {
  52433. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  52434. {
  52435. // we want to dismiss the menu, but if we do it synchronously, then
  52436. // the mouse-click will be allowed to pass through. That's good, except
  52437. // when the user clicks on the button that orginally popped the menu up,
  52438. // as they'll expect the menu to go away, and in fact it'll just
  52439. // come back. So only dismiss synchronously if they're not on the original
  52440. // comp that we're attached to.
  52441. int mx, my;
  52442. componentAttachedTo->getMouseXYRelative (mx, my);
  52443. if (componentAttachedTo->reallyContains (mx, my, true))
  52444. {
  52445. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  52446. return;
  52447. }
  52448. }
  52449. dismissMenu (0);
  52450. }
  52451. }
  52452. void handleCommandMessage (int commandId)
  52453. {
  52454. Component::handleCommandMessage (commandId);
  52455. if (commandId == dismissCommandId)
  52456. dismissMenu (0);
  52457. }
  52458. void timerCallback()
  52459. {
  52460. if (! isVisible())
  52461. return;
  52462. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  52463. {
  52464. dismissMenu (0);
  52465. return;
  52466. }
  52467. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  52468. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  52469. return;
  52470. startTimer (timerInterval); // do this in case it was called from a mouse
  52471. // move rather than a real timer callback
  52472. int mx, my;
  52473. Desktop::getMousePosition (mx, my);
  52474. int x = mx, y = my;
  52475. globalPositionToRelative (x, y);
  52476. const uint32 now = Time::getMillisecondCounter();
  52477. if (now > timeEnteredCurrentChildComp + 100
  52478. && reallyContains (x, y, true)
  52479. && currentChild->isValidComponent()
  52480. && (! disableMouseMoves)
  52481. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  52482. {
  52483. showSubMenuFor (currentChild);
  52484. }
  52485. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  52486. {
  52487. highlightItemUnderMouse (mx, my, x, y);
  52488. }
  52489. bool overScrollArea = false;
  52490. if (isScrolling()
  52491. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  52492. && ((isScrollZoneActive (false) && y < scrollZone)
  52493. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  52494. {
  52495. if (now > lastScroll + 20)
  52496. {
  52497. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  52498. int amount = 0;
  52499. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  52500. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  52501. alterChildYPos (y < scrollZone ? -amount : amount);
  52502. lastScroll = now;
  52503. }
  52504. overScrollArea = true;
  52505. lastMouseX = -1; // trigger a mouse-move
  52506. }
  52507. else
  52508. {
  52509. scrollAcceleration = 1.0;
  52510. }
  52511. const bool wasDown = isDown;
  52512. bool isOverAny = isOverAnyMenu();
  52513. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  52514. {
  52515. activeSubMenu->updateMouseOverStatus (mx, my);
  52516. isOverAny = isOverAnyMenu();
  52517. }
  52518. if (hideOnExit && hasBeenOver && ! isOverAny)
  52519. {
  52520. hide (0);
  52521. }
  52522. else
  52523. {
  52524. isDown = hasBeenOver
  52525. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  52526. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  52527. bool anyFocused = Process::isForegroundProcess();
  52528. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  52529. {
  52530. // because no component at all may have focus, our test here will
  52531. // only be triggered when something has focus and then loses it.
  52532. anyFocused = ! hasAnyJuceCompHadFocus;
  52533. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  52534. {
  52535. if (ComponentPeer::getPeer (i)->isFocused())
  52536. {
  52537. anyFocused = true;
  52538. hasAnyJuceCompHadFocus = true;
  52539. break;
  52540. }
  52541. }
  52542. }
  52543. if (! anyFocused)
  52544. {
  52545. if (now > lastFocused + 10)
  52546. {
  52547. wasHiddenBecauseOfAppChange = true;
  52548. dismissMenu (0);
  52549. return; // may have been deleted by the previous call..
  52550. }
  52551. }
  52552. else if (wasDown && now > menuCreationTime + 250
  52553. && ! (isDown || overScrollArea))
  52554. {
  52555. isOver = reallyContains (x, y, true);
  52556. if (isOver)
  52557. {
  52558. triggerCurrentlyHighlightedItem();
  52559. }
  52560. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  52561. {
  52562. dismissMenu (0);
  52563. }
  52564. return; // may have been deleted by the previous calls..
  52565. }
  52566. else
  52567. {
  52568. lastFocused = now;
  52569. }
  52570. }
  52571. }
  52572. juce_UseDebuggingNewOperator
  52573. private:
  52574. PopupMenuWindow* owner;
  52575. MenuItemComponent* currentChild;
  52576. PopupMenuWindow* activeSubMenu;
  52577. Component* menuBarComponent;
  52578. ApplicationCommandManager** managerOfChosenCommand;
  52579. Component* componentAttachedTo;
  52580. ComponentDeletionWatcher* attachedCompWatcher;
  52581. Rectangle windowPos;
  52582. int lastMouseX, lastMouseY;
  52583. int minimumWidth, maximumNumColumns, standardItemHeight;
  52584. bool isOver, hasBeenOver, isDown, needsToScroll;
  52585. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  52586. int numColumns, contentHeight, childYOffset;
  52587. Array <int> columnWidths;
  52588. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  52589. double scrollAcceleration;
  52590. bool overlaps (const Rectangle& r) const throw()
  52591. {
  52592. return r.intersects (getBounds())
  52593. || (owner != 0 && owner->overlaps (r));
  52594. }
  52595. bool isOverAnyMenu() const throw()
  52596. {
  52597. return (owner != 0) ? owner->isOverAnyMenu()
  52598. : isOverChildren();
  52599. }
  52600. bool isOverChildren() const throw()
  52601. {
  52602. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52603. return isVisible()
  52604. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  52605. }
  52606. void updateMouseOverStatus (const int mx, const int my) throw()
  52607. {
  52608. int rx = mx, ry = my;
  52609. globalPositionToRelative (rx, ry);
  52610. isOver = reallyContains (rx, ry, true);
  52611. if (activeSubMenu != 0)
  52612. activeSubMenu->updateMouseOverStatus (mx, my);
  52613. }
  52614. bool treeContains (const PopupMenuWindow* const window) const throw()
  52615. {
  52616. const PopupMenuWindow* mw = this;
  52617. while (mw->owner != 0)
  52618. mw = mw->owner;
  52619. while (mw != 0)
  52620. {
  52621. if (mw == window)
  52622. return true;
  52623. mw = mw->activeSubMenu;
  52624. }
  52625. return false;
  52626. }
  52627. void calculateWindowPos (const int minX, const int maxX,
  52628. const int minY, const int maxY,
  52629. const bool alignToRectangle)
  52630. {
  52631. const Rectangle mon (Desktop::getInstance()
  52632. .getMonitorAreaContaining ((minX + maxX) / 2,
  52633. (minY + maxY) / 2,
  52634. #if JUCE_MAC
  52635. true));
  52636. #else
  52637. false)); // on windows, don't stop the menu overlapping the taskbar
  52638. #endif
  52639. int x, y, widthToUse, heightToUse;
  52640. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  52641. if (alignToRectangle)
  52642. {
  52643. x = minX;
  52644. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  52645. const int spaceOver = minY - mon.getY();
  52646. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  52647. y = maxY;
  52648. else
  52649. y = minY - heightToUse;
  52650. }
  52651. else
  52652. {
  52653. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  52654. if (owner != 0)
  52655. {
  52656. if (owner->owner != 0)
  52657. {
  52658. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  52659. > owner->owner->getX() + owner->owner->getWidth() / 2);
  52660. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  52661. tendTowardsRight = true;
  52662. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  52663. tendTowardsRight = false;
  52664. }
  52665. else if (maxX + widthToUse < mon.getRight() - 32)
  52666. {
  52667. tendTowardsRight = true;
  52668. }
  52669. }
  52670. const int biggestSpace = jmax (mon.getRight() - maxX,
  52671. minX - mon.getX()) - 32;
  52672. if (biggestSpace < widthToUse)
  52673. {
  52674. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  52675. if (numColumns > 1)
  52676. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  52677. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  52678. }
  52679. if (tendTowardsRight)
  52680. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  52681. else
  52682. x = jmax (mon.getX() + 4, minX - widthToUse);
  52683. y = minY;
  52684. if ((minY + maxY) / 2 > mon.getCentreY())
  52685. y = jmax (mon.getY(), maxY - heightToUse);
  52686. }
  52687. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  52688. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  52689. windowPos.setBounds (x, y, widthToUse, heightToUse);
  52690. // sets this flag if it's big enough to obscure any of its parent menus
  52691. hideOnExit = (owner != 0)
  52692. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  52693. }
  52694. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  52695. {
  52696. numColumns = 0;
  52697. contentHeight = 0;
  52698. const int maxMenuH = getParentHeight() - 24;
  52699. int totalW;
  52700. do
  52701. {
  52702. ++numColumns;
  52703. totalW = workOutBestSize (numColumns, maxMenuW);
  52704. if (totalW > maxMenuW)
  52705. {
  52706. numColumns = jmax (1, numColumns - 1);
  52707. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  52708. break;
  52709. }
  52710. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  52711. {
  52712. break;
  52713. }
  52714. } while (numColumns < maximumNumColumns);
  52715. const int actualH = jmin (contentHeight, maxMenuH);
  52716. needsToScroll = contentHeight > actualH;
  52717. width = updateYPositions();
  52718. height = actualH + borderSize * 2;
  52719. }
  52720. int workOutBestSize (const int numColumns, const int maxMenuW)
  52721. {
  52722. int totalW = 0;
  52723. contentHeight = 0;
  52724. int childNum = 0;
  52725. for (int col = 0; col < numColumns; ++col)
  52726. {
  52727. int i, colW = 50, colH = 0;
  52728. const int numChildren = jmin (getNumChildComponents() - childNum,
  52729. (getNumChildComponents() + numColumns - 1) / numColumns);
  52730. for (i = numChildren; --i >= 0;)
  52731. {
  52732. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  52733. colH += getChildComponent (childNum + i)->getHeight();
  52734. }
  52735. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  52736. columnWidths.set (col, colW);
  52737. totalW += colW;
  52738. contentHeight = jmax (contentHeight, colH);
  52739. childNum += numChildren;
  52740. }
  52741. if (totalW < minimumWidth)
  52742. {
  52743. totalW = minimumWidth;
  52744. for (int col = 0; col < numColumns; ++col)
  52745. columnWidths.set (0, totalW / numColumns);
  52746. }
  52747. return totalW;
  52748. }
  52749. void ensureItemIsVisible (const int itemId, int wantedY)
  52750. {
  52751. jassert (itemId != 0)
  52752. for (int i = getNumChildComponents(); --i >= 0;)
  52753. {
  52754. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  52755. if (m != 0
  52756. && m->itemInfo.itemId == itemId
  52757. && windowPos.getHeight() > scrollZone * 4)
  52758. {
  52759. const int currentY = m->getY();
  52760. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  52761. {
  52762. if (wantedY < 0)
  52763. wantedY = jlimit (scrollZone,
  52764. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  52765. currentY);
  52766. const Rectangle mon (Desktop::getInstance()
  52767. .getMonitorAreaContaining (windowPos.getX(),
  52768. windowPos.getY(),
  52769. true));
  52770. int deltaY = wantedY - currentY;
  52771. const int newY = jlimit (mon.getY(),
  52772. mon.getBottom() - windowPos.getHeight(),
  52773. windowPos.getY() + deltaY);
  52774. deltaY -= newY - windowPos.getY();
  52775. childYOffset -= deltaY;
  52776. windowPos.setPosition (windowPos.getX(), newY);
  52777. updateYPositions();
  52778. }
  52779. break;
  52780. }
  52781. }
  52782. }
  52783. void resizeToBestWindowPos()
  52784. {
  52785. Rectangle r (windowPos);
  52786. if (childYOffset < 0)
  52787. {
  52788. r.setBounds (r.getX(), r.getY() - childYOffset,
  52789. r.getWidth(), r.getHeight() + childYOffset);
  52790. }
  52791. else if (childYOffset > 0)
  52792. {
  52793. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  52794. if (spaceAtBottom > 0)
  52795. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  52796. }
  52797. setBounds (r);
  52798. updateYPositions();
  52799. }
  52800. void alterChildYPos (const int delta)
  52801. {
  52802. if (isScrolling())
  52803. {
  52804. childYOffset += delta;
  52805. if (delta < 0)
  52806. {
  52807. childYOffset = jmax (childYOffset, 0);
  52808. }
  52809. else if (delta > 0)
  52810. {
  52811. childYOffset = jmin (childYOffset,
  52812. contentHeight - windowPos.getHeight() + borderSize);
  52813. }
  52814. updateYPositions();
  52815. }
  52816. else
  52817. {
  52818. childYOffset = 0;
  52819. }
  52820. resizeToBestWindowPos();
  52821. repaint();
  52822. }
  52823. int updateYPositions()
  52824. {
  52825. int x = 0;
  52826. int childNum = 0;
  52827. for (int col = 0; col < numColumns; ++col)
  52828. {
  52829. const int numChildren = jmin (getNumChildComponents() - childNum,
  52830. (getNumChildComponents() + numColumns - 1) / numColumns);
  52831. const int colW = columnWidths [col];
  52832. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  52833. for (int i = 0; i < numChildren; ++i)
  52834. {
  52835. Component* const c = getChildComponent (childNum + i);
  52836. c->setBounds (x, y, colW, c->getHeight());
  52837. y += c->getHeight();
  52838. }
  52839. x += colW;
  52840. childNum += numChildren;
  52841. }
  52842. return x;
  52843. }
  52844. bool isScrolling() const throw()
  52845. {
  52846. return childYOffset != 0 || needsToScroll;
  52847. }
  52848. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  52849. {
  52850. if (currentChild->isValidComponent())
  52851. currentChild->setHighlighted (false);
  52852. currentChild = child;
  52853. if (currentChild != 0)
  52854. {
  52855. currentChild->setHighlighted (true);
  52856. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  52857. }
  52858. }
  52859. bool showSubMenuFor (MenuItemComponent* const childComp)
  52860. {
  52861. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52862. deleteAndZero (activeSubMenu);
  52863. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  52864. {
  52865. int left = 0, top = 0;
  52866. childComp->relativePositionToGlobal (left, top);
  52867. int right = childComp->getWidth(), bottom = childComp->getHeight();
  52868. childComp->relativePositionToGlobal (right, bottom);
  52869. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  52870. dismissOnMouseUp,
  52871. this,
  52872. left, right, top, bottom,
  52873. 0, maximumNumColumns,
  52874. standardItemHeight,
  52875. false, 0, menuBarComponent,
  52876. managerOfChosenCommand,
  52877. componentAttachedTo);
  52878. if (activeSubMenu != 0)
  52879. {
  52880. activeSubMenu->setVisible (true);
  52881. activeSubMenu->enterModalState (false);
  52882. activeSubMenu->toFront (false);
  52883. return true;
  52884. }
  52885. }
  52886. return false;
  52887. }
  52888. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  52889. {
  52890. isOver = reallyContains (x, y, true);
  52891. if (isOver)
  52892. hasBeenOver = true;
  52893. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  52894. {
  52895. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  52896. if (disableMouseMoves && isOver)
  52897. disableMouseMoves = false;
  52898. }
  52899. if (disableMouseMoves)
  52900. return;
  52901. bool isMovingTowardsMenu = false;
  52902. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  52903. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  52904. {
  52905. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  52906. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  52907. // extends from the last mouse pos to the submenu's rectangle..
  52908. float subX = (float) activeSubMenu->getScreenX();
  52909. if (activeSubMenu->getX() > getX())
  52910. {
  52911. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  52912. }
  52913. else
  52914. {
  52915. lastMouseX += 2;
  52916. subX += activeSubMenu->getWidth();
  52917. }
  52918. Path areaTowardsSubMenu;
  52919. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  52920. (float) lastMouseY,
  52921. subX,
  52922. (float) activeSubMenu->getScreenY(),
  52923. subX,
  52924. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  52925. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  52926. }
  52927. lastMouseX = mx;
  52928. lastMouseY = my;
  52929. if (! isMovingTowardsMenu)
  52930. {
  52931. Component* c = getComponentAt (x, y);
  52932. if (c == this)
  52933. c = 0;
  52934. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  52935. if (mic == 0 && c != 0)
  52936. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  52937. if (mic != currentChild
  52938. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  52939. {
  52940. if (isOver && (c != 0) && (activeSubMenu != 0))
  52941. {
  52942. activeSubMenu->hide (0);
  52943. }
  52944. if (! isOver)
  52945. mic = 0;
  52946. setCurrentlyHighlightedChild (mic);
  52947. }
  52948. }
  52949. }
  52950. void triggerCurrentlyHighlightedItem()
  52951. {
  52952. if (currentChild->isValidComponent()
  52953. && currentChild->itemInfo.canBeTriggered()
  52954. && (currentChild->itemInfo.customComp == 0
  52955. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  52956. {
  52957. dismissMenu (&currentChild->itemInfo);
  52958. }
  52959. }
  52960. void selectNextItem (const int delta)
  52961. {
  52962. disableTimerUntilMouseMoves();
  52963. MenuItemComponent* mic = 0;
  52964. bool wasLastOne = (currentChild == 0);
  52965. const int numItems = getNumChildComponents();
  52966. for (int i = 0; i < numItems + 1; ++i)
  52967. {
  52968. int index = (delta > 0) ? i : (numItems - 1 - i);
  52969. index = (index + numItems) % numItems;
  52970. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  52971. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  52972. && wasLastOne)
  52973. break;
  52974. if (mic == currentChild)
  52975. wasLastOne = true;
  52976. }
  52977. setCurrentlyHighlightedChild (mic);
  52978. }
  52979. void disableTimerUntilMouseMoves() throw()
  52980. {
  52981. disableMouseMoves = true;
  52982. if (owner != 0)
  52983. owner->disableTimerUntilMouseMoves();
  52984. }
  52985. PopupMenuWindow (const PopupMenuWindow&);
  52986. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  52987. };
  52988. PopupMenu::PopupMenu() throw()
  52989. : items (8),
  52990. lookAndFeel (0),
  52991. separatorPending (false)
  52992. {
  52993. }
  52994. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  52995. : items (8),
  52996. lookAndFeel (other.lookAndFeel),
  52997. separatorPending (false)
  52998. {
  52999. items.ensureStorageAllocated (other.items.size());
  53000. for (int i = 0; i < other.items.size(); ++i)
  53001. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  53002. }
  53003. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  53004. {
  53005. if (this != &other)
  53006. {
  53007. lookAndFeel = other.lookAndFeel;
  53008. clear();
  53009. items.ensureStorageAllocated (other.items.size());
  53010. for (int i = 0; i < other.items.size(); ++i)
  53011. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  53012. }
  53013. return *this;
  53014. }
  53015. PopupMenu::~PopupMenu() throw()
  53016. {
  53017. clear();
  53018. }
  53019. void PopupMenu::clear() throw()
  53020. {
  53021. for (int i = items.size(); --i >= 0;)
  53022. {
  53023. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  53024. delete mi;
  53025. }
  53026. items.clear();
  53027. separatorPending = false;
  53028. }
  53029. void PopupMenu::addSeparatorIfPending()
  53030. {
  53031. if (separatorPending)
  53032. {
  53033. separatorPending = false;
  53034. if (items.size() > 0)
  53035. items.add (new MenuItemInfo());
  53036. }
  53037. }
  53038. void PopupMenu::addItem (const int itemResultId,
  53039. const String& itemText,
  53040. const bool isActive,
  53041. const bool isTicked,
  53042. const Image* const iconToUse) throw()
  53043. {
  53044. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  53045. // didn't pick anything, so you shouldn't use it as the id
  53046. // for an item..
  53047. addSeparatorIfPending();
  53048. items.add (new MenuItemInfo (itemResultId,
  53049. itemText,
  53050. isActive,
  53051. isTicked,
  53052. iconToUse,
  53053. Colours::black,
  53054. false,
  53055. 0, 0, 0));
  53056. }
  53057. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  53058. const int commandID,
  53059. const String& displayName) throw()
  53060. {
  53061. jassert (commandManager != 0 && commandID != 0);
  53062. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  53063. if (registeredInfo != 0)
  53064. {
  53065. ApplicationCommandInfo info (*registeredInfo);
  53066. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  53067. addSeparatorIfPending();
  53068. items.add (new MenuItemInfo (commandID,
  53069. displayName.isNotEmpty() ? displayName
  53070. : info.shortName,
  53071. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  53072. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  53073. 0,
  53074. Colours::black,
  53075. false,
  53076. 0, 0,
  53077. commandManager));
  53078. }
  53079. }
  53080. void PopupMenu::addColouredItem (const int itemResultId,
  53081. const String& itemText,
  53082. const Colour& itemTextColour,
  53083. const bool isActive,
  53084. const bool isTicked,
  53085. const Image* const iconToUse) throw()
  53086. {
  53087. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  53088. // didn't pick anything, so you shouldn't use it as the id
  53089. // for an item..
  53090. addSeparatorIfPending();
  53091. items.add (new MenuItemInfo (itemResultId,
  53092. itemText,
  53093. isActive,
  53094. isTicked,
  53095. iconToUse,
  53096. itemTextColour,
  53097. true,
  53098. 0, 0, 0));
  53099. }
  53100. void PopupMenu::addCustomItem (const int itemResultId,
  53101. PopupMenuCustomComponent* const customComponent) throw()
  53102. {
  53103. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  53104. // didn't pick anything, so you shouldn't use it as the id
  53105. // for an item..
  53106. addSeparatorIfPending();
  53107. items.add (new MenuItemInfo (itemResultId,
  53108. String::empty,
  53109. true,
  53110. false,
  53111. 0,
  53112. Colours::black,
  53113. false,
  53114. customComponent,
  53115. 0, 0));
  53116. }
  53117. class NormalComponentWrapper : public PopupMenuCustomComponent
  53118. {
  53119. public:
  53120. NormalComponentWrapper (Component* const comp,
  53121. const int w, const int h,
  53122. const bool triggerMenuItemAutomaticallyWhenClicked)
  53123. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  53124. width (w),
  53125. height (h)
  53126. {
  53127. addAndMakeVisible (comp);
  53128. }
  53129. ~NormalComponentWrapper() {}
  53130. void getIdealSize (int& idealWidth, int& idealHeight)
  53131. {
  53132. idealWidth = width;
  53133. idealHeight = height;
  53134. }
  53135. void resized()
  53136. {
  53137. if (getChildComponent(0) != 0)
  53138. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  53139. }
  53140. juce_UseDebuggingNewOperator
  53141. private:
  53142. const int width, height;
  53143. NormalComponentWrapper (const NormalComponentWrapper&);
  53144. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  53145. };
  53146. void PopupMenu::addCustomItem (const int itemResultId,
  53147. Component* customComponent,
  53148. int idealWidth, int idealHeight,
  53149. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  53150. {
  53151. addCustomItem (itemResultId,
  53152. new NormalComponentWrapper (customComponent,
  53153. idealWidth, idealHeight,
  53154. triggerMenuItemAutomaticallyWhenClicked));
  53155. }
  53156. void PopupMenu::addSubMenu (const String& subMenuName,
  53157. const PopupMenu& subMenu,
  53158. const bool isActive,
  53159. Image* const iconToUse,
  53160. const bool isTicked) throw()
  53161. {
  53162. addSeparatorIfPending();
  53163. items.add (new MenuItemInfo (0,
  53164. subMenuName,
  53165. isActive && (subMenu.getNumItems() > 0),
  53166. isTicked,
  53167. iconToUse,
  53168. Colours::black,
  53169. false,
  53170. 0,
  53171. &subMenu,
  53172. 0));
  53173. }
  53174. void PopupMenu::addSeparator() throw()
  53175. {
  53176. separatorPending = true;
  53177. }
  53178. class HeaderItemComponent : public PopupMenuCustomComponent
  53179. {
  53180. public:
  53181. HeaderItemComponent (const String& name)
  53182. : PopupMenuCustomComponent (false)
  53183. {
  53184. setName (name);
  53185. }
  53186. ~HeaderItemComponent()
  53187. {
  53188. }
  53189. void paint (Graphics& g)
  53190. {
  53191. Font f (getLookAndFeel().getPopupMenuFont());
  53192. f.setBold (true);
  53193. g.setFont (f);
  53194. g.setColour (findColour (PopupMenu::headerTextColourId));
  53195. g.drawFittedText (getName(),
  53196. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  53197. Justification::bottomLeft, 1);
  53198. }
  53199. void getIdealSize (int& idealWidth,
  53200. int& idealHeight)
  53201. {
  53202. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  53203. idealHeight += idealHeight / 2;
  53204. idealWidth += idealWidth / 4;
  53205. }
  53206. juce_UseDebuggingNewOperator
  53207. };
  53208. void PopupMenu::addSectionHeader (const String& title) throw()
  53209. {
  53210. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  53211. }
  53212. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  53213. const int itemIdThatMustBeVisible,
  53214. const int minimumWidth,
  53215. const int maximumNumColumns,
  53216. const int standardItemHeight,
  53217. const bool alignToRectangle,
  53218. Component* menuBarComponent,
  53219. ApplicationCommandManager** managerOfChosenCommand,
  53220. Component* const componentAttachedTo) throw()
  53221. {
  53222. PopupMenuWindow* const pw
  53223. = PopupMenuWindow::create (*this,
  53224. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  53225. 0,
  53226. x, x + w,
  53227. y, y + h,
  53228. minimumWidth,
  53229. maximumNumColumns,
  53230. standardItemHeight,
  53231. alignToRectangle,
  53232. itemIdThatMustBeVisible,
  53233. menuBarComponent,
  53234. managerOfChosenCommand,
  53235. componentAttachedTo);
  53236. if (pw != 0)
  53237. pw->setVisible (true);
  53238. return pw;
  53239. }
  53240. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  53241. const int itemIdThatMustBeVisible,
  53242. const int minimumWidth,
  53243. const int maximumNumColumns,
  53244. const int standardItemHeight,
  53245. const bool alignToRectangle,
  53246. Component* const componentAttachedTo) throw()
  53247. {
  53248. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  53249. ComponentDeletionWatcher* deletionChecker1 = 0;
  53250. if (prevFocused != 0)
  53251. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  53252. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  53253. ComponentDeletionWatcher* deletionChecker2 = 0;
  53254. if (prevTopLevel != 0)
  53255. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  53256. wasHiddenBecauseOfAppChange = false;
  53257. int result = 0;
  53258. ApplicationCommandManager* managerOfChosenCommand = 0;
  53259. Component* const popupComp = createMenuComponent (x, y, w, h,
  53260. itemIdThatMustBeVisible,
  53261. minimumWidth,
  53262. maximumNumColumns > 0 ? maximumNumColumns : 7,
  53263. standardItemHeight,
  53264. alignToRectangle, 0,
  53265. &managerOfChosenCommand,
  53266. componentAttachedTo);
  53267. if (popupComp != 0)
  53268. {
  53269. popupComp->enterModalState (false);
  53270. popupComp->toFront (false); // need to do this after making it modal, or it could
  53271. // be stuck behind other comps that are already modal..
  53272. result = popupComp->runModalLoop();
  53273. delete popupComp;
  53274. if (! wasHiddenBecauseOfAppChange)
  53275. {
  53276. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  53277. prevTopLevel->toFront (true);
  53278. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  53279. prevFocused->grabKeyboardFocus();
  53280. }
  53281. }
  53282. delete deletionChecker1;
  53283. delete deletionChecker2;
  53284. if (managerOfChosenCommand != 0 && result != 0)
  53285. {
  53286. ApplicationCommandTarget::InvocationInfo info (result);
  53287. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  53288. managerOfChosenCommand->invoke (info, true);
  53289. }
  53290. return result;
  53291. }
  53292. int PopupMenu::show (const int itemIdThatMustBeVisible,
  53293. const int minimumWidth,
  53294. const int maximumNumColumns,
  53295. const int standardItemHeight)
  53296. {
  53297. int x, y;
  53298. Desktop::getMousePosition (x, y);
  53299. return showAt (x, y,
  53300. itemIdThatMustBeVisible,
  53301. minimumWidth,
  53302. maximumNumColumns,
  53303. standardItemHeight);
  53304. }
  53305. int PopupMenu::showAt (const int screenX,
  53306. const int screenY,
  53307. const int itemIdThatMustBeVisible,
  53308. const int minimumWidth,
  53309. const int maximumNumColumns,
  53310. const int standardItemHeight)
  53311. {
  53312. return showMenu (screenX, screenY, 1, 1,
  53313. itemIdThatMustBeVisible,
  53314. minimumWidth, maximumNumColumns,
  53315. standardItemHeight,
  53316. false, 0);
  53317. }
  53318. int PopupMenu::showAt (Component* componentToAttachTo,
  53319. const int itemIdThatMustBeVisible,
  53320. const int minimumWidth,
  53321. const int maximumNumColumns,
  53322. const int standardItemHeight)
  53323. {
  53324. if (componentToAttachTo != 0)
  53325. {
  53326. return showMenu (componentToAttachTo->getScreenX(),
  53327. componentToAttachTo->getScreenY(),
  53328. componentToAttachTo->getWidth(),
  53329. componentToAttachTo->getHeight(),
  53330. itemIdThatMustBeVisible,
  53331. minimumWidth,
  53332. maximumNumColumns,
  53333. standardItemHeight,
  53334. true, componentToAttachTo);
  53335. }
  53336. else
  53337. {
  53338. return show (itemIdThatMustBeVisible,
  53339. minimumWidth,
  53340. maximumNumColumns,
  53341. standardItemHeight);
  53342. }
  53343. }
  53344. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  53345. {
  53346. for (int i = activeMenuWindows.size(); --i >= 0;)
  53347. {
  53348. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  53349. if (pmw != 0)
  53350. pmw->dismissMenu (0);
  53351. }
  53352. }
  53353. int PopupMenu::getNumItems() const throw()
  53354. {
  53355. int num = 0;
  53356. for (int i = items.size(); --i >= 0;)
  53357. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  53358. ++num;
  53359. return num;
  53360. }
  53361. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  53362. {
  53363. for (int i = items.size(); --i >= 0;)
  53364. {
  53365. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  53366. if ((mi->itemId == commandID && mi->commandManager != 0)
  53367. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  53368. {
  53369. return true;
  53370. }
  53371. }
  53372. return false;
  53373. }
  53374. bool PopupMenu::containsAnyActiveItems() const throw()
  53375. {
  53376. for (int i = items.size(); --i >= 0;)
  53377. {
  53378. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  53379. if (mi->subMenu != 0)
  53380. {
  53381. if (mi->subMenu->containsAnyActiveItems())
  53382. return true;
  53383. }
  53384. else if (mi->active)
  53385. {
  53386. return true;
  53387. }
  53388. }
  53389. return false;
  53390. }
  53391. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  53392. {
  53393. lookAndFeel = newLookAndFeel;
  53394. }
  53395. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  53396. : refCount_ (0),
  53397. isHighlighted (false),
  53398. isTriggeredAutomatically (isTriggeredAutomatically_)
  53399. {
  53400. }
  53401. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  53402. {
  53403. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  53404. }
  53405. void PopupMenuCustomComponent::triggerMenuItem()
  53406. {
  53407. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  53408. if (mic != 0)
  53409. {
  53410. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  53411. if (pmw != 0)
  53412. {
  53413. pmw->dismissMenu (&mic->itemInfo);
  53414. }
  53415. else
  53416. {
  53417. // something must have gone wrong with the component hierarchy if this happens..
  53418. jassertfalse
  53419. }
  53420. }
  53421. else
  53422. {
  53423. // why isn't this component inside a menu? Not much point triggering the item if
  53424. // there's no menu.
  53425. jassertfalse
  53426. }
  53427. }
  53428. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  53429. : subMenu (0),
  53430. itemId (0),
  53431. isSeparator (false),
  53432. isTicked (false),
  53433. isEnabled (false),
  53434. isCustomComponent (false),
  53435. isSectionHeader (false),
  53436. customColour (0),
  53437. customImage (0),
  53438. menu (menu_),
  53439. index (0)
  53440. {
  53441. }
  53442. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  53443. {
  53444. }
  53445. bool PopupMenu::MenuItemIterator::next() throw()
  53446. {
  53447. if (index >= menu.items.size())
  53448. return false;
  53449. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  53450. ++index;
  53451. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  53452. subMenu = item->subMenu;
  53453. itemId = item->itemId;
  53454. isSeparator = item->isSeparator;
  53455. isTicked = item->isTicked;
  53456. isEnabled = item->active;
  53457. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  53458. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  53459. customColour = item->usesColour ? &(item->textColour) : 0;
  53460. customImage = item->image;
  53461. commandManager = item->commandManager;
  53462. return true;
  53463. }
  53464. END_JUCE_NAMESPACE
  53465. /********* End of inlined file: juce_PopupMenu.cpp *********/
  53466. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  53467. BEGIN_JUCE_NAMESPACE
  53468. ComponentDragger::ComponentDragger()
  53469. : constrainer (0),
  53470. originalX (0),
  53471. originalY (0)
  53472. {
  53473. }
  53474. ComponentDragger::~ComponentDragger()
  53475. {
  53476. }
  53477. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  53478. ComponentBoundsConstrainer* const constrainer_)
  53479. {
  53480. jassert (componentToDrag->isValidComponent());
  53481. if (componentToDrag->isValidComponent())
  53482. {
  53483. constrainer = constrainer_;
  53484. originalX = 0;
  53485. originalY = 0;
  53486. componentToDrag->relativePositionToGlobal (originalX, originalY);
  53487. }
  53488. }
  53489. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  53490. {
  53491. jassert (componentToDrag->isValidComponent());
  53492. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  53493. if (componentToDrag->isValidComponent())
  53494. {
  53495. int x = originalX;
  53496. int y = originalY;
  53497. int w = componentToDrag->getWidth();
  53498. int h = componentToDrag->getHeight();
  53499. const Component* const parentComp = componentToDrag->getParentComponent();
  53500. if (parentComp != 0)
  53501. parentComp->globalPositionToRelative (x, y);
  53502. x += e.getDistanceFromDragStartX();
  53503. y += e.getDistanceFromDragStartY();
  53504. if (constrainer != 0)
  53505. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  53506. false, false, false, false);
  53507. else
  53508. componentToDrag->setBounds (x, y, w, h);
  53509. }
  53510. }
  53511. END_JUCE_NAMESPACE
  53512. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  53513. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  53514. BEGIN_JUCE_NAMESPACE
  53515. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  53516. bool juce_performDragDropText (const String& text, bool& shouldStop);
  53517. class DragImageComponent : public Component,
  53518. public Timer
  53519. {
  53520. private:
  53521. Image* image;
  53522. Component* const source;
  53523. DragAndDropContainer* const owner;
  53524. ComponentDeletionWatcher* sourceWatcher;
  53525. Component* mouseDragSource;
  53526. ComponentDeletionWatcher* mouseDragSourceWatcher;
  53527. DragAndDropTarget* currentlyOver;
  53528. ComponentDeletionWatcher* currentlyOverWatcher;
  53529. String dragDesc;
  53530. int xOff, yOff;
  53531. bool hasCheckedForExternalDrag, drawImage;
  53532. DragImageComponent (const DragImageComponent&);
  53533. const DragImageComponent& operator= (const DragImageComponent&);
  53534. public:
  53535. DragImageComponent (Image* const im,
  53536. const String& desc,
  53537. Component* const s,
  53538. DragAndDropContainer* const o)
  53539. : image (im),
  53540. source (s),
  53541. owner (o),
  53542. currentlyOver (0),
  53543. currentlyOverWatcher (0),
  53544. dragDesc (desc),
  53545. hasCheckedForExternalDrag (false),
  53546. drawImage (true)
  53547. {
  53548. setSize (im->getWidth(), im->getHeight());
  53549. sourceWatcher = new ComponentDeletionWatcher (source);
  53550. mouseDragSource = Component::getComponentUnderMouse();
  53551. if (mouseDragSource == 0)
  53552. mouseDragSource = source;
  53553. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  53554. mouseDragSource->addMouseListener (this, false);
  53555. int mx, my;
  53556. Desktop::getLastMouseDownPosition (mx, my);
  53557. source->globalPositionToRelative (mx, my);
  53558. xOff = jlimit (0, im->getWidth(), mx);
  53559. yOff = jlimit (0, im->getHeight(), my);
  53560. startTimer (200);
  53561. setInterceptsMouseClicks (false, false);
  53562. setAlwaysOnTop (true);
  53563. }
  53564. ~DragImageComponent()
  53565. {
  53566. if (owner->dragImageComponent == this)
  53567. owner->dragImageComponent = 0;
  53568. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53569. {
  53570. mouseDragSource->removeMouseListener (this);
  53571. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53572. if (currentlyOver->isInterestedInDragSource (dragDesc, source))
  53573. currentlyOver->itemDragExit (dragDesc, source);
  53574. }
  53575. delete mouseDragSourceWatcher;
  53576. delete sourceWatcher;
  53577. delete image;
  53578. delete currentlyOverWatcher;
  53579. }
  53580. void paint (Graphics& g)
  53581. {
  53582. if (isOpaque())
  53583. g.fillAll (Colours::white);
  53584. if (drawImage)
  53585. {
  53586. g.setOpacity (1.0f);
  53587. g.drawImageAt (image, 0, 0);
  53588. }
  53589. }
  53590. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  53591. int& relX, int& relY) const throw()
  53592. {
  53593. Component* hit = getParentComponent();
  53594. if (hit == 0)
  53595. {
  53596. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  53597. }
  53598. else
  53599. {
  53600. int rx = screenX, ry = screenY;
  53601. hit->globalPositionToRelative (rx, ry);
  53602. hit = hit->getComponentAt (rx, ry);
  53603. }
  53604. // (note: use a local copy of the dragDesc member in case the callback runs
  53605. // a modal loop and deletes this object before the method completes)
  53606. const String dragDescLocal (dragDesc);
  53607. while (hit != 0)
  53608. {
  53609. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  53610. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  53611. {
  53612. relX = screenX;
  53613. relY = screenY;
  53614. hit->globalPositionToRelative (relX, relY);
  53615. return ddt;
  53616. }
  53617. hit = hit->getParentComponent();
  53618. }
  53619. return 0;
  53620. }
  53621. void mouseUp (const MouseEvent& e)
  53622. {
  53623. if (e.originalComponent != this)
  53624. {
  53625. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53626. mouseDragSource->removeMouseListener (this);
  53627. bool dropAccepted = false;
  53628. DragAndDropTarget* ddt = 0;
  53629. int relX = 0, relY = 0;
  53630. if (isVisible())
  53631. {
  53632. setVisible (false);
  53633. ddt = findTarget (e.getScreenX(),
  53634. e.getScreenY(),
  53635. relX, relY);
  53636. // fade this component and remove it - it'll be deleted later by the timer callback
  53637. dropAccepted = ddt != 0;
  53638. setVisible (true);
  53639. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  53640. {
  53641. fadeOutComponent (120);
  53642. }
  53643. else
  53644. {
  53645. int targetX = source->getWidth() / 2;
  53646. int targetY = source->getHeight() / 2;
  53647. source->relativePositionToGlobal (targetX, targetY);
  53648. int ourCentreX = getWidth() / 2;
  53649. int ourCentreY = getHeight() / 2;
  53650. relativePositionToGlobal (ourCentreX, ourCentreY);
  53651. fadeOutComponent (120,
  53652. targetX - ourCentreX,
  53653. targetY - ourCentreY);
  53654. }
  53655. }
  53656. if (getParentComponent() != 0)
  53657. getParentComponent()->removeChildComponent (this);
  53658. if (dropAccepted && ddt != 0)
  53659. {
  53660. // (note: use a local copy of the dragDesc member in case the callback runs
  53661. // a modal loop and deletes this object before the method completes)
  53662. const String dragDescLocal (dragDesc);
  53663. currentlyOver = 0;
  53664. deleteAndZero (currentlyOverWatcher);
  53665. ddt->itemDropped (dragDescLocal, source, relX, relY);
  53666. }
  53667. // careful - this object could now be deleted..
  53668. }
  53669. }
  53670. void updateLocation (const bool canDoExternalDrag, int x, int y)
  53671. {
  53672. // (note: use a local copy of the dragDesc member in case the callback runs
  53673. // a modal loop and deletes this object before it returns)
  53674. const String dragDescLocal (dragDesc);
  53675. int newX = x - xOff;
  53676. int newY = y - yOff;
  53677. if (getParentComponent() != 0)
  53678. getParentComponent()->globalPositionToRelative (newX, newY);
  53679. if (newX != getX() || newY != getY())
  53680. {
  53681. setTopLeftPosition (newX, newY);
  53682. int relX = 0, relY = 0;
  53683. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  53684. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  53685. if (ddt != currentlyOver)
  53686. {
  53687. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53688. {
  53689. Component* const over = dynamic_cast <Component*> (currentlyOver);
  53690. if (over != 0
  53691. && over->isValidComponent()
  53692. && ! (sourceWatcher->hasBeenDeleted())
  53693. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53694. {
  53695. currentlyOver->itemDragExit (dragDescLocal, source);
  53696. }
  53697. }
  53698. currentlyOver = ddt;
  53699. deleteAndZero (currentlyOverWatcher);
  53700. if (ddt != 0)
  53701. {
  53702. currentlyOverWatcher = new ComponentDeletionWatcher (dynamic_cast <Component*> (ddt));
  53703. if (currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53704. currentlyOver->itemDragEnter (dragDescLocal, source, relX, relY);
  53705. }
  53706. }
  53707. else if (currentlyOverWatcher != 0 && currentlyOverWatcher->hasBeenDeleted())
  53708. {
  53709. currentlyOver = 0;
  53710. deleteAndZero (currentlyOverWatcher);
  53711. }
  53712. if (currentlyOver != 0
  53713. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53714. currentlyOver->itemDragMove (dragDescLocal, source, relX, relY);
  53715. if (currentlyOver == 0
  53716. && canDoExternalDrag
  53717. && ! hasCheckedForExternalDrag)
  53718. {
  53719. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  53720. {
  53721. hasCheckedForExternalDrag = true;
  53722. StringArray files;
  53723. bool canMoveFiles = false;
  53724. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  53725. && files.size() > 0)
  53726. {
  53727. ComponentDeletionWatcher cdw (this);
  53728. setVisible (false);
  53729. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  53730. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  53731. if (! cdw.hasBeenDeleted())
  53732. delete this;
  53733. return;
  53734. }
  53735. }
  53736. }
  53737. }
  53738. }
  53739. void mouseDrag (const MouseEvent& e)
  53740. {
  53741. if (e.originalComponent != this)
  53742. updateLocation (true, e.getScreenX(), e.getScreenY());
  53743. }
  53744. void timerCallback()
  53745. {
  53746. if (sourceWatcher->hasBeenDeleted())
  53747. {
  53748. delete this;
  53749. }
  53750. else if (! isMouseButtonDownAnywhere())
  53751. {
  53752. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53753. mouseDragSource->removeMouseListener (this);
  53754. delete this;
  53755. }
  53756. }
  53757. };
  53758. DragAndDropContainer::DragAndDropContainer()
  53759. : dragImageComponent (0)
  53760. {
  53761. }
  53762. DragAndDropContainer::~DragAndDropContainer()
  53763. {
  53764. if (dragImageComponent != 0)
  53765. delete dragImageComponent;
  53766. }
  53767. void DragAndDropContainer::startDragging (const String& sourceDescription,
  53768. Component* sourceComponent,
  53769. Image* im,
  53770. const bool allowDraggingToExternalWindows)
  53771. {
  53772. if (dragImageComponent != 0)
  53773. {
  53774. if (im != 0)
  53775. delete im;
  53776. }
  53777. else
  53778. {
  53779. Component* const thisComp = dynamic_cast <Component*> (this);
  53780. if (thisComp != 0)
  53781. {
  53782. int mx, my;
  53783. Desktop::getLastMouseDownPosition (mx, my);
  53784. if (im == 0)
  53785. {
  53786. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  53787. if (im->getFormat() != Image::ARGB)
  53788. {
  53789. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  53790. Graphics g2 (*newIm);
  53791. g2.drawImageAt (im, 0, 0);
  53792. delete im;
  53793. im = newIm;
  53794. }
  53795. im->multiplyAllAlphas (0.6f);
  53796. const int lo = 150;
  53797. const int hi = 400;
  53798. int rx = mx, ry = my;
  53799. sourceComponent->globalPositionToRelative (rx, ry);
  53800. const int cx = jlimit (0, im->getWidth(), rx);
  53801. const int cy = jlimit (0, im->getHeight(), ry);
  53802. for (int y = im->getHeight(); --y >= 0;)
  53803. {
  53804. const double dy = (y - cy) * (y - cy);
  53805. for (int x = im->getWidth(); --x >= 0;)
  53806. {
  53807. const int dx = x - cx;
  53808. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  53809. if (distance > lo)
  53810. {
  53811. const float alpha = (distance > hi) ? 0
  53812. : (hi - distance) / (float) (hi - lo)
  53813. + Random::getSystemRandom().nextFloat() * 0.008f;
  53814. im->multiplyAlphaAt (x, y, alpha);
  53815. }
  53816. }
  53817. }
  53818. }
  53819. DragImageComponent* const dic
  53820. = new DragImageComponent (im,
  53821. sourceDescription,
  53822. sourceComponent,
  53823. this);
  53824. dragImageComponent = dic;
  53825. currentDragDesc = sourceDescription;
  53826. if (allowDraggingToExternalWindows)
  53827. {
  53828. if (! Desktop::canUseSemiTransparentWindows())
  53829. dic->setOpaque (true);
  53830. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53831. | ComponentPeer::windowIsTemporary
  53832. | ComponentPeer::windowIgnoresKeyPresses);
  53833. }
  53834. else
  53835. thisComp->addChildComponent (dic);
  53836. dic->updateLocation (false, mx, my);
  53837. dic->setVisible (true);
  53838. }
  53839. else
  53840. {
  53841. // this class must only be implemented by an object that
  53842. // is also a Component.
  53843. jassertfalse
  53844. if (im != 0)
  53845. delete im;
  53846. }
  53847. }
  53848. }
  53849. bool DragAndDropContainer::isDragAndDropActive() const
  53850. {
  53851. return dragImageComponent != 0;
  53852. }
  53853. const String DragAndDropContainer::getCurrentDragDescription() const
  53854. {
  53855. return (dragImageComponent != 0) ? currentDragDesc
  53856. : String::empty;
  53857. }
  53858. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  53859. {
  53860. if (c == 0)
  53861. return 0;
  53862. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53863. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  53864. }
  53865. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  53866. {
  53867. return false;
  53868. }
  53869. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  53870. {
  53871. }
  53872. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  53873. {
  53874. }
  53875. void DragAndDropTarget::itemDragExit (const String&, Component*)
  53876. {
  53877. }
  53878. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  53879. {
  53880. return true;
  53881. }
  53882. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  53883. {
  53884. }
  53885. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  53886. {
  53887. }
  53888. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  53889. {
  53890. }
  53891. END_JUCE_NAMESPACE
  53892. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  53893. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  53894. BEGIN_JUCE_NAMESPACE
  53895. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  53896. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  53897. // isStandard set depending on which interface was used to create the cursor
  53898. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  53899. static CriticalSection mouseCursorLock;
  53900. static VoidArray standardCursors (2);
  53901. class RefCountedMouseCursor
  53902. {
  53903. public:
  53904. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  53905. : refCount (1),
  53906. standardType (t),
  53907. isStandard (true)
  53908. {
  53909. handle = juce_createStandardMouseCursor (standardType);
  53910. standardCursors.add (this);
  53911. }
  53912. RefCountedMouseCursor (Image& image,
  53913. const int hotSpotX,
  53914. const int hotSpotY) throw()
  53915. : refCount (1),
  53916. standardType (MouseCursor::NormalCursor),
  53917. isStandard (false)
  53918. {
  53919. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  53920. }
  53921. ~RefCountedMouseCursor() throw()
  53922. {
  53923. juce_deleteMouseCursor (handle, isStandard);
  53924. standardCursors.removeValue (this);
  53925. }
  53926. void decRef() throw()
  53927. {
  53928. if (--refCount == 0)
  53929. delete this;
  53930. }
  53931. void incRef() throw()
  53932. {
  53933. ++refCount;
  53934. }
  53935. void* getHandle() const throw()
  53936. {
  53937. return handle;
  53938. }
  53939. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  53940. {
  53941. const ScopedLock sl (mouseCursorLock);
  53942. for (int i = 0; i < standardCursors.size(); i++)
  53943. {
  53944. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  53945. if (r->standardType == type)
  53946. {
  53947. r->incRef();
  53948. return r;
  53949. }
  53950. }
  53951. return new RefCountedMouseCursor (type);
  53952. }
  53953. juce_UseDebuggingNewOperator
  53954. private:
  53955. void* handle;
  53956. int refCount;
  53957. const MouseCursor::StandardCursorType standardType;
  53958. const bool isStandard;
  53959. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  53960. };
  53961. MouseCursor::MouseCursor() throw()
  53962. {
  53963. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  53964. }
  53965. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  53966. {
  53967. cursorHandle = RefCountedMouseCursor::findInstance (type);
  53968. }
  53969. MouseCursor::MouseCursor (Image& image,
  53970. const int hotSpotX,
  53971. const int hotSpotY) throw()
  53972. {
  53973. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  53974. }
  53975. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  53976. : cursorHandle (other.cursorHandle)
  53977. {
  53978. const ScopedLock sl (mouseCursorLock);
  53979. cursorHandle->incRef();
  53980. }
  53981. MouseCursor::~MouseCursor() throw()
  53982. {
  53983. const ScopedLock sl (mouseCursorLock);
  53984. cursorHandle->decRef();
  53985. }
  53986. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  53987. {
  53988. if (this != &other)
  53989. {
  53990. const ScopedLock sl (mouseCursorLock);
  53991. cursorHandle->decRef();
  53992. cursorHandle = other.cursorHandle;
  53993. cursorHandle->incRef();
  53994. }
  53995. return *this;
  53996. }
  53997. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  53998. {
  53999. return cursorHandle == other.cursorHandle;
  54000. }
  54001. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  54002. {
  54003. return cursorHandle != other.cursorHandle;
  54004. }
  54005. void* MouseCursor::getHandle() const throw()
  54006. {
  54007. return cursorHandle->getHandle();
  54008. }
  54009. void MouseCursor::showWaitCursor() throw()
  54010. {
  54011. const MouseCursor mc (MouseCursor::WaitCursor);
  54012. mc.showInAllWindows();
  54013. }
  54014. void MouseCursor::hideWaitCursor() throw()
  54015. {
  54016. if (Component::getComponentUnderMouse()->isValidComponent())
  54017. {
  54018. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  54019. }
  54020. else
  54021. {
  54022. const MouseCursor mc (MouseCursor::NormalCursor);
  54023. mc.showInAllWindows();
  54024. }
  54025. }
  54026. END_JUCE_NAMESPACE
  54027. /********* End of inlined file: juce_MouseCursor.cpp *********/
  54028. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  54029. BEGIN_JUCE_NAMESPACE
  54030. MouseEvent::MouseEvent (const int x_,
  54031. const int y_,
  54032. const ModifierKeys& mods_,
  54033. Component* const originator,
  54034. const Time& eventTime_,
  54035. const int mouseDownX_,
  54036. const int mouseDownY_,
  54037. const Time& mouseDownTime_,
  54038. const int numberOfClicks_,
  54039. const bool mouseWasDragged) throw()
  54040. : x (x_),
  54041. y (y_),
  54042. mods (mods_),
  54043. eventComponent (originator),
  54044. originalComponent (originator),
  54045. eventTime (eventTime_),
  54046. mouseDownX (mouseDownX_),
  54047. mouseDownY (mouseDownY_),
  54048. mouseDownTime (mouseDownTime_),
  54049. numberOfClicks (numberOfClicks_),
  54050. wasMovedSinceMouseDown (mouseWasDragged)
  54051. {
  54052. }
  54053. MouseEvent::~MouseEvent() throw()
  54054. {
  54055. }
  54056. bool MouseEvent::mouseWasClicked() const throw()
  54057. {
  54058. return ! wasMovedSinceMouseDown;
  54059. }
  54060. int MouseEvent::getMouseDownX() const throw()
  54061. {
  54062. return mouseDownX;
  54063. }
  54064. int MouseEvent::getMouseDownY() const throw()
  54065. {
  54066. return mouseDownY;
  54067. }
  54068. int MouseEvent::getDistanceFromDragStartX() const throw()
  54069. {
  54070. return x - mouseDownX;
  54071. }
  54072. int MouseEvent::getDistanceFromDragStartY() const throw()
  54073. {
  54074. return y - mouseDownY;
  54075. }
  54076. int MouseEvent::getDistanceFromDragStart() const throw()
  54077. {
  54078. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  54079. getDistanceFromDragStartY()));
  54080. }
  54081. int MouseEvent::getLengthOfMousePress() const throw()
  54082. {
  54083. if (mouseDownTime.toMilliseconds() > 0)
  54084. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  54085. return 0;
  54086. }
  54087. int MouseEvent::getScreenX() const throw()
  54088. {
  54089. int sx = x, sy = y;
  54090. eventComponent->relativePositionToGlobal (sx, sy);
  54091. return sx;
  54092. }
  54093. int MouseEvent::getScreenY() const throw()
  54094. {
  54095. int sx = x, sy = y;
  54096. eventComponent->relativePositionToGlobal (sx, sy);
  54097. return sy;
  54098. }
  54099. int MouseEvent::getMouseDownScreenX() const throw()
  54100. {
  54101. int sx = mouseDownX, sy = mouseDownY;
  54102. eventComponent->relativePositionToGlobal (sx, sy);
  54103. return sx;
  54104. }
  54105. int MouseEvent::getMouseDownScreenY() const throw()
  54106. {
  54107. int sx = mouseDownX, sy = mouseDownY;
  54108. eventComponent->relativePositionToGlobal (sx, sy);
  54109. return sy;
  54110. }
  54111. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  54112. {
  54113. if (otherComponent == 0)
  54114. {
  54115. jassertfalse
  54116. return *this;
  54117. }
  54118. MouseEvent me (*this);
  54119. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  54120. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  54121. me.eventComponent = otherComponent;
  54122. return me;
  54123. }
  54124. static int doubleClickTimeOutMs = 400;
  54125. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  54126. {
  54127. doubleClickTimeOutMs = newTime;
  54128. }
  54129. int MouseEvent::getDoubleClickTimeout() throw()
  54130. {
  54131. return doubleClickTimeOutMs;
  54132. }
  54133. END_JUCE_NAMESPACE
  54134. /********* End of inlined file: juce_MouseEvent.cpp *********/
  54135. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  54136. BEGIN_JUCE_NAMESPACE
  54137. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  54138. : source (0),
  54139. hoverTimeMillisecs (hoverTimeMillisecs_),
  54140. hasJustHovered (false)
  54141. {
  54142. internalTimer.owner = this;
  54143. }
  54144. MouseHoverDetector::~MouseHoverDetector()
  54145. {
  54146. setHoverComponent (0);
  54147. }
  54148. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  54149. {
  54150. hoverTimeMillisecs = newTimeInMillisecs;
  54151. }
  54152. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  54153. {
  54154. if (source != newSourceComponent)
  54155. {
  54156. internalTimer.stopTimer();
  54157. hasJustHovered = false;
  54158. if (source != 0)
  54159. {
  54160. // ! you need to delete the hover detector before deleting its component
  54161. jassert (source->isValidComponent());
  54162. source->removeMouseListener (&internalTimer);
  54163. }
  54164. source = newSourceComponent;
  54165. if (newSourceComponent != 0)
  54166. newSourceComponent->addMouseListener (&internalTimer, false);
  54167. }
  54168. }
  54169. void MouseHoverDetector::hoverTimerCallback()
  54170. {
  54171. internalTimer.stopTimer();
  54172. if (source != 0)
  54173. {
  54174. int mx, my;
  54175. source->getMouseXYRelative (mx, my);
  54176. if (source->reallyContains (mx, my, false))
  54177. {
  54178. hasJustHovered = true;
  54179. mouseHovered (mx, my);
  54180. }
  54181. }
  54182. }
  54183. void MouseHoverDetector::checkJustHoveredCallback()
  54184. {
  54185. if (hasJustHovered)
  54186. {
  54187. hasJustHovered = false;
  54188. mouseMovedAfterHover();
  54189. }
  54190. }
  54191. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  54192. {
  54193. owner->hoverTimerCallback();
  54194. }
  54195. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  54196. {
  54197. stopTimer();
  54198. owner->checkJustHoveredCallback();
  54199. }
  54200. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  54201. {
  54202. stopTimer();
  54203. owner->checkJustHoveredCallback();
  54204. }
  54205. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  54206. {
  54207. stopTimer();
  54208. owner->checkJustHoveredCallback();
  54209. }
  54210. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  54211. {
  54212. stopTimer();
  54213. owner->checkJustHoveredCallback();
  54214. }
  54215. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  54216. {
  54217. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  54218. {
  54219. lastX = e.x;
  54220. lastY = e.y;
  54221. if (owner->source != 0)
  54222. startTimer (owner->hoverTimeMillisecs);
  54223. owner->checkJustHoveredCallback();
  54224. }
  54225. }
  54226. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  54227. {
  54228. stopTimer();
  54229. owner->checkJustHoveredCallback();
  54230. }
  54231. END_JUCE_NAMESPACE
  54232. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  54233. /********* Start of inlined file: juce_MouseListener.cpp *********/
  54234. BEGIN_JUCE_NAMESPACE
  54235. void MouseListener::mouseEnter (const MouseEvent&)
  54236. {
  54237. }
  54238. void MouseListener::mouseExit (const MouseEvent&)
  54239. {
  54240. }
  54241. void MouseListener::mouseDown (const MouseEvent&)
  54242. {
  54243. }
  54244. void MouseListener::mouseUp (const MouseEvent&)
  54245. {
  54246. }
  54247. void MouseListener::mouseDrag (const MouseEvent&)
  54248. {
  54249. }
  54250. void MouseListener::mouseMove (const MouseEvent&)
  54251. {
  54252. }
  54253. void MouseListener::mouseDoubleClick (const MouseEvent&)
  54254. {
  54255. }
  54256. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  54257. {
  54258. }
  54259. END_JUCE_NAMESPACE
  54260. /********* End of inlined file: juce_MouseListener.cpp *********/
  54261. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54262. BEGIN_JUCE_NAMESPACE
  54263. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  54264. const String& buttonTextWhenTrue,
  54265. const String& buttonTextWhenFalse)
  54266. : PropertyComponent (name),
  54267. onText (buttonTextWhenTrue),
  54268. offText (buttonTextWhenFalse)
  54269. {
  54270. addAndMakeVisible (button = new ToggleButton (String::empty));
  54271. button->setClickingTogglesState (false);
  54272. button->addButtonListener (this);
  54273. }
  54274. BooleanPropertyComponent::~BooleanPropertyComponent()
  54275. {
  54276. deleteAllChildren();
  54277. }
  54278. void BooleanPropertyComponent::paint (Graphics& g)
  54279. {
  54280. PropertyComponent::paint (g);
  54281. const Rectangle r (button->getBounds());
  54282. g.setColour (Colours::white);
  54283. g.fillRect (r);
  54284. g.setColour (findColour (ComboBox::outlineColourId));
  54285. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  54286. }
  54287. void BooleanPropertyComponent::refresh()
  54288. {
  54289. button->setToggleState (getState(), false);
  54290. button->setButtonText (button->getToggleState() ? onText : offText);
  54291. }
  54292. void BooleanPropertyComponent::buttonClicked (Button*)
  54293. {
  54294. setState (! getState());
  54295. }
  54296. END_JUCE_NAMESPACE
  54297. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54298. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54299. BEGIN_JUCE_NAMESPACE
  54300. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  54301. const bool triggerOnMouseDown)
  54302. : PropertyComponent (name)
  54303. {
  54304. addAndMakeVisible (button = new TextButton (String::empty));
  54305. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  54306. button->addButtonListener (this);
  54307. }
  54308. ButtonPropertyComponent::~ButtonPropertyComponent()
  54309. {
  54310. deleteAllChildren();
  54311. }
  54312. void ButtonPropertyComponent::refresh()
  54313. {
  54314. button->setButtonText (getButtonText());
  54315. }
  54316. void ButtonPropertyComponent::buttonClicked (Button*)
  54317. {
  54318. buttonClicked();
  54319. }
  54320. END_JUCE_NAMESPACE
  54321. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54322. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54323. BEGIN_JUCE_NAMESPACE
  54324. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  54325. : PropertyComponent (name),
  54326. comboBox (0)
  54327. {
  54328. }
  54329. ChoicePropertyComponent::~ChoicePropertyComponent()
  54330. {
  54331. deleteAllChildren();
  54332. }
  54333. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  54334. {
  54335. return choices;
  54336. }
  54337. void ChoicePropertyComponent::refresh()
  54338. {
  54339. if (comboBox == 0)
  54340. {
  54341. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  54342. for (int i = 0; i < choices.size(); ++i)
  54343. {
  54344. if (choices[i].isNotEmpty())
  54345. comboBox->addItem (choices[i], i + 1);
  54346. else
  54347. comboBox->addSeparator();
  54348. }
  54349. comboBox->setEditableText (false);
  54350. comboBox->addListener (this);
  54351. }
  54352. comboBox->setSelectedId (getIndex() + 1, true);
  54353. }
  54354. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  54355. {
  54356. const int newIndex = comboBox->getSelectedId() - 1;
  54357. if (newIndex != getIndex())
  54358. setIndex (newIndex);
  54359. }
  54360. END_JUCE_NAMESPACE
  54361. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54362. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  54363. BEGIN_JUCE_NAMESPACE
  54364. PropertyComponent::PropertyComponent (const String& name,
  54365. const int preferredHeight_)
  54366. : Component (name),
  54367. preferredHeight (preferredHeight_)
  54368. {
  54369. jassert (name.isNotEmpty());
  54370. }
  54371. PropertyComponent::~PropertyComponent()
  54372. {
  54373. }
  54374. void PropertyComponent::paint (Graphics& g)
  54375. {
  54376. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  54377. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  54378. }
  54379. void PropertyComponent::resized()
  54380. {
  54381. if (getNumChildComponents() > 0)
  54382. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  54383. }
  54384. void PropertyComponent::enablementChanged()
  54385. {
  54386. repaint();
  54387. }
  54388. END_JUCE_NAMESPACE
  54389. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  54390. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  54391. BEGIN_JUCE_NAMESPACE
  54392. class PropertyHolderComponent : public Component
  54393. {
  54394. public:
  54395. PropertyHolderComponent()
  54396. {
  54397. }
  54398. ~PropertyHolderComponent()
  54399. {
  54400. deleteAllChildren();
  54401. }
  54402. void paint (Graphics&)
  54403. {
  54404. }
  54405. void updateLayout (const int width);
  54406. void refreshAll() const;
  54407. };
  54408. class PropertySectionComponent : public Component
  54409. {
  54410. public:
  54411. PropertySectionComponent (const String& sectionTitle,
  54412. const Array <PropertyComponent*>& newProperties,
  54413. const bool open)
  54414. : Component (sectionTitle),
  54415. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  54416. isOpen_ (open)
  54417. {
  54418. for (int i = newProperties.size(); --i >= 0;)
  54419. {
  54420. addAndMakeVisible (newProperties.getUnchecked(i));
  54421. newProperties.getUnchecked(i)->refresh();
  54422. }
  54423. }
  54424. ~PropertySectionComponent()
  54425. {
  54426. deleteAllChildren();
  54427. }
  54428. void paint (Graphics& g)
  54429. {
  54430. if (titleHeight > 0)
  54431. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  54432. }
  54433. void resized()
  54434. {
  54435. int y = titleHeight;
  54436. for (int i = getNumChildComponents(); --i >= 0;)
  54437. {
  54438. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54439. if (pec != 0)
  54440. {
  54441. const int prefH = pec->getPreferredHeight();
  54442. pec->setBounds (1, y, getWidth() - 2, prefH);
  54443. y += prefH;
  54444. }
  54445. }
  54446. }
  54447. int getPreferredHeight() const
  54448. {
  54449. int y = titleHeight;
  54450. if (isOpen())
  54451. {
  54452. for (int i = 0; i < getNumChildComponents(); ++i)
  54453. {
  54454. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54455. if (pec != 0)
  54456. y += pec->getPreferredHeight();
  54457. }
  54458. }
  54459. return y;
  54460. }
  54461. void setOpen (const bool open)
  54462. {
  54463. if (isOpen_ != open)
  54464. {
  54465. isOpen_ = open;
  54466. for (int i = 0; i < getNumChildComponents(); ++i)
  54467. {
  54468. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54469. if (pec != 0)
  54470. pec->setVisible (open);
  54471. }
  54472. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  54473. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  54474. if (pp != 0)
  54475. pp->resized();
  54476. }
  54477. }
  54478. bool isOpen() const throw()
  54479. {
  54480. return isOpen_;
  54481. }
  54482. void refreshAll() const
  54483. {
  54484. for (int i = 0; i < getNumChildComponents(); ++i)
  54485. {
  54486. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54487. if (pec != 0)
  54488. pec->refresh();
  54489. }
  54490. }
  54491. void mouseDown (const MouseEvent&)
  54492. {
  54493. }
  54494. void mouseUp (const MouseEvent& e)
  54495. {
  54496. if (e.getMouseDownX() < titleHeight
  54497. && e.x < titleHeight
  54498. && e.y < titleHeight
  54499. && e.getNumberOfClicks() != 2)
  54500. {
  54501. setOpen (! isOpen());
  54502. }
  54503. }
  54504. void mouseDoubleClick (const MouseEvent& e)
  54505. {
  54506. if (e.y < titleHeight)
  54507. setOpen (! isOpen());
  54508. }
  54509. private:
  54510. int titleHeight;
  54511. bool isOpen_;
  54512. };
  54513. void PropertyHolderComponent::updateLayout (const int width)
  54514. {
  54515. int y = 0;
  54516. for (int i = getNumChildComponents(); --i >= 0;)
  54517. {
  54518. PropertySectionComponent* const section
  54519. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54520. if (section != 0)
  54521. {
  54522. const int prefH = section->getPreferredHeight();
  54523. section->setBounds (0, y, width, prefH);
  54524. y += prefH;
  54525. }
  54526. }
  54527. setSize (width, y);
  54528. repaint();
  54529. }
  54530. void PropertyHolderComponent::refreshAll() const
  54531. {
  54532. for (int i = getNumChildComponents(); --i >= 0;)
  54533. {
  54534. PropertySectionComponent* const section
  54535. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54536. if (section != 0)
  54537. section->refreshAll();
  54538. }
  54539. }
  54540. PropertyPanel::PropertyPanel()
  54541. {
  54542. messageWhenEmpty = TRANS("(nothing selected)");
  54543. addAndMakeVisible (viewport = new Viewport());
  54544. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  54545. viewport->setFocusContainer (true);
  54546. }
  54547. PropertyPanel::~PropertyPanel()
  54548. {
  54549. clear();
  54550. deleteAllChildren();
  54551. }
  54552. void PropertyPanel::paint (Graphics& g)
  54553. {
  54554. if (propertyHolderComponent->getNumChildComponents() == 0)
  54555. {
  54556. g.setColour (Colours::black.withAlpha (0.5f));
  54557. g.setFont (14.0f);
  54558. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  54559. Justification::centred, true);
  54560. }
  54561. }
  54562. void PropertyPanel::resized()
  54563. {
  54564. viewport->setBounds (0, 0, getWidth(), getHeight());
  54565. updatePropHolderLayout();
  54566. }
  54567. void PropertyPanel::clear()
  54568. {
  54569. if (propertyHolderComponent->getNumChildComponents() > 0)
  54570. {
  54571. propertyHolderComponent->deleteAllChildren();
  54572. repaint();
  54573. }
  54574. }
  54575. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  54576. {
  54577. if (propertyHolderComponent->getNumChildComponents() == 0)
  54578. repaint();
  54579. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  54580. newProperties,
  54581. true), 0);
  54582. updatePropHolderLayout();
  54583. }
  54584. void PropertyPanel::addSection (const String& sectionTitle,
  54585. const Array <PropertyComponent*>& newProperties,
  54586. const bool shouldBeOpen)
  54587. {
  54588. jassert (sectionTitle.isNotEmpty());
  54589. if (propertyHolderComponent->getNumChildComponents() == 0)
  54590. repaint();
  54591. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  54592. newProperties,
  54593. shouldBeOpen), 0);
  54594. updatePropHolderLayout();
  54595. }
  54596. void PropertyPanel::updatePropHolderLayout() const
  54597. {
  54598. const int maxWidth = viewport->getMaximumVisibleWidth();
  54599. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  54600. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  54601. if (maxWidth != newMaxWidth)
  54602. {
  54603. // need to do this twice because of scrollbars changing the size, etc.
  54604. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  54605. }
  54606. }
  54607. void PropertyPanel::refreshAll() const
  54608. {
  54609. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  54610. }
  54611. const StringArray PropertyPanel::getSectionNames() const
  54612. {
  54613. StringArray s;
  54614. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54615. {
  54616. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54617. if (section != 0 && section->getName().isNotEmpty())
  54618. s.add (section->getName());
  54619. }
  54620. return s;
  54621. }
  54622. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  54623. {
  54624. int index = 0;
  54625. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54626. {
  54627. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54628. if (section != 0 && section->getName().isNotEmpty())
  54629. {
  54630. if (index == sectionIndex)
  54631. return section->isOpen();
  54632. ++index;
  54633. }
  54634. }
  54635. return false;
  54636. }
  54637. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  54638. {
  54639. int index = 0;
  54640. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54641. {
  54642. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54643. if (section != 0 && section->getName().isNotEmpty())
  54644. {
  54645. if (index == sectionIndex)
  54646. {
  54647. section->setOpen (shouldBeOpen);
  54648. break;
  54649. }
  54650. ++index;
  54651. }
  54652. }
  54653. }
  54654. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  54655. {
  54656. int index = 0;
  54657. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54658. {
  54659. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54660. if (section != 0 && section->getName().isNotEmpty())
  54661. {
  54662. if (index == sectionIndex)
  54663. {
  54664. section->setEnabled (shouldBeEnabled);
  54665. break;
  54666. }
  54667. ++index;
  54668. }
  54669. }
  54670. }
  54671. XmlElement* PropertyPanel::getOpennessState() const
  54672. {
  54673. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  54674. const StringArray sections (getSectionNames());
  54675. for (int i = 0; i < sections.size(); ++i)
  54676. {
  54677. if (sections[i].isNotEmpty())
  54678. {
  54679. XmlElement* const e = new XmlElement (T("SECTION"));
  54680. e->setAttribute (T("name"), sections[i]);
  54681. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  54682. xml->addChildElement (e);
  54683. }
  54684. }
  54685. return xml;
  54686. }
  54687. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  54688. {
  54689. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  54690. {
  54691. const StringArray sections (getSectionNames());
  54692. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  54693. {
  54694. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  54695. e->getBoolAttribute (T("open")));
  54696. }
  54697. }
  54698. }
  54699. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  54700. {
  54701. if (messageWhenEmpty != newMessage)
  54702. {
  54703. messageWhenEmpty = newMessage;
  54704. repaint();
  54705. }
  54706. }
  54707. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  54708. {
  54709. return messageWhenEmpty;
  54710. }
  54711. END_JUCE_NAMESPACE
  54712. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  54713. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  54714. BEGIN_JUCE_NAMESPACE
  54715. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  54716. const double rangeMin,
  54717. const double rangeMax,
  54718. const double interval,
  54719. const double skewFactor)
  54720. : PropertyComponent (name)
  54721. {
  54722. addAndMakeVisible (slider = new Slider (name));
  54723. slider->setRange (rangeMin, rangeMax, interval);
  54724. slider->setSkewFactor (skewFactor);
  54725. slider->setSliderStyle (Slider::LinearBar);
  54726. slider->addListener (this);
  54727. }
  54728. SliderPropertyComponent::~SliderPropertyComponent()
  54729. {
  54730. deleteAllChildren();
  54731. }
  54732. void SliderPropertyComponent::refresh()
  54733. {
  54734. slider->setValue (getValue(), false);
  54735. }
  54736. void SliderPropertyComponent::sliderValueChanged (Slider*)
  54737. {
  54738. if (getValue() != slider->getValue())
  54739. setValue (slider->getValue());
  54740. }
  54741. END_JUCE_NAMESPACE
  54742. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  54743. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  54744. BEGIN_JUCE_NAMESPACE
  54745. class TextPropLabel : public Label
  54746. {
  54747. TextPropertyComponent& owner;
  54748. int maxChars;
  54749. bool isMultiline;
  54750. public:
  54751. TextPropLabel (TextPropertyComponent& owner_,
  54752. const int maxChars_, const bool isMultiline_)
  54753. : Label (String::empty, String::empty),
  54754. owner (owner_),
  54755. maxChars (maxChars_),
  54756. isMultiline (isMultiline_)
  54757. {
  54758. setEditable (true, true, false);
  54759. setColour (backgroundColourId, Colours::white);
  54760. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  54761. }
  54762. ~TextPropLabel()
  54763. {
  54764. }
  54765. TextEditor* createEditorComponent()
  54766. {
  54767. TextEditor* const textEditor = Label::createEditorComponent();
  54768. textEditor->setInputRestrictions (maxChars);
  54769. if (isMultiline)
  54770. {
  54771. textEditor->setMultiLine (true, true);
  54772. textEditor->setReturnKeyStartsNewLine (true);
  54773. }
  54774. return textEditor;
  54775. }
  54776. void textWasEdited()
  54777. {
  54778. owner.textWasEdited();
  54779. }
  54780. };
  54781. TextPropertyComponent::TextPropertyComponent (const String& name,
  54782. const int maxNumChars,
  54783. const bool isMultiLine)
  54784. : PropertyComponent (name)
  54785. {
  54786. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  54787. if (isMultiLine)
  54788. {
  54789. textEditor->setJustificationType (Justification::topLeft);
  54790. preferredHeight = 120;
  54791. }
  54792. }
  54793. TextPropertyComponent::~TextPropertyComponent()
  54794. {
  54795. deleteAllChildren();
  54796. }
  54797. void TextPropertyComponent::refresh()
  54798. {
  54799. textEditor->setText (getText(), false);
  54800. }
  54801. void TextPropertyComponent::textWasEdited()
  54802. {
  54803. const String newText (textEditor->getText());
  54804. if (getText() != newText)
  54805. setText (newText);
  54806. }
  54807. END_JUCE_NAMESPACE
  54808. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  54809. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54810. BEGIN_JUCE_NAMESPACE
  54811. class SimpleDeviceManagerInputLevelMeter : public Component,
  54812. public Timer
  54813. {
  54814. public:
  54815. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  54816. : manager (manager_),
  54817. level (0)
  54818. {
  54819. startTimer (50);
  54820. manager->enableInputLevelMeasurement (true);
  54821. }
  54822. ~SimpleDeviceManagerInputLevelMeter()
  54823. {
  54824. manager->enableInputLevelMeasurement (false);
  54825. }
  54826. void timerCallback()
  54827. {
  54828. const float newLevel = (float) manager->getCurrentInputLevel();
  54829. if (fabsf (level - newLevel) > 0.005f)
  54830. {
  54831. level = newLevel;
  54832. repaint();
  54833. }
  54834. }
  54835. void paint (Graphics& g)
  54836. {
  54837. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  54838. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  54839. }
  54840. private:
  54841. AudioDeviceManager* const manager;
  54842. float level;
  54843. };
  54844. class MidiInputSelectorComponentListBox : public ListBox,
  54845. public ListBoxModel
  54846. {
  54847. public:
  54848. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  54849. const String& noItemsMessage_,
  54850. const int minNumber_,
  54851. const int maxNumber_)
  54852. : ListBox (String::empty, 0),
  54853. deviceManager (deviceManager_),
  54854. noItemsMessage (noItemsMessage_),
  54855. minNumber (minNumber_),
  54856. maxNumber (maxNumber_)
  54857. {
  54858. items = MidiInput::getDevices();
  54859. setModel (this);
  54860. setOutlineThickness (1);
  54861. }
  54862. ~MidiInputSelectorComponentListBox()
  54863. {
  54864. }
  54865. int getNumRows()
  54866. {
  54867. return items.size();
  54868. }
  54869. void paintListBoxItem (int row,
  54870. Graphics& g,
  54871. int width, int height,
  54872. bool rowIsSelected)
  54873. {
  54874. if (((unsigned int) row) < (unsigned int) items.size())
  54875. {
  54876. if (rowIsSelected)
  54877. g.fillAll (findColour (TextEditor::highlightColourId)
  54878. .withMultipliedAlpha (0.3f));
  54879. const String item (items [row]);
  54880. bool enabled = deviceManager.isMidiInputEnabled (item);
  54881. const int x = getTickX();
  54882. const int tickW = height - height / 4;
  54883. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  54884. enabled, true, true, false);
  54885. g.setFont (height * 0.6f);
  54886. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  54887. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  54888. }
  54889. }
  54890. void listBoxItemClicked (int row, const MouseEvent& e)
  54891. {
  54892. selectRow (row);
  54893. if (e.x < getTickX())
  54894. flipEnablement (row);
  54895. }
  54896. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  54897. {
  54898. flipEnablement (row);
  54899. }
  54900. void returnKeyPressed (int row)
  54901. {
  54902. flipEnablement (row);
  54903. }
  54904. void paint (Graphics& g)
  54905. {
  54906. ListBox::paint (g);
  54907. if (items.size() == 0)
  54908. {
  54909. g.setColour (Colours::grey);
  54910. g.setFont (13.0f);
  54911. g.drawText (noItemsMessage,
  54912. 0, 0, getWidth(), getHeight() / 2,
  54913. Justification::centred, true);
  54914. }
  54915. }
  54916. int getBestHeight (const int preferredHeight)
  54917. {
  54918. const int extra = getOutlineThickness() * 2;
  54919. return jmax (getRowHeight() * 2 + extra,
  54920. jmin (getRowHeight() * getNumRows() + extra,
  54921. preferredHeight));
  54922. }
  54923. juce_UseDebuggingNewOperator
  54924. private:
  54925. AudioDeviceManager& deviceManager;
  54926. const String noItemsMessage;
  54927. StringArray items;
  54928. int minNumber, maxNumber;
  54929. void flipEnablement (const int row)
  54930. {
  54931. if (((unsigned int) row) < (unsigned int) items.size())
  54932. {
  54933. const String item (items [row]);
  54934. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  54935. }
  54936. }
  54937. int getTickX() const throw()
  54938. {
  54939. return getRowHeight() + 5;
  54940. }
  54941. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  54942. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  54943. };
  54944. class AudioDeviceSettingsPanel : public Component,
  54945. public ComboBoxListener,
  54946. public ChangeListener,
  54947. public ButtonListener
  54948. {
  54949. public:
  54950. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  54951. AudioIODeviceType::DeviceSetupDetails& setup_,
  54952. const bool hideAdvancedOptionsWithButton)
  54953. : type (type_),
  54954. setup (setup_)
  54955. {
  54956. sampleRateDropDown = 0;
  54957. sampleRateLabel = 0;
  54958. bufferSizeDropDown = 0;
  54959. bufferSizeLabel = 0;
  54960. outputDeviceDropDown = 0;
  54961. outputDeviceLabel = 0;
  54962. inputDeviceDropDown = 0;
  54963. inputDeviceLabel = 0;
  54964. testButton = 0;
  54965. inputLevelMeter = 0;
  54966. showUIButton = 0;
  54967. inputChanList = 0;
  54968. outputChanList = 0;
  54969. inputChanLabel = 0;
  54970. outputChanLabel = 0;
  54971. showAdvancedSettingsButton = 0;
  54972. if (hideAdvancedOptionsWithButton)
  54973. {
  54974. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  54975. showAdvancedSettingsButton->addButtonListener (this);
  54976. }
  54977. type->scanForDevices();
  54978. setup.manager->addChangeListener (this);
  54979. changeListenerCallback (0);
  54980. }
  54981. ~AudioDeviceSettingsPanel()
  54982. {
  54983. setup.manager->removeChangeListener (this);
  54984. deleteAndZero (outputDeviceLabel);
  54985. deleteAndZero (inputDeviceLabel);
  54986. deleteAndZero (sampleRateLabel);
  54987. deleteAndZero (bufferSizeLabel);
  54988. deleteAndZero (showUIButton);
  54989. deleteAndZero (inputChanLabel);
  54990. deleteAndZero (outputChanLabel);
  54991. deleteAndZero (showAdvancedSettingsButton);
  54992. deleteAllChildren();
  54993. }
  54994. void resized()
  54995. {
  54996. const int lx = proportionOfWidth (0.35f);
  54997. const int w = proportionOfWidth (0.4f);
  54998. const int h = 24;
  54999. const int space = 6;
  55000. const int dh = h + space;
  55001. int y = 0;
  55002. if (outputDeviceDropDown != 0)
  55003. {
  55004. outputDeviceDropDown->setBounds (lx, y, w, h);
  55005. if (testButton != 0)
  55006. testButton->setBounds (proportionOfWidth (0.77f),
  55007. outputDeviceDropDown->getY(),
  55008. proportionOfWidth (0.18f),
  55009. h);
  55010. y += dh;
  55011. }
  55012. if (inputDeviceDropDown != 0)
  55013. {
  55014. inputDeviceDropDown->setBounds (lx, y, w, h);
  55015. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  55016. inputDeviceDropDown->getY(),
  55017. proportionOfWidth (0.18f),
  55018. h);
  55019. y += dh;
  55020. }
  55021. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  55022. if (outputChanList != 0)
  55023. {
  55024. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  55025. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  55026. y += bh + space;
  55027. }
  55028. if (inputChanList != 0)
  55029. {
  55030. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  55031. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  55032. y += bh + space;
  55033. }
  55034. y += space * 2;
  55035. if (showAdvancedSettingsButton != 0)
  55036. {
  55037. showAdvancedSettingsButton->changeWidthToFitText (h);
  55038. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  55039. }
  55040. if (sampleRateDropDown != 0)
  55041. {
  55042. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  55043. || ! showAdvancedSettingsButton->isVisible());
  55044. sampleRateDropDown->setBounds (lx, y, w, h);
  55045. y += dh;
  55046. }
  55047. if (bufferSizeDropDown != 0)
  55048. {
  55049. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  55050. || ! showAdvancedSettingsButton->isVisible());
  55051. bufferSizeDropDown->setBounds (lx, y, w, h);
  55052. y += dh;
  55053. }
  55054. if (showUIButton != 0)
  55055. {
  55056. showUIButton->setVisible (showAdvancedSettingsButton == 0
  55057. || ! showAdvancedSettingsButton->isVisible());
  55058. showUIButton->changeWidthToFitText (h);
  55059. showUIButton->setTopLeftPosition (lx, y);
  55060. }
  55061. }
  55062. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55063. {
  55064. if (comboBoxThatHasChanged == 0)
  55065. return;
  55066. AudioDeviceManager::AudioDeviceSetup config;
  55067. setup.manager->getAudioDeviceSetup (config);
  55068. String error;
  55069. if (comboBoxThatHasChanged == outputDeviceDropDown
  55070. || comboBoxThatHasChanged == inputDeviceDropDown)
  55071. {
  55072. if (outputDeviceDropDown != 0)
  55073. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  55074. : outputDeviceDropDown->getText();
  55075. if (inputDeviceDropDown != 0)
  55076. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  55077. : inputDeviceDropDown->getText();
  55078. if (! type->hasSeparateInputsAndOutputs())
  55079. config.inputDeviceName = config.outputDeviceName;
  55080. if (comboBoxThatHasChanged == inputDeviceDropDown)
  55081. config.useDefaultInputChannels = true;
  55082. else
  55083. config.useDefaultOutputChannels = true;
  55084. error = setup.manager->setAudioDeviceSetup (config, true);
  55085. showCorrectDeviceName (inputDeviceDropDown, true);
  55086. showCorrectDeviceName (outputDeviceDropDown, false);
  55087. updateControlPanelButton();
  55088. resized();
  55089. }
  55090. else if (comboBoxThatHasChanged == sampleRateDropDown)
  55091. {
  55092. if (sampleRateDropDown->getSelectedId() > 0)
  55093. {
  55094. config.sampleRate = sampleRateDropDown->getSelectedId();
  55095. error = setup.manager->setAudioDeviceSetup (config, true);
  55096. }
  55097. }
  55098. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  55099. {
  55100. if (bufferSizeDropDown->getSelectedId() > 0)
  55101. {
  55102. config.bufferSize = bufferSizeDropDown->getSelectedId();
  55103. error = setup.manager->setAudioDeviceSetup (config, true);
  55104. }
  55105. }
  55106. if (error.isNotEmpty())
  55107. {
  55108. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  55109. T("Error when trying to open audio device!"),
  55110. error);
  55111. }
  55112. }
  55113. void buttonClicked (Button* button)
  55114. {
  55115. if (button == showAdvancedSettingsButton)
  55116. {
  55117. showAdvancedSettingsButton->setVisible (false);
  55118. resized();
  55119. }
  55120. else if (button == showUIButton)
  55121. {
  55122. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  55123. if (device != 0 && device->showControlPanel())
  55124. {
  55125. setup.manager->closeAudioDevice();
  55126. setup.manager->restartLastAudioDevice();
  55127. getTopLevelComponent()->toFront (true);
  55128. }
  55129. }
  55130. else if (button == testButton && testButton != 0)
  55131. {
  55132. setup.manager->playTestSound();
  55133. }
  55134. }
  55135. void updateControlPanelButton()
  55136. {
  55137. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55138. deleteAndZero (showUIButton);
  55139. if (currentDevice != 0 && currentDevice->hasControlPanel())
  55140. {
  55141. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  55142. TRANS ("opens the device's own control panel")));
  55143. showUIButton->addButtonListener (this);
  55144. }
  55145. resized();
  55146. }
  55147. void changeListenerCallback (void*)
  55148. {
  55149. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55150. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  55151. {
  55152. if (outputDeviceDropDown == 0)
  55153. {
  55154. outputDeviceDropDown = new ComboBox (String::empty);
  55155. outputDeviceDropDown->addListener (this);
  55156. addAndMakeVisible (outputDeviceDropDown);
  55157. outputDeviceLabel = new Label (String::empty,
  55158. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  55159. : TRANS ("device:"));
  55160. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  55161. if (setup.maxNumOutputChannels > 0)
  55162. {
  55163. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  55164. testButton->addButtonListener (this);
  55165. }
  55166. }
  55167. addNamesToDeviceBox (*outputDeviceDropDown, false);
  55168. }
  55169. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  55170. {
  55171. if (inputDeviceDropDown == 0)
  55172. {
  55173. inputDeviceDropDown = new ComboBox (String::empty);
  55174. inputDeviceDropDown->addListener (this);
  55175. addAndMakeVisible (inputDeviceDropDown);
  55176. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  55177. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  55178. addAndMakeVisible (inputLevelMeter
  55179. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  55180. }
  55181. addNamesToDeviceBox (*inputDeviceDropDown, true);
  55182. }
  55183. updateControlPanelButton();
  55184. showCorrectDeviceName (inputDeviceDropDown, true);
  55185. showCorrectDeviceName (outputDeviceDropDown, false);
  55186. if (currentDevice != 0)
  55187. {
  55188. if (setup.maxNumOutputChannels > 0
  55189. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  55190. {
  55191. if (outputChanList == 0)
  55192. {
  55193. addAndMakeVisible (outputChanList
  55194. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  55195. TRANS ("(no audio output channels found)")));
  55196. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  55197. outputChanLabel->attachToComponent (outputChanList, true);
  55198. }
  55199. outputChanList->refresh();
  55200. }
  55201. else
  55202. {
  55203. deleteAndZero (outputChanLabel);
  55204. deleteAndZero (outputChanList);
  55205. }
  55206. if (setup.maxNumInputChannels > 0
  55207. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  55208. {
  55209. if (inputChanList == 0)
  55210. {
  55211. addAndMakeVisible (inputChanList
  55212. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  55213. TRANS ("(no audio input channels found)")));
  55214. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  55215. inputChanLabel->attachToComponent (inputChanList, true);
  55216. }
  55217. inputChanList->refresh();
  55218. }
  55219. else
  55220. {
  55221. deleteAndZero (inputChanLabel);
  55222. deleteAndZero (inputChanList);
  55223. }
  55224. // sample rate..
  55225. {
  55226. if (sampleRateDropDown == 0)
  55227. {
  55228. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  55229. sampleRateDropDown->addListener (this);
  55230. delete sampleRateLabel;
  55231. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  55232. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  55233. }
  55234. else
  55235. {
  55236. sampleRateDropDown->clear();
  55237. sampleRateDropDown->removeListener (this);
  55238. }
  55239. const int numRates = currentDevice->getNumSampleRates();
  55240. for (int i = 0; i < numRates; ++i)
  55241. {
  55242. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  55243. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  55244. }
  55245. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  55246. sampleRateDropDown->addListener (this);
  55247. }
  55248. // buffer size
  55249. {
  55250. if (bufferSizeDropDown == 0)
  55251. {
  55252. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  55253. bufferSizeDropDown->addListener (this);
  55254. delete bufferSizeLabel;
  55255. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  55256. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  55257. }
  55258. else
  55259. {
  55260. bufferSizeDropDown->clear();
  55261. }
  55262. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  55263. double currentRate = currentDevice->getCurrentSampleRate();
  55264. if (currentRate == 0)
  55265. currentRate = 48000.0;
  55266. for (int i = 0; i < numBufferSizes; ++i)
  55267. {
  55268. const int bs = currentDevice->getBufferSizeSamples (i);
  55269. bufferSizeDropDown->addItem (String (bs)
  55270. + T(" samples (")
  55271. + String (bs * 1000.0 / currentRate, 1)
  55272. + T(" ms)"),
  55273. bs);
  55274. }
  55275. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  55276. }
  55277. }
  55278. else
  55279. {
  55280. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  55281. deleteAndZero (sampleRateLabel);
  55282. deleteAndZero (bufferSizeLabel);
  55283. deleteAndZero (sampleRateDropDown);
  55284. deleteAndZero (bufferSizeDropDown);
  55285. if (outputDeviceDropDown != 0)
  55286. outputDeviceDropDown->setSelectedId (-1, true);
  55287. if (inputDeviceDropDown != 0)
  55288. inputDeviceDropDown->setSelectedId (-1, true);
  55289. }
  55290. resized();
  55291. setSize (getWidth(), getLowestY() + 4);
  55292. }
  55293. private:
  55294. AudioIODeviceType* const type;
  55295. const AudioIODeviceType::DeviceSetupDetails setup;
  55296. ComboBox* outputDeviceDropDown;
  55297. ComboBox* inputDeviceDropDown;
  55298. ComboBox* sampleRateDropDown;
  55299. ComboBox* bufferSizeDropDown;
  55300. Label* outputDeviceLabel;
  55301. Label* inputDeviceLabel;
  55302. Label* sampleRateLabel;
  55303. Label* bufferSizeLabel;
  55304. Label* inputChanLabel;
  55305. Label* outputChanLabel;
  55306. TextButton* testButton;
  55307. Component* inputLevelMeter;
  55308. TextButton* showUIButton;
  55309. TextButton* showAdvancedSettingsButton;
  55310. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  55311. {
  55312. if (box != 0)
  55313. {
  55314. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  55315. const int index = type->getIndexOfDevice (currentDevice, isInput);
  55316. box->setSelectedId (index + 1, true);
  55317. if (testButton != 0 && ! isInput)
  55318. testButton->setEnabled (index >= 0);
  55319. }
  55320. }
  55321. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  55322. {
  55323. const StringArray devs (type->getDeviceNames (isInputs));
  55324. combo.clear (true);
  55325. for (int i = 0; i < devs.size(); ++i)
  55326. combo.addItem (devs[i], i + 1);
  55327. combo.addItem (TRANS("<< none >>"), -1);
  55328. combo.setSelectedId (-1, true);
  55329. }
  55330. int getLowestY() const
  55331. {
  55332. int y = 0;
  55333. for (int i = getNumChildComponents(); --i >= 0;)
  55334. y = jmax (y, getChildComponent (i)->getBottom());
  55335. return y;
  55336. }
  55337. class ChannelSelectorListBox : public ListBox,
  55338. public ListBoxModel
  55339. {
  55340. public:
  55341. enum BoxType
  55342. {
  55343. audioInputType,
  55344. audioOutputType
  55345. };
  55346. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  55347. const BoxType type_,
  55348. const String& noItemsMessage_)
  55349. : ListBox (String::empty, 0),
  55350. setup (setup_),
  55351. type (type_),
  55352. noItemsMessage (noItemsMessage_)
  55353. {
  55354. refresh();
  55355. setModel (this);
  55356. setOutlineThickness (1);
  55357. }
  55358. ~ChannelSelectorListBox()
  55359. {
  55360. }
  55361. void refresh()
  55362. {
  55363. items.clear();
  55364. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55365. if (currentDevice != 0)
  55366. {
  55367. if (type == audioInputType)
  55368. items = currentDevice->getInputChannelNames();
  55369. else if (type == audioOutputType)
  55370. items = currentDevice->getOutputChannelNames();
  55371. if (setup.useStereoPairs)
  55372. {
  55373. StringArray pairs;
  55374. for (int i = 0; i < items.size(); i += 2)
  55375. {
  55376. String name (items[i]);
  55377. String name2 (items[i + 1]);
  55378. String commonBit;
  55379. for (int j = 0; j < name.length(); ++j)
  55380. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  55381. commonBit = name.substring (0, j);
  55382. pairs.add (name.trim()
  55383. + " + "
  55384. + name2.substring (commonBit.length()).trim());
  55385. }
  55386. items = pairs;
  55387. }
  55388. }
  55389. updateContent();
  55390. repaint();
  55391. }
  55392. int getNumRows()
  55393. {
  55394. return items.size();
  55395. }
  55396. void paintListBoxItem (int row,
  55397. Graphics& g,
  55398. int width, int height,
  55399. bool rowIsSelected)
  55400. {
  55401. if (((unsigned int) row) < (unsigned int) items.size())
  55402. {
  55403. if (rowIsSelected)
  55404. g.fillAll (findColour (TextEditor::highlightColourId)
  55405. .withMultipliedAlpha (0.3f));
  55406. const String item (items [row]);
  55407. bool enabled = false;
  55408. AudioDeviceManager::AudioDeviceSetup config;
  55409. setup.manager->getAudioDeviceSetup (config);
  55410. if (setup.useStereoPairs)
  55411. {
  55412. if (type == audioInputType)
  55413. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  55414. else if (type == audioOutputType)
  55415. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  55416. }
  55417. else
  55418. {
  55419. if (type == audioInputType)
  55420. enabled = config.inputChannels [row];
  55421. else if (type == audioOutputType)
  55422. enabled = config.outputChannels [row];
  55423. }
  55424. const int x = getTickX();
  55425. const int tickW = height - height / 4;
  55426. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  55427. enabled, true, true, false);
  55428. g.setFont (height * 0.6f);
  55429. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  55430. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  55431. }
  55432. }
  55433. void listBoxItemClicked (int row, const MouseEvent& e)
  55434. {
  55435. selectRow (row);
  55436. if (e.x < getTickX())
  55437. flipEnablement (row);
  55438. }
  55439. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  55440. {
  55441. flipEnablement (row);
  55442. }
  55443. void returnKeyPressed (int row)
  55444. {
  55445. flipEnablement (row);
  55446. }
  55447. void paint (Graphics& g)
  55448. {
  55449. ListBox::paint (g);
  55450. if (items.size() == 0)
  55451. {
  55452. g.setColour (Colours::grey);
  55453. g.setFont (13.0f);
  55454. g.drawText (noItemsMessage,
  55455. 0, 0, getWidth(), getHeight() / 2,
  55456. Justification::centred, true);
  55457. }
  55458. }
  55459. int getBestHeight (int maxHeight)
  55460. {
  55461. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  55462. getNumRows())
  55463. + getOutlineThickness() * 2;
  55464. }
  55465. juce_UseDebuggingNewOperator
  55466. private:
  55467. const AudioIODeviceType::DeviceSetupDetails setup;
  55468. const BoxType type;
  55469. const String noItemsMessage;
  55470. StringArray items;
  55471. void flipEnablement (const int row)
  55472. {
  55473. jassert (type == audioInputType || type == audioOutputType);
  55474. if (((unsigned int) row) < (unsigned int) items.size())
  55475. {
  55476. AudioDeviceManager::AudioDeviceSetup config;
  55477. setup.manager->getAudioDeviceSetup (config);
  55478. if (setup.useStereoPairs)
  55479. {
  55480. BitArray bits;
  55481. BitArray& original = (type == audioInputType ? config.inputChannels
  55482. : config.outputChannels);
  55483. int i;
  55484. for (i = 0; i < 256; i += 2)
  55485. bits.setBit (i / 2, original [i] || original [i + 1]);
  55486. if (type == audioInputType)
  55487. {
  55488. config.useDefaultInputChannels = false;
  55489. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  55490. }
  55491. else
  55492. {
  55493. config.useDefaultOutputChannels = false;
  55494. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  55495. }
  55496. for (i = 0; i < 256; ++i)
  55497. original.setBit (i, bits [i / 2]);
  55498. }
  55499. else
  55500. {
  55501. if (type == audioInputType)
  55502. {
  55503. config.useDefaultInputChannels = false;
  55504. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  55505. }
  55506. else
  55507. {
  55508. config.useDefaultOutputChannels = false;
  55509. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  55510. }
  55511. }
  55512. String error (setup.manager->setAudioDeviceSetup (config, true));
  55513. if (! error.isEmpty())
  55514. {
  55515. //xxx
  55516. }
  55517. }
  55518. }
  55519. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  55520. {
  55521. const int numActive = chans.countNumberOfSetBits();
  55522. if (chans [index])
  55523. {
  55524. if (numActive > minNumber)
  55525. chans.setBit (index, false);
  55526. }
  55527. else
  55528. {
  55529. if (numActive >= maxNumber)
  55530. {
  55531. const int firstActiveChan = chans.findNextSetBit();
  55532. chans.setBit (index > firstActiveChan
  55533. ? firstActiveChan : chans.getHighestBit(),
  55534. false);
  55535. }
  55536. chans.setBit (index, true);
  55537. }
  55538. }
  55539. int getTickX() const throw()
  55540. {
  55541. return getRowHeight() + 5;
  55542. }
  55543. ChannelSelectorListBox (const ChannelSelectorListBox&);
  55544. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  55545. };
  55546. ChannelSelectorListBox* inputChanList;
  55547. ChannelSelectorListBox* outputChanList;
  55548. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  55549. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  55550. };
  55551. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  55552. const int minInputChannels_,
  55553. const int maxInputChannels_,
  55554. const int minOutputChannels_,
  55555. const int maxOutputChannels_,
  55556. const bool showMidiInputOptions,
  55557. const bool showMidiOutputSelector,
  55558. const bool showChannelsAsStereoPairs_,
  55559. const bool hideAdvancedOptionsWithButton_)
  55560. : deviceManager (deviceManager_),
  55561. deviceTypeDropDown (0),
  55562. deviceTypeDropDownLabel (0),
  55563. audioDeviceSettingsComp (0),
  55564. minOutputChannels (minOutputChannels_),
  55565. maxOutputChannels (maxOutputChannels_),
  55566. minInputChannels (minInputChannels_),
  55567. maxInputChannels (maxInputChannels_),
  55568. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  55569. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  55570. {
  55571. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  55572. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  55573. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  55574. {
  55575. deviceTypeDropDown = new ComboBox (String::empty);
  55576. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  55577. {
  55578. deviceTypeDropDown
  55579. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  55580. i + 1);
  55581. }
  55582. addAndMakeVisible (deviceTypeDropDown);
  55583. deviceTypeDropDown->addListener (this);
  55584. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  55585. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  55586. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  55587. }
  55588. if (showMidiInputOptions)
  55589. {
  55590. addAndMakeVisible (midiInputsList
  55591. = new MidiInputSelectorComponentListBox (deviceManager,
  55592. TRANS("(no midi inputs available)"),
  55593. 0, 0));
  55594. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  55595. midiInputsLabel->setJustificationType (Justification::topRight);
  55596. midiInputsLabel->attachToComponent (midiInputsList, true);
  55597. }
  55598. else
  55599. {
  55600. midiInputsList = 0;
  55601. midiInputsLabel = 0;
  55602. }
  55603. if (showMidiOutputSelector)
  55604. {
  55605. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  55606. midiOutputSelector->addListener (this);
  55607. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  55608. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  55609. }
  55610. else
  55611. {
  55612. midiOutputSelector = 0;
  55613. midiOutputLabel = 0;
  55614. }
  55615. deviceManager_.addChangeListener (this);
  55616. changeListenerCallback (0);
  55617. }
  55618. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  55619. {
  55620. deviceManager.removeChangeListener (this);
  55621. deleteAllChildren();
  55622. }
  55623. void AudioDeviceSelectorComponent::resized()
  55624. {
  55625. const int lx = proportionOfWidth (0.35f);
  55626. const int w = proportionOfWidth (0.4f);
  55627. const int h = 24;
  55628. const int space = 6;
  55629. const int dh = h + space;
  55630. int y = 15;
  55631. if (deviceTypeDropDown != 0)
  55632. {
  55633. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  55634. y += dh + space * 2;
  55635. }
  55636. if (audioDeviceSettingsComp != 0)
  55637. {
  55638. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  55639. y += audioDeviceSettingsComp->getHeight() + space;
  55640. }
  55641. if (midiInputsList != 0)
  55642. {
  55643. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  55644. midiInputsList->setBounds (lx, y, w, bh);
  55645. y += bh + space;
  55646. }
  55647. if (midiOutputSelector != 0)
  55648. midiOutputSelector->setBounds (lx, y, w, h);
  55649. }
  55650. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  55651. {
  55652. if (child == audioDeviceSettingsComp)
  55653. resized();
  55654. }
  55655. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  55656. {
  55657. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  55658. if (device != 0 && device->hasControlPanel())
  55659. {
  55660. if (device->showControlPanel())
  55661. deviceManager.restartLastAudioDevice();
  55662. getTopLevelComponent()->toFront (true);
  55663. }
  55664. }
  55665. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55666. {
  55667. if (comboBoxThatHasChanged == deviceTypeDropDown)
  55668. {
  55669. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  55670. if (type != 0)
  55671. {
  55672. deleteAndZero (audioDeviceSettingsComp);
  55673. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  55674. changeListenerCallback (0); // needed in case the type hasn't actally changed
  55675. }
  55676. }
  55677. else if (comboBoxThatHasChanged == midiOutputSelector)
  55678. {
  55679. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  55680. }
  55681. }
  55682. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  55683. {
  55684. if (deviceTypeDropDown != 0)
  55685. {
  55686. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  55687. }
  55688. if (audioDeviceSettingsComp == 0
  55689. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  55690. {
  55691. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  55692. deleteAndZero (audioDeviceSettingsComp);
  55693. AudioIODeviceType* const type
  55694. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  55695. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  55696. if (type != 0)
  55697. {
  55698. AudioIODeviceType::DeviceSetupDetails details;
  55699. details.manager = &deviceManager;
  55700. details.minNumInputChannels = minInputChannels;
  55701. details.maxNumInputChannels = maxInputChannels;
  55702. details.minNumOutputChannels = minOutputChannels;
  55703. details.maxNumOutputChannels = maxOutputChannels;
  55704. details.useStereoPairs = showChannelsAsStereoPairs;
  55705. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  55706. if (audioDeviceSettingsComp != 0)
  55707. {
  55708. addAndMakeVisible (audioDeviceSettingsComp);
  55709. audioDeviceSettingsComp->resized();
  55710. }
  55711. }
  55712. }
  55713. if (midiInputsList != 0)
  55714. {
  55715. midiInputsList->updateContent();
  55716. midiInputsList->repaint();
  55717. }
  55718. if (midiOutputSelector != 0)
  55719. {
  55720. midiOutputSelector->clear();
  55721. const StringArray midiOuts (MidiOutput::getDevices());
  55722. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  55723. midiOutputSelector->addSeparator();
  55724. for (int i = 0; i < midiOuts.size(); ++i)
  55725. midiOutputSelector->addItem (midiOuts[i], i + 1);
  55726. int current = -1;
  55727. if (deviceManager.getDefaultMidiOutput() != 0)
  55728. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  55729. midiOutputSelector->setSelectedId (current, true);
  55730. }
  55731. resized();
  55732. }
  55733. END_JUCE_NAMESPACE
  55734. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  55735. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  55736. BEGIN_JUCE_NAMESPACE
  55737. BubbleComponent::BubbleComponent()
  55738. : side (0),
  55739. allowablePlacements (above | below | left | right),
  55740. arrowTipX (0.0f),
  55741. arrowTipY (0.0f)
  55742. {
  55743. setInterceptsMouseClicks (false, false);
  55744. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  55745. setComponentEffect (&shadow);
  55746. }
  55747. BubbleComponent::~BubbleComponent()
  55748. {
  55749. }
  55750. void BubbleComponent::paint (Graphics& g)
  55751. {
  55752. int x = content.getX();
  55753. int y = content.getY();
  55754. int w = content.getWidth();
  55755. int h = content.getHeight();
  55756. int cw, ch;
  55757. getContentSize (cw, ch);
  55758. if (side == 3)
  55759. x += w - cw;
  55760. else if (side != 1)
  55761. x += (w - cw) / 2;
  55762. w = cw;
  55763. if (side == 2)
  55764. y += h - ch;
  55765. else if (side != 0)
  55766. y += (h - ch) / 2;
  55767. h = ch;
  55768. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  55769. (float) x, (float) y,
  55770. (float) w, (float) h);
  55771. const int cx = x + (w - cw) / 2;
  55772. const int cy = y + (h - ch) / 2;
  55773. const int indent = 3;
  55774. g.setOrigin (cx + indent, cy + indent);
  55775. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  55776. paintContent (g, cw - indent * 2, ch - indent * 2);
  55777. }
  55778. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  55779. {
  55780. allowablePlacements = newPlacement;
  55781. }
  55782. void BubbleComponent::setPosition (Component* componentToPointTo)
  55783. {
  55784. jassert (componentToPointTo->isValidComponent());
  55785. int tx = 0;
  55786. int ty = 0;
  55787. if (getParentComponent() != 0)
  55788. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  55789. else
  55790. componentToPointTo->relativePositionToGlobal (tx, ty);
  55791. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  55792. }
  55793. void BubbleComponent::setPosition (const int arrowTipX,
  55794. const int arrowTipY)
  55795. {
  55796. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  55797. }
  55798. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  55799. {
  55800. Rectangle availableSpace;
  55801. if (getParentComponent() != 0)
  55802. {
  55803. availableSpace.setSize (getParentComponent()->getWidth(),
  55804. getParentComponent()->getHeight());
  55805. }
  55806. else
  55807. {
  55808. availableSpace = getParentMonitorArea();
  55809. }
  55810. int x = 0;
  55811. int y = 0;
  55812. int w = 150;
  55813. int h = 30;
  55814. getContentSize (w, h);
  55815. w += 30;
  55816. h += 30;
  55817. const float edgeIndent = 2.0f;
  55818. const int arrowLength = jmin (10, h / 3, w / 3);
  55819. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  55820. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  55821. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  55822. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  55823. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  55824. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  55825. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  55826. {
  55827. spaceLeft = spaceRight = 0;
  55828. }
  55829. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  55830. && (spaceLeft > w + 20 || spaceRight > w + 20))
  55831. {
  55832. spaceAbove = spaceBelow = 0;
  55833. }
  55834. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  55835. {
  55836. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  55837. arrowTipX = w * 0.5f;
  55838. content.setSize (w, h - arrowLength);
  55839. if (spaceAbove >= spaceBelow)
  55840. {
  55841. // above
  55842. y = rectangleToPointTo.getY() - h;
  55843. content.setPosition (0, 0);
  55844. arrowTipY = h - edgeIndent;
  55845. side = 2;
  55846. }
  55847. else
  55848. {
  55849. // below
  55850. y = rectangleToPointTo.getBottom();
  55851. content.setPosition (0, arrowLength);
  55852. arrowTipY = edgeIndent;
  55853. side = 0;
  55854. }
  55855. }
  55856. else
  55857. {
  55858. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  55859. arrowTipY = h * 0.5f;
  55860. content.setSize (w - arrowLength, h);
  55861. if (spaceLeft > spaceRight)
  55862. {
  55863. // on the left
  55864. x = rectangleToPointTo.getX() - w;
  55865. content.setPosition (0, 0);
  55866. arrowTipX = w - edgeIndent;
  55867. side = 3;
  55868. }
  55869. else
  55870. {
  55871. // on the right
  55872. x = rectangleToPointTo.getRight();
  55873. content.setPosition (arrowLength, 0);
  55874. arrowTipX = edgeIndent;
  55875. side = 1;
  55876. }
  55877. }
  55878. setBounds (x, y, w, h);
  55879. }
  55880. END_JUCE_NAMESPACE
  55881. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  55882. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  55883. BEGIN_JUCE_NAMESPACE
  55884. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  55885. : fadeOutLength (fadeOutLengthMs),
  55886. deleteAfterUse (false)
  55887. {
  55888. }
  55889. BubbleMessageComponent::~BubbleMessageComponent()
  55890. {
  55891. fadeOutComponent (fadeOutLength);
  55892. }
  55893. void BubbleMessageComponent::showAt (int x, int y,
  55894. const String& text,
  55895. const int numMillisecondsBeforeRemoving,
  55896. const bool removeWhenMouseClicked,
  55897. const bool deleteSelfAfterUse)
  55898. {
  55899. textLayout.clear();
  55900. textLayout.setText (text, Font (14.0f));
  55901. textLayout.layout (256, Justification::centredLeft, true);
  55902. setPosition (x, y);
  55903. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55904. }
  55905. void BubbleMessageComponent::showAt (Component* const component,
  55906. const String& text,
  55907. const int numMillisecondsBeforeRemoving,
  55908. const bool removeWhenMouseClicked,
  55909. const bool deleteSelfAfterUse)
  55910. {
  55911. textLayout.clear();
  55912. textLayout.setText (text, Font (14.0f));
  55913. textLayout.layout (256, Justification::centredLeft, true);
  55914. setPosition (component);
  55915. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55916. }
  55917. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  55918. const bool removeWhenMouseClicked,
  55919. const bool deleteSelfAfterUse)
  55920. {
  55921. setVisible (true);
  55922. deleteAfterUse = deleteSelfAfterUse;
  55923. if (numMillisecondsBeforeRemoving > 0)
  55924. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  55925. else
  55926. expiryTime = 0;
  55927. startTimer (77);
  55928. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  55929. if (! (removeWhenMouseClicked && isShowing()))
  55930. mouseClickCounter += 0xfffff;
  55931. repaint();
  55932. }
  55933. void BubbleMessageComponent::getContentSize (int& w, int& h)
  55934. {
  55935. w = textLayout.getWidth() + 16;
  55936. h = textLayout.getHeight() + 16;
  55937. }
  55938. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  55939. {
  55940. g.setColour (findColour (TooltipWindow::textColourId));
  55941. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  55942. }
  55943. void BubbleMessageComponent::timerCallback()
  55944. {
  55945. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  55946. {
  55947. stopTimer();
  55948. setVisible (false);
  55949. if (deleteAfterUse)
  55950. delete this;
  55951. }
  55952. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  55953. {
  55954. stopTimer();
  55955. fadeOutComponent (fadeOutLength);
  55956. if (deleteAfterUse)
  55957. delete this;
  55958. }
  55959. }
  55960. END_JUCE_NAMESPACE
  55961. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  55962. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  55963. BEGIN_JUCE_NAMESPACE
  55964. static const int swatchesPerRow = 8;
  55965. static const int swatchHeight = 22;
  55966. class ColourComponentSlider : public Slider
  55967. {
  55968. public:
  55969. ColourComponentSlider (const String& name)
  55970. : Slider (name)
  55971. {
  55972. setRange (0.0, 255.0, 1.0);
  55973. }
  55974. ~ColourComponentSlider()
  55975. {
  55976. }
  55977. const String getTextFromValue (double currentValue)
  55978. {
  55979. return String::formatted (T("%02X"), (int)currentValue);
  55980. }
  55981. double getValueFromText (const String& text)
  55982. {
  55983. return (double) text.getHexValue32();
  55984. }
  55985. private:
  55986. ColourComponentSlider (const ColourComponentSlider&);
  55987. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  55988. };
  55989. class ColourSpaceMarker : public Component
  55990. {
  55991. public:
  55992. ColourSpaceMarker()
  55993. {
  55994. setInterceptsMouseClicks (false, false);
  55995. }
  55996. ~ColourSpaceMarker()
  55997. {
  55998. }
  55999. void paint (Graphics& g)
  56000. {
  56001. g.setColour (Colour::greyLevel (0.1f));
  56002. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  56003. g.setColour (Colour::greyLevel (0.9f));
  56004. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  56005. }
  56006. private:
  56007. ColourSpaceMarker (const ColourSpaceMarker&);
  56008. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  56009. };
  56010. class ColourSpaceView : public Component
  56011. {
  56012. ColourSelector* const owner;
  56013. float& h;
  56014. float& s;
  56015. float& v;
  56016. float lastHue;
  56017. ColourSpaceMarker* marker;
  56018. const int edge;
  56019. public:
  56020. ColourSpaceView (ColourSelector* owner_,
  56021. float& h_, float& s_, float& v_,
  56022. const int edgeSize)
  56023. : owner (owner_),
  56024. h (h_), s (s_), v (v_),
  56025. lastHue (0.0f),
  56026. edge (edgeSize)
  56027. {
  56028. addAndMakeVisible (marker = new ColourSpaceMarker());
  56029. setMouseCursor (MouseCursor::CrosshairCursor);
  56030. }
  56031. ~ColourSpaceView()
  56032. {
  56033. deleteAllChildren();
  56034. }
  56035. void paint (Graphics& g)
  56036. {
  56037. const float hue = h;
  56038. const float xScale = 1.0f / (getWidth() - edge * 2);
  56039. const float yScale = 1.0f / (getHeight() - edge * 2);
  56040. const Rectangle clip (g.getClipBounds());
  56041. const int x1 = jmax (clip.getX(), edge) & ~1;
  56042. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  56043. const int y1 = jmax (clip.getY(), edge) & ~1;
  56044. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  56045. for (int y = y1; y < y2; y += 2)
  56046. {
  56047. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  56048. for (int x = x1; x < x2; x += 2)
  56049. {
  56050. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  56051. g.setColour (Colour (hue, s, v, 1.0f));
  56052. g.fillRect (x, y, 2, 2);
  56053. }
  56054. }
  56055. }
  56056. void mouseDown (const MouseEvent& e)
  56057. {
  56058. mouseDrag (e);
  56059. }
  56060. void mouseDrag (const MouseEvent& e)
  56061. {
  56062. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  56063. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  56064. owner->setSV (s, v);
  56065. }
  56066. void updateIfNeeded()
  56067. {
  56068. if (lastHue != h)
  56069. {
  56070. lastHue = h;
  56071. repaint();
  56072. }
  56073. resized();
  56074. }
  56075. void resized()
  56076. {
  56077. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  56078. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  56079. edge * 2, edge * 2);
  56080. }
  56081. private:
  56082. ColourSpaceView (const ColourSpaceView&);
  56083. const ColourSpaceView& operator= (const ColourSpaceView&);
  56084. };
  56085. class HueSelectorMarker : public Component
  56086. {
  56087. public:
  56088. HueSelectorMarker()
  56089. {
  56090. setInterceptsMouseClicks (false, false);
  56091. }
  56092. ~HueSelectorMarker()
  56093. {
  56094. }
  56095. void paint (Graphics& g)
  56096. {
  56097. Path p;
  56098. p.addTriangle (1.0f, 1.0f,
  56099. getWidth() * 0.3f, getHeight() * 0.5f,
  56100. 1.0f, getHeight() - 1.0f);
  56101. p.addTriangle (getWidth() - 1.0f, 1.0f,
  56102. getWidth() * 0.7f, getHeight() * 0.5f,
  56103. getWidth() - 1.0f, getHeight() - 1.0f);
  56104. g.setColour (Colours::white.withAlpha (0.75f));
  56105. g.fillPath (p);
  56106. g.setColour (Colours::black.withAlpha (0.75f));
  56107. g.strokePath (p, PathStrokeType (1.2f));
  56108. }
  56109. private:
  56110. HueSelectorMarker (const HueSelectorMarker&);
  56111. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  56112. };
  56113. class HueSelectorComp : public Component
  56114. {
  56115. public:
  56116. HueSelectorComp (ColourSelector* owner_,
  56117. float& h_, float& s_, float& v_,
  56118. const int edgeSize)
  56119. : owner (owner_),
  56120. h (h_), s (s_), v (v_),
  56121. lastHue (0.0f),
  56122. edge (edgeSize)
  56123. {
  56124. addAndMakeVisible (marker = new HueSelectorMarker());
  56125. }
  56126. ~HueSelectorComp()
  56127. {
  56128. deleteAllChildren();
  56129. }
  56130. void paint (Graphics& g)
  56131. {
  56132. const float yScale = 1.0f / (getHeight() - edge * 2);
  56133. const Rectangle clip (g.getClipBounds());
  56134. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  56135. {
  56136. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  56137. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  56138. }
  56139. }
  56140. void resized()
  56141. {
  56142. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  56143. getWidth(), edge * 2);
  56144. }
  56145. void mouseDown (const MouseEvent& e)
  56146. {
  56147. mouseDrag (e);
  56148. }
  56149. void mouseDrag (const MouseEvent& e)
  56150. {
  56151. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  56152. owner->setHue (hue);
  56153. }
  56154. void updateIfNeeded()
  56155. {
  56156. resized();
  56157. }
  56158. private:
  56159. ColourSelector* const owner;
  56160. float& h;
  56161. float& s;
  56162. float& v;
  56163. float lastHue;
  56164. HueSelectorMarker* marker;
  56165. const int edge;
  56166. HueSelectorComp (const HueSelectorComp&);
  56167. const HueSelectorComp& operator= (const HueSelectorComp&);
  56168. };
  56169. class SwatchComponent : public Component
  56170. {
  56171. public:
  56172. SwatchComponent (ColourSelector* owner_, int index_)
  56173. : owner (owner_),
  56174. index (index_)
  56175. {
  56176. }
  56177. ~SwatchComponent()
  56178. {
  56179. }
  56180. void paint (Graphics& g)
  56181. {
  56182. const Colour colour (owner->getSwatchColour (index));
  56183. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  56184. 6, 6,
  56185. Colour (0xffdddddd).overlaidWith (colour),
  56186. Colour (0xffffffff).overlaidWith (colour));
  56187. }
  56188. void mouseDown (const MouseEvent&)
  56189. {
  56190. PopupMenu m;
  56191. m.addItem (1, TRANS("Use this swatch as the current colour"));
  56192. m.addSeparator();
  56193. m.addItem (2, TRANS("Set this swatch to the current colour"));
  56194. const int r = m.showAt (this);
  56195. if (r == 1)
  56196. {
  56197. owner->setCurrentColour (owner->getSwatchColour (index));
  56198. }
  56199. else if (r == 2)
  56200. {
  56201. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  56202. {
  56203. owner->setSwatchColour (index, owner->getCurrentColour());
  56204. repaint();
  56205. }
  56206. }
  56207. }
  56208. private:
  56209. ColourSelector* const owner;
  56210. const int index;
  56211. SwatchComponent (const SwatchComponent&);
  56212. const SwatchComponent& operator= (const SwatchComponent&);
  56213. };
  56214. ColourSelector::ColourSelector (const int flags_,
  56215. const int edgeGap_,
  56216. const int gapAroundColourSpaceComponent)
  56217. : colour (Colours::white),
  56218. flags (flags_),
  56219. topSpace (0),
  56220. edgeGap (edgeGap_)
  56221. {
  56222. // not much point having a selector with no components in it!
  56223. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  56224. updateHSV();
  56225. if ((flags & showSliders) != 0)
  56226. {
  56227. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  56228. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  56229. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  56230. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  56231. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  56232. for (int i = 4; --i >= 0;)
  56233. sliders[i]->addListener (this);
  56234. }
  56235. else
  56236. {
  56237. zeromem (sliders, sizeof (sliders));
  56238. }
  56239. if ((flags & showColourspace) != 0)
  56240. {
  56241. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  56242. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  56243. }
  56244. else
  56245. {
  56246. colourSpace = 0;
  56247. hueSelector = 0;
  56248. }
  56249. update();
  56250. }
  56251. ColourSelector::~ColourSelector()
  56252. {
  56253. dispatchPendingMessages();
  56254. deleteAllChildren();
  56255. }
  56256. const Colour ColourSelector::getCurrentColour() const
  56257. {
  56258. return ((flags & showAlphaChannel) != 0) ? colour
  56259. : colour.withAlpha ((uint8) 0xff);
  56260. }
  56261. void ColourSelector::setCurrentColour (const Colour& c)
  56262. {
  56263. if (c != colour)
  56264. {
  56265. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  56266. updateHSV();
  56267. update();
  56268. }
  56269. }
  56270. void ColourSelector::setHue (float newH)
  56271. {
  56272. newH = jlimit (0.0f, 1.0f, newH);
  56273. if (h != newH)
  56274. {
  56275. h = newH;
  56276. colour = Colour (h, s, v, colour.getFloatAlpha());
  56277. update();
  56278. }
  56279. }
  56280. void ColourSelector::setSV (float newS, float newV)
  56281. {
  56282. newS = jlimit (0.0f, 1.0f, newS);
  56283. newV = jlimit (0.0f, 1.0f, newV);
  56284. if (s != newS || v != newV)
  56285. {
  56286. s = newS;
  56287. v = newV;
  56288. colour = Colour (h, s, v, colour.getFloatAlpha());
  56289. update();
  56290. }
  56291. }
  56292. void ColourSelector::updateHSV()
  56293. {
  56294. colour.getHSB (h, s, v);
  56295. }
  56296. void ColourSelector::update()
  56297. {
  56298. if (sliders[0] != 0)
  56299. {
  56300. sliders[0]->setValue ((int) colour.getRed());
  56301. sliders[1]->setValue ((int) colour.getGreen());
  56302. sliders[2]->setValue ((int) colour.getBlue());
  56303. sliders[3]->setValue ((int) colour.getAlpha());
  56304. }
  56305. if (colourSpace != 0)
  56306. {
  56307. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  56308. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  56309. }
  56310. if ((flags & showColourAtTop) != 0)
  56311. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  56312. sendChangeMessage (this);
  56313. }
  56314. void ColourSelector::paint (Graphics& g)
  56315. {
  56316. g.fillAll (findColour (backgroundColourId));
  56317. if ((flags & showColourAtTop) != 0)
  56318. {
  56319. const Colour colour (getCurrentColour());
  56320. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  56321. 10, 10,
  56322. Colour (0xffdddddd).overlaidWith (colour),
  56323. Colour (0xffffffff).overlaidWith (colour));
  56324. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  56325. g.setFont (14.0f, true);
  56326. g.drawText (((flags & showAlphaChannel) != 0)
  56327. ? String::formatted (T("#%02X%02X%02X%02X"),
  56328. (int) colour.getAlpha(),
  56329. (int) colour.getRed(),
  56330. (int) colour.getGreen(),
  56331. (int) colour.getBlue())
  56332. : String::formatted (T("#%02X%02X%02X"),
  56333. (int) colour.getRed(),
  56334. (int) colour.getGreen(),
  56335. (int) colour.getBlue()),
  56336. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  56337. Justification::centred, false);
  56338. }
  56339. if ((flags & showSliders) != 0)
  56340. {
  56341. g.setColour (findColour (labelTextColourId));
  56342. g.setFont (11.0f);
  56343. for (int i = 4; --i >= 0;)
  56344. {
  56345. if (sliders[i]->isVisible())
  56346. g.drawText (sliders[i]->getName() + T(":"),
  56347. 0, sliders[i]->getY(),
  56348. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  56349. Justification::centredRight, false);
  56350. }
  56351. }
  56352. }
  56353. void ColourSelector::resized()
  56354. {
  56355. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  56356. const int numSwatches = getNumSwatches();
  56357. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  56358. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  56359. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  56360. int y = topSpace;
  56361. if ((flags & showColourspace) != 0)
  56362. {
  56363. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  56364. colourSpace->setBounds (edgeGap, y,
  56365. getWidth() - hueWidth - edgeGap - 4,
  56366. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  56367. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  56368. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  56369. colourSpace->getHeight());
  56370. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  56371. }
  56372. if ((flags & showSliders) != 0)
  56373. {
  56374. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  56375. for (int i = 0; i < numSliders; ++i)
  56376. {
  56377. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  56378. proportionOfWidth (0.72f), sliderHeight - 2);
  56379. y += sliderHeight;
  56380. }
  56381. }
  56382. if (numSwatches > 0)
  56383. {
  56384. const int startX = 8;
  56385. const int xGap = 4;
  56386. const int yGap = 4;
  56387. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  56388. y += edgeGap;
  56389. if (swatchComponents.size() != numSwatches)
  56390. {
  56391. int i;
  56392. for (i = swatchComponents.size(); --i >= 0;)
  56393. {
  56394. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56395. delete sc;
  56396. }
  56397. for (i = 0; i < numSwatches; ++i)
  56398. {
  56399. SwatchComponent* const sc = new SwatchComponent (this, i);
  56400. swatchComponents.add (sc);
  56401. addAndMakeVisible (sc);
  56402. }
  56403. }
  56404. int x = startX;
  56405. for (int i = 0; i < swatchComponents.size(); ++i)
  56406. {
  56407. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56408. sc->setBounds (x + xGap / 2,
  56409. y + yGap / 2,
  56410. swatchWidth - xGap,
  56411. swatchHeight - yGap);
  56412. if (((i + 1) % swatchesPerRow) == 0)
  56413. {
  56414. x = startX;
  56415. y += swatchHeight;
  56416. }
  56417. else
  56418. {
  56419. x += swatchWidth;
  56420. }
  56421. }
  56422. }
  56423. }
  56424. void ColourSelector::sliderValueChanged (Slider*)
  56425. {
  56426. if (sliders[0] != 0)
  56427. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  56428. (uint8) sliders[1]->getValue(),
  56429. (uint8) sliders[2]->getValue(),
  56430. (uint8) sliders[3]->getValue()));
  56431. }
  56432. int ColourSelector::getNumSwatches() const
  56433. {
  56434. return 0;
  56435. }
  56436. const Colour ColourSelector::getSwatchColour (const int) const
  56437. {
  56438. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56439. return Colours::black;
  56440. }
  56441. void ColourSelector::setSwatchColour (const int, const Colour&) const
  56442. {
  56443. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56444. }
  56445. END_JUCE_NAMESPACE
  56446. /********* End of inlined file: juce_ColourSelector.cpp *********/
  56447. /********* Start of inlined file: juce_DropShadower.cpp *********/
  56448. BEGIN_JUCE_NAMESPACE
  56449. class ShadowWindow : public Component
  56450. {
  56451. Component* owner;
  56452. Image** shadowImageSections;
  56453. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  56454. public:
  56455. ShadowWindow (Component* const owner_,
  56456. const int type_,
  56457. Image** const shadowImageSections_)
  56458. : owner (owner_),
  56459. shadowImageSections (shadowImageSections_),
  56460. type (type_)
  56461. {
  56462. setInterceptsMouseClicks (false, false);
  56463. if (owner_->isOnDesktop())
  56464. {
  56465. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  56466. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56467. | ComponentPeer::windowIsTemporary
  56468. | ComponentPeer::windowIgnoresKeyPresses);
  56469. }
  56470. else if (owner_->getParentComponent() != 0)
  56471. {
  56472. owner_->getParentComponent()->addChildComponent (this);
  56473. }
  56474. }
  56475. ~ShadowWindow()
  56476. {
  56477. }
  56478. void paint (Graphics& g)
  56479. {
  56480. Image* const topLeft = shadowImageSections [type * 3];
  56481. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  56482. Image* const filler = shadowImageSections [type * 3 + 2];
  56483. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  56484. g.setOpacity (1.0f);
  56485. if (type < 2)
  56486. {
  56487. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  56488. g.drawImage (topLeft,
  56489. 0, 0, topLeft->getWidth(), imH,
  56490. 0, 0, topLeft->getWidth(), imH);
  56491. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  56492. g.drawImage (bottomRight,
  56493. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  56494. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  56495. g.setBrush (&fillBrush);
  56496. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  56497. }
  56498. else
  56499. {
  56500. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  56501. g.drawImage (topLeft,
  56502. 0, 0, imW, topLeft->getHeight(),
  56503. 0, 0, imW, topLeft->getHeight());
  56504. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  56505. g.drawImage (bottomRight,
  56506. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  56507. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  56508. g.setBrush (&fillBrush);
  56509. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  56510. }
  56511. }
  56512. void resized()
  56513. {
  56514. repaint(); // (needed for correct repainting)
  56515. }
  56516. private:
  56517. ShadowWindow (const ShadowWindow&);
  56518. const ShadowWindow& operator= (const ShadowWindow&);
  56519. };
  56520. DropShadower::DropShadower (const float alpha_,
  56521. const int xOffset_,
  56522. const int yOffset_,
  56523. const float blurRadius_)
  56524. : owner (0),
  56525. numShadows (0),
  56526. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  56527. xOffset (xOffset_),
  56528. yOffset (yOffset_),
  56529. alpha (alpha_),
  56530. blurRadius (blurRadius_),
  56531. inDestructor (false),
  56532. reentrant (false)
  56533. {
  56534. }
  56535. DropShadower::~DropShadower()
  56536. {
  56537. if (owner != 0)
  56538. owner->removeComponentListener (this);
  56539. inDestructor = true;
  56540. deleteShadowWindows();
  56541. }
  56542. void DropShadower::deleteShadowWindows()
  56543. {
  56544. if (numShadows > 0)
  56545. {
  56546. int i;
  56547. for (i = numShadows; --i >= 0;)
  56548. delete shadowWindows[i];
  56549. for (i = 12; --i >= 0;)
  56550. delete shadowImageSections[i];
  56551. numShadows = 0;
  56552. }
  56553. }
  56554. void DropShadower::setOwner (Component* componentToFollow)
  56555. {
  56556. if (componentToFollow != owner)
  56557. {
  56558. if (owner != 0)
  56559. owner->removeComponentListener (this);
  56560. // (the component can't be null)
  56561. jassert (componentToFollow != 0);
  56562. owner = componentToFollow;
  56563. jassert (owner != 0);
  56564. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  56565. owner->addComponentListener (this);
  56566. updateShadows();
  56567. }
  56568. }
  56569. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  56570. {
  56571. updateShadows();
  56572. }
  56573. void DropShadower::componentBroughtToFront (Component&)
  56574. {
  56575. bringShadowWindowsToFront();
  56576. }
  56577. void DropShadower::componentChildrenChanged (Component&)
  56578. {
  56579. }
  56580. void DropShadower::componentParentHierarchyChanged (Component&)
  56581. {
  56582. deleteShadowWindows();
  56583. updateShadows();
  56584. }
  56585. void DropShadower::componentVisibilityChanged (Component&)
  56586. {
  56587. updateShadows();
  56588. }
  56589. void DropShadower::updateShadows()
  56590. {
  56591. if (reentrant || inDestructor || (owner == 0))
  56592. return;
  56593. reentrant = true;
  56594. ComponentPeer* const nw = owner->getPeer();
  56595. const bool isOwnerVisible = owner->isVisible()
  56596. && (nw == 0 || ! nw->isMinimised());
  56597. const bool createShadowWindows = numShadows == 0
  56598. && owner->getWidth() > 0
  56599. && owner->getHeight() > 0
  56600. && isOwnerVisible
  56601. && (Desktop::canUseSemiTransparentWindows()
  56602. || owner->getParentComponent() != 0);
  56603. if (createShadowWindows)
  56604. {
  56605. // keep a cached version of the image to save doing the gaussian too often
  56606. String imageId;
  56607. imageId << shadowEdge << T(',')
  56608. << xOffset << T(',')
  56609. << yOffset << T(',')
  56610. << alpha;
  56611. const int hash = imageId.hashCode();
  56612. Image* bigIm = ImageCache::getFromHashCode (hash);
  56613. if (bigIm == 0)
  56614. {
  56615. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  56616. Graphics bigG (*bigIm);
  56617. bigG.setColour (Colours::black.withAlpha (alpha));
  56618. bigG.fillRect (shadowEdge + xOffset,
  56619. shadowEdge + yOffset,
  56620. bigIm->getWidth() - (shadowEdge * 2),
  56621. bigIm->getHeight() - (shadowEdge * 2));
  56622. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  56623. blurKernel.createGaussianBlur (blurRadius);
  56624. blurKernel.applyToImage (*bigIm, 0,
  56625. xOffset,
  56626. yOffset,
  56627. bigIm->getWidth(),
  56628. bigIm->getHeight());
  56629. ImageCache::addImageToCache (bigIm, hash);
  56630. }
  56631. const int iw = bigIm->getWidth();
  56632. const int ih = bigIm->getHeight();
  56633. const int shadowEdge2 = shadowEdge * 2;
  56634. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  56635. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  56636. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  56637. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  56638. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  56639. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  56640. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  56641. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  56642. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  56643. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  56644. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  56645. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  56646. ImageCache::release (bigIm);
  56647. for (int i = 0; i < 4; ++i)
  56648. {
  56649. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  56650. ++numShadows;
  56651. }
  56652. }
  56653. if (numShadows > 0)
  56654. {
  56655. for (int i = numShadows; --i >= 0;)
  56656. {
  56657. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  56658. shadowWindows[i]->setVisible (isOwnerVisible);
  56659. }
  56660. const int x = owner->getX();
  56661. const int y = owner->getY() - shadowEdge;
  56662. const int w = owner->getWidth();
  56663. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  56664. shadowWindows[0]->setBounds (x - shadowEdge,
  56665. y,
  56666. shadowEdge,
  56667. h);
  56668. shadowWindows[1]->setBounds (x + w,
  56669. y,
  56670. shadowEdge,
  56671. h);
  56672. shadowWindows[2]->setBounds (x,
  56673. y,
  56674. w,
  56675. shadowEdge);
  56676. shadowWindows[3]->setBounds (x,
  56677. owner->getBottom(),
  56678. w,
  56679. shadowEdge);
  56680. }
  56681. reentrant = false;
  56682. if (createShadowWindows)
  56683. bringShadowWindowsToFront();
  56684. }
  56685. void DropShadower::setShadowImage (Image* const src,
  56686. const int num,
  56687. const int w,
  56688. const int h,
  56689. const int sx,
  56690. const int sy) throw()
  56691. {
  56692. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  56693. Graphics g (*shadowImageSections[num]);
  56694. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  56695. }
  56696. void DropShadower::bringShadowWindowsToFront()
  56697. {
  56698. if (! (inDestructor || reentrant))
  56699. {
  56700. updateShadows();
  56701. reentrant = true;
  56702. for (int i = numShadows; --i >= 0;)
  56703. shadowWindows[i]->toBehind (owner);
  56704. reentrant = false;
  56705. }
  56706. }
  56707. END_JUCE_NAMESPACE
  56708. /********* End of inlined file: juce_DropShadower.cpp *********/
  56709. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  56710. BEGIN_JUCE_NAMESPACE
  56711. class MagnifyingPeer : public ComponentPeer
  56712. {
  56713. public:
  56714. MagnifyingPeer (Component* const component_,
  56715. MagnifierComponent* const magnifierComp_)
  56716. : ComponentPeer (component_, 0),
  56717. magnifierComp (magnifierComp_)
  56718. {
  56719. }
  56720. ~MagnifyingPeer()
  56721. {
  56722. }
  56723. void* getNativeHandle() const { return 0; }
  56724. void setVisible (bool) {}
  56725. void setTitle (const String&) {}
  56726. void setPosition (int, int) {}
  56727. void setSize (int, int) {}
  56728. void setBounds (int, int, int, int, const bool) {}
  56729. void setMinimised (bool) {}
  56730. bool isMinimised() const { return false; }
  56731. void setFullScreen (bool) {}
  56732. bool isFullScreen() const { return false; }
  56733. const BorderSize getFrameSize() const { return BorderSize (0); }
  56734. bool setAlwaysOnTop (bool) { return true; }
  56735. void toFront (bool) {}
  56736. void toBehind (ComponentPeer*) {}
  56737. void setIcon (const Image&) {}
  56738. bool isFocused() const
  56739. {
  56740. return magnifierComp->hasKeyboardFocus (true);
  56741. }
  56742. void grabFocus()
  56743. {
  56744. ComponentPeer* peer = magnifierComp->getPeer();
  56745. if (peer != 0)
  56746. peer->grabFocus();
  56747. }
  56748. void textInputRequired (int x, int y)
  56749. {
  56750. ComponentPeer* peer = magnifierComp->getPeer();
  56751. if (peer != 0)
  56752. peer->textInputRequired (x, y);
  56753. }
  56754. void getBounds (int& x, int& y, int& w, int& h) const
  56755. {
  56756. x = magnifierComp->getScreenX();
  56757. y = magnifierComp->getScreenY();
  56758. w = component->getWidth();
  56759. h = component->getHeight();
  56760. }
  56761. int getScreenX() const { return magnifierComp->getScreenX(); }
  56762. int getScreenY() const { return magnifierComp->getScreenY(); }
  56763. void relativePositionToGlobal (int& x, int& y)
  56764. {
  56765. const double zoom = magnifierComp->getScaleFactor();
  56766. x = roundDoubleToInt (x * zoom);
  56767. y = roundDoubleToInt (y * zoom);
  56768. magnifierComp->relativePositionToGlobal (x, y);
  56769. }
  56770. void globalPositionToRelative (int& x, int& y)
  56771. {
  56772. magnifierComp->globalPositionToRelative (x, y);
  56773. const double zoom = magnifierComp->getScaleFactor();
  56774. x = roundDoubleToInt (x / zoom);
  56775. y = roundDoubleToInt (y / zoom);
  56776. }
  56777. bool contains (int x, int y, bool) const
  56778. {
  56779. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  56780. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  56781. }
  56782. void repaint (int x, int y, int w, int h)
  56783. {
  56784. const double zoom = magnifierComp->getScaleFactor();
  56785. magnifierComp->repaint ((int) (x * zoom),
  56786. (int) (y * zoom),
  56787. roundDoubleToInt (w * zoom) + 1,
  56788. roundDoubleToInt (h * zoom) + 1);
  56789. }
  56790. void performAnyPendingRepaintsNow()
  56791. {
  56792. }
  56793. juce_UseDebuggingNewOperator
  56794. private:
  56795. MagnifierComponent* const magnifierComp;
  56796. MagnifyingPeer (const MagnifyingPeer&);
  56797. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  56798. };
  56799. class PeerHolderComp : public Component
  56800. {
  56801. public:
  56802. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  56803. : magnifierComp (magnifierComp_)
  56804. {
  56805. setVisible (true);
  56806. }
  56807. ~PeerHolderComp()
  56808. {
  56809. }
  56810. ComponentPeer* createNewPeer (int, void*)
  56811. {
  56812. return new MagnifyingPeer (this, magnifierComp);
  56813. }
  56814. void childBoundsChanged (Component* c)
  56815. {
  56816. if (c != 0)
  56817. {
  56818. setSize (c->getWidth(), c->getHeight());
  56819. magnifierComp->childBoundsChanged (this);
  56820. }
  56821. }
  56822. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56823. {
  56824. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  56825. Component* const p = magnifierComp->getParentComponent();
  56826. if (p != 0)
  56827. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  56828. }
  56829. private:
  56830. MagnifierComponent* const magnifierComp;
  56831. PeerHolderComp (const PeerHolderComp&);
  56832. const PeerHolderComp& operator= (const PeerHolderComp&);
  56833. };
  56834. MagnifierComponent::MagnifierComponent (Component* const content_,
  56835. const bool deleteContentCompWhenNoLongerNeeded)
  56836. : content (content_),
  56837. scaleFactor (0.0),
  56838. peer (0),
  56839. deleteContent (deleteContentCompWhenNoLongerNeeded),
  56840. quality (Graphics::lowResamplingQuality)
  56841. {
  56842. holderComp = new PeerHolderComp (this);
  56843. setScaleFactor (1.0);
  56844. }
  56845. MagnifierComponent::~MagnifierComponent()
  56846. {
  56847. delete holderComp;
  56848. if (deleteContent)
  56849. delete content;
  56850. }
  56851. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  56852. {
  56853. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  56854. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  56855. if (scaleFactor != newScaleFactor)
  56856. {
  56857. scaleFactor = newScaleFactor;
  56858. if (scaleFactor == 1.0)
  56859. {
  56860. holderComp->removeFromDesktop();
  56861. peer = 0;
  56862. addChildComponent (content);
  56863. childBoundsChanged (content);
  56864. }
  56865. else
  56866. {
  56867. holderComp->addAndMakeVisible (content);
  56868. holderComp->childBoundsChanged (content);
  56869. childBoundsChanged (holderComp);
  56870. holderComp->addToDesktop (0);
  56871. peer = holderComp->getPeer();
  56872. }
  56873. repaint();
  56874. }
  56875. }
  56876. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  56877. {
  56878. quality = newQuality;
  56879. }
  56880. void MagnifierComponent::paint (Graphics& g)
  56881. {
  56882. const int w = holderComp->getWidth();
  56883. const int h = holderComp->getHeight();
  56884. if (w == 0 || h == 0)
  56885. return;
  56886. const Rectangle r (g.getClipBounds());
  56887. const int srcX = (int) (r.getX() / scaleFactor);
  56888. const int srcY = (int) (r.getY() / scaleFactor);
  56889. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  56890. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  56891. if (scaleFactor >= 1.0)
  56892. {
  56893. ++srcW;
  56894. ++srcH;
  56895. }
  56896. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  56897. temp.clear (srcX, srcY, srcW, srcH);
  56898. Graphics g2 (temp);
  56899. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  56900. holderComp->paintEntireComponent (g2);
  56901. g.setImageResamplingQuality (quality);
  56902. g.drawImage (&temp,
  56903. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  56904. 0, 0, w, h,
  56905. false);
  56906. }
  56907. void MagnifierComponent::childBoundsChanged (Component* c)
  56908. {
  56909. if (c != 0)
  56910. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  56911. roundDoubleToInt (c->getHeight() * scaleFactor));
  56912. }
  56913. void MagnifierComponent::mouseDown (const MouseEvent& e)
  56914. {
  56915. if (peer != 0)
  56916. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56917. }
  56918. void MagnifierComponent::mouseUp (const MouseEvent& e)
  56919. {
  56920. if (peer != 0)
  56921. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56922. }
  56923. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  56924. {
  56925. if (peer != 0)
  56926. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56927. }
  56928. void MagnifierComponent::mouseMove (const MouseEvent& e)
  56929. {
  56930. if (peer != 0)
  56931. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56932. }
  56933. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  56934. {
  56935. if (peer != 0)
  56936. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56937. }
  56938. void MagnifierComponent::mouseExit (const MouseEvent& e)
  56939. {
  56940. if (peer != 0)
  56941. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56942. }
  56943. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56944. {
  56945. if (peer != 0)
  56946. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  56947. roundFloatToInt (iy * 256.0f),
  56948. e.eventTime.toMilliseconds());
  56949. else
  56950. Component::mouseWheelMove (e, ix, iy);
  56951. }
  56952. int MagnifierComponent::scaleInt (const int n) const throw()
  56953. {
  56954. return roundDoubleToInt (n / scaleFactor);
  56955. }
  56956. END_JUCE_NAMESPACE
  56957. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  56958. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  56959. BEGIN_JUCE_NAMESPACE
  56960. class MidiKeyboardUpDownButton : public Button
  56961. {
  56962. public:
  56963. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  56964. const int delta_)
  56965. : Button (String::empty),
  56966. owner (owner_),
  56967. delta (delta_)
  56968. {
  56969. setOpaque (true);
  56970. }
  56971. ~MidiKeyboardUpDownButton()
  56972. {
  56973. }
  56974. void clicked()
  56975. {
  56976. int note = owner->getLowestVisibleKey();
  56977. if (delta < 0)
  56978. note = (note - 1) / 12;
  56979. else
  56980. note = note / 12 + 1;
  56981. owner->setLowestVisibleKey (note * 12);
  56982. }
  56983. void paintButton (Graphics& g,
  56984. bool isMouseOverButton,
  56985. bool isButtonDown)
  56986. {
  56987. owner->drawUpDownButton (g, getWidth(), getHeight(),
  56988. isMouseOverButton, isButtonDown,
  56989. delta > 0);
  56990. }
  56991. private:
  56992. MidiKeyboardComponent* const owner;
  56993. const int delta;
  56994. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  56995. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  56996. };
  56997. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  56998. const Orientation orientation_)
  56999. : state (state_),
  57000. xOffset (0),
  57001. blackNoteLength (1),
  57002. keyWidth (16.0f),
  57003. orientation (orientation_),
  57004. midiChannel (1),
  57005. midiInChannelMask (0xffff),
  57006. velocity (1.0f),
  57007. noteUnderMouse (-1),
  57008. mouseDownNote (-1),
  57009. rangeStart (0),
  57010. rangeEnd (127),
  57011. firstKey (12 * 4),
  57012. canScroll (true),
  57013. mouseDragging (false),
  57014. keyPresses (4),
  57015. keyPressNotes (16),
  57016. keyMappingOctave (6),
  57017. octaveNumForMiddleC (3)
  57018. {
  57019. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  57020. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  57021. // initialise with a default set of querty key-mappings..
  57022. const char* const keymap = "awsedftgyhujkolp;";
  57023. for (int i = String (keymap).length(); --i >= 0;)
  57024. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  57025. setOpaque (true);
  57026. setWantsKeyboardFocus (true);
  57027. state.addListener (this);
  57028. }
  57029. MidiKeyboardComponent::~MidiKeyboardComponent()
  57030. {
  57031. state.removeListener (this);
  57032. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  57033. deleteAllChildren();
  57034. }
  57035. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  57036. {
  57037. keyWidth = widthInPixels;
  57038. resized();
  57039. }
  57040. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  57041. {
  57042. if (orientation != newOrientation)
  57043. {
  57044. orientation = newOrientation;
  57045. resized();
  57046. }
  57047. }
  57048. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  57049. const int highestNote)
  57050. {
  57051. jassert (lowestNote >= 0 && lowestNote <= 127);
  57052. jassert (highestNote >= 0 && highestNote <= 127);
  57053. jassert (lowestNote <= highestNote);
  57054. if (rangeStart != lowestNote || rangeEnd != highestNote)
  57055. {
  57056. rangeStart = jlimit (0, 127, lowestNote);
  57057. rangeEnd = jlimit (0, 127, highestNote);
  57058. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  57059. resized();
  57060. }
  57061. }
  57062. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  57063. {
  57064. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  57065. if (noteNumber != firstKey)
  57066. {
  57067. firstKey = noteNumber;
  57068. sendChangeMessage (this);
  57069. resized();
  57070. }
  57071. }
  57072. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  57073. {
  57074. if (canScroll != canScroll_)
  57075. {
  57076. canScroll = canScroll_;
  57077. resized();
  57078. }
  57079. }
  57080. void MidiKeyboardComponent::colourChanged()
  57081. {
  57082. repaint();
  57083. }
  57084. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  57085. {
  57086. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  57087. if (midiChannel != midiChannelNumber)
  57088. {
  57089. resetAnyKeysInUse();
  57090. midiChannel = jlimit (1, 16, midiChannelNumber);
  57091. }
  57092. }
  57093. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  57094. {
  57095. midiInChannelMask = midiChannelMask;
  57096. triggerAsyncUpdate();
  57097. }
  57098. void MidiKeyboardComponent::setVelocity (const float velocity_)
  57099. {
  57100. velocity = jlimit (0.0f, 1.0f, velocity_);
  57101. }
  57102. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  57103. {
  57104. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  57105. static const float blackNoteWidth = 0.7f;
  57106. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  57107. 1.0f, 2 - blackNoteWidth * 0.4f,
  57108. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  57109. 4.0f, 5 - blackNoteWidth * 0.5f,
  57110. 5.0f, 6 - blackNoteWidth * 0.3f,
  57111. 6.0f };
  57112. static const float widths[] = { 1.0f, blackNoteWidth,
  57113. 1.0f, blackNoteWidth,
  57114. 1.0f, 1.0f, blackNoteWidth,
  57115. 1.0f, blackNoteWidth,
  57116. 1.0f, blackNoteWidth,
  57117. 1.0f };
  57118. const int octave = midiNoteNumber / 12;
  57119. const int note = midiNoteNumber % 12;
  57120. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  57121. w = roundFloatToInt (widths [note] * keyWidth);
  57122. }
  57123. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  57124. {
  57125. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  57126. int rx, rw;
  57127. getKeyPosition (rangeStart, keyWidth, rx, rw);
  57128. x -= xOffset + rx;
  57129. }
  57130. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  57131. {
  57132. int x, y;
  57133. getKeyPos (midiNoteNumber, x, y);
  57134. return x;
  57135. }
  57136. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  57137. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  57138. int MidiKeyboardComponent::xyToNote (int x, int y)
  57139. {
  57140. if (! reallyContains (x, y, false))
  57141. return -1;
  57142. if (orientation != horizontalKeyboard)
  57143. {
  57144. swapVariables (x, y);
  57145. if (orientation == verticalKeyboardFacingLeft)
  57146. y = getWidth() - y;
  57147. else
  57148. x = getHeight() - x;
  57149. }
  57150. return remappedXYToNote (x + xOffset, y);
  57151. }
  57152. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  57153. {
  57154. if (y < blackNoteLength)
  57155. {
  57156. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57157. {
  57158. for (int i = 0; i < 5; ++i)
  57159. {
  57160. const int note = octaveStart + blackNotes [i];
  57161. if (note >= rangeStart && note <= rangeEnd)
  57162. {
  57163. int kx, kw;
  57164. getKeyPos (note, kx, kw);
  57165. kx += xOffset;
  57166. if (x >= kx && x < kx + kw)
  57167. return note;
  57168. }
  57169. }
  57170. }
  57171. }
  57172. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57173. {
  57174. for (int i = 0; i < 7; ++i)
  57175. {
  57176. const int note = octaveStart + whiteNotes [i];
  57177. if (note >= rangeStart && note <= rangeEnd)
  57178. {
  57179. int kx, kw;
  57180. getKeyPos (note, kx, kw);
  57181. kx += xOffset;
  57182. if (x >= kx && x < kx + kw)
  57183. return note;
  57184. }
  57185. }
  57186. }
  57187. return -1;
  57188. }
  57189. void MidiKeyboardComponent::repaintNote (const int noteNum)
  57190. {
  57191. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57192. {
  57193. int x, w;
  57194. getKeyPos (noteNum, x, w);
  57195. if (orientation == horizontalKeyboard)
  57196. repaint (x, 0, w, getHeight());
  57197. else if (orientation == verticalKeyboardFacingLeft)
  57198. repaint (0, x, getWidth(), w);
  57199. else if (orientation == verticalKeyboardFacingRight)
  57200. repaint (0, getHeight() - x - w, getWidth(), w);
  57201. }
  57202. }
  57203. void MidiKeyboardComponent::paint (Graphics& g)
  57204. {
  57205. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  57206. const Colour lineColour (findColour (keySeparatorLineColourId));
  57207. const Colour textColour (findColour (textLabelColourId));
  57208. int x, w, octave;
  57209. for (octave = 0; octave < 128; octave += 12)
  57210. {
  57211. for (int white = 0; white < 7; ++white)
  57212. {
  57213. const int noteNum = octave + whiteNotes [white];
  57214. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57215. {
  57216. getKeyPos (noteNum, x, w);
  57217. if (orientation == horizontalKeyboard)
  57218. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  57219. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57220. noteUnderMouse == noteNum,
  57221. lineColour, textColour);
  57222. else if (orientation == verticalKeyboardFacingLeft)
  57223. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  57224. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57225. noteUnderMouse == noteNum,
  57226. lineColour, textColour);
  57227. else if (orientation == verticalKeyboardFacingRight)
  57228. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  57229. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57230. noteUnderMouse == noteNum,
  57231. lineColour, textColour);
  57232. }
  57233. }
  57234. }
  57235. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  57236. if (orientation == verticalKeyboardFacingLeft)
  57237. {
  57238. x1 = getWidth() - 1.0f;
  57239. x2 = getWidth() - 5.0f;
  57240. }
  57241. else if (orientation == verticalKeyboardFacingRight)
  57242. x2 = 5.0f;
  57243. else
  57244. y2 = 5.0f;
  57245. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  57246. Colours::transparentBlack, x2, y2, false);
  57247. g.setBrush (&gb);
  57248. getKeyPos (rangeEnd, x, w);
  57249. x += w;
  57250. if (orientation == verticalKeyboardFacingLeft)
  57251. g.fillRect (getWidth() - 5, 0, 5, x);
  57252. else if (orientation == verticalKeyboardFacingRight)
  57253. g.fillRect (0, 0, 5, x);
  57254. else
  57255. g.fillRect (0, 0, x, 5);
  57256. g.setColour (lineColour);
  57257. if (orientation == verticalKeyboardFacingLeft)
  57258. g.fillRect (0, 0, 1, x);
  57259. else if (orientation == verticalKeyboardFacingRight)
  57260. g.fillRect (getWidth() - 1, 0, 1, x);
  57261. else
  57262. g.fillRect (0, getHeight() - 1, x, 1);
  57263. const Colour blackNoteColour (findColour (blackNoteColourId));
  57264. for (octave = 0; octave < 128; octave += 12)
  57265. {
  57266. for (int black = 0; black < 5; ++black)
  57267. {
  57268. const int noteNum = octave + blackNotes [black];
  57269. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57270. {
  57271. getKeyPos (noteNum, x, w);
  57272. if (orientation == horizontalKeyboard)
  57273. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  57274. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57275. noteUnderMouse == noteNum,
  57276. blackNoteColour);
  57277. else if (orientation == verticalKeyboardFacingLeft)
  57278. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  57279. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57280. noteUnderMouse == noteNum,
  57281. blackNoteColour);
  57282. else if (orientation == verticalKeyboardFacingRight)
  57283. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  57284. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57285. noteUnderMouse == noteNum,
  57286. blackNoteColour);
  57287. }
  57288. }
  57289. }
  57290. }
  57291. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  57292. Graphics& g, int x, int y, int w, int h,
  57293. bool isDown, bool isOver,
  57294. const Colour& lineColour,
  57295. const Colour& textColour)
  57296. {
  57297. Colour c (Colours::transparentWhite);
  57298. if (isDown)
  57299. c = findColour (keyDownOverlayColourId);
  57300. if (isOver)
  57301. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57302. g.setColour (c);
  57303. g.fillRect (x, y, w, h);
  57304. const String text (getWhiteNoteText (midiNoteNumber));
  57305. if (! text.isEmpty())
  57306. {
  57307. g.setColour (textColour);
  57308. Font f (jmin (12.0f, keyWidth * 0.9f));
  57309. f.setHorizontalScale (0.8f);
  57310. g.setFont (f);
  57311. Justification justification (Justification::centredBottom);
  57312. if (orientation == verticalKeyboardFacingLeft)
  57313. justification = Justification::centredLeft;
  57314. else if (orientation == verticalKeyboardFacingRight)
  57315. justification = Justification::centredRight;
  57316. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  57317. }
  57318. g.setColour (lineColour);
  57319. if (orientation == horizontalKeyboard)
  57320. g.fillRect (x, y, 1, h);
  57321. else if (orientation == verticalKeyboardFacingLeft)
  57322. g.fillRect (x, y, w, 1);
  57323. else if (orientation == verticalKeyboardFacingRight)
  57324. g.fillRect (x, y + h - 1, w, 1);
  57325. if (midiNoteNumber == rangeEnd)
  57326. {
  57327. if (orientation == horizontalKeyboard)
  57328. g.fillRect (x + w, y, 1, h);
  57329. else if (orientation == verticalKeyboardFacingLeft)
  57330. g.fillRect (x, y + h, w, 1);
  57331. else if (orientation == verticalKeyboardFacingRight)
  57332. g.fillRect (x, y - 1, w, 1);
  57333. }
  57334. }
  57335. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  57336. Graphics& g, int x, int y, int w, int h,
  57337. bool isDown, bool isOver,
  57338. const Colour& noteFillColour)
  57339. {
  57340. Colour c (noteFillColour);
  57341. if (isDown)
  57342. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  57343. if (isOver)
  57344. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57345. g.setColour (c);
  57346. g.fillRect (x, y, w, h);
  57347. if (isDown)
  57348. {
  57349. g.setColour (noteFillColour);
  57350. g.drawRect (x, y, w, h);
  57351. }
  57352. else
  57353. {
  57354. const int xIndent = jmax (1, jmin (w, h) / 8);
  57355. g.setColour (c.brighter());
  57356. if (orientation == horizontalKeyboard)
  57357. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  57358. else if (orientation == verticalKeyboardFacingLeft)
  57359. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  57360. else if (orientation == verticalKeyboardFacingRight)
  57361. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  57362. }
  57363. }
  57364. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  57365. {
  57366. octaveNumForMiddleC = octaveNumForMiddleC_;
  57367. repaint();
  57368. }
  57369. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  57370. {
  57371. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  57372. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  57373. return String::empty;
  57374. }
  57375. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  57376. const bool isMouseOver,
  57377. const bool isButtonDown,
  57378. const bool movesOctavesUp)
  57379. {
  57380. g.fillAll (findColour (upDownButtonBackgroundColourId));
  57381. float angle;
  57382. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  57383. angle = movesOctavesUp ? 0.0f : 0.5f;
  57384. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  57385. angle = movesOctavesUp ? 0.25f : 0.75f;
  57386. else
  57387. angle = movesOctavesUp ? 0.75f : 0.25f;
  57388. Path path;
  57389. path.lineTo (0.0f, 1.0f);
  57390. path.lineTo (1.0f, 0.5f);
  57391. path.closeSubPath();
  57392. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  57393. g.setColour (findColour (upDownButtonArrowColourId)
  57394. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  57395. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  57396. w - 2.0f,
  57397. h - 2.0f,
  57398. true));
  57399. }
  57400. void MidiKeyboardComponent::resized()
  57401. {
  57402. int w = getWidth();
  57403. int h = getHeight();
  57404. if (w > 0 && h > 0)
  57405. {
  57406. if (orientation != horizontalKeyboard)
  57407. swapVariables (w, h);
  57408. blackNoteLength = roundFloatToInt (h * 0.7f);
  57409. int kx2, kw2;
  57410. getKeyPos (rangeEnd, kx2, kw2);
  57411. kx2 += kw2;
  57412. if (firstKey != rangeStart)
  57413. {
  57414. int kx1, kw1;
  57415. getKeyPos (rangeStart, kx1, kw1);
  57416. if (kx2 - kx1 <= w)
  57417. {
  57418. firstKey = rangeStart;
  57419. sendChangeMessage (this);
  57420. repaint();
  57421. }
  57422. }
  57423. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  57424. scrollDown->setVisible (showScrollButtons);
  57425. scrollUp->setVisible (showScrollButtons);
  57426. xOffset = 0;
  57427. if (showScrollButtons)
  57428. {
  57429. const int scrollButtonW = jmin (12, w / 2);
  57430. if (orientation == horizontalKeyboard)
  57431. {
  57432. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  57433. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  57434. }
  57435. else if (orientation == verticalKeyboardFacingLeft)
  57436. {
  57437. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  57438. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57439. }
  57440. else if (orientation == verticalKeyboardFacingRight)
  57441. {
  57442. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57443. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  57444. }
  57445. int endOfLastKey, kw;
  57446. getKeyPos (rangeEnd, endOfLastKey, kw);
  57447. endOfLastKey += kw;
  57448. const int spaceAvailable = w - scrollButtonW * 2;
  57449. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  57450. if (lastStartKey >= 0 && firstKey > lastStartKey)
  57451. {
  57452. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  57453. sendChangeMessage (this);
  57454. }
  57455. int newOffset = 0;
  57456. getKeyPos (firstKey, newOffset, kw);
  57457. xOffset = newOffset - scrollButtonW;
  57458. }
  57459. else
  57460. {
  57461. firstKey = rangeStart;
  57462. }
  57463. timerCallback();
  57464. repaint();
  57465. }
  57466. }
  57467. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  57468. {
  57469. triggerAsyncUpdate();
  57470. }
  57471. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  57472. {
  57473. triggerAsyncUpdate();
  57474. }
  57475. void MidiKeyboardComponent::handleAsyncUpdate()
  57476. {
  57477. for (int i = rangeStart; i <= rangeEnd; ++i)
  57478. {
  57479. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  57480. {
  57481. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  57482. repaintNote (i);
  57483. }
  57484. }
  57485. }
  57486. void MidiKeyboardComponent::resetAnyKeysInUse()
  57487. {
  57488. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  57489. {
  57490. state.allNotesOff (midiChannel);
  57491. keysPressed.clear();
  57492. mouseDownNote = -1;
  57493. }
  57494. }
  57495. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  57496. {
  57497. const int newNote = (mouseDragging || isMouseOver())
  57498. ? xyToNote (x, y) : -1;
  57499. if (noteUnderMouse != newNote)
  57500. {
  57501. if (mouseDownNote >= 0)
  57502. {
  57503. state.noteOff (midiChannel, mouseDownNote);
  57504. mouseDownNote = -1;
  57505. }
  57506. if (mouseDragging && newNote >= 0)
  57507. {
  57508. state.noteOn (midiChannel, newNote, velocity);
  57509. mouseDownNote = newNote;
  57510. }
  57511. repaintNote (noteUnderMouse);
  57512. noteUnderMouse = newNote;
  57513. repaintNote (noteUnderMouse);
  57514. }
  57515. else if (mouseDownNote >= 0 && ! mouseDragging)
  57516. {
  57517. state.noteOff (midiChannel, mouseDownNote);
  57518. mouseDownNote = -1;
  57519. }
  57520. }
  57521. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  57522. {
  57523. updateNoteUnderMouse (e.x, e.y);
  57524. stopTimer();
  57525. }
  57526. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  57527. {
  57528. const int newNote = xyToNote (e.x, e.y);
  57529. if (newNote >= 0)
  57530. mouseDraggedToKey (newNote, e);
  57531. updateNoteUnderMouse (e.x, e.y);
  57532. }
  57533. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  57534. {
  57535. return true;
  57536. }
  57537. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  57538. {
  57539. }
  57540. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  57541. {
  57542. const int newNote = xyToNote (e.x, e.y);
  57543. mouseDragging = false;
  57544. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  57545. {
  57546. repaintNote (noteUnderMouse);
  57547. noteUnderMouse = -1;
  57548. mouseDragging = true;
  57549. updateNoteUnderMouse (e.x, e.y);
  57550. startTimer (500);
  57551. }
  57552. }
  57553. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  57554. {
  57555. mouseDragging = false;
  57556. updateNoteUnderMouse (e.x, e.y);
  57557. stopTimer();
  57558. }
  57559. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  57560. {
  57561. updateNoteUnderMouse (e.x, e.y);
  57562. }
  57563. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  57564. {
  57565. updateNoteUnderMouse (e.x, e.y);
  57566. }
  57567. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  57568. {
  57569. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  57570. }
  57571. void MidiKeyboardComponent::timerCallback()
  57572. {
  57573. int mx, my;
  57574. getMouseXYRelative (mx, my);
  57575. updateNoteUnderMouse (mx, my);
  57576. }
  57577. void MidiKeyboardComponent::clearKeyMappings()
  57578. {
  57579. resetAnyKeysInUse();
  57580. keyPressNotes.clear();
  57581. keyPresses.clear();
  57582. }
  57583. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  57584. const int midiNoteOffsetFromC)
  57585. {
  57586. removeKeyPressForNote (midiNoteOffsetFromC);
  57587. keyPressNotes.add (midiNoteOffsetFromC);
  57588. keyPresses.add (key);
  57589. }
  57590. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  57591. {
  57592. for (int i = keyPressNotes.size(); --i >= 0;)
  57593. {
  57594. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  57595. {
  57596. keyPressNotes.remove (i);
  57597. keyPresses.remove (i);
  57598. }
  57599. }
  57600. }
  57601. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  57602. {
  57603. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  57604. keyMappingOctave = newOctaveNumber;
  57605. }
  57606. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  57607. {
  57608. bool keyPressUsed = false;
  57609. for (int i = keyPresses.size(); --i >= 0;)
  57610. {
  57611. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  57612. if (keyPresses.getReference(i).isCurrentlyDown())
  57613. {
  57614. if (! keysPressed [note])
  57615. {
  57616. keysPressed.setBit (note);
  57617. state.noteOn (midiChannel, note, velocity);
  57618. keyPressUsed = true;
  57619. }
  57620. }
  57621. else
  57622. {
  57623. if (keysPressed [note])
  57624. {
  57625. keysPressed.clearBit (note);
  57626. state.noteOff (midiChannel, note);
  57627. keyPressUsed = true;
  57628. }
  57629. }
  57630. }
  57631. return keyPressUsed;
  57632. }
  57633. void MidiKeyboardComponent::focusLost (FocusChangeType)
  57634. {
  57635. resetAnyKeysInUse();
  57636. }
  57637. END_JUCE_NAMESPACE
  57638. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57639. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  57640. #if JUCE_OPENGL
  57641. BEGIN_JUCE_NAMESPACE
  57642. extern void juce_glViewport (const int w, const int h);
  57643. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  57644. const int alphaBits_,
  57645. const int depthBufferBits_,
  57646. const int stencilBufferBits_) throw()
  57647. : redBits (bitsPerRGBComponent),
  57648. greenBits (bitsPerRGBComponent),
  57649. blueBits (bitsPerRGBComponent),
  57650. alphaBits (alphaBits_),
  57651. depthBufferBits (depthBufferBits_),
  57652. stencilBufferBits (stencilBufferBits_),
  57653. accumulationBufferRedBits (0),
  57654. accumulationBufferGreenBits (0),
  57655. accumulationBufferBlueBits (0),
  57656. accumulationBufferAlphaBits (0),
  57657. fullSceneAntiAliasingNumSamples (0)
  57658. {
  57659. }
  57660. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  57661. {
  57662. return memcmp (this, &other, sizeof (other)) == 0;
  57663. }
  57664. static VoidArray knownContexts;
  57665. OpenGLContext::OpenGLContext() throw()
  57666. {
  57667. knownContexts.add (this);
  57668. }
  57669. OpenGLContext::~OpenGLContext()
  57670. {
  57671. knownContexts.removeValue (this);
  57672. }
  57673. OpenGLContext* OpenGLContext::getCurrentContext()
  57674. {
  57675. for (int i = knownContexts.size(); --i >= 0;)
  57676. {
  57677. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  57678. if (oglc->isActive())
  57679. return oglc;
  57680. }
  57681. return 0;
  57682. }
  57683. class OpenGLComponentWatcher : public ComponentMovementWatcher
  57684. {
  57685. public:
  57686. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  57687. : ComponentMovementWatcher (owner_),
  57688. owner (owner_),
  57689. wasShowing (false)
  57690. {
  57691. }
  57692. ~OpenGLComponentWatcher() {}
  57693. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  57694. {
  57695. owner->updateContextPosition();
  57696. }
  57697. void componentPeerChanged()
  57698. {
  57699. const ScopedLock sl (owner->getContextLock());
  57700. owner->deleteContext();
  57701. }
  57702. void componentVisibilityChanged (Component&)
  57703. {
  57704. const bool isShowingNow = owner->isShowing();
  57705. if (wasShowing != isShowingNow)
  57706. {
  57707. wasShowing = isShowingNow;
  57708. owner->updateContextPosition();
  57709. }
  57710. }
  57711. juce_UseDebuggingNewOperator
  57712. private:
  57713. OpenGLComponent* const owner;
  57714. bool wasShowing;
  57715. };
  57716. OpenGLComponent::OpenGLComponent()
  57717. : context (0),
  57718. contextToShareListsWith (0),
  57719. needToUpdateViewport (true)
  57720. {
  57721. setOpaque (true);
  57722. componentWatcher = new OpenGLComponentWatcher (this);
  57723. }
  57724. OpenGLComponent::~OpenGLComponent()
  57725. {
  57726. deleteContext();
  57727. delete componentWatcher;
  57728. }
  57729. void OpenGLComponent::deleteContext()
  57730. {
  57731. const ScopedLock sl (contextLock);
  57732. deleteAndZero (context);
  57733. }
  57734. void OpenGLComponent::updateContextPosition()
  57735. {
  57736. needToUpdateViewport = true;
  57737. if (getWidth() > 0 && getHeight() > 0)
  57738. {
  57739. Component* const topComp = getTopLevelComponent();
  57740. if (topComp->getPeer() != 0)
  57741. {
  57742. const ScopedLock sl (contextLock);
  57743. if (context != 0)
  57744. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  57745. getScreenY() - topComp->getScreenY(),
  57746. getWidth(),
  57747. getHeight(),
  57748. topComp->getHeight());
  57749. }
  57750. }
  57751. }
  57752. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  57753. {
  57754. OpenGLPixelFormat pf;
  57755. const ScopedLock sl (contextLock);
  57756. if (context != 0)
  57757. pf = context->getPixelFormat();
  57758. return pf;
  57759. }
  57760. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  57761. {
  57762. if (! (preferredPixelFormat == formatToUse))
  57763. {
  57764. const ScopedLock sl (contextLock);
  57765. deleteContext();
  57766. preferredPixelFormat = formatToUse;
  57767. }
  57768. }
  57769. void OpenGLComponent::shareWith (OpenGLContext* context)
  57770. {
  57771. if (contextToShareListsWith != context)
  57772. {
  57773. const ScopedLock sl (contextLock);
  57774. deleteContext();
  57775. contextToShareListsWith = context;
  57776. }
  57777. }
  57778. bool OpenGLComponent::makeCurrentContextActive()
  57779. {
  57780. if (context == 0)
  57781. {
  57782. const ScopedLock sl (contextLock);
  57783. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  57784. {
  57785. context = OpenGLContext::createContextForWindow (this,
  57786. preferredPixelFormat,
  57787. contextToShareListsWith);
  57788. if (context != 0)
  57789. {
  57790. updateContextPosition();
  57791. if (context->makeActive())
  57792. newOpenGLContextCreated();
  57793. }
  57794. }
  57795. }
  57796. return context != 0 && context->makeActive();
  57797. }
  57798. void OpenGLComponent::makeCurrentContextInactive()
  57799. {
  57800. if (context != 0)
  57801. context->makeInactive();
  57802. }
  57803. bool OpenGLComponent::isActiveContext() const throw()
  57804. {
  57805. return context != 0 && context->isActive();
  57806. }
  57807. void OpenGLComponent::swapBuffers()
  57808. {
  57809. if (context != 0)
  57810. context->swapBuffers();
  57811. }
  57812. void OpenGLComponent::paint (Graphics&)
  57813. {
  57814. if (renderAndSwapBuffers())
  57815. {
  57816. ComponentPeer* const peer = getPeer();
  57817. if (peer != 0)
  57818. {
  57819. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  57820. getScreenY() - peer->getScreenY(),
  57821. getWidth(), getHeight());
  57822. }
  57823. }
  57824. }
  57825. bool OpenGLComponent::renderAndSwapBuffers()
  57826. {
  57827. const ScopedLock sl (contextLock);
  57828. if (! makeCurrentContextActive())
  57829. return false;
  57830. if (needToUpdateViewport)
  57831. {
  57832. needToUpdateViewport = false;
  57833. juce_glViewport (getWidth(), getHeight());
  57834. }
  57835. renderOpenGL();
  57836. swapBuffers();
  57837. return true;
  57838. }
  57839. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  57840. {
  57841. Component::internalRepaint (x, y, w, h);
  57842. if (context != 0)
  57843. context->repaint();
  57844. }
  57845. END_JUCE_NAMESPACE
  57846. #endif
  57847. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  57848. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  57849. BEGIN_JUCE_NAMESPACE
  57850. PreferencesPanel::PreferencesPanel()
  57851. : currentPage (0),
  57852. buttonSize (70)
  57853. {
  57854. }
  57855. PreferencesPanel::~PreferencesPanel()
  57856. {
  57857. deleteAllChildren();
  57858. }
  57859. void PreferencesPanel::addSettingsPage (const String& title,
  57860. const Drawable* icon,
  57861. const Drawable* overIcon,
  57862. const Drawable* downIcon)
  57863. {
  57864. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  57865. button->setImages (icon, overIcon, downIcon);
  57866. button->setRadioGroupId (1);
  57867. button->addButtonListener (this);
  57868. button->setClickingTogglesState (true);
  57869. button->setWantsKeyboardFocus (false);
  57870. addAndMakeVisible (button);
  57871. resized();
  57872. if (currentPage == 0)
  57873. setCurrentPage (title);
  57874. }
  57875. void PreferencesPanel::addSettingsPage (const String& title,
  57876. const char* imageData,
  57877. const int imageDataSize)
  57878. {
  57879. DrawableImage icon, iconOver, iconDown;
  57880. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57881. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57882. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  57883. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57884. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  57885. addSettingsPage (title, &icon, &iconOver, &iconDown);
  57886. }
  57887. class PrefsDialogWindow : public DialogWindow
  57888. {
  57889. public:
  57890. PrefsDialogWindow (const String& dialogtitle,
  57891. const Colour& backgroundColour)
  57892. : DialogWindow (dialogtitle, backgroundColour, true)
  57893. {
  57894. }
  57895. ~PrefsDialogWindow()
  57896. {
  57897. }
  57898. void closeButtonPressed()
  57899. {
  57900. exitModalState (0);
  57901. }
  57902. private:
  57903. PrefsDialogWindow (const PrefsDialogWindow&);
  57904. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  57905. };
  57906. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  57907. int dialogWidth,
  57908. int dialogHeight,
  57909. const Colour& backgroundColour)
  57910. {
  57911. setSize (dialogWidth, dialogHeight);
  57912. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  57913. dw.setContentComponent (this, true, true);
  57914. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  57915. dw.runModalLoop();
  57916. dw.setContentComponent (0, false, false);
  57917. }
  57918. void PreferencesPanel::resized()
  57919. {
  57920. int x = 0;
  57921. for (int i = 0; i < getNumChildComponents(); ++i)
  57922. {
  57923. Component* c = getChildComponent (i);
  57924. if (dynamic_cast <DrawableButton*> (c) == 0)
  57925. {
  57926. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  57927. }
  57928. else
  57929. {
  57930. c->setBounds (x, 0, buttonSize, buttonSize);
  57931. x += buttonSize;
  57932. }
  57933. }
  57934. }
  57935. void PreferencesPanel::paint (Graphics& g)
  57936. {
  57937. g.setColour (Colours::grey);
  57938. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  57939. }
  57940. void PreferencesPanel::setCurrentPage (const String& pageName)
  57941. {
  57942. if (currentPageName != pageName)
  57943. {
  57944. currentPageName = pageName;
  57945. deleteAndZero (currentPage);
  57946. currentPage = createComponentForPage (pageName);
  57947. if (currentPage != 0)
  57948. {
  57949. addAndMakeVisible (currentPage);
  57950. currentPage->toBack();
  57951. resized();
  57952. }
  57953. for (int i = 0; i < getNumChildComponents(); ++i)
  57954. {
  57955. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57956. if (db != 0 && db->getName() == pageName)
  57957. {
  57958. db->setToggleState (true, false);
  57959. break;
  57960. }
  57961. }
  57962. }
  57963. }
  57964. void PreferencesPanel::buttonClicked (Button*)
  57965. {
  57966. for (int i = 0; i < getNumChildComponents(); ++i)
  57967. {
  57968. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57969. if (db != 0 && db->getToggleState())
  57970. {
  57971. setCurrentPage (db->getName());
  57972. break;
  57973. }
  57974. }
  57975. }
  57976. END_JUCE_NAMESPACE
  57977. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  57978. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57979. #if JUCE_WINDOWS || JUCE_LINUX
  57980. BEGIN_JUCE_NAMESPACE
  57981. SystemTrayIconComponent::SystemTrayIconComponent()
  57982. {
  57983. addToDesktop (0);
  57984. }
  57985. SystemTrayIconComponent::~SystemTrayIconComponent()
  57986. {
  57987. }
  57988. END_JUCE_NAMESPACE
  57989. #endif
  57990. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57991. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  57992. BEGIN_JUCE_NAMESPACE
  57993. static const int titleH = 24;
  57994. static const int iconWidth = 80;
  57995. class AlertWindowTextEditor : public TextEditor
  57996. {
  57997. public:
  57998. #if JUCE_LINUX
  57999. #define PASSWORD_CHAR 0x2022
  58000. #else
  58001. #define PASSWORD_CHAR 0x25cf
  58002. #endif
  58003. AlertWindowTextEditor (const String& name,
  58004. const bool isPasswordBox)
  58005. : TextEditor (name,
  58006. isPasswordBox ? (const tchar) PASSWORD_CHAR
  58007. : (const tchar) 0)
  58008. {
  58009. setSelectAllWhenFocused (true);
  58010. }
  58011. ~AlertWindowTextEditor()
  58012. {
  58013. }
  58014. void returnPressed()
  58015. {
  58016. // pass these up the component hierarchy to be trigger the buttons
  58017. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  58018. }
  58019. void escapePressed()
  58020. {
  58021. // pass these up the component hierarchy to be trigger the buttons
  58022. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  58023. }
  58024. private:
  58025. AlertWindowTextEditor (const AlertWindowTextEditor&);
  58026. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  58027. };
  58028. AlertWindow::AlertWindow (const String& title,
  58029. const String& message,
  58030. AlertIconType iconType,
  58031. Component* associatedComponent_)
  58032. : TopLevelWindow (title, true),
  58033. alertIconType (iconType),
  58034. associatedComponent (associatedComponent_)
  58035. {
  58036. if (message.isEmpty())
  58037. text = T(" "); // to force an update if the message is empty
  58038. setMessage (message);
  58039. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  58040. {
  58041. Component* const c = Desktop::getInstance().getComponent (i);
  58042. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  58043. {
  58044. setAlwaysOnTop (true);
  58045. break;
  58046. }
  58047. }
  58048. if (JUCEApplication::getInstance() == 0)
  58049. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  58050. lookAndFeelChanged();
  58051. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  58052. }
  58053. AlertWindow::~AlertWindow()
  58054. {
  58055. for (int i = customComps.size(); --i >= 0;)
  58056. removeChildComponent ((Component*) customComps[i]);
  58057. deleteAllChildren();
  58058. }
  58059. void AlertWindow::userTriedToCloseWindow()
  58060. {
  58061. exitModalState (0);
  58062. }
  58063. void AlertWindow::setMessage (const String& message)
  58064. {
  58065. const String newMessage (message.substring (0, 2048));
  58066. if (text != newMessage)
  58067. {
  58068. text = newMessage;
  58069. font.setHeight (15.0f);
  58070. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  58071. textLayout.setText (getName() + T("\n\n"), titleFont);
  58072. textLayout.appendText (text, font);
  58073. updateLayout (true);
  58074. repaint();
  58075. }
  58076. }
  58077. void AlertWindow::buttonClicked (Button* button)
  58078. {
  58079. for (int i = 0; i < buttons.size(); i++)
  58080. {
  58081. TextButton* const c = (TextButton*) buttons[i];
  58082. if (button->getName() == c->getName())
  58083. {
  58084. if (c->getParentComponent() != 0)
  58085. c->getParentComponent()->exitModalState (c->getCommandID());
  58086. break;
  58087. }
  58088. }
  58089. }
  58090. void AlertWindow::addButton (const String& name,
  58091. const int returnValue,
  58092. const KeyPress& shortcutKey1,
  58093. const KeyPress& shortcutKey2)
  58094. {
  58095. TextButton* const b = new TextButton (name, String::empty);
  58096. b->setWantsKeyboardFocus (true);
  58097. b->setMouseClickGrabsKeyboardFocus (false);
  58098. b->setCommandToTrigger (0, returnValue, false);
  58099. b->addShortcut (shortcutKey1);
  58100. b->addShortcut (shortcutKey2);
  58101. b->addButtonListener (this);
  58102. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  58103. addAndMakeVisible (b, 0);
  58104. buttons.add (b);
  58105. updateLayout (false);
  58106. }
  58107. int AlertWindow::getNumButtons() const
  58108. {
  58109. return buttons.size();
  58110. }
  58111. void AlertWindow::addTextEditor (const String& name,
  58112. const String& initialContents,
  58113. const String& onScreenLabel,
  58114. const bool isPasswordBox)
  58115. {
  58116. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  58117. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  58118. tc->setFont (font);
  58119. tc->setText (initialContents);
  58120. tc->setCaretPosition (initialContents.length());
  58121. addAndMakeVisible (tc);
  58122. textBoxes.add (tc);
  58123. allComps.add (tc);
  58124. textboxNames.add (onScreenLabel);
  58125. updateLayout (false);
  58126. }
  58127. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  58128. {
  58129. for (int i = textBoxes.size(); --i >= 0;)
  58130. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  58131. return ((TextEditor*)textBoxes[i])->getText();
  58132. return String::empty;
  58133. }
  58134. void AlertWindow::addComboBox (const String& name,
  58135. const StringArray& items,
  58136. const String& onScreenLabel)
  58137. {
  58138. ComboBox* const cb = new ComboBox (name);
  58139. for (int i = 0; i < items.size(); ++i)
  58140. cb->addItem (items[i], i + 1);
  58141. addAndMakeVisible (cb);
  58142. cb->setSelectedItemIndex (0);
  58143. comboBoxes.add (cb);
  58144. allComps.add (cb);
  58145. comboBoxNames.add (onScreenLabel);
  58146. updateLayout (false);
  58147. }
  58148. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  58149. {
  58150. for (int i = comboBoxes.size(); --i >= 0;)
  58151. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  58152. return (ComboBox*) comboBoxes[i];
  58153. return 0;
  58154. }
  58155. class AlertTextComp : public TextEditor
  58156. {
  58157. AlertTextComp (const AlertTextComp&);
  58158. const AlertTextComp& operator= (const AlertTextComp&);
  58159. int bestWidth;
  58160. public:
  58161. AlertTextComp (const String& message,
  58162. const Font& font)
  58163. {
  58164. setReadOnly (true);
  58165. setMultiLine (true, true);
  58166. setCaretVisible (false);
  58167. setScrollbarsShown (true);
  58168. lookAndFeelChanged();
  58169. setWantsKeyboardFocus (false);
  58170. setFont (font);
  58171. setText (message, false);
  58172. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  58173. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  58174. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  58175. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  58176. }
  58177. ~AlertTextComp()
  58178. {
  58179. }
  58180. int getPreferredWidth() const throw() { return bestWidth; }
  58181. void updateLayout (const int width)
  58182. {
  58183. TextLayout text;
  58184. text.appendText (getText(), getFont());
  58185. text.layout (width - 8, Justification::topLeft, true);
  58186. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  58187. }
  58188. };
  58189. void AlertWindow::addTextBlock (const String& text)
  58190. {
  58191. AlertTextComp* const c = new AlertTextComp (text, font);
  58192. textBlocks.add (c);
  58193. allComps.add (c);
  58194. addAndMakeVisible (c);
  58195. updateLayout (false);
  58196. }
  58197. void AlertWindow::addProgressBarComponent (double& progressValue)
  58198. {
  58199. ProgressBar* const pb = new ProgressBar (progressValue);
  58200. progressBars.add (pb);
  58201. allComps.add (pb);
  58202. addAndMakeVisible (pb);
  58203. updateLayout (false);
  58204. }
  58205. void AlertWindow::addCustomComponent (Component* const component)
  58206. {
  58207. customComps.add (component);
  58208. allComps.add (component);
  58209. addAndMakeVisible (component);
  58210. updateLayout (false);
  58211. }
  58212. int AlertWindow::getNumCustomComponents() const
  58213. {
  58214. return customComps.size();
  58215. }
  58216. Component* AlertWindow::getCustomComponent (const int index) const
  58217. {
  58218. return (Component*) customComps [index];
  58219. }
  58220. Component* AlertWindow::removeCustomComponent (const int index)
  58221. {
  58222. Component* const c = getCustomComponent (index);
  58223. if (c != 0)
  58224. {
  58225. customComps.removeValue (c);
  58226. allComps.removeValue (c);
  58227. removeChildComponent (c);
  58228. updateLayout (false);
  58229. }
  58230. return c;
  58231. }
  58232. void AlertWindow::paint (Graphics& g)
  58233. {
  58234. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  58235. g.setColour (findColour (textColourId));
  58236. g.setFont (getLookAndFeel().getAlertWindowFont());
  58237. int i;
  58238. for (i = textBoxes.size(); --i >= 0;)
  58239. {
  58240. if (textboxNames[i].isNotEmpty())
  58241. {
  58242. const TextEditor* const te = (TextEditor*) textBoxes[i];
  58243. g.drawFittedText (textboxNames[i],
  58244. te->getX(), te->getY() - 14,
  58245. te->getWidth(), 14,
  58246. Justification::centredLeft, 1);
  58247. }
  58248. }
  58249. for (i = comboBoxNames.size(); --i >= 0;)
  58250. {
  58251. if (comboBoxNames[i].isNotEmpty())
  58252. {
  58253. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  58254. g.drawFittedText (comboBoxNames[i],
  58255. cb->getX(), cb->getY() - 14,
  58256. cb->getWidth(), 14,
  58257. Justification::centredLeft, 1);
  58258. }
  58259. }
  58260. }
  58261. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  58262. {
  58263. const int wid = jmax (font.getStringWidth (text),
  58264. font.getStringWidth (getName()));
  58265. const int sw = (int) sqrt (font.getHeight() * wid);
  58266. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  58267. const int edgeGap = 10;
  58268. int iconSpace;
  58269. if (alertIconType == NoIcon)
  58270. {
  58271. textLayout.layout (w, Justification::horizontallyCentred, true);
  58272. iconSpace = 0;
  58273. }
  58274. else
  58275. {
  58276. textLayout.layout (w, Justification::left, true);
  58277. iconSpace = iconWidth;
  58278. }
  58279. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  58280. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58281. const int textLayoutH = textLayout.getHeight();
  58282. const int textBottom = 16 + titleH + textLayoutH;
  58283. int h = textBottom;
  58284. int buttonW = 40;
  58285. int i;
  58286. for (i = 0; i < buttons.size(); ++i)
  58287. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  58288. w = jmax (buttonW, w);
  58289. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  58290. if (buttons.size() > 0)
  58291. h += 20 + ((TextButton*) buttons[0])->getHeight();
  58292. for (i = customComps.size(); --i >= 0;)
  58293. {
  58294. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  58295. h += 10 + ((Component*) customComps[i])->getHeight();
  58296. }
  58297. for (i = textBlocks.size(); --i >= 0;)
  58298. {
  58299. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58300. w = jmax (w, ac->getPreferredWidth());
  58301. }
  58302. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58303. for (i = textBlocks.size(); --i >= 0;)
  58304. {
  58305. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58306. ac->updateLayout ((int) (w * 0.8f));
  58307. h += ac->getHeight() + 10;
  58308. }
  58309. h = jmin (getParentHeight() - 50, h);
  58310. if (onlyIncreaseSize)
  58311. {
  58312. w = jmax (w, getWidth());
  58313. h = jmax (h, getHeight());
  58314. }
  58315. if (! isVisible())
  58316. {
  58317. centreAroundComponent (associatedComponent, w, h);
  58318. }
  58319. else
  58320. {
  58321. const int cx = getX() + getWidth() / 2;
  58322. const int cy = getY() + getHeight() / 2;
  58323. setBounds (cx - w / 2,
  58324. cy - h / 2,
  58325. w, h);
  58326. }
  58327. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  58328. const int spacer = 16;
  58329. int totalWidth = -spacer;
  58330. for (i = buttons.size(); --i >= 0;)
  58331. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  58332. int x = (w - totalWidth) / 2;
  58333. int y = (int) (getHeight() * 0.95f);
  58334. for (i = 0; i < buttons.size(); ++i)
  58335. {
  58336. TextButton* const c = (TextButton*) buttons[i];
  58337. int ny = proportionOfHeight (0.95f) - c->getHeight();
  58338. c->setTopLeftPosition (x, ny);
  58339. if (ny < y)
  58340. y = ny;
  58341. x += c->getWidth() + spacer;
  58342. c->toFront (false);
  58343. }
  58344. y = textBottom;
  58345. for (i = 0; i < allComps.size(); ++i)
  58346. {
  58347. Component* const c = (Component*) allComps[i];
  58348. const int h = 22;
  58349. const int comboIndex = comboBoxes.indexOf (c);
  58350. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  58351. y += 18;
  58352. const int tbIndex = textBoxes.indexOf (c);
  58353. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  58354. y += 18;
  58355. if (customComps.contains (c) || textBlocks.contains (c))
  58356. {
  58357. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  58358. y += c->getHeight() + 10;
  58359. }
  58360. else
  58361. {
  58362. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  58363. y += h + 10;
  58364. }
  58365. }
  58366. setWantsKeyboardFocus (getNumChildComponents() == 0);
  58367. }
  58368. bool AlertWindow::containsAnyExtraComponents() const
  58369. {
  58370. return textBoxes.size()
  58371. + comboBoxes.size()
  58372. + progressBars.size()
  58373. + customComps.size() > 0;
  58374. }
  58375. void AlertWindow::mouseDown (const MouseEvent&)
  58376. {
  58377. dragger.startDraggingComponent (this, &constrainer);
  58378. }
  58379. void AlertWindow::mouseDrag (const MouseEvent& e)
  58380. {
  58381. dragger.dragComponent (this, e);
  58382. }
  58383. bool AlertWindow::keyPressed (const KeyPress& key)
  58384. {
  58385. for (int i = buttons.size(); --i >= 0;)
  58386. {
  58387. TextButton* const b = (TextButton*) buttons[i];
  58388. if (b->isRegisteredForShortcut (key))
  58389. {
  58390. b->triggerClick();
  58391. return true;
  58392. }
  58393. }
  58394. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  58395. {
  58396. exitModalState (0);
  58397. return true;
  58398. }
  58399. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  58400. {
  58401. ((TextButton*) buttons.getFirst())->triggerClick();
  58402. return true;
  58403. }
  58404. return false;
  58405. }
  58406. void AlertWindow::lookAndFeelChanged()
  58407. {
  58408. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  58409. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  58410. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  58411. }
  58412. int AlertWindow::getDesktopWindowStyleFlags() const
  58413. {
  58414. return getLookAndFeel().getAlertBoxWindowFlags();
  58415. }
  58416. struct AlertWindowInfo
  58417. {
  58418. String title, message, button1, button2, button3;
  58419. AlertWindow::AlertIconType iconType;
  58420. int numButtons;
  58421. Component* associatedComponent;
  58422. int run() const
  58423. {
  58424. return (int) (pointer_sized_int)
  58425. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  58426. }
  58427. private:
  58428. int show() const
  58429. {
  58430. jassert (associatedComponent == 0 || associatedComponent->isValidComponent()); // has your comp been deleted?
  58431. LookAndFeel& lf = associatedComponent->isValidComponent() ? associatedComponent->getLookAndFeel()
  58432. : LookAndFeel::getDefaultLookAndFeel();
  58433. Component* const alertBox = lf.createAlertWindow (title, message, button1, button2, button3,
  58434. iconType, numButtons, associatedComponent);
  58435. jassert (alertBox != 0); // you have to return one of these!
  58436. const int result = alertBox->runModalLoop();
  58437. delete alertBox;
  58438. return result;
  58439. }
  58440. static void* showCallback (void* userData)
  58441. {
  58442. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  58443. }
  58444. };
  58445. void AlertWindow::showMessageBox (AlertIconType iconType,
  58446. const String& title,
  58447. const String& message,
  58448. const String& buttonText,
  58449. Component* associatedComponent)
  58450. {
  58451. AlertWindowInfo info;
  58452. info.title = title;
  58453. info.message = message;
  58454. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  58455. info.iconType = iconType;
  58456. info.numButtons = 1;
  58457. info.associatedComponent = associatedComponent;
  58458. info.run();
  58459. }
  58460. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  58461. const String& title,
  58462. const String& message,
  58463. const String& button1Text,
  58464. const String& button2Text,
  58465. Component* associatedComponent)
  58466. {
  58467. AlertWindowInfo info;
  58468. info.title = title;
  58469. info.message = message;
  58470. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  58471. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  58472. info.iconType = iconType;
  58473. info.numButtons = 2;
  58474. info.associatedComponent = associatedComponent;
  58475. return info.run() != 0;
  58476. }
  58477. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  58478. const String& title,
  58479. const String& message,
  58480. const String& button1Text,
  58481. const String& button2Text,
  58482. const String& button3Text,
  58483. Component* associatedComponent)
  58484. {
  58485. AlertWindowInfo info;
  58486. info.title = title;
  58487. info.message = message;
  58488. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  58489. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  58490. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  58491. info.iconType = iconType;
  58492. info.numButtons = 3;
  58493. info.associatedComponent = associatedComponent;
  58494. return info.run();
  58495. }
  58496. END_JUCE_NAMESPACE
  58497. /********* End of inlined file: juce_AlertWindow.cpp *********/
  58498. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  58499. BEGIN_JUCE_NAMESPACE
  58500. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  58501. // these are over in juce_component.cpp
  58502. extern int64 juce_recentMouseDownTimes[4];
  58503. extern int juce_recentMouseDownX [4];
  58504. extern int juce_recentMouseDownY [4];
  58505. extern Component* juce_recentMouseDownComponent [4];
  58506. extern int juce_LastMousePosX;
  58507. extern int juce_LastMousePosY;
  58508. extern int juce_MouseClickCounter;
  58509. extern bool juce_MouseHasMovedSignificantlySincePressed;
  58510. static const int fakeMouseMoveMessage = 0x7fff00ff;
  58511. static VoidArray heavyweightPeers (4);
  58512. ComponentPeer::ComponentPeer (Component* const component_,
  58513. const int styleFlags_) throw()
  58514. : component (component_),
  58515. styleFlags (styleFlags_),
  58516. lastPaintTime (0),
  58517. constrainer (0),
  58518. lastFocusedComponent (0),
  58519. dragAndDropTargetComponent (0),
  58520. lastDragAndDropCompUnderMouse (0),
  58521. fakeMouseMessageSent (false),
  58522. isWindowMinimised (false)
  58523. {
  58524. heavyweightPeers.add (this);
  58525. }
  58526. ComponentPeer::~ComponentPeer()
  58527. {
  58528. heavyweightPeers.removeValue (this);
  58529. delete dragAndDropTargetComponent;
  58530. Desktop::getInstance().triggerFocusCallback();
  58531. }
  58532. int ComponentPeer::getNumPeers() throw()
  58533. {
  58534. return heavyweightPeers.size();
  58535. }
  58536. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  58537. {
  58538. return (ComponentPeer*) heavyweightPeers [index];
  58539. }
  58540. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  58541. {
  58542. for (int i = heavyweightPeers.size(); --i >= 0;)
  58543. {
  58544. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  58545. if (peer->getComponent() == component)
  58546. return peer;
  58547. }
  58548. return 0;
  58549. }
  58550. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  58551. {
  58552. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  58553. }
  58554. void ComponentPeer::updateCurrentModifiers() throw()
  58555. {
  58556. ModifierKeys::updateCurrentModifiers();
  58557. }
  58558. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  58559. {
  58560. jassert (component->isValidComponent());
  58561. updateCurrentModifiers();
  58562. Component* c = component->getComponentAt (x, y);
  58563. const ComponentDeletionWatcher deletionChecker (component);
  58564. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  58565. {
  58566. jassert (Component::componentUnderMouse->isValidComponent());
  58567. const int oldX = x;
  58568. const int oldY = y;
  58569. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58570. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58571. Component::componentUnderMouse = 0;
  58572. if (deletionChecker.hasBeenDeleted())
  58573. return;
  58574. c = component->getComponentAt (oldX, oldY);
  58575. }
  58576. Component::componentUnderMouse = c;
  58577. if (Component::componentUnderMouse != 0)
  58578. {
  58579. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58580. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58581. }
  58582. }
  58583. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  58584. {
  58585. jassert (component->isValidComponent());
  58586. updateCurrentModifiers();
  58587. fakeMouseMessageSent = false;
  58588. const ComponentDeletionWatcher deletionChecker (component);
  58589. Component* c = component->getComponentAt (x, y);
  58590. if (c != Component::componentUnderMouse)
  58591. {
  58592. const int oldX = x;
  58593. const int oldY = y;
  58594. if (Component::componentUnderMouse != 0)
  58595. {
  58596. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58597. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58598. x = oldX;
  58599. y = oldY;
  58600. Component::componentUnderMouse = 0;
  58601. if (deletionChecker.hasBeenDeleted())
  58602. return; // if this window has just been deleted..
  58603. c = component->getComponentAt (x, y);
  58604. }
  58605. Component::componentUnderMouse = c;
  58606. if (c != 0)
  58607. {
  58608. component->relativePositionToOtherComponent (c, x, y);
  58609. c->internalMouseEnter (x, y, time);
  58610. x = oldX;
  58611. y = oldY;
  58612. if (deletionChecker.hasBeenDeleted())
  58613. return; // if this window has just been deleted..
  58614. }
  58615. }
  58616. if (Component::componentUnderMouse != 0)
  58617. {
  58618. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58619. Component::componentUnderMouse->internalMouseMove (x, y, time);
  58620. }
  58621. }
  58622. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  58623. {
  58624. ++juce_MouseClickCounter;
  58625. updateCurrentModifiers();
  58626. int numMouseButtonsDown = 0;
  58627. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  58628. ++numMouseButtonsDown;
  58629. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  58630. ++numMouseButtonsDown;
  58631. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  58632. ++numMouseButtonsDown;
  58633. if (numMouseButtonsDown == 1)
  58634. {
  58635. Component::componentUnderMouse = component->getComponentAt (x, y);
  58636. if (Component::componentUnderMouse != 0)
  58637. {
  58638. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  58639. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  58640. {
  58641. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  58642. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  58643. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  58644. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  58645. }
  58646. juce_recentMouseDownTimes[0] = time;
  58647. juce_recentMouseDownX[0] = x;
  58648. juce_recentMouseDownY[0] = y;
  58649. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  58650. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  58651. juce_MouseHasMovedSignificantlySincePressed = false;
  58652. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58653. Component::componentUnderMouse->internalMouseDown (x, y);
  58654. }
  58655. }
  58656. }
  58657. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  58658. {
  58659. updateCurrentModifiers();
  58660. if (Component::componentUnderMouse != 0)
  58661. {
  58662. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58663. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  58664. }
  58665. }
  58666. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  58667. {
  58668. updateCurrentModifiers();
  58669. int numMouseButtonsDown = 0;
  58670. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  58671. ++numMouseButtonsDown;
  58672. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  58673. ++numMouseButtonsDown;
  58674. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  58675. ++numMouseButtonsDown;
  58676. if (numMouseButtonsDown == 1)
  58677. {
  58678. const ComponentDeletionWatcher deletionChecker (component);
  58679. Component* c = component->getComponentAt (x, y);
  58680. if (c != Component::componentUnderMouse)
  58681. {
  58682. const int oldX = x;
  58683. const int oldY = y;
  58684. if (Component::componentUnderMouse != 0)
  58685. {
  58686. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58687. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58688. x = oldX;
  58689. y = oldY;
  58690. if (Component::componentUnderMouse != 0)
  58691. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58692. if (deletionChecker.hasBeenDeleted())
  58693. return;
  58694. c = component->getComponentAt (oldX, oldY);
  58695. }
  58696. Component::componentUnderMouse = c;
  58697. if (Component::componentUnderMouse != 0)
  58698. {
  58699. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58700. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58701. }
  58702. }
  58703. else
  58704. {
  58705. if (Component::componentUnderMouse != 0)
  58706. {
  58707. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58708. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58709. }
  58710. }
  58711. }
  58712. }
  58713. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  58714. {
  58715. jassert (component->isValidComponent());
  58716. updateCurrentModifiers();
  58717. if (Component::componentUnderMouse != 0)
  58718. {
  58719. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58720. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58721. Component::componentUnderMouse = 0;
  58722. }
  58723. }
  58724. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  58725. {
  58726. updateCurrentModifiers();
  58727. if (Component::componentUnderMouse != 0)
  58728. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  58729. }
  58730. void ComponentPeer::sendFakeMouseMove() throw()
  58731. {
  58732. if ((! fakeMouseMessageSent)
  58733. && component->flags.hasHeavyweightPeerFlag
  58734. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58735. {
  58736. if (! isMinimised())
  58737. {
  58738. int realX, realY, realW, realH;
  58739. getBounds (realX, realY, realW, realH);
  58740. component->bounds_.setBounds (realX, realY, realW, realH);
  58741. }
  58742. int x, y;
  58743. component->getMouseXYRelative (x, y);
  58744. if (((unsigned int) x) < (unsigned int) component->getWidth()
  58745. && ((unsigned int) y) < (unsigned int) component->getHeight()
  58746. && contains (x, y, false))
  58747. {
  58748. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  58749. }
  58750. fakeMouseMessageSent = true;
  58751. }
  58752. }
  58753. void ComponentPeer::handleMessage (const Message& message)
  58754. {
  58755. if (message.intParameter1 == fakeMouseMoveMessage)
  58756. {
  58757. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58758. handleMouseMove (message.intParameter2,
  58759. message.intParameter3,
  58760. Time::currentTimeMillis());
  58761. }
  58762. }
  58763. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  58764. {
  58765. Graphics g (&contextToPaintTo);
  58766. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58767. g.saveState();
  58768. #endif
  58769. JUCE_TRY
  58770. {
  58771. component->paintEntireComponent (g);
  58772. }
  58773. JUCE_CATCH_EXCEPTION
  58774. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58775. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  58776. // clearly when things are being repainted.
  58777. {
  58778. g.restoreState();
  58779. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  58780. (uint8) Random::getSystemRandom().nextInt (255),
  58781. (uint8) Random::getSystemRandom().nextInt (255),
  58782. (uint8) 0x50));
  58783. }
  58784. #endif
  58785. }
  58786. bool ComponentPeer::handleKeyPress (const int keyCode,
  58787. const juce_wchar textCharacter)
  58788. {
  58789. updateCurrentModifiers();
  58790. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58791. ? Component::currentlyFocusedComponent
  58792. : component;
  58793. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58794. {
  58795. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58796. if (currentModalComp != 0)
  58797. target = currentModalComp;
  58798. }
  58799. const KeyPress keyInfo (keyCode,
  58800. ModifierKeys::getCurrentModifiers().getRawFlags()
  58801. & ModifierKeys::allKeyboardModifiers,
  58802. textCharacter);
  58803. bool keyWasUsed = false;
  58804. while (target != 0)
  58805. {
  58806. const ComponentDeletionWatcher deletionChecker (target);
  58807. if (target->keyListeners_ != 0)
  58808. {
  58809. for (int i = target->keyListeners_->size(); --i >= 0;)
  58810. {
  58811. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  58812. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58813. return keyWasUsed;
  58814. i = jmin (i, target->keyListeners_->size());
  58815. }
  58816. }
  58817. keyWasUsed = target->keyPressed (keyInfo);
  58818. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58819. break;
  58820. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  58821. {
  58822. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  58823. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  58824. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  58825. break;
  58826. }
  58827. target = target->parentComponent_;
  58828. }
  58829. return keyWasUsed;
  58830. }
  58831. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  58832. {
  58833. updateCurrentModifiers();
  58834. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58835. ? Component::currentlyFocusedComponent
  58836. : component;
  58837. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58838. {
  58839. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58840. if (currentModalComp != 0)
  58841. target = currentModalComp;
  58842. }
  58843. bool keyWasUsed = false;
  58844. while (target != 0)
  58845. {
  58846. const ComponentDeletionWatcher deletionChecker (target);
  58847. keyWasUsed = target->keyStateChanged (isKeyDown);
  58848. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58849. break;
  58850. if (target->keyListeners_ != 0)
  58851. {
  58852. for (int i = target->keyListeners_->size(); --i >= 0;)
  58853. {
  58854. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  58855. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58856. return keyWasUsed;
  58857. i = jmin (i, target->keyListeners_->size());
  58858. }
  58859. }
  58860. target = target->parentComponent_;
  58861. }
  58862. return keyWasUsed;
  58863. }
  58864. void ComponentPeer::handleModifierKeysChange()
  58865. {
  58866. updateCurrentModifiers();
  58867. Component* target = Component::getComponentUnderMouse();
  58868. if (target == 0)
  58869. target = Component::getCurrentlyFocusedComponent();
  58870. if (target == 0)
  58871. target = component;
  58872. if (target->isValidComponent())
  58873. target->internalModifierKeysChanged();
  58874. }
  58875. void ComponentPeer::handleBroughtToFront()
  58876. {
  58877. updateCurrentModifiers();
  58878. if (component != 0)
  58879. component->internalBroughtToFront();
  58880. }
  58881. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  58882. {
  58883. constrainer = newConstrainer;
  58884. }
  58885. void ComponentPeer::handleMovedOrResized()
  58886. {
  58887. jassert (component->isValidComponent());
  58888. updateCurrentModifiers();
  58889. const bool nowMinimised = isMinimised();
  58890. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  58891. {
  58892. const ComponentDeletionWatcher deletionChecker (component);
  58893. int realX, realY, realW, realH;
  58894. getBounds (realX, realY, realW, realH);
  58895. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  58896. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  58897. if (wasMoved || wasResized)
  58898. {
  58899. component->bounds_.setBounds (realX, realY, realW, realH);
  58900. if (wasResized)
  58901. component->repaint();
  58902. component->sendMovedResizedMessages (wasMoved, wasResized);
  58903. if (deletionChecker.hasBeenDeleted())
  58904. return;
  58905. }
  58906. }
  58907. if (isWindowMinimised != nowMinimised)
  58908. {
  58909. isWindowMinimised = nowMinimised;
  58910. component->minimisationStateChanged (nowMinimised);
  58911. component->sendVisibilityChangeMessage();
  58912. }
  58913. if (! isFullScreen())
  58914. lastNonFullscreenBounds = component->getBounds();
  58915. }
  58916. void ComponentPeer::handleFocusGain()
  58917. {
  58918. updateCurrentModifiers();
  58919. if (component->isParentOf (lastFocusedComponent))
  58920. {
  58921. Component::currentlyFocusedComponent = lastFocusedComponent;
  58922. Desktop::getInstance().triggerFocusCallback();
  58923. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  58924. }
  58925. else
  58926. {
  58927. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  58928. component->grabKeyboardFocus();
  58929. else
  58930. Component::bringModalComponentToFront();
  58931. }
  58932. }
  58933. void ComponentPeer::handleFocusLoss()
  58934. {
  58935. updateCurrentModifiers();
  58936. if (component->hasKeyboardFocus (true))
  58937. {
  58938. lastFocusedComponent = Component::currentlyFocusedComponent;
  58939. if (lastFocusedComponent != 0)
  58940. {
  58941. Component::currentlyFocusedComponent = 0;
  58942. Desktop::getInstance().triggerFocusCallback();
  58943. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  58944. }
  58945. }
  58946. }
  58947. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  58948. {
  58949. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  58950. ? lastFocusedComponent
  58951. : component;
  58952. }
  58953. void ComponentPeer::handleScreenSizeChange()
  58954. {
  58955. updateCurrentModifiers();
  58956. component->parentSizeChanged();
  58957. handleMovedOrResized();
  58958. }
  58959. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  58960. {
  58961. lastNonFullscreenBounds = newBounds;
  58962. }
  58963. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  58964. {
  58965. return lastNonFullscreenBounds;
  58966. }
  58967. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  58968. const StringArray& files,
  58969. FileDragAndDropTarget* const lastOne)
  58970. {
  58971. while (c != 0)
  58972. {
  58973. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  58974. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  58975. return t;
  58976. c = c->getParentComponent();
  58977. }
  58978. return 0;
  58979. }
  58980. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  58981. {
  58982. updateCurrentModifiers();
  58983. FileDragAndDropTarget* lastTarget = 0;
  58984. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58985. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58986. FileDragAndDropTarget* newTarget = 0;
  58987. Component* const compUnderMouse = component->getComponentAt (x, y);
  58988. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  58989. {
  58990. lastDragAndDropCompUnderMouse = compUnderMouse;
  58991. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  58992. if (newTarget != lastTarget)
  58993. {
  58994. if (lastTarget != 0)
  58995. lastTarget->fileDragExit (files);
  58996. deleteAndZero (dragAndDropTargetComponent);
  58997. if (newTarget != 0)
  58998. {
  58999. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  59000. int mx = x, my = y;
  59001. component->relativePositionToOtherComponent (targetComp, mx, my);
  59002. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  59003. newTarget->fileDragEnter (files, mx, my);
  59004. }
  59005. }
  59006. }
  59007. else
  59008. {
  59009. newTarget = lastTarget;
  59010. }
  59011. if (newTarget != 0)
  59012. {
  59013. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  59014. component->relativePositionToOtherComponent (targetComp, x, y);
  59015. newTarget->fileDragMove (files, x, y);
  59016. }
  59017. }
  59018. void ComponentPeer::handleFileDragExit (const StringArray& files)
  59019. {
  59020. handleFileDragMove (files, -1, -1);
  59021. jassert (dragAndDropTargetComponent == 0);
  59022. lastDragAndDropCompUnderMouse = 0;
  59023. }
  59024. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  59025. {
  59026. handleFileDragMove (files, x, y);
  59027. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  59028. {
  59029. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  59030. deleteAndZero (dragAndDropTargetComponent);
  59031. lastDragAndDropCompUnderMouse = 0;
  59032. if (target != 0)
  59033. {
  59034. Component* const targetComp = dynamic_cast <Component*> (target);
  59035. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  59036. {
  59037. targetComp->internalModalInputAttempt();
  59038. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  59039. return;
  59040. }
  59041. component->relativePositionToOtherComponent (targetComp, x, y);
  59042. target->filesDropped (files, x, y);
  59043. }
  59044. }
  59045. }
  59046. void ComponentPeer::handleUserClosingWindow()
  59047. {
  59048. updateCurrentModifiers();
  59049. component->userTriedToCloseWindow();
  59050. }
  59051. void ComponentPeer::bringModalComponentToFront()
  59052. {
  59053. Component::bringModalComponentToFront();
  59054. }
  59055. void ComponentPeer::clearMaskedRegion() throw()
  59056. {
  59057. maskedRegion.clear();
  59058. }
  59059. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  59060. {
  59061. maskedRegion.add (x, y, w, h);
  59062. }
  59063. END_JUCE_NAMESPACE
  59064. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  59065. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  59066. BEGIN_JUCE_NAMESPACE
  59067. DialogWindow::DialogWindow (const String& name,
  59068. const Colour& backgroundColour_,
  59069. const bool escapeKeyTriggersCloseButton_,
  59070. const bool addToDesktop_)
  59071. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  59072. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  59073. {
  59074. }
  59075. DialogWindow::~DialogWindow()
  59076. {
  59077. }
  59078. void DialogWindow::resized()
  59079. {
  59080. DocumentWindow::resized();
  59081. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  59082. if (escapeKeyTriggersCloseButton
  59083. && getCloseButton() != 0
  59084. && ! getCloseButton()->isRegisteredForShortcut (esc))
  59085. {
  59086. getCloseButton()->addShortcut (esc);
  59087. }
  59088. }
  59089. class TempDialogWindow : public DialogWindow
  59090. {
  59091. public:
  59092. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  59093. : DialogWindow (title, colour, escapeCloses, true)
  59094. {
  59095. }
  59096. ~TempDialogWindow()
  59097. {
  59098. }
  59099. void closeButtonPressed()
  59100. {
  59101. setVisible (false);
  59102. }
  59103. private:
  59104. TempDialogWindow (const TempDialogWindow&);
  59105. const TempDialogWindow& operator= (const TempDialogWindow&);
  59106. };
  59107. int DialogWindow::showModalDialog (const String& dialogTitle,
  59108. Component* contentComponent,
  59109. Component* componentToCentreAround,
  59110. const Colour& colour,
  59111. const bool escapeKeyTriggersCloseButton,
  59112. const bool shouldBeResizable,
  59113. const bool useBottomRightCornerResizer)
  59114. {
  59115. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  59116. dw.setContentComponent (contentComponent, true, true);
  59117. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  59118. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59119. const int result = dw.runModalLoop();
  59120. dw.setContentComponent (0, false);
  59121. return result;
  59122. }
  59123. END_JUCE_NAMESPACE
  59124. /********* End of inlined file: juce_DialogWindow.cpp *********/
  59125. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  59126. BEGIN_JUCE_NAMESPACE
  59127. DocumentWindow::DocumentWindow (const String& title,
  59128. const Colour& backgroundColour,
  59129. const int requiredButtons_,
  59130. const bool addToDesktop_)
  59131. : ResizableWindow (title, backgroundColour, addToDesktop_),
  59132. titleBarHeight (26),
  59133. menuBarHeight (24),
  59134. requiredButtons (requiredButtons_),
  59135. #if JUCE_MAC
  59136. positionTitleBarButtonsOnLeft (true),
  59137. #else
  59138. positionTitleBarButtonsOnLeft (false),
  59139. #endif
  59140. drawTitleTextCentred (true),
  59141. titleBarIcon (0),
  59142. menuBar (0),
  59143. menuBarModel (0)
  59144. {
  59145. zeromem (titleBarButtons, sizeof (titleBarButtons));
  59146. setResizeLimits (128, 128, 32768, 32768);
  59147. lookAndFeelChanged();
  59148. }
  59149. DocumentWindow::~DocumentWindow()
  59150. {
  59151. for (int i = 0; i < 3; ++i)
  59152. delete titleBarButtons[i];
  59153. delete titleBarIcon;
  59154. delete menuBar;
  59155. }
  59156. void DocumentWindow::repaintTitleBar()
  59157. {
  59158. const Rectangle titleBarArea (getTitleBarArea());
  59159. repaint (titleBarArea.getX(), titleBarArea.getY(),
  59160. titleBarArea.getWidth(), titleBarArea.getHeight());
  59161. }
  59162. void DocumentWindow::setName (const String& newName)
  59163. {
  59164. if (newName != getName())
  59165. {
  59166. Component::setName (newName);
  59167. repaintTitleBar();
  59168. }
  59169. }
  59170. void DocumentWindow::setIcon (const Image* imageToUse)
  59171. {
  59172. deleteAndZero (titleBarIcon);
  59173. if (imageToUse != 0)
  59174. titleBarIcon = imageToUse->createCopy();
  59175. repaintTitleBar();
  59176. }
  59177. void DocumentWindow::setTitleBarHeight (const int newHeight)
  59178. {
  59179. titleBarHeight = newHeight;
  59180. resized();
  59181. repaintTitleBar();
  59182. }
  59183. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  59184. const bool positionTitleBarButtonsOnLeft_)
  59185. {
  59186. requiredButtons = requiredButtons_;
  59187. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  59188. lookAndFeelChanged();
  59189. }
  59190. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  59191. {
  59192. drawTitleTextCentred = textShouldBeCentred;
  59193. repaintTitleBar();
  59194. }
  59195. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  59196. const int menuBarHeight_)
  59197. {
  59198. if (menuBarModel != menuBarModel_)
  59199. {
  59200. delete menuBar;
  59201. menuBar = 0;
  59202. menuBarModel = menuBarModel_;
  59203. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  59204. : getLookAndFeel().getDefaultMenuBarHeight();
  59205. if (menuBarModel != 0)
  59206. {
  59207. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59208. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  59209. menuBar->setEnabled (isActiveWindow());
  59210. }
  59211. resized();
  59212. }
  59213. }
  59214. void DocumentWindow::closeButtonPressed()
  59215. {
  59216. /* If you've got a close button, you have to override this method to get
  59217. rid of your window!
  59218. If the window is just a pop-up, you should override this method and make
  59219. it delete the window in whatever way is appropriate for your app. E.g. you
  59220. might just want to call "delete this".
  59221. If your app is centred around this window such that the whole app should quit when
  59222. the window is closed, then you will probably want to use this method as an opportunity
  59223. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  59224. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  59225. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  59226. or closing it via the taskbar icon on Windows).
  59227. */
  59228. jassertfalse
  59229. }
  59230. void DocumentWindow::minimiseButtonPressed()
  59231. {
  59232. setMinimised (true);
  59233. }
  59234. void DocumentWindow::maximiseButtonPressed()
  59235. {
  59236. setFullScreen (! isFullScreen());
  59237. }
  59238. void DocumentWindow::paint (Graphics& g)
  59239. {
  59240. ResizableWindow::paint (g);
  59241. if (resizableBorder == 0)
  59242. {
  59243. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  59244. const BorderSize border (getBorderThickness());
  59245. g.fillRect (0, 0, getWidth(), border.getTop());
  59246. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  59247. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  59248. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  59249. }
  59250. const Rectangle titleBarArea (getTitleBarArea());
  59251. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  59252. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  59253. int titleSpaceX1 = 6;
  59254. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  59255. for (int i = 0; i < 3; ++i)
  59256. {
  59257. if (titleBarButtons[i] != 0)
  59258. {
  59259. if (positionTitleBarButtonsOnLeft)
  59260. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  59261. else
  59262. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  59263. }
  59264. }
  59265. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  59266. titleBarArea.getWidth(),
  59267. titleBarArea.getHeight(),
  59268. titleSpaceX1,
  59269. jmax (1, titleSpaceX2 - titleSpaceX1),
  59270. titleBarIcon,
  59271. ! drawTitleTextCentred);
  59272. }
  59273. void DocumentWindow::resized()
  59274. {
  59275. ResizableWindow::resized();
  59276. if (titleBarButtons[1] != 0)
  59277. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  59278. const Rectangle titleBarArea (getTitleBarArea());
  59279. getLookAndFeel()
  59280. .positionDocumentWindowButtons (*this,
  59281. titleBarArea.getX(), titleBarArea.getY(),
  59282. titleBarArea.getWidth(), titleBarArea.getHeight(),
  59283. titleBarButtons[0],
  59284. titleBarButtons[1],
  59285. titleBarButtons[2],
  59286. positionTitleBarButtonsOnLeft);
  59287. if (menuBar != 0)
  59288. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  59289. titleBarArea.getWidth(), menuBarHeight);
  59290. }
  59291. const BorderSize DocumentWindow::getBorderThickness()
  59292. {
  59293. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  59294. ? 0 : (resizableBorder != 0 ? 4 : 1));
  59295. }
  59296. const BorderSize DocumentWindow::getContentComponentBorder()
  59297. {
  59298. BorderSize border (getBorderThickness());
  59299. border.setTop (border.getTop()
  59300. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  59301. + (menuBar != 0 ? menuBarHeight : 0));
  59302. return border;
  59303. }
  59304. int DocumentWindow::getTitleBarHeight() const
  59305. {
  59306. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  59307. }
  59308. const Rectangle DocumentWindow::getTitleBarArea()
  59309. {
  59310. const BorderSize border (getBorderThickness());
  59311. return Rectangle (border.getLeft(), border.getTop(),
  59312. getWidth() - border.getLeftAndRight(),
  59313. getTitleBarHeight());
  59314. }
  59315. Button* DocumentWindow::getCloseButton() const throw()
  59316. {
  59317. return titleBarButtons[2];
  59318. }
  59319. Button* DocumentWindow::getMinimiseButton() const throw()
  59320. {
  59321. return titleBarButtons[0];
  59322. }
  59323. Button* DocumentWindow::getMaximiseButton() const throw()
  59324. {
  59325. return titleBarButtons[1];
  59326. }
  59327. int DocumentWindow::getDesktopWindowStyleFlags() const
  59328. {
  59329. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  59330. if ((requiredButtons & minimiseButton) != 0)
  59331. flags |= ComponentPeer::windowHasMinimiseButton;
  59332. if ((requiredButtons & maximiseButton) != 0)
  59333. flags |= ComponentPeer::windowHasMaximiseButton;
  59334. if ((requiredButtons & closeButton) != 0)
  59335. flags |= ComponentPeer::windowHasCloseButton;
  59336. return flags;
  59337. }
  59338. void DocumentWindow::lookAndFeelChanged()
  59339. {
  59340. int i;
  59341. for (i = 0; i < 3; ++i)
  59342. deleteAndZero (titleBarButtons[i]);
  59343. if (! isUsingNativeTitleBar())
  59344. {
  59345. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  59346. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  59347. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  59348. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  59349. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  59350. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  59351. for (i = 0; i < 3; ++i)
  59352. {
  59353. if (titleBarButtons[i] != 0)
  59354. {
  59355. buttonListener.owner = this;
  59356. titleBarButtons[i]->addButtonListener (&buttonListener);
  59357. titleBarButtons[i]->setWantsKeyboardFocus (false);
  59358. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59359. Component::addAndMakeVisible (titleBarButtons[i]);
  59360. }
  59361. }
  59362. if (getCloseButton() != 0)
  59363. {
  59364. #if JUCE_MAC
  59365. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  59366. #else
  59367. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  59368. #endif
  59369. }
  59370. }
  59371. activeWindowStatusChanged();
  59372. ResizableWindow::lookAndFeelChanged();
  59373. }
  59374. void DocumentWindow::parentHierarchyChanged()
  59375. {
  59376. lookAndFeelChanged();
  59377. }
  59378. void DocumentWindow::activeWindowStatusChanged()
  59379. {
  59380. ResizableWindow::activeWindowStatusChanged();
  59381. for (int i = 0; i < 3; ++i)
  59382. if (titleBarButtons[i] != 0)
  59383. titleBarButtons[i]->setEnabled (isActiveWindow());
  59384. if (menuBar != 0)
  59385. menuBar->setEnabled (isActiveWindow());
  59386. }
  59387. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  59388. {
  59389. if (getTitleBarArea().contains (e.x, e.y)
  59390. && getMaximiseButton() != 0)
  59391. {
  59392. getMaximiseButton()->triggerClick();
  59393. }
  59394. }
  59395. void DocumentWindow::userTriedToCloseWindow()
  59396. {
  59397. closeButtonPressed();
  59398. }
  59399. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  59400. {
  59401. }
  59402. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  59403. {
  59404. if (button == owner->getMinimiseButton())
  59405. {
  59406. owner->minimiseButtonPressed();
  59407. }
  59408. else if (button == owner->getMaximiseButton())
  59409. {
  59410. owner->maximiseButtonPressed();
  59411. }
  59412. else if (button == owner->getCloseButton())
  59413. {
  59414. owner->closeButtonPressed();
  59415. }
  59416. }
  59417. END_JUCE_NAMESPACE
  59418. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  59419. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  59420. BEGIN_JUCE_NAMESPACE
  59421. ResizableWindow::ResizableWindow (const String& name,
  59422. const bool addToDesktop_)
  59423. : TopLevelWindow (name, addToDesktop_),
  59424. resizableCorner (0),
  59425. resizableBorder (0),
  59426. contentComponent (0),
  59427. resizeToFitContent (false),
  59428. fullscreen (false),
  59429. lastNonFullScreenPos (50, 50, 256, 256),
  59430. constrainer (0)
  59431. #ifdef JUCE_DEBUG
  59432. , hasBeenResized (false)
  59433. #endif
  59434. {
  59435. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59436. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  59437. if (addToDesktop_)
  59438. Component::addToDesktop (getDesktopWindowStyleFlags());
  59439. }
  59440. ResizableWindow::ResizableWindow (const String& name,
  59441. const Colour& backgroundColour_,
  59442. const bool addToDesktop_)
  59443. : TopLevelWindow (name, addToDesktop_),
  59444. resizableCorner (0),
  59445. resizableBorder (0),
  59446. contentComponent (0),
  59447. resizeToFitContent (false),
  59448. fullscreen (false),
  59449. lastNonFullScreenPos (50, 50, 256, 256),
  59450. constrainer (0)
  59451. #ifdef JUCE_DEBUG
  59452. , hasBeenResized (false)
  59453. #endif
  59454. {
  59455. setBackgroundColour (backgroundColour_);
  59456. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59457. if (addToDesktop_)
  59458. Component::addToDesktop (getDesktopWindowStyleFlags());
  59459. }
  59460. ResizableWindow::~ResizableWindow()
  59461. {
  59462. deleteAndZero (resizableCorner);
  59463. deleteAndZero (resizableBorder);
  59464. deleteAndZero (contentComponent);
  59465. // have you been adding your own components directly to this window..? tut tut tut.
  59466. // Read the instructions for using a ResizableWindow!
  59467. jassert (getNumChildComponents() == 0);
  59468. }
  59469. int ResizableWindow::getDesktopWindowStyleFlags() const
  59470. {
  59471. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  59472. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  59473. flags |= ComponentPeer::windowIsResizable;
  59474. return flags;
  59475. }
  59476. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  59477. const bool deleteOldOne,
  59478. const bool resizeToFit)
  59479. {
  59480. resizeToFitContent = resizeToFit;
  59481. if (contentComponent != newContentComponent)
  59482. {
  59483. if (deleteOldOne)
  59484. delete contentComponent;
  59485. else
  59486. removeChildComponent (contentComponent);
  59487. contentComponent = newContentComponent;
  59488. Component::addAndMakeVisible (contentComponent);
  59489. }
  59490. if (resizeToFit)
  59491. childBoundsChanged (contentComponent);
  59492. resized(); // must always be called to position the new content comp
  59493. }
  59494. void ResizableWindow::setContentComponentSize (int width, int height)
  59495. {
  59496. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  59497. const BorderSize border (getContentComponentBorder());
  59498. setSize (width + border.getLeftAndRight(),
  59499. height + border.getTopAndBottom());
  59500. }
  59501. const BorderSize ResizableWindow::getBorderThickness()
  59502. {
  59503. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  59504. }
  59505. const BorderSize ResizableWindow::getContentComponentBorder()
  59506. {
  59507. return getBorderThickness();
  59508. }
  59509. void ResizableWindow::moved()
  59510. {
  59511. updateLastPos();
  59512. }
  59513. void ResizableWindow::visibilityChanged()
  59514. {
  59515. TopLevelWindow::visibilityChanged();
  59516. updateLastPos();
  59517. }
  59518. void ResizableWindow::resized()
  59519. {
  59520. if (resizableBorder != 0)
  59521. {
  59522. resizableBorder->setVisible (! isFullScreen());
  59523. resizableBorder->setBorderThickness (getBorderThickness());
  59524. resizableBorder->setSize (getWidth(), getHeight());
  59525. resizableBorder->toBack();
  59526. }
  59527. if (resizableCorner != 0)
  59528. {
  59529. resizableCorner->setVisible (! isFullScreen());
  59530. const int resizerSize = 18;
  59531. resizableCorner->setBounds (getWidth() - resizerSize,
  59532. getHeight() - resizerSize,
  59533. resizerSize, resizerSize);
  59534. }
  59535. if (contentComponent != 0)
  59536. contentComponent->setBoundsInset (getContentComponentBorder());
  59537. updateLastPos();
  59538. #ifdef JUCE_DEBUG
  59539. hasBeenResized = true;
  59540. #endif
  59541. }
  59542. void ResizableWindow::childBoundsChanged (Component* child)
  59543. {
  59544. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  59545. {
  59546. // not going to look very good if this component has a zero size..
  59547. jassert (child->getWidth() > 0);
  59548. jassert (child->getHeight() > 0);
  59549. const BorderSize borders (getContentComponentBorder());
  59550. setSize (child->getWidth() + borders.getLeftAndRight(),
  59551. child->getHeight() + borders.getTopAndBottom());
  59552. }
  59553. }
  59554. void ResizableWindow::activeWindowStatusChanged()
  59555. {
  59556. const BorderSize borders (getContentComponentBorder());
  59557. repaint (0, 0, getWidth(), borders.getTop());
  59558. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  59559. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  59560. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  59561. }
  59562. void ResizableWindow::setResizable (const bool shouldBeResizable,
  59563. const bool useBottomRightCornerResizer)
  59564. {
  59565. if (shouldBeResizable)
  59566. {
  59567. if (useBottomRightCornerResizer)
  59568. {
  59569. deleteAndZero (resizableBorder);
  59570. if (resizableCorner == 0)
  59571. {
  59572. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  59573. resizableCorner->setAlwaysOnTop (true);
  59574. }
  59575. }
  59576. else
  59577. {
  59578. deleteAndZero (resizableCorner);
  59579. if (resizableBorder == 0)
  59580. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  59581. }
  59582. }
  59583. else
  59584. {
  59585. deleteAndZero (resizableCorner);
  59586. deleteAndZero (resizableBorder);
  59587. }
  59588. if (isUsingNativeTitleBar())
  59589. recreateDesktopWindow();
  59590. childBoundsChanged (contentComponent);
  59591. resized();
  59592. }
  59593. bool ResizableWindow::isResizable() const throw()
  59594. {
  59595. return resizableCorner != 0
  59596. || resizableBorder != 0;
  59597. }
  59598. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  59599. const int newMinimumHeight,
  59600. const int newMaximumWidth,
  59601. const int newMaximumHeight) throw()
  59602. {
  59603. // if you've set up a custom constrainer then these settings won't have any effect..
  59604. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  59605. if (constrainer == 0)
  59606. setConstrainer (&defaultConstrainer);
  59607. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  59608. newMaximumWidth, newMaximumHeight);
  59609. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  59610. }
  59611. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  59612. {
  59613. if (constrainer != newConstrainer)
  59614. {
  59615. constrainer = newConstrainer;
  59616. const bool useBottomRightCornerResizer = resizableCorner != 0;
  59617. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  59618. deleteAndZero (resizableCorner);
  59619. deleteAndZero (resizableBorder);
  59620. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59621. ComponentPeer* const peer = getPeer();
  59622. if (peer != 0)
  59623. peer->setConstrainer (newConstrainer);
  59624. }
  59625. }
  59626. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  59627. {
  59628. if (constrainer != 0)
  59629. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  59630. else
  59631. setBounds (x, y, w, h);
  59632. }
  59633. void ResizableWindow::paint (Graphics& g)
  59634. {
  59635. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  59636. getBorderThickness(), *this);
  59637. if (! isFullScreen())
  59638. {
  59639. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  59640. getBorderThickness(), *this);
  59641. }
  59642. #ifdef JUCE_DEBUG
  59643. /* If this fails, then you've probably written a subclass with a resized()
  59644. callback but forgotten to make it call its parent class's resized() method.
  59645. It's important when you override methods like resized(), moved(),
  59646. etc., that you make sure the base class methods also get called.
  59647. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  59648. because your content should all be inside the content component - and it's the
  59649. content component's resized() method that you should be using to do your
  59650. layout.
  59651. */
  59652. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  59653. #endif
  59654. }
  59655. void ResizableWindow::lookAndFeelChanged()
  59656. {
  59657. resized();
  59658. if (isOnDesktop())
  59659. {
  59660. Component::addToDesktop (getDesktopWindowStyleFlags());
  59661. ComponentPeer* const peer = getPeer();
  59662. if (peer != 0)
  59663. peer->setConstrainer (constrainer);
  59664. }
  59665. }
  59666. const Colour ResizableWindow::getBackgroundColour() const throw()
  59667. {
  59668. return findColour (backgroundColourId, false);
  59669. }
  59670. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  59671. {
  59672. Colour backgroundColour (newColour);
  59673. if (! Desktop::canUseSemiTransparentWindows())
  59674. backgroundColour = newColour.withAlpha (1.0f);
  59675. setColour (backgroundColourId, backgroundColour);
  59676. setOpaque (backgroundColour.isOpaque());
  59677. repaint();
  59678. }
  59679. bool ResizableWindow::isFullScreen() const
  59680. {
  59681. if (isOnDesktop())
  59682. {
  59683. ComponentPeer* const peer = getPeer();
  59684. return peer != 0 && peer->isFullScreen();
  59685. }
  59686. return fullscreen;
  59687. }
  59688. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  59689. {
  59690. if (shouldBeFullScreen != isFullScreen())
  59691. {
  59692. updateLastPos();
  59693. fullscreen = shouldBeFullScreen;
  59694. if (isOnDesktop())
  59695. {
  59696. ComponentPeer* const peer = getPeer();
  59697. if (peer != 0)
  59698. {
  59699. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  59700. const Rectangle lastPos (lastNonFullScreenPos);
  59701. peer->setFullScreen (shouldBeFullScreen);
  59702. if (! shouldBeFullScreen)
  59703. setBounds (lastPos);
  59704. }
  59705. else
  59706. {
  59707. jassertfalse
  59708. }
  59709. }
  59710. else
  59711. {
  59712. if (shouldBeFullScreen)
  59713. setBounds (0, 0, getParentWidth(), getParentHeight());
  59714. else
  59715. setBounds (lastNonFullScreenPos);
  59716. }
  59717. resized();
  59718. }
  59719. }
  59720. bool ResizableWindow::isMinimised() const
  59721. {
  59722. ComponentPeer* const peer = getPeer();
  59723. return (peer != 0) && peer->isMinimised();
  59724. }
  59725. void ResizableWindow::setMinimised (const bool shouldMinimise)
  59726. {
  59727. if (shouldMinimise != isMinimised())
  59728. {
  59729. ComponentPeer* const peer = getPeer();
  59730. if (peer != 0)
  59731. {
  59732. updateLastPos();
  59733. peer->setMinimised (shouldMinimise);
  59734. }
  59735. else
  59736. {
  59737. jassertfalse
  59738. }
  59739. }
  59740. }
  59741. void ResizableWindow::updateLastPos()
  59742. {
  59743. if (isShowing() && ! (isFullScreen() || isMinimised()))
  59744. {
  59745. lastNonFullScreenPos = getBounds();
  59746. }
  59747. }
  59748. void ResizableWindow::parentSizeChanged()
  59749. {
  59750. if (isFullScreen() && getParentComponent() != 0)
  59751. {
  59752. setBounds (0, 0, getParentWidth(), getParentHeight());
  59753. }
  59754. }
  59755. const String ResizableWindow::getWindowStateAsString()
  59756. {
  59757. updateLastPos();
  59758. String s;
  59759. if (isFullScreen())
  59760. s << "fs ";
  59761. s << lastNonFullScreenPos.getX() << T(' ')
  59762. << lastNonFullScreenPos.getY() << T(' ')
  59763. << lastNonFullScreenPos.getWidth() << T(' ')
  59764. << lastNonFullScreenPos.getHeight();
  59765. return s;
  59766. }
  59767. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  59768. {
  59769. StringArray tokens;
  59770. tokens.addTokens (s, false);
  59771. tokens.removeEmptyStrings();
  59772. tokens.trim();
  59773. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  59774. const int n = fs ? 1 : 0;
  59775. if (tokens.size() != 4 + n)
  59776. return false;
  59777. Rectangle r (tokens[n].getIntValue(),
  59778. tokens[n + 1].getIntValue(),
  59779. tokens[n + 2].getIntValue(),
  59780. tokens[n + 3].getIntValue());
  59781. if (r.isEmpty())
  59782. return false;
  59783. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  59784. if (! screen.contains (r))
  59785. {
  59786. r.setSize (jmin (r.getWidth(), screen.getWidth()),
  59787. jmin (r.getHeight(), screen.getHeight()));
  59788. r.setPosition (jlimit (screen.getX(), screen.getRight() - r.getWidth(), r.getX()),
  59789. jlimit (screen.getY(), screen.getBottom() - r.getHeight(), r.getY()));
  59790. }
  59791. lastNonFullScreenPos = r;
  59792. if (isOnDesktop())
  59793. {
  59794. ComponentPeer* const peer = getPeer();
  59795. if (peer != 0)
  59796. peer->setNonFullScreenBounds (r);
  59797. }
  59798. setFullScreen (fs);
  59799. if (! fs)
  59800. setBoundsConstrained (r.getX(),
  59801. r.getY(),
  59802. r.getWidth(),
  59803. r.getHeight());
  59804. return true;
  59805. }
  59806. void ResizableWindow::mouseDown (const MouseEvent&)
  59807. {
  59808. if (! isFullScreen())
  59809. dragger.startDraggingComponent (this, constrainer);
  59810. }
  59811. void ResizableWindow::mouseDrag (const MouseEvent& e)
  59812. {
  59813. if (! isFullScreen())
  59814. dragger.dragComponent (this, e);
  59815. }
  59816. #ifdef JUCE_DEBUG
  59817. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  59818. {
  59819. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59820. manages its child components automatically, and if you add your own it'll cause
  59821. trouble. Instead, use setContentComponent() to give it a component which
  59822. will be automatically resized and kept in the right place - then you can add
  59823. subcomponents to the content comp. See the notes for the ResizableWindow class
  59824. for more info.
  59825. If you really know what you're doing and want to avoid this assertion, just call
  59826. Component::addChildComponent directly.
  59827. */
  59828. jassertfalse
  59829. Component::addChildComponent (child, zOrder);
  59830. }
  59831. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  59832. {
  59833. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59834. manages its child components automatically, and if you add your own it'll cause
  59835. trouble. Instead, use setContentComponent() to give it a component which
  59836. will be automatically resized and kept in the right place - then you can add
  59837. subcomponents to the content comp. See the notes for the ResizableWindow class
  59838. for more info.
  59839. If you really know what you're doing and want to avoid this assertion, just call
  59840. Component::addAndMakeVisible directly.
  59841. */
  59842. jassertfalse
  59843. Component::addAndMakeVisible (child, zOrder);
  59844. }
  59845. #endif
  59846. END_JUCE_NAMESPACE
  59847. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  59848. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  59849. BEGIN_JUCE_NAMESPACE
  59850. SplashScreen::SplashScreen()
  59851. : backgroundImage (0),
  59852. isImageInCache (false)
  59853. {
  59854. setOpaque (true);
  59855. }
  59856. SplashScreen::~SplashScreen()
  59857. {
  59858. if (isImageInCache)
  59859. ImageCache::release (backgroundImage);
  59860. else
  59861. delete backgroundImage;
  59862. }
  59863. void SplashScreen::show (const String& title,
  59864. Image* const backgroundImage_,
  59865. const int minimumTimeToDisplayFor,
  59866. const bool useDropShadow,
  59867. const bool removeOnMouseClick)
  59868. {
  59869. backgroundImage = backgroundImage_;
  59870. jassert (backgroundImage_ != 0);
  59871. if (backgroundImage_ != 0)
  59872. {
  59873. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  59874. setOpaque (! backgroundImage_->hasAlphaChannel());
  59875. show (title,
  59876. backgroundImage_->getWidth(),
  59877. backgroundImage_->getHeight(),
  59878. minimumTimeToDisplayFor,
  59879. useDropShadow,
  59880. removeOnMouseClick);
  59881. }
  59882. }
  59883. void SplashScreen::show (const String& title,
  59884. const int width,
  59885. const int height,
  59886. const int minimumTimeToDisplayFor,
  59887. const bool useDropShadow,
  59888. const bool removeOnMouseClick)
  59889. {
  59890. setName (title);
  59891. setAlwaysOnTop (true);
  59892. setVisible (true);
  59893. centreWithSize (width, height);
  59894. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  59895. toFront (false);
  59896. MessageManager::getInstance()->runDispatchLoopUntil (300);
  59897. repaint();
  59898. originalClickCounter = removeOnMouseClick
  59899. ? Desktop::getMouseButtonClickCounter()
  59900. : INT_MAX;
  59901. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  59902. startTimer (50);
  59903. }
  59904. void SplashScreen::paint (Graphics& g)
  59905. {
  59906. if (backgroundImage != 0)
  59907. {
  59908. g.setOpacity (1.0f);
  59909. g.drawImage (backgroundImage,
  59910. 0, 0, getWidth(), getHeight(),
  59911. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  59912. }
  59913. }
  59914. void SplashScreen::timerCallback()
  59915. {
  59916. if (Time::getCurrentTime() > earliestTimeToDelete
  59917. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  59918. {
  59919. delete this;
  59920. }
  59921. }
  59922. END_JUCE_NAMESPACE
  59923. /********* End of inlined file: juce_SplashScreen.cpp *********/
  59924. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59925. BEGIN_JUCE_NAMESPACE
  59926. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  59927. const bool hasProgressBar,
  59928. const bool hasCancelButton,
  59929. const int timeOutMsWhenCancelling_,
  59930. const String& cancelButtonText)
  59931. : Thread ("Juce Progress Window"),
  59932. progress (0.0),
  59933. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  59934. {
  59935. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  59936. .createAlertWindow (title, String::empty, cancelButtonText,
  59937. String::empty, String::empty,
  59938. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  59939. if (hasProgressBar)
  59940. alertWindow->addProgressBarComponent (progress);
  59941. }
  59942. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  59943. {
  59944. stopThread (timeOutMsWhenCancelling);
  59945. delete alertWindow;
  59946. }
  59947. bool ThreadWithProgressWindow::runThread (const int priority)
  59948. {
  59949. startThread (priority);
  59950. startTimer (100);
  59951. {
  59952. const ScopedLock sl (messageLock);
  59953. alertWindow->setMessage (message);
  59954. }
  59955. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  59956. stopThread (timeOutMsWhenCancelling);
  59957. alertWindow->setVisible (false);
  59958. return finishedNaturally;
  59959. }
  59960. void ThreadWithProgressWindow::setProgress (const double newProgress)
  59961. {
  59962. progress = newProgress;
  59963. }
  59964. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  59965. {
  59966. const ScopedLock sl (messageLock);
  59967. message = newStatusMessage;
  59968. }
  59969. void ThreadWithProgressWindow::timerCallback()
  59970. {
  59971. if (! isThreadRunning())
  59972. {
  59973. // thread has finished normally..
  59974. alertWindow->exitModalState (1);
  59975. alertWindow->setVisible (false);
  59976. }
  59977. else
  59978. {
  59979. const ScopedLock sl (messageLock);
  59980. alertWindow->setMessage (message);
  59981. }
  59982. }
  59983. END_JUCE_NAMESPACE
  59984. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59985. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  59986. BEGIN_JUCE_NAMESPACE
  59987. TooltipWindow::TooltipWindow (Component* const parentComponent,
  59988. const int millisecondsBeforeTipAppears_)
  59989. : Component ("tooltip"),
  59990. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  59991. mouseX (0),
  59992. mouseY (0),
  59993. lastHideTime (0),
  59994. lastComponentUnderMouse (0),
  59995. changedCompsSinceShown (true)
  59996. {
  59997. startTimer (123);
  59998. setAlwaysOnTop (true);
  59999. setOpaque (true);
  60000. if (parentComponent != 0)
  60001. parentComponent->addChildComponent (this);
  60002. }
  60003. TooltipWindow::~TooltipWindow()
  60004. {
  60005. hide();
  60006. }
  60007. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  60008. {
  60009. millisecondsBeforeTipAppears = newTimeMs;
  60010. }
  60011. void TooltipWindow::paint (Graphics& g)
  60012. {
  60013. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  60014. }
  60015. void TooltipWindow::mouseEnter (const MouseEvent&)
  60016. {
  60017. hide();
  60018. }
  60019. void TooltipWindow::showFor (Component* const c, const String& tip)
  60020. {
  60021. jassert (tip.isNotEmpty());
  60022. tipShowing = tip;
  60023. int mx, my;
  60024. Desktop::getMousePosition (mx, my);
  60025. if (getParentComponent() != 0)
  60026. getParentComponent()->globalPositionToRelative (mx, my);
  60027. int x, y, w, h;
  60028. getLookAndFeel().getTooltipSize (tip, w, h);
  60029. if (mx > getParentWidth() / 2)
  60030. x = mx - (w + 12);
  60031. else
  60032. x = mx + 24;
  60033. if (my > getParentHeight() / 2)
  60034. y = my - (h + 6);
  60035. else
  60036. y = my + 6;
  60037. setBounds (x, y, w, h);
  60038. setVisible (true);
  60039. if (getParentComponent() == 0)
  60040. {
  60041. addToDesktop (ComponentPeer::windowHasDropShadow
  60042. | ComponentPeer::windowIsTemporary
  60043. | ComponentPeer::windowIgnoresKeyPresses);
  60044. }
  60045. toFront (false);
  60046. }
  60047. const String TooltipWindow::getTipFor (Component* const c)
  60048. {
  60049. if (c->isValidComponent()
  60050. && Process::isForegroundProcess()
  60051. && ! Component::isMouseButtonDownAnywhere())
  60052. {
  60053. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  60054. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  60055. return ttc->getTooltip();
  60056. }
  60057. return String::empty;
  60058. }
  60059. void TooltipWindow::hide()
  60060. {
  60061. tipShowing = String::empty;
  60062. removeFromDesktop();
  60063. setVisible (false);
  60064. }
  60065. void TooltipWindow::timerCallback()
  60066. {
  60067. const unsigned int now = Time::getApproximateMillisecondCounter();
  60068. Component* const newComp = Component::getComponentUnderMouse();
  60069. const String newTip (getTipFor (newComp));
  60070. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  60071. lastComponentUnderMouse = newComp;
  60072. lastTipUnderMouse = newTip;
  60073. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  60074. const bool mouseWasClicked = clickCount > mouseClicks;
  60075. mouseClicks = clickCount;
  60076. int mx, my;
  60077. Desktop::getMousePosition (mx, my);
  60078. const bool mouseMovedQuickly = (abs (mx - mouseX) + abs (my - mouseY) > 12);
  60079. mouseX = mx;
  60080. mouseY = my;
  60081. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  60082. lastCompChangeTime = now;
  60083. if (isVisible() || now < lastHideTime + 500)
  60084. {
  60085. // if a tip is currently visible (or has just disappeared), update to a new one
  60086. // immediately if needed..
  60087. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  60088. {
  60089. if (isVisible())
  60090. {
  60091. lastHideTime = now;
  60092. hide();
  60093. }
  60094. }
  60095. else if (tipChanged)
  60096. {
  60097. showFor (newComp, newTip);
  60098. }
  60099. }
  60100. else
  60101. {
  60102. // if there isn't currently a tip, but one is needed, only let it
  60103. // appear after a timeout..
  60104. if (newTip.isNotEmpty()
  60105. && newTip != tipShowing
  60106. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  60107. {
  60108. showFor (newComp, newTip);
  60109. }
  60110. }
  60111. }
  60112. END_JUCE_NAMESPACE
  60113. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  60114. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  60115. BEGIN_JUCE_NAMESPACE
  60116. /** Keeps track of the active top level window.
  60117. */
  60118. class TopLevelWindowManager : public Timer,
  60119. public DeletedAtShutdown
  60120. {
  60121. public:
  60122. TopLevelWindowManager()
  60123. : windows (8),
  60124. currentActive (0)
  60125. {
  60126. }
  60127. ~TopLevelWindowManager()
  60128. {
  60129. clearSingletonInstance();
  60130. }
  60131. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  60132. void timerCallback()
  60133. {
  60134. startTimer (jmin (1731, getTimerInterval() * 2));
  60135. TopLevelWindow* active = 0;
  60136. if (Process::isForegroundProcess())
  60137. {
  60138. active = currentActive;
  60139. Component* const c = Component::getCurrentlyFocusedComponent();
  60140. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  60141. if (tlw == 0 && c != 0)
  60142. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  60143. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  60144. if (tlw != 0)
  60145. active = tlw;
  60146. }
  60147. if (active != currentActive)
  60148. {
  60149. currentActive = active;
  60150. for (int i = windows.size(); --i >= 0;)
  60151. {
  60152. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  60153. tlw->setWindowActive (isWindowActive (tlw));
  60154. i = jmin (i, windows.size() - 1);
  60155. }
  60156. Desktop::getInstance().triggerFocusCallback();
  60157. }
  60158. }
  60159. bool addWindow (TopLevelWindow* const w) throw()
  60160. {
  60161. windows.add (w);
  60162. startTimer (10);
  60163. return isWindowActive (w);
  60164. }
  60165. void removeWindow (TopLevelWindow* const w) throw()
  60166. {
  60167. startTimer (10);
  60168. if (currentActive == w)
  60169. currentActive = 0;
  60170. windows.removeValue (w);
  60171. if (windows.size() == 0)
  60172. deleteInstance();
  60173. }
  60174. VoidArray windows;
  60175. private:
  60176. TopLevelWindow* currentActive;
  60177. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  60178. {
  60179. return (tlw == currentActive
  60180. || tlw->isParentOf (currentActive)
  60181. || tlw->hasKeyboardFocus (true))
  60182. && tlw->isShowing();
  60183. }
  60184. TopLevelWindowManager (const TopLevelWindowManager&);
  60185. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  60186. };
  60187. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  60188. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  60189. {
  60190. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  60191. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  60192. }
  60193. TopLevelWindow::TopLevelWindow (const String& name,
  60194. const bool addToDesktop_)
  60195. : Component (name),
  60196. useDropShadow (true),
  60197. useNativeTitleBar (false),
  60198. windowIsActive_ (false),
  60199. shadower (0)
  60200. {
  60201. setOpaque (true);
  60202. if (addToDesktop_)
  60203. Component::addToDesktop (getDesktopWindowStyleFlags());
  60204. else
  60205. setDropShadowEnabled (true);
  60206. setWantsKeyboardFocus (true);
  60207. setBroughtToFrontOnMouseClick (true);
  60208. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  60209. }
  60210. TopLevelWindow::~TopLevelWindow()
  60211. {
  60212. deleteAndZero (shadower);
  60213. TopLevelWindowManager::getInstance()->removeWindow (this);
  60214. }
  60215. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  60216. {
  60217. if (hasKeyboardFocus (true))
  60218. TopLevelWindowManager::getInstance()->timerCallback();
  60219. else
  60220. TopLevelWindowManager::getInstance()->startTimer (10);
  60221. }
  60222. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  60223. {
  60224. if (windowIsActive_ != isNowActive)
  60225. {
  60226. windowIsActive_ = isNowActive;
  60227. activeWindowStatusChanged();
  60228. }
  60229. }
  60230. void TopLevelWindow::activeWindowStatusChanged()
  60231. {
  60232. }
  60233. void TopLevelWindow::parentHierarchyChanged()
  60234. {
  60235. setDropShadowEnabled (useDropShadow);
  60236. }
  60237. void TopLevelWindow::visibilityChanged()
  60238. {
  60239. if (isShowing())
  60240. toFront (true);
  60241. }
  60242. int TopLevelWindow::getDesktopWindowStyleFlags() const
  60243. {
  60244. int flags = ComponentPeer::windowAppearsOnTaskbar;
  60245. if (useDropShadow)
  60246. flags |= ComponentPeer::windowHasDropShadow;
  60247. if (useNativeTitleBar)
  60248. flags |= ComponentPeer::windowHasTitleBar;
  60249. return flags;
  60250. }
  60251. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  60252. {
  60253. useDropShadow = useShadow;
  60254. if (isOnDesktop())
  60255. {
  60256. deleteAndZero (shadower);
  60257. Component::addToDesktop (getDesktopWindowStyleFlags());
  60258. }
  60259. else
  60260. {
  60261. if (useShadow && isOpaque())
  60262. {
  60263. if (shadower == 0)
  60264. {
  60265. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  60266. if (shadower != 0)
  60267. shadower->setOwner (this);
  60268. }
  60269. }
  60270. else
  60271. {
  60272. deleteAndZero (shadower);
  60273. }
  60274. }
  60275. }
  60276. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  60277. {
  60278. if (useNativeTitleBar != useNativeTitleBar_)
  60279. {
  60280. useNativeTitleBar = useNativeTitleBar_;
  60281. recreateDesktopWindow();
  60282. sendLookAndFeelChange();
  60283. }
  60284. }
  60285. void TopLevelWindow::recreateDesktopWindow()
  60286. {
  60287. if (isOnDesktop())
  60288. {
  60289. Component::addToDesktop (getDesktopWindowStyleFlags());
  60290. toFront (true);
  60291. }
  60292. }
  60293. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  60294. {
  60295. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  60296. because this class needs to make sure its layout corresponds with settings like whether
  60297. it's got a native title bar or not.
  60298. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  60299. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  60300. method, then add or remove whatever flags are necessary from this value before returning it.
  60301. */
  60302. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  60303. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  60304. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  60305. if (windowStyleFlags != getDesktopWindowStyleFlags())
  60306. sendLookAndFeelChange();
  60307. }
  60308. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  60309. {
  60310. if (c == 0)
  60311. c = TopLevelWindow::getActiveTopLevelWindow();
  60312. if (c == 0)
  60313. {
  60314. centreWithSize (width, height);
  60315. }
  60316. else
  60317. {
  60318. int x = (c->getWidth() - width) / 2;
  60319. int y = (c->getHeight() - height) / 2;
  60320. c->relativePositionToGlobal (x, y);
  60321. Rectangle parentArea (c->getParentMonitorArea());
  60322. if (getParentComponent() != 0)
  60323. {
  60324. getParentComponent()->globalPositionToRelative (x, y);
  60325. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  60326. }
  60327. parentArea.reduce (12, 12);
  60328. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  60329. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  60330. width, height);
  60331. }
  60332. }
  60333. int TopLevelWindow::getNumTopLevelWindows() throw()
  60334. {
  60335. return TopLevelWindowManager::getInstance()->windows.size();
  60336. }
  60337. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  60338. {
  60339. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  60340. }
  60341. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  60342. {
  60343. TopLevelWindow* best = 0;
  60344. int bestNumTWLParents = -1;
  60345. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  60346. {
  60347. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  60348. if (tlw->isActiveWindow())
  60349. {
  60350. int numTWLParents = 0;
  60351. const Component* c = tlw->getParentComponent();
  60352. while (c != 0)
  60353. {
  60354. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  60355. ++numTWLParents;
  60356. c = c->getParentComponent();
  60357. }
  60358. if (bestNumTWLParents < numTWLParents)
  60359. {
  60360. best = tlw;
  60361. bestNumTWLParents = numTWLParents;
  60362. }
  60363. }
  60364. }
  60365. return best;
  60366. }
  60367. END_JUCE_NAMESPACE
  60368. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  60369. /********* Start of inlined file: juce_Brush.cpp *********/
  60370. BEGIN_JUCE_NAMESPACE
  60371. Brush::Brush() throw()
  60372. {
  60373. }
  60374. Brush::~Brush() throw()
  60375. {
  60376. }
  60377. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  60378. int x, float y1, float y2) throw()
  60379. {
  60380. Path p;
  60381. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  60382. paintPath (context, p, AffineTransform::identity);
  60383. }
  60384. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60385. int y, float x1, float x2) throw()
  60386. {
  60387. Path p;
  60388. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  60389. paintPath (context, p, AffineTransform::identity);
  60390. }
  60391. void Brush::paintLine (LowLevelGraphicsContext& context,
  60392. float x1, float y1, float x2, float y2) throw()
  60393. {
  60394. Path p;
  60395. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  60396. paintPath (context, p, AffineTransform::identity);
  60397. }
  60398. END_JUCE_NAMESPACE
  60399. /********* End of inlined file: juce_Brush.cpp *********/
  60400. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  60401. BEGIN_JUCE_NAMESPACE
  60402. GradientBrush::GradientBrush (const Colour& colour1,
  60403. const float x1,
  60404. const float y1,
  60405. const Colour& colour2,
  60406. const float x2,
  60407. const float y2,
  60408. const bool isRadial) throw()
  60409. : gradient (colour1, x1, y1,
  60410. colour2, x2, y2,
  60411. isRadial)
  60412. {
  60413. }
  60414. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  60415. : gradient (gradient_)
  60416. {
  60417. }
  60418. GradientBrush::~GradientBrush() throw()
  60419. {
  60420. }
  60421. Brush* GradientBrush::createCopy() const throw()
  60422. {
  60423. return new GradientBrush (gradient);
  60424. }
  60425. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  60426. {
  60427. gradient.transform = gradient.transform.followedBy (transform);
  60428. }
  60429. void GradientBrush::multiplyOpacity (const float multiple) throw()
  60430. {
  60431. gradient.multiplyOpacity (multiple);
  60432. }
  60433. bool GradientBrush::isInvisible() const throw()
  60434. {
  60435. return gradient.isInvisible();
  60436. }
  60437. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  60438. const Path& path, const AffineTransform& transform) throw()
  60439. {
  60440. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  60441. }
  60442. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  60443. int x, int y, int w, int h) throw()
  60444. {
  60445. context.fillRectWithGradient (x, y, w, h, gradient);
  60446. }
  60447. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60448. const Image& alphaChannelImage, int imageX, int imageY,
  60449. int x, int y, int w, int h) throw()
  60450. {
  60451. context.saveState();
  60452. if (context.reduceClipRegion (x, y, w, h))
  60453. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  60454. context.restoreState();
  60455. }
  60456. END_JUCE_NAMESPACE
  60457. /********* End of inlined file: juce_GradientBrush.cpp *********/
  60458. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  60459. BEGIN_JUCE_NAMESPACE
  60460. ImageBrush::ImageBrush (Image* const image_,
  60461. const int anchorX_,
  60462. const int anchorY_,
  60463. const float opacity_) throw()
  60464. : image (image_),
  60465. anchorX (anchorX_),
  60466. anchorY (anchorY_),
  60467. opacity (opacity_)
  60468. {
  60469. jassert (image != 0); // not much point creating a brush without an image, is there?
  60470. if (image != 0)
  60471. {
  60472. if (image->getWidth() == 0 || image->getHeight() == 0)
  60473. {
  60474. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  60475. image = 0;
  60476. }
  60477. }
  60478. }
  60479. ImageBrush::~ImageBrush() throw()
  60480. {
  60481. }
  60482. Brush* ImageBrush::createCopy() const throw()
  60483. {
  60484. return new ImageBrush (image, anchorX, anchorY, opacity);
  60485. }
  60486. void ImageBrush::multiplyOpacity (const float multiple) throw()
  60487. {
  60488. opacity *= multiple;
  60489. }
  60490. bool ImageBrush::isInvisible() const throw()
  60491. {
  60492. return opacity == 0.0f;
  60493. }
  60494. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60495. {
  60496. //xxx should probably be smarter and warp the image
  60497. }
  60498. void ImageBrush::getStartXY (int& x, int& y) const throw()
  60499. {
  60500. x -= anchorX;
  60501. y -= anchorY;
  60502. const int iw = image->getWidth();
  60503. const int ih = image->getHeight();
  60504. if (x < 0)
  60505. x = ((x / iw) - 1) * iw;
  60506. else
  60507. x = (x / iw) * iw;
  60508. if (y < 0)
  60509. y = ((y / ih) - 1) * ih;
  60510. else
  60511. y = (y / ih) * ih;
  60512. x += anchorX;
  60513. y += anchorY;
  60514. }
  60515. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  60516. int x, int y, int w, int h) throw()
  60517. {
  60518. context.saveState();
  60519. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60520. {
  60521. const int right = x + w;
  60522. const int bottom = y + h;
  60523. const int iw = image->getWidth();
  60524. const int ih = image->getHeight();
  60525. int startX = x;
  60526. getStartXY (startX, y);
  60527. while (y < bottom)
  60528. {
  60529. x = startX;
  60530. while (x < right)
  60531. {
  60532. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  60533. x += iw;
  60534. }
  60535. y += ih;
  60536. }
  60537. }
  60538. context.restoreState();
  60539. }
  60540. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  60541. const Path& path, const AffineTransform& transform) throw()
  60542. {
  60543. if (image != 0)
  60544. {
  60545. Rectangle clip (context.getClipBounds());
  60546. {
  60547. float x, y, w, h;
  60548. path.getBoundsTransformed (transform, x, y, w, h);
  60549. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  60550. (int) floorf (y),
  60551. 2 + (int) floorf (w),
  60552. 2 + (int) floorf (h)));
  60553. }
  60554. int x = clip.getX();
  60555. int y = clip.getY();
  60556. const int right = clip.getRight();
  60557. const int bottom = clip.getBottom();
  60558. const int iw = image->getWidth();
  60559. const int ih = image->getHeight();
  60560. int startX = x;
  60561. getStartXY (startX, y);
  60562. while (y < bottom)
  60563. {
  60564. x = startX;
  60565. while (x < right)
  60566. {
  60567. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  60568. x += iw;
  60569. }
  60570. y += ih;
  60571. }
  60572. }
  60573. }
  60574. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60575. const Image& alphaChannelImage, int imageX, int imageY,
  60576. int x, int y, int w, int h) throw()
  60577. {
  60578. context.saveState();
  60579. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60580. {
  60581. const Rectangle clip (context.getClipBounds());
  60582. x = clip.getX();
  60583. y = clip.getY();
  60584. const int right = clip.getRight();
  60585. const int bottom = clip.getBottom();
  60586. const int iw = image->getWidth();
  60587. const int ih = image->getHeight();
  60588. int startX = x;
  60589. getStartXY (startX, y);
  60590. while (y < bottom)
  60591. {
  60592. x = startX;
  60593. while (x < right)
  60594. {
  60595. context.fillAlphaChannelWithImage (alphaChannelImage,
  60596. imageX, imageY, *image,
  60597. x, y, opacity);
  60598. x += iw;
  60599. }
  60600. y += ih;
  60601. }
  60602. }
  60603. context.restoreState();
  60604. }
  60605. END_JUCE_NAMESPACE
  60606. /********* End of inlined file: juce_ImageBrush.cpp *********/
  60607. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  60608. BEGIN_JUCE_NAMESPACE
  60609. SolidColourBrush::SolidColourBrush() throw()
  60610. : colour (0xff000000)
  60611. {
  60612. }
  60613. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  60614. : colour (colour_)
  60615. {
  60616. }
  60617. SolidColourBrush::~SolidColourBrush() throw()
  60618. {
  60619. }
  60620. Brush* SolidColourBrush::createCopy() const throw()
  60621. {
  60622. return new SolidColourBrush (colour);
  60623. }
  60624. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60625. {
  60626. }
  60627. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  60628. {
  60629. colour = colour.withMultipliedAlpha (multiple);
  60630. }
  60631. bool SolidColourBrush::isInvisible() const throw()
  60632. {
  60633. return colour.isTransparent();
  60634. }
  60635. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  60636. const Path& path, const AffineTransform& transform) throw()
  60637. {
  60638. if (! colour.isTransparent())
  60639. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  60640. }
  60641. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  60642. int x, int y, int w, int h) throw()
  60643. {
  60644. if (! colour.isTransparent())
  60645. context.fillRectWithColour (x, y, w, h, colour, false);
  60646. }
  60647. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60648. const Image& alphaChannelImage, int imageX, int imageY,
  60649. int x, int y, int w, int h) throw()
  60650. {
  60651. if (! colour.isTransparent())
  60652. {
  60653. context.saveState();
  60654. if (context.reduceClipRegion (x, y, w, h))
  60655. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  60656. context.restoreState();
  60657. }
  60658. }
  60659. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  60660. int x, float y1, float y2) throw()
  60661. {
  60662. context.drawVerticalLine (x, y1, y2, colour);
  60663. }
  60664. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60665. int y, float x1, float x2) throw()
  60666. {
  60667. context.drawHorizontalLine (y, x1, x2, colour);
  60668. }
  60669. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  60670. float x1, float y1, float x2, float y2) throw()
  60671. {
  60672. context.drawLine (x1, y1, x2, y2, colour);
  60673. }
  60674. END_JUCE_NAMESPACE
  60675. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  60676. /********* Start of inlined file: juce_Colour.cpp *********/
  60677. BEGIN_JUCE_NAMESPACE
  60678. static forcedinline uint8 floatAlphaToInt (const float alpha)
  60679. {
  60680. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  60681. }
  60682. static const float oneOver255 = 1.0f / 255.0f;
  60683. Colour::Colour() throw()
  60684. : argb (0)
  60685. {
  60686. }
  60687. Colour::Colour (const Colour& other) throw()
  60688. : argb (other.argb)
  60689. {
  60690. }
  60691. const Colour& Colour::operator= (const Colour& other) throw()
  60692. {
  60693. argb = other.argb;
  60694. return *this;
  60695. }
  60696. bool Colour::operator== (const Colour& other) const throw()
  60697. {
  60698. return argb.getARGB() == other.argb.getARGB();
  60699. }
  60700. bool Colour::operator!= (const Colour& other) const throw()
  60701. {
  60702. return argb.getARGB() != other.argb.getARGB();
  60703. }
  60704. Colour::Colour (const uint32 argb_) throw()
  60705. : argb (argb_)
  60706. {
  60707. }
  60708. Colour::Colour (const uint8 red,
  60709. const uint8 green,
  60710. const uint8 blue) throw()
  60711. {
  60712. argb.setARGB (0xff, red, green, blue);
  60713. }
  60714. const Colour Colour::fromRGB (const uint8 red,
  60715. const uint8 green,
  60716. const uint8 blue) throw()
  60717. {
  60718. return Colour (red, green, blue);
  60719. }
  60720. Colour::Colour (const uint8 red,
  60721. const uint8 green,
  60722. const uint8 blue,
  60723. const uint8 alpha) throw()
  60724. {
  60725. argb.setARGB (alpha, red, green, blue);
  60726. }
  60727. const Colour Colour::fromRGBA (const uint8 red,
  60728. const uint8 green,
  60729. const uint8 blue,
  60730. const uint8 alpha) throw()
  60731. {
  60732. return Colour (red, green, blue, alpha);
  60733. }
  60734. Colour::Colour (const uint8 red,
  60735. const uint8 green,
  60736. const uint8 blue,
  60737. const float alpha) throw()
  60738. {
  60739. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  60740. }
  60741. const Colour Colour::fromRGBAFloat (const uint8 red,
  60742. const uint8 green,
  60743. const uint8 blue,
  60744. const float alpha) throw()
  60745. {
  60746. return Colour (red, green, blue, alpha);
  60747. }
  60748. static void convertHSBtoRGB (float h, float s, float v,
  60749. uint8& r, uint8& g, uint8& b) throw()
  60750. {
  60751. v = jlimit (0.0f, 1.0f, v);
  60752. v *= 255.0f;
  60753. const uint8 intV = (uint8) roundFloatToInt (v);
  60754. if (s <= 0)
  60755. {
  60756. r = intV;
  60757. g = intV;
  60758. b = intV;
  60759. }
  60760. else
  60761. {
  60762. s = jmin (1.0f, s);
  60763. h = jlimit (0.0f, 1.0f, h);
  60764. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  60765. const float f = h - floorf (h);
  60766. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  60767. const float y = v * (1.0f - s * f);
  60768. const float z = v * (1.0f - (s * (1.0f - f)));
  60769. if (h < 1.0f)
  60770. {
  60771. r = intV;
  60772. g = (uint8) roundFloatToInt (z);
  60773. b = x;
  60774. }
  60775. else if (h < 2.0f)
  60776. {
  60777. r = (uint8) roundFloatToInt (y);
  60778. g = intV;
  60779. b = x;
  60780. }
  60781. else if (h < 3.0f)
  60782. {
  60783. r = x;
  60784. g = intV;
  60785. b = (uint8) roundFloatToInt (z);
  60786. }
  60787. else if (h < 4.0f)
  60788. {
  60789. r = x;
  60790. g = (uint8) roundFloatToInt (y);
  60791. b = intV;
  60792. }
  60793. else if (h < 5.0f)
  60794. {
  60795. r = (uint8) roundFloatToInt (z);
  60796. g = x;
  60797. b = intV;
  60798. }
  60799. else if (h < 6.0f)
  60800. {
  60801. r = intV;
  60802. g = x;
  60803. b = (uint8) roundFloatToInt (y);
  60804. }
  60805. else
  60806. {
  60807. r = 0;
  60808. g = 0;
  60809. b = 0;
  60810. }
  60811. }
  60812. }
  60813. Colour::Colour (const float hue,
  60814. const float saturation,
  60815. const float brightness,
  60816. const float alpha) throw()
  60817. {
  60818. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60819. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60820. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  60821. }
  60822. const Colour Colour::fromHSV (const float hue,
  60823. const float saturation,
  60824. const float brightness,
  60825. const float alpha) throw()
  60826. {
  60827. return Colour (hue, saturation, brightness, alpha);
  60828. }
  60829. Colour::Colour (const float hue,
  60830. const float saturation,
  60831. const float brightness,
  60832. const uint8 alpha) throw()
  60833. {
  60834. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60835. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60836. argb.setARGB (alpha, r, g, b);
  60837. }
  60838. Colour::~Colour() throw()
  60839. {
  60840. }
  60841. const PixelARGB Colour::getPixelARGB() const throw()
  60842. {
  60843. PixelARGB p (argb);
  60844. p.premultiply();
  60845. return p;
  60846. }
  60847. uint32 Colour::getARGB() const throw()
  60848. {
  60849. return argb.getARGB();
  60850. }
  60851. bool Colour::isTransparent() const throw()
  60852. {
  60853. return getAlpha() == 0;
  60854. }
  60855. bool Colour::isOpaque() const throw()
  60856. {
  60857. return getAlpha() == 0xff;
  60858. }
  60859. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  60860. {
  60861. PixelARGB newCol (argb);
  60862. newCol.setAlpha (newAlpha);
  60863. return Colour (newCol.getARGB());
  60864. }
  60865. const Colour Colour::withAlpha (const float newAlpha) const throw()
  60866. {
  60867. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  60868. PixelARGB newCol (argb);
  60869. newCol.setAlpha (floatAlphaToInt (newAlpha));
  60870. return Colour (newCol.getARGB());
  60871. }
  60872. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  60873. {
  60874. jassert (alphaMultiplier >= 0);
  60875. PixelARGB newCol (argb);
  60876. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  60877. return Colour (newCol.getARGB());
  60878. }
  60879. const Colour Colour::overlaidWith (const Colour& src) const throw()
  60880. {
  60881. const int destAlpha = getAlpha();
  60882. if (destAlpha > 0)
  60883. {
  60884. const int invA = 0xff - (int) src.getAlpha();
  60885. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  60886. if (resA > 0)
  60887. {
  60888. const int da = (invA * destAlpha) / resA;
  60889. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  60890. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  60891. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  60892. (uint8) resA);
  60893. }
  60894. return *this;
  60895. }
  60896. else
  60897. {
  60898. return src;
  60899. }
  60900. }
  60901. float Colour::getFloatRed() const throw()
  60902. {
  60903. return getRed() * oneOver255;
  60904. }
  60905. float Colour::getFloatGreen() const throw()
  60906. {
  60907. return getGreen() * oneOver255;
  60908. }
  60909. float Colour::getFloatBlue() const throw()
  60910. {
  60911. return getBlue() * oneOver255;
  60912. }
  60913. float Colour::getFloatAlpha() const throw()
  60914. {
  60915. return getAlpha() * oneOver255;
  60916. }
  60917. void Colour::getHSB (float& h, float& s, float& v) const throw()
  60918. {
  60919. const int r = getRed();
  60920. const int g = getGreen();
  60921. const int b = getBlue();
  60922. const int hi = jmax (r, g, b);
  60923. const int lo = jmin (r, g, b);
  60924. if (hi != 0)
  60925. {
  60926. s = (hi - lo) / (float) hi;
  60927. if (s != 0)
  60928. {
  60929. const float invDiff = 1.0f / (hi - lo);
  60930. const float red = (hi - r) * invDiff;
  60931. const float green = (hi - g) * invDiff;
  60932. const float blue = (hi - b) * invDiff;
  60933. if (r == hi)
  60934. h = blue - green;
  60935. else if (g == hi)
  60936. h = 2.0f + red - blue;
  60937. else
  60938. h = 4.0f + green - red;
  60939. h *= 1.0f / 6.0f;
  60940. if (h < 0)
  60941. ++h;
  60942. }
  60943. else
  60944. {
  60945. h = 0;
  60946. }
  60947. }
  60948. else
  60949. {
  60950. s = 0;
  60951. h = 0;
  60952. }
  60953. v = hi * oneOver255;
  60954. }
  60955. float Colour::getHue() const throw()
  60956. {
  60957. float h, s, b;
  60958. getHSB (h, s, b);
  60959. return h;
  60960. }
  60961. const Colour Colour::withHue (const float hue) const throw()
  60962. {
  60963. float h, s, b;
  60964. getHSB (h, s, b);
  60965. return Colour (hue, s, b, getAlpha());
  60966. }
  60967. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  60968. {
  60969. float h, s, b;
  60970. getHSB (h, s, b);
  60971. h += amountToRotate;
  60972. h -= floorf (h);
  60973. return Colour (h, s, b, getAlpha());
  60974. }
  60975. float Colour::getSaturation() const throw()
  60976. {
  60977. float h, s, b;
  60978. getHSB (h, s, b);
  60979. return s;
  60980. }
  60981. const Colour Colour::withSaturation (const float saturation) const throw()
  60982. {
  60983. float h, s, b;
  60984. getHSB (h, s, b);
  60985. return Colour (h, saturation, b, getAlpha());
  60986. }
  60987. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  60988. {
  60989. float h, s, b;
  60990. getHSB (h, s, b);
  60991. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  60992. }
  60993. float Colour::getBrightness() const throw()
  60994. {
  60995. float h, s, b;
  60996. getHSB (h, s, b);
  60997. return b;
  60998. }
  60999. const Colour Colour::withBrightness (const float brightness) const throw()
  61000. {
  61001. float h, s, b;
  61002. getHSB (h, s, b);
  61003. return Colour (h, s, brightness, getAlpha());
  61004. }
  61005. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  61006. {
  61007. float h, s, b;
  61008. getHSB (h, s, b);
  61009. b *= amount;
  61010. if (b > 1.0f)
  61011. b = 1.0f;
  61012. return Colour (h, s, b, getAlpha());
  61013. }
  61014. const Colour Colour::brighter (float amount) const throw()
  61015. {
  61016. amount = 1.0f / (1.0f + amount);
  61017. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  61018. (uint8) (255 - (amount * (255 - getGreen()))),
  61019. (uint8) (255 - (amount * (255 - getBlue()))),
  61020. getAlpha());
  61021. }
  61022. const Colour Colour::darker (float amount) const throw()
  61023. {
  61024. amount = 1.0f / (1.0f + amount);
  61025. return Colour ((uint8) (amount * getRed()),
  61026. (uint8) (amount * getGreen()),
  61027. (uint8) (amount * getBlue()),
  61028. getAlpha());
  61029. }
  61030. const Colour Colour::greyLevel (const float brightness) throw()
  61031. {
  61032. const uint8 level
  61033. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  61034. return Colour (level, level, level);
  61035. }
  61036. const Colour Colour::contrasting (const float amount) const throw()
  61037. {
  61038. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  61039. ? Colours::black
  61040. : Colours::white).withAlpha (amount));
  61041. }
  61042. const Colour Colour::contrasting (const Colour& colour1,
  61043. const Colour& colour2) throw()
  61044. {
  61045. const float b1 = colour1.getBrightness();
  61046. const float b2 = colour2.getBrightness();
  61047. float best = 0.0f;
  61048. float bestDist = 0.0f;
  61049. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  61050. {
  61051. const float d1 = fabsf (i - b1);
  61052. const float d2 = fabsf (i - b2);
  61053. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  61054. if (dist > bestDist)
  61055. {
  61056. best = i;
  61057. bestDist = dist;
  61058. }
  61059. }
  61060. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  61061. .withBrightness (best);
  61062. }
  61063. const String Colour::toString() const throw()
  61064. {
  61065. return String::toHexString ((int) argb.getARGB());
  61066. }
  61067. const Colour Colour::fromString (const String& encodedColourString)
  61068. {
  61069. return Colour ((uint32) encodedColourString.getHexValue32());
  61070. }
  61071. END_JUCE_NAMESPACE
  61072. /********* End of inlined file: juce_Colour.cpp *********/
  61073. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  61074. BEGIN_JUCE_NAMESPACE
  61075. ColourGradient::ColourGradient() throw()
  61076. : colours (4)
  61077. {
  61078. #ifdef JUCE_DEBUG
  61079. x1 = 987654.0f;
  61080. #endif
  61081. }
  61082. ColourGradient::ColourGradient (const Colour& colour1,
  61083. const float x1_,
  61084. const float y1_,
  61085. const Colour& colour2,
  61086. const float x2_,
  61087. const float y2_,
  61088. const bool isRadial_) throw()
  61089. : x1 (x1_),
  61090. y1 (y1_),
  61091. x2 (x2_),
  61092. y2 (y2_),
  61093. isRadial (isRadial_),
  61094. colours (4)
  61095. {
  61096. colours.add (0);
  61097. colours.add (colour1.getARGB());
  61098. colours.add (1 << 16);
  61099. colours.add (colour2.getARGB());
  61100. }
  61101. ColourGradient::~ColourGradient() throw()
  61102. {
  61103. }
  61104. void ColourGradient::clearColours() throw()
  61105. {
  61106. colours.clear();
  61107. }
  61108. void ColourGradient::addColour (const double proportionAlongGradient,
  61109. const Colour& colour) throw()
  61110. {
  61111. // must be within the two end-points
  61112. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  61113. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  61114. int i;
  61115. for (i = 0; i < colours.size(); i += 2)
  61116. if (colours.getUnchecked(i) > pos)
  61117. break;
  61118. colours.insert (i, pos);
  61119. colours.insert (i + 1, colour.getARGB());
  61120. }
  61121. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  61122. {
  61123. for (int i = 1; i < colours.size(); i += 2)
  61124. {
  61125. const Colour c (colours.getUnchecked(i));
  61126. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  61127. }
  61128. }
  61129. int ColourGradient::getNumColours() const throw()
  61130. {
  61131. return colours.size() >> 1;
  61132. }
  61133. double ColourGradient::getColourPosition (const int index) const throw()
  61134. {
  61135. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  61136. }
  61137. const Colour ColourGradient::getColour (const int index) const throw()
  61138. {
  61139. return Colour (colours [(index << 1) + 1]);
  61140. }
  61141. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  61142. {
  61143. #ifdef JUCE_DEBUG
  61144. // trying to use the object without setting its co-ordinates? Have a careful read of
  61145. // the comments for the constructors.
  61146. jassert (x1 != 987654.0f);
  61147. #endif
  61148. const int numColours = colours.size() >> 1;
  61149. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  61150. transform.transformPoint (tx1, ty1);
  61151. transform.transformPoint (tx2, ty2);
  61152. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  61153. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  61154. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  61155. if (numColours >= 2)
  61156. {
  61157. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  61158. PixelARGB pix1 (colours.getUnchecked (1));
  61159. pix1.premultiply();
  61160. int index = 0;
  61161. for (int j = 2; j < colours.size(); j += 2)
  61162. {
  61163. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  61164. PixelARGB pix2 (colours.getUnchecked (j + 1));
  61165. pix2.premultiply();
  61166. for (int i = 0; i < numToDo; ++i)
  61167. {
  61168. jassert (index >= 0 && index < numEntries);
  61169. lookupTable[index] = pix1;
  61170. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  61171. ++index;
  61172. }
  61173. pix1 = pix2;
  61174. }
  61175. while (index < numEntries)
  61176. lookupTable [index++] = pix1;
  61177. }
  61178. else
  61179. {
  61180. jassertfalse // no colours specified!
  61181. }
  61182. return lookupTable;
  61183. }
  61184. bool ColourGradient::isOpaque() const throw()
  61185. {
  61186. for (int i = 1; i < colours.size(); i += 2)
  61187. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  61188. return false;
  61189. return true;
  61190. }
  61191. bool ColourGradient::isInvisible() const throw()
  61192. {
  61193. for (int i = 1; i < colours.size(); i += 2)
  61194. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  61195. return false;
  61196. return true;
  61197. }
  61198. END_JUCE_NAMESPACE
  61199. /********* End of inlined file: juce_ColourGradient.cpp *********/
  61200. /********* Start of inlined file: juce_Colours.cpp *********/
  61201. BEGIN_JUCE_NAMESPACE
  61202. const Colour Colours::transparentBlack (0);
  61203. const Colour Colours::transparentWhite (0x00ffffff);
  61204. const Colour Colours::aliceblue (0xfff0f8ff);
  61205. const Colour Colours::antiquewhite (0xfffaebd7);
  61206. const Colour Colours::aqua (0xff00ffff);
  61207. const Colour Colours::aquamarine (0xff7fffd4);
  61208. const Colour Colours::azure (0xfff0ffff);
  61209. const Colour Colours::beige (0xfff5f5dc);
  61210. const Colour Colours::bisque (0xffffe4c4);
  61211. const Colour Colours::black (0xff000000);
  61212. const Colour Colours::blanchedalmond (0xffffebcd);
  61213. const Colour Colours::blue (0xff0000ff);
  61214. const Colour Colours::blueviolet (0xff8a2be2);
  61215. const Colour Colours::brown (0xffa52a2a);
  61216. const Colour Colours::burlywood (0xffdeb887);
  61217. const Colour Colours::cadetblue (0xff5f9ea0);
  61218. const Colour Colours::chartreuse (0xff7fff00);
  61219. const Colour Colours::chocolate (0xffd2691e);
  61220. const Colour Colours::coral (0xffff7f50);
  61221. const Colour Colours::cornflowerblue (0xff6495ed);
  61222. const Colour Colours::cornsilk (0xfffff8dc);
  61223. const Colour Colours::crimson (0xffdc143c);
  61224. const Colour Colours::cyan (0xff00ffff);
  61225. const Colour Colours::darkblue (0xff00008b);
  61226. const Colour Colours::darkcyan (0xff008b8b);
  61227. const Colour Colours::darkgoldenrod (0xffb8860b);
  61228. const Colour Colours::darkgrey (0xff555555);
  61229. const Colour Colours::darkgreen (0xff006400);
  61230. const Colour Colours::darkkhaki (0xffbdb76b);
  61231. const Colour Colours::darkmagenta (0xff8b008b);
  61232. const Colour Colours::darkolivegreen (0xff556b2f);
  61233. const Colour Colours::darkorange (0xffff8c00);
  61234. const Colour Colours::darkorchid (0xff9932cc);
  61235. const Colour Colours::darkred (0xff8b0000);
  61236. const Colour Colours::darksalmon (0xffe9967a);
  61237. const Colour Colours::darkseagreen (0xff8fbc8f);
  61238. const Colour Colours::darkslateblue (0xff483d8b);
  61239. const Colour Colours::darkslategrey (0xff2f4f4f);
  61240. const Colour Colours::darkturquoise (0xff00ced1);
  61241. const Colour Colours::darkviolet (0xff9400d3);
  61242. const Colour Colours::deeppink (0xffff1493);
  61243. const Colour Colours::deepskyblue (0xff00bfff);
  61244. const Colour Colours::dimgrey (0xff696969);
  61245. const Colour Colours::dodgerblue (0xff1e90ff);
  61246. const Colour Colours::firebrick (0xffb22222);
  61247. const Colour Colours::floralwhite (0xfffffaf0);
  61248. const Colour Colours::forestgreen (0xff228b22);
  61249. const Colour Colours::fuchsia (0xffff00ff);
  61250. const Colour Colours::gainsboro (0xffdcdcdc);
  61251. const Colour Colours::gold (0xffffd700);
  61252. const Colour Colours::goldenrod (0xffdaa520);
  61253. const Colour Colours::grey (0xff808080);
  61254. const Colour Colours::green (0xff008000);
  61255. const Colour Colours::greenyellow (0xffadff2f);
  61256. const Colour Colours::honeydew (0xfff0fff0);
  61257. const Colour Colours::hotpink (0xffff69b4);
  61258. const Colour Colours::indianred (0xffcd5c5c);
  61259. const Colour Colours::indigo (0xff4b0082);
  61260. const Colour Colours::ivory (0xfffffff0);
  61261. const Colour Colours::khaki (0xfff0e68c);
  61262. const Colour Colours::lavender (0xffe6e6fa);
  61263. const Colour Colours::lavenderblush (0xfffff0f5);
  61264. const Colour Colours::lemonchiffon (0xfffffacd);
  61265. const Colour Colours::lightblue (0xffadd8e6);
  61266. const Colour Colours::lightcoral (0xfff08080);
  61267. const Colour Colours::lightcyan (0xffe0ffff);
  61268. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  61269. const Colour Colours::lightgreen (0xff90ee90);
  61270. const Colour Colours::lightgrey (0xffd3d3d3);
  61271. const Colour Colours::lightpink (0xffffb6c1);
  61272. const Colour Colours::lightsalmon (0xffffa07a);
  61273. const Colour Colours::lightseagreen (0xff20b2aa);
  61274. const Colour Colours::lightskyblue (0xff87cefa);
  61275. const Colour Colours::lightslategrey (0xff778899);
  61276. const Colour Colours::lightsteelblue (0xffb0c4de);
  61277. const Colour Colours::lightyellow (0xffffffe0);
  61278. const Colour Colours::lime (0xff00ff00);
  61279. const Colour Colours::limegreen (0xff32cd32);
  61280. const Colour Colours::linen (0xfffaf0e6);
  61281. const Colour Colours::magenta (0xffff00ff);
  61282. const Colour Colours::maroon (0xff800000);
  61283. const Colour Colours::mediumaquamarine (0xff66cdaa);
  61284. const Colour Colours::mediumblue (0xff0000cd);
  61285. const Colour Colours::mediumorchid (0xffba55d3);
  61286. const Colour Colours::mediumpurple (0xff9370db);
  61287. const Colour Colours::mediumseagreen (0xff3cb371);
  61288. const Colour Colours::mediumslateblue (0xff7b68ee);
  61289. const Colour Colours::mediumspringgreen (0xff00fa9a);
  61290. const Colour Colours::mediumturquoise (0xff48d1cc);
  61291. const Colour Colours::mediumvioletred (0xffc71585);
  61292. const Colour Colours::midnightblue (0xff191970);
  61293. const Colour Colours::mintcream (0xfff5fffa);
  61294. const Colour Colours::mistyrose (0xffffe4e1);
  61295. const Colour Colours::navajowhite (0xffffdead);
  61296. const Colour Colours::navy (0xff000080);
  61297. const Colour Colours::oldlace (0xfffdf5e6);
  61298. const Colour Colours::olive (0xff808000);
  61299. const Colour Colours::olivedrab (0xff6b8e23);
  61300. const Colour Colours::orange (0xffffa500);
  61301. const Colour Colours::orangered (0xffff4500);
  61302. const Colour Colours::orchid (0xffda70d6);
  61303. const Colour Colours::palegoldenrod (0xffeee8aa);
  61304. const Colour Colours::palegreen (0xff98fb98);
  61305. const Colour Colours::paleturquoise (0xffafeeee);
  61306. const Colour Colours::palevioletred (0xffdb7093);
  61307. const Colour Colours::papayawhip (0xffffefd5);
  61308. const Colour Colours::peachpuff (0xffffdab9);
  61309. const Colour Colours::peru (0xffcd853f);
  61310. const Colour Colours::pink (0xffffc0cb);
  61311. const Colour Colours::plum (0xffdda0dd);
  61312. const Colour Colours::powderblue (0xffb0e0e6);
  61313. const Colour Colours::purple (0xff800080);
  61314. const Colour Colours::red (0xffff0000);
  61315. const Colour Colours::rosybrown (0xffbc8f8f);
  61316. const Colour Colours::royalblue (0xff4169e1);
  61317. const Colour Colours::saddlebrown (0xff8b4513);
  61318. const Colour Colours::salmon (0xfffa8072);
  61319. const Colour Colours::sandybrown (0xfff4a460);
  61320. const Colour Colours::seagreen (0xff2e8b57);
  61321. const Colour Colours::seashell (0xfffff5ee);
  61322. const Colour Colours::sienna (0xffa0522d);
  61323. const Colour Colours::silver (0xffc0c0c0);
  61324. const Colour Colours::skyblue (0xff87ceeb);
  61325. const Colour Colours::slateblue (0xff6a5acd);
  61326. const Colour Colours::slategrey (0xff708090);
  61327. const Colour Colours::snow (0xfffffafa);
  61328. const Colour Colours::springgreen (0xff00ff7f);
  61329. const Colour Colours::steelblue (0xff4682b4);
  61330. const Colour Colours::tan (0xffd2b48c);
  61331. const Colour Colours::teal (0xff008080);
  61332. const Colour Colours::thistle (0xffd8bfd8);
  61333. const Colour Colours::tomato (0xffff6347);
  61334. const Colour Colours::turquoise (0xff40e0d0);
  61335. const Colour Colours::violet (0xffee82ee);
  61336. const Colour Colours::wheat (0xfff5deb3);
  61337. const Colour Colours::white (0xffffffff);
  61338. const Colour Colours::whitesmoke (0xfff5f5f5);
  61339. const Colour Colours::yellow (0xffffff00);
  61340. const Colour Colours::yellowgreen (0xff9acd32);
  61341. const Colour Colours::findColourForName (const String& colourName,
  61342. const Colour& defaultColour)
  61343. {
  61344. static const int presets[] =
  61345. {
  61346. // (first value is the string's hashcode, second is ARGB)
  61347. 0x05978fff, 0xff000000, /* black */
  61348. 0x06bdcc29, 0xffffffff, /* white */
  61349. 0x002e305a, 0xff0000ff, /* blue */
  61350. 0x00308adf, 0xff808080, /* grey */
  61351. 0x05e0cf03, 0xff008000, /* green */
  61352. 0x0001b891, 0xffff0000, /* red */
  61353. 0xd43c6474, 0xffffff00, /* yellow */
  61354. 0x620886da, 0xfff0f8ff, /* aliceblue */
  61355. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  61356. 0x002dcebc, 0xff00ffff, /* aqua */
  61357. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  61358. 0x0590228f, 0xfff0ffff, /* azure */
  61359. 0x05947fe4, 0xfff5f5dc, /* beige */
  61360. 0xad388e35, 0xffffe4c4, /* bisque */
  61361. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  61362. 0x39129959, 0xff8a2be2, /* blueviolet */
  61363. 0x059a8136, 0xffa52a2a, /* brown */
  61364. 0x89cea8f9, 0xffdeb887, /* burlywood */
  61365. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  61366. 0x6b748956, 0xff7fff00, /* chartreuse */
  61367. 0x2903623c, 0xffd2691e, /* chocolate */
  61368. 0x05a74431, 0xffff7f50, /* coral */
  61369. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  61370. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  61371. 0x3d8c4edf, 0xffdc143c, /* crimson */
  61372. 0x002ed323, 0xff00ffff, /* cyan */
  61373. 0x67cc74d0, 0xff00008b, /* darkblue */
  61374. 0x67cd1799, 0xff008b8b, /* darkcyan */
  61375. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  61376. 0x67cecf55, 0xff555555, /* darkgrey */
  61377. 0x920b194d, 0xff006400, /* darkgreen */
  61378. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  61379. 0x5c293873, 0xff8b008b, /* darkmagenta */
  61380. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  61381. 0xbcfd2524, 0xffff8c00, /* darkorange */
  61382. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  61383. 0x55ee0d5b, 0xff8b0000, /* darkred */
  61384. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  61385. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  61386. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  61387. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  61388. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  61389. 0xc8769375, 0xff9400d3, /* darkviolet */
  61390. 0x25832862, 0xffff1493, /* deeppink */
  61391. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  61392. 0x634c8b67, 0xff696969, /* dimgrey */
  61393. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  61394. 0xef19e3cb, 0xffb22222, /* firebrick */
  61395. 0xb852b195, 0xfffffaf0, /* floralwhite */
  61396. 0xd086fd06, 0xff228b22, /* forestgreen */
  61397. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  61398. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  61399. 0x00308060, 0xffffd700, /* gold */
  61400. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  61401. 0xbab8a537, 0xffadff2f, /* greenyellow */
  61402. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  61403. 0x41892743, 0xffff69b4, /* hotpink */
  61404. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  61405. 0xb969fed2, 0xff4b0082, /* indigo */
  61406. 0x05fef6a9, 0xfffffff0, /* ivory */
  61407. 0x06149302, 0xfff0e68c, /* khaki */
  61408. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  61409. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  61410. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  61411. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  61412. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  61413. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  61414. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  61415. 0xf40157ad, 0xff90ee90, /* lightgreen */
  61416. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  61417. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  61418. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  61419. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  61420. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  61421. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  61422. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  61423. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  61424. 0x0032afd5, 0xff00ff00, /* lime */
  61425. 0x607bbc4e, 0xff32cd32, /* limegreen */
  61426. 0x06234efa, 0xfffaf0e6, /* linen */
  61427. 0x316858a9, 0xffff00ff, /* magenta */
  61428. 0xbf8ca470, 0xff800000, /* maroon */
  61429. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  61430. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  61431. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  61432. 0x07556b71, 0xff9370db, /* mediumpurple */
  61433. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  61434. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  61435. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  61436. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  61437. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  61438. 0x168eb32a, 0xff191970, /* midnightblue */
  61439. 0x4306b960, 0xfff5fffa, /* mintcream */
  61440. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  61441. 0xe97218a6, 0xffffdead, /* navajowhite */
  61442. 0x00337bb6, 0xff000080, /* navy */
  61443. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  61444. 0x064ee1db, 0xff808000, /* olive */
  61445. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  61446. 0xc3de262e, 0xffffa500, /* orange */
  61447. 0x58bebba3, 0xffff4500, /* orangered */
  61448. 0xc3def8a3, 0xffda70d6, /* orchid */
  61449. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  61450. 0x3d9dd619, 0xff98fb98, /* palegreen */
  61451. 0x74022737, 0xffafeeee, /* paleturquoise */
  61452. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  61453. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  61454. 0x93e1b776, 0xffffdab9, /* peachpuff */
  61455. 0x003472f8, 0xffcd853f, /* peru */
  61456. 0x00348176, 0xffffc0cb, /* pink */
  61457. 0x00348d94, 0xffdda0dd, /* plum */
  61458. 0xd036be93, 0xffb0e0e6, /* powderblue */
  61459. 0xc5c507bc, 0xff800080, /* purple */
  61460. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  61461. 0xbd9413e1, 0xff4169e1, /* royalblue */
  61462. 0xf456044f, 0xff8b4513, /* saddlebrown */
  61463. 0xc9c6f66e, 0xfffa8072, /* salmon */
  61464. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  61465. 0x34636c14, 0xff2e8b57, /* seagreen */
  61466. 0x3507fb41, 0xfffff5ee, /* seashell */
  61467. 0xca348772, 0xffa0522d, /* sienna */
  61468. 0xca37d30d, 0xffc0c0c0, /* silver */
  61469. 0x80da74fb, 0xff87ceeb, /* skyblue */
  61470. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  61471. 0x44ab37f8, 0xff708090, /* slategrey */
  61472. 0x0035f183, 0xfffffafa, /* snow */
  61473. 0xd5440d16, 0xff00ff7f, /* springgreen */
  61474. 0x3e1524a5, 0xff4682b4, /* steelblue */
  61475. 0x0001bfa1, 0xffd2b48c, /* tan */
  61476. 0x0036425c, 0xff008080, /* teal */
  61477. 0xafc8858f, 0xffd8bfd8, /* thistle */
  61478. 0xcc41600a, 0xffff6347, /* tomato */
  61479. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  61480. 0xcf57947f, 0xffee82ee, /* violet */
  61481. 0x06bdbae7, 0xfff5deb3, /* wheat */
  61482. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  61483. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  61484. };
  61485. const int hash = colourName.trim().toLowerCase().hashCode();
  61486. for (int i = 0; i < numElementsInArray (presets); i += 2)
  61487. if (presets [i] == hash)
  61488. return Colour (presets [i + 1]);
  61489. return defaultColour;
  61490. }
  61491. END_JUCE_NAMESPACE
  61492. /********* End of inlined file: juce_Colours.cpp *********/
  61493. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  61494. BEGIN_JUCE_NAMESPACE
  61495. EdgeTable::EdgeTable (const int top_,
  61496. const int height_,
  61497. const OversamplingLevel oversampling_,
  61498. const int expectedEdgesPerLine) throw()
  61499. : top (top_),
  61500. height (height_),
  61501. maxEdgesPerLine (expectedEdgesPerLine),
  61502. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  61503. oversampling (oversampling_)
  61504. {
  61505. table = (int*) juce_calloc ((height << (int)oversampling_)
  61506. * lineStrideElements * sizeof (int));
  61507. }
  61508. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  61509. : table (0)
  61510. {
  61511. operator= (other);
  61512. }
  61513. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  61514. {
  61515. juce_free (table);
  61516. top = other.top;
  61517. height = other.height;
  61518. maxEdgesPerLine = other.maxEdgesPerLine;
  61519. lineStrideElements = other.lineStrideElements;
  61520. oversampling = other.oversampling;
  61521. const int tableSize = (height << (int)oversampling)
  61522. * lineStrideElements * sizeof (int);
  61523. table = (int*) juce_malloc (tableSize);
  61524. memcpy (table, other.table, tableSize);
  61525. return *this;
  61526. }
  61527. EdgeTable::~EdgeTable() throw()
  61528. {
  61529. juce_free (table);
  61530. }
  61531. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  61532. {
  61533. if (newNumEdgesPerLine != maxEdgesPerLine)
  61534. {
  61535. maxEdgesPerLine = newNumEdgesPerLine;
  61536. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  61537. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  61538. * newLineStrideElements * sizeof (int));
  61539. for (int i = 0; i < (height << (int) oversampling); ++i)
  61540. {
  61541. const int* srcLine = table + lineStrideElements * i;
  61542. int* dstLine = newTable + newLineStrideElements * i;
  61543. int num = *srcLine++;
  61544. *dstLine++ = num;
  61545. num <<= 1;
  61546. while (--num >= 0)
  61547. *dstLine++ = *srcLine++;
  61548. }
  61549. juce_free (table);
  61550. table = newTable;
  61551. lineStrideElements = newLineStrideElements;
  61552. }
  61553. }
  61554. void EdgeTable::optimiseTable() throw()
  61555. {
  61556. int maxLineElements = 0;
  61557. for (int i = height; --i >= 0;)
  61558. maxLineElements = jmax (maxLineElements,
  61559. table [i * lineStrideElements]);
  61560. remapTableForNumEdges (maxLineElements);
  61561. }
  61562. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  61563. {
  61564. jassert (y >= 0 && y < (height << oversampling))
  61565. int* lineStart = table + lineStrideElements * y;
  61566. int n = lineStart[0];
  61567. if (n >= maxEdgesPerLine)
  61568. {
  61569. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  61570. jassert (n < maxEdgesPerLine);
  61571. lineStart = table + lineStrideElements * y;
  61572. }
  61573. n <<= 1;
  61574. int* const line = lineStart + 1;
  61575. while (n > 0)
  61576. {
  61577. const int cx = line [n - 2];
  61578. if (cx <= x)
  61579. break;
  61580. line [n] = cx;
  61581. line [n + 1] = line [n - 1];
  61582. n -= 2;
  61583. }
  61584. line [n] = x;
  61585. line [n + 1] = winding;
  61586. lineStart[0]++;
  61587. }
  61588. void EdgeTable::addPath (const Path& path,
  61589. const AffineTransform& transform) throw()
  61590. {
  61591. const int windingAmount = 256 / (1 << (int) oversampling);
  61592. const float timesOversampling = (float) (1 << (int) oversampling);
  61593. const int bottomLimit = (height << (int) oversampling);
  61594. PathFlatteningIterator iter (path, transform);
  61595. while (iter.next())
  61596. {
  61597. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  61598. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  61599. if (y1 != y2)
  61600. {
  61601. const double x1 = 256.0 * iter.x1;
  61602. const double x2 = 256.0 * iter.x2;
  61603. const double multiplier = (x2 - x1) / (y2 - y1);
  61604. const int oldY1 = y1;
  61605. int winding;
  61606. if (y1 > y2)
  61607. {
  61608. swapVariables (y1, y2);
  61609. winding = windingAmount;
  61610. }
  61611. else
  61612. {
  61613. winding = -windingAmount;
  61614. }
  61615. jassert (y1 < y2);
  61616. if (y1 < 0)
  61617. y1 = 0;
  61618. if (y2 > bottomLimit)
  61619. y2 = bottomLimit;
  61620. while (y1 < y2)
  61621. {
  61622. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  61623. y1,
  61624. winding);
  61625. ++y1;
  61626. }
  61627. }
  61628. }
  61629. if (! path.isUsingNonZeroWinding())
  61630. {
  61631. // if it's an alternate-winding path, we need to go through and
  61632. // make sure all the windings are alternating.
  61633. int* lineStart = table;
  61634. for (int i = height << (int) oversampling; --i >= 0;)
  61635. {
  61636. int* line = lineStart;
  61637. lineStart += lineStrideElements;
  61638. int num = *line;
  61639. while (--num >= 0)
  61640. {
  61641. line += 2;
  61642. *line = abs (*line);
  61643. if (--num >= 0)
  61644. {
  61645. line += 2;
  61646. *line = -abs (*line);
  61647. }
  61648. }
  61649. }
  61650. }
  61651. }
  61652. END_JUCE_NAMESPACE
  61653. /********* End of inlined file: juce_EdgeTable.cpp *********/
  61654. /********* Start of inlined file: juce_Graphics.cpp *********/
  61655. BEGIN_JUCE_NAMESPACE
  61656. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  61657. #define MINIMUM_COORD -0x3fffffff
  61658. #define MAXIMUM_COORD 0x3fffffff
  61659. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61660. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61661. jassert ((int) x >= MINIMUM_COORD \
  61662. && (int) x <= MAXIMUM_COORD \
  61663. && (int) y >= MINIMUM_COORD \
  61664. && (int) y <= MAXIMUM_COORD \
  61665. && (int) w >= MINIMUM_COORD \
  61666. && (int) w <= MAXIMUM_COORD \
  61667. && (int) h >= MINIMUM_COORD \
  61668. && (int) h <= MAXIMUM_COORD);
  61669. LowLevelGraphicsContext::LowLevelGraphicsContext()
  61670. {
  61671. }
  61672. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  61673. {
  61674. }
  61675. Graphics::Graphics (Image& imageToDrawOnto) throw()
  61676. : context (imageToDrawOnto.createLowLevelContext()),
  61677. ownsContext (true),
  61678. state (new GraphicsState()),
  61679. saveStatePending (false)
  61680. {
  61681. }
  61682. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  61683. : context (internalContext),
  61684. ownsContext (false),
  61685. state (new GraphicsState()),
  61686. saveStatePending (false)
  61687. {
  61688. }
  61689. Graphics::~Graphics() throw()
  61690. {
  61691. delete state;
  61692. if (ownsContext)
  61693. delete context;
  61694. }
  61695. void Graphics::resetToDefaultState() throw()
  61696. {
  61697. setColour (Colours::black);
  61698. state->font.resetToDefaultState();
  61699. state->quality = defaultQuality;
  61700. }
  61701. bool Graphics::isVectorDevice() const throw()
  61702. {
  61703. return context->isVectorDevice();
  61704. }
  61705. bool Graphics::reduceClipRegion (const int x, const int y,
  61706. const int w, const int h) throw()
  61707. {
  61708. saveStateIfPending();
  61709. return context->reduceClipRegion (x, y, w, h);
  61710. }
  61711. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  61712. {
  61713. saveStateIfPending();
  61714. return context->reduceClipRegion (clipRegion);
  61715. }
  61716. void Graphics::excludeClipRegion (const int x, const int y,
  61717. const int w, const int h) throw()
  61718. {
  61719. saveStateIfPending();
  61720. context->excludeClipRegion (x, y, w, h);
  61721. }
  61722. bool Graphics::isClipEmpty() const throw()
  61723. {
  61724. return context->isClipEmpty();
  61725. }
  61726. const Rectangle Graphics::getClipBounds() const throw()
  61727. {
  61728. return context->getClipBounds();
  61729. }
  61730. void Graphics::saveState() throw()
  61731. {
  61732. saveStateIfPending();
  61733. saveStatePending = true;
  61734. }
  61735. void Graphics::restoreState() throw()
  61736. {
  61737. if (saveStatePending)
  61738. {
  61739. saveStatePending = false;
  61740. }
  61741. else
  61742. {
  61743. const int stackSize = stateStack.size();
  61744. if (stackSize > 0)
  61745. {
  61746. context->restoreState();
  61747. delete state;
  61748. state = stateStack.getUnchecked (stackSize - 1);
  61749. stateStack.removeLast (1, false);
  61750. }
  61751. else
  61752. {
  61753. // Trying to call restoreState() more times than you've called saveState() !
  61754. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  61755. jassertfalse
  61756. }
  61757. }
  61758. }
  61759. void Graphics::saveStateIfPending() throw()
  61760. {
  61761. if (saveStatePending)
  61762. {
  61763. saveStatePending = false;
  61764. context->saveState();
  61765. stateStack.add (new GraphicsState (*state));
  61766. }
  61767. }
  61768. void Graphics::setOrigin (const int newOriginX,
  61769. const int newOriginY) throw()
  61770. {
  61771. saveStateIfPending();
  61772. context->setOrigin (newOriginX, newOriginY);
  61773. }
  61774. bool Graphics::clipRegionIntersects (const int x, const int y,
  61775. const int w, const int h) const throw()
  61776. {
  61777. return context->clipRegionIntersects (x, y, w, h);
  61778. }
  61779. void Graphics::setColour (const Colour& newColour) throw()
  61780. {
  61781. saveStateIfPending();
  61782. state->colour = newColour;
  61783. deleteAndZero (state->brush);
  61784. }
  61785. const Colour& Graphics::getCurrentColour() const throw()
  61786. {
  61787. return state->colour;
  61788. }
  61789. void Graphics::setOpacity (const float newOpacity) throw()
  61790. {
  61791. saveStateIfPending();
  61792. state->colour = state->colour.withAlpha (newOpacity);
  61793. }
  61794. void Graphics::setBrush (const Brush* const newBrush) throw()
  61795. {
  61796. saveStateIfPending();
  61797. delete state->brush;
  61798. if (newBrush != 0)
  61799. state->brush = newBrush->createCopy();
  61800. else
  61801. state->brush = 0;
  61802. }
  61803. Graphics::GraphicsState::GraphicsState() throw()
  61804. : colour (Colours::black),
  61805. brush (0),
  61806. quality (defaultQuality)
  61807. {
  61808. }
  61809. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  61810. : colour (other.colour),
  61811. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  61812. font (other.font),
  61813. quality (other.quality)
  61814. {
  61815. }
  61816. Graphics::GraphicsState::~GraphicsState() throw()
  61817. {
  61818. delete brush;
  61819. }
  61820. void Graphics::setFont (const Font& newFont) throw()
  61821. {
  61822. saveStateIfPending();
  61823. state->font = newFont;
  61824. }
  61825. void Graphics::setFont (const float newFontHeight,
  61826. const int newFontStyleFlags) throw()
  61827. {
  61828. saveStateIfPending();
  61829. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  61830. }
  61831. const Font& Graphics::getCurrentFont() const throw()
  61832. {
  61833. return state->font;
  61834. }
  61835. void Graphics::drawSingleLineText (const String& text,
  61836. const int startX,
  61837. const int baselineY) const throw()
  61838. {
  61839. if (text.isNotEmpty()
  61840. && startX < context->getClipBounds().getRight())
  61841. {
  61842. GlyphArrangement arr;
  61843. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  61844. arr.draw (*this);
  61845. }
  61846. }
  61847. void Graphics::drawTextAsPath (const String& text,
  61848. const AffineTransform& transform) const throw()
  61849. {
  61850. if (text.isNotEmpty())
  61851. {
  61852. GlyphArrangement arr;
  61853. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  61854. arr.draw (*this, transform);
  61855. }
  61856. }
  61857. void Graphics::drawMultiLineText (const String& text,
  61858. const int startX,
  61859. const int baselineY,
  61860. const int maximumLineWidth) const throw()
  61861. {
  61862. if (text.isNotEmpty()
  61863. && startX < context->getClipBounds().getRight())
  61864. {
  61865. GlyphArrangement arr;
  61866. arr.addJustifiedText (state->font, text,
  61867. (float) startX, (float) baselineY, (float) maximumLineWidth,
  61868. Justification::left);
  61869. arr.draw (*this);
  61870. }
  61871. }
  61872. void Graphics::drawText (const String& text,
  61873. const int x,
  61874. const int y,
  61875. const int width,
  61876. const int height,
  61877. const Justification& justificationType,
  61878. const bool useEllipsesIfTooBig) const throw()
  61879. {
  61880. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  61881. {
  61882. GlyphArrangement arr;
  61883. arr.addCurtailedLineOfText (state->font, text,
  61884. 0.0f, 0.0f, (float)width,
  61885. useEllipsesIfTooBig);
  61886. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  61887. (float) x, (float) y,
  61888. (float) width, (float) height,
  61889. justificationType);
  61890. arr.draw (*this);
  61891. }
  61892. }
  61893. void Graphics::drawFittedText (const String& text,
  61894. const int x,
  61895. const int y,
  61896. const int width,
  61897. const int height,
  61898. const Justification& justification,
  61899. const int maximumNumberOfLines,
  61900. const float minimumHorizontalScale) const throw()
  61901. {
  61902. if (text.isNotEmpty()
  61903. && width > 0 && height > 0
  61904. && context->clipRegionIntersects (x, y, width, height))
  61905. {
  61906. GlyphArrangement arr;
  61907. arr.addFittedText (state->font, text,
  61908. (float) x, (float) y,
  61909. (float) width, (float) height,
  61910. justification,
  61911. maximumNumberOfLines,
  61912. minimumHorizontalScale);
  61913. arr.draw (*this);
  61914. }
  61915. }
  61916. void Graphics::fillRect (int x,
  61917. int y,
  61918. int width,
  61919. int height) const throw()
  61920. {
  61921. // passing in a silly number can cause maths problems in rendering!
  61922. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61923. SolidColourBrush colourBrush (state->colour);
  61924. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  61925. }
  61926. void Graphics::fillRect (const Rectangle& r) const throw()
  61927. {
  61928. fillRect (r.getX(),
  61929. r.getY(),
  61930. r.getWidth(),
  61931. r.getHeight());
  61932. }
  61933. void Graphics::fillRect (const float x,
  61934. const float y,
  61935. const float width,
  61936. const float height) const throw()
  61937. {
  61938. // passing in a silly number can cause maths problems in rendering!
  61939. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61940. Path p;
  61941. p.addRectangle (x, y, width, height);
  61942. fillPath (p);
  61943. }
  61944. void Graphics::setPixel (int x, int y) const throw()
  61945. {
  61946. if (context->clipRegionIntersects (x, y, 1, 1))
  61947. {
  61948. SolidColourBrush colourBrush (state->colour);
  61949. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  61950. }
  61951. }
  61952. void Graphics::fillAll() const throw()
  61953. {
  61954. fillRect (context->getClipBounds());
  61955. }
  61956. void Graphics::fillAll (const Colour& colourToUse) const throw()
  61957. {
  61958. if (! colourToUse.isTransparent())
  61959. {
  61960. const Rectangle clip (context->getClipBounds());
  61961. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  61962. colourToUse, false);
  61963. }
  61964. }
  61965. void Graphics::fillPath (const Path& path,
  61966. const AffineTransform& transform) const throw()
  61967. {
  61968. if ((! context->isClipEmpty()) && ! path.isEmpty())
  61969. {
  61970. SolidColourBrush colourBrush (state->colour);
  61971. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  61972. }
  61973. }
  61974. void Graphics::strokePath (const Path& path,
  61975. const PathStrokeType& strokeType,
  61976. const AffineTransform& transform) const throw()
  61977. {
  61978. if ((! state->colour.isTransparent()) || state->brush != 0)
  61979. {
  61980. Path stroke;
  61981. strokeType.createStrokedPath (stroke, path, transform);
  61982. fillPath (stroke);
  61983. }
  61984. }
  61985. void Graphics::drawRect (const int x,
  61986. const int y,
  61987. const int width,
  61988. const int height,
  61989. const int lineThickness) const throw()
  61990. {
  61991. // passing in a silly number can cause maths problems in rendering!
  61992. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61993. SolidColourBrush colourBrush (state->colour);
  61994. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  61995. b.paintRectangle (*context, x, y, width, lineThickness);
  61996. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  61997. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  61998. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  61999. }
  62000. void Graphics::drawRect (const float x,
  62001. const float y,
  62002. const float width,
  62003. const float height,
  62004. const float lineThickness) const throw()
  62005. {
  62006. // passing in a silly number can cause maths problems in rendering!
  62007. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62008. Path p;
  62009. p.addRectangle (x, y, width, lineThickness);
  62010. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  62011. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  62012. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  62013. fillPath (p);
  62014. }
  62015. void Graphics::drawRect (const Rectangle& r,
  62016. const int lineThickness) const throw()
  62017. {
  62018. drawRect (r.getX(), r.getY(),
  62019. r.getWidth(), r.getHeight(),
  62020. lineThickness);
  62021. }
  62022. void Graphics::drawBevel (const int x,
  62023. const int y,
  62024. const int width,
  62025. const int height,
  62026. const int bevelThickness,
  62027. const Colour& topLeftColour,
  62028. const Colour& bottomRightColour,
  62029. const bool useGradient,
  62030. const bool sharpEdgeOnOutside) const throw()
  62031. {
  62032. // passing in a silly number can cause maths problems in rendering!
  62033. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62034. if (clipRegionIntersects (x, y, width, height))
  62035. {
  62036. const float oldOpacity = state->colour.getFloatAlpha();
  62037. const float ramp = oldOpacity / bevelThickness;
  62038. for (int i = bevelThickness; --i >= 0;)
  62039. {
  62040. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  62041. : oldOpacity;
  62042. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  62043. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  62044. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  62045. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  62046. }
  62047. }
  62048. }
  62049. void Graphics::fillEllipse (const float x,
  62050. const float y,
  62051. const float width,
  62052. const float height) const throw()
  62053. {
  62054. // passing in a silly number can cause maths problems in rendering!
  62055. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62056. Path p;
  62057. p.addEllipse (x, y, width, height);
  62058. fillPath (p);
  62059. }
  62060. void Graphics::drawEllipse (const float x,
  62061. const float y,
  62062. const float width,
  62063. const float height,
  62064. const float lineThickness) const throw()
  62065. {
  62066. // passing in a silly number can cause maths problems in rendering!
  62067. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62068. Path p;
  62069. p.addEllipse (x, y, width, height);
  62070. strokePath (p, PathStrokeType (lineThickness));
  62071. }
  62072. void Graphics::fillRoundedRectangle (const float x,
  62073. const float y,
  62074. const float width,
  62075. const float height,
  62076. const float cornerSize) const throw()
  62077. {
  62078. // passing in a silly number can cause maths problems in rendering!
  62079. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62080. Path p;
  62081. p.addRoundedRectangle (x, y, width, height, cornerSize);
  62082. fillPath (p);
  62083. }
  62084. void Graphics::fillRoundedRectangle (const Rectangle& r,
  62085. const float cornerSize) const throw()
  62086. {
  62087. fillRoundedRectangle ((float) r.getX(),
  62088. (float) r.getY(),
  62089. (float) r.getWidth(),
  62090. (float) r.getHeight(),
  62091. cornerSize);
  62092. }
  62093. void Graphics::drawRoundedRectangle (const float x,
  62094. const float y,
  62095. const float width,
  62096. const float height,
  62097. const float cornerSize,
  62098. const float lineThickness) const throw()
  62099. {
  62100. // passing in a silly number can cause maths problems in rendering!
  62101. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62102. Path p;
  62103. p.addRoundedRectangle (x, y, width, height, cornerSize);
  62104. strokePath (p, PathStrokeType (lineThickness));
  62105. }
  62106. void Graphics::drawRoundedRectangle (const Rectangle& r,
  62107. const float cornerSize,
  62108. const float lineThickness) const throw()
  62109. {
  62110. drawRoundedRectangle ((float) r.getX(),
  62111. (float) r.getY(),
  62112. (float) r.getWidth(),
  62113. (float) r.getHeight(),
  62114. cornerSize, lineThickness);
  62115. }
  62116. void Graphics::drawArrow (const float startX,
  62117. const float startY,
  62118. const float endX,
  62119. const float endY,
  62120. const float lineThickness,
  62121. const float arrowheadWidth,
  62122. const float arrowheadLength) const throw()
  62123. {
  62124. Path p;
  62125. p.addArrow (startX, startY, endX, endY,
  62126. lineThickness, arrowheadWidth, arrowheadLength);
  62127. fillPath (p);
  62128. }
  62129. void Graphics::fillCheckerBoard (int x, int y,
  62130. int width, int height,
  62131. const int checkWidth,
  62132. const int checkHeight,
  62133. const Colour& colour1,
  62134. const Colour& colour2) const throw()
  62135. {
  62136. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  62137. if (checkWidth > 0 && checkHeight > 0)
  62138. {
  62139. if (colour1 == colour2)
  62140. {
  62141. context->fillRectWithColour (x, y, width, height, colour1, false);
  62142. }
  62143. else
  62144. {
  62145. const Rectangle clip (context->getClipBounds());
  62146. const int right = jmin (x + width, clip.getRight());
  62147. const int bottom = jmin (y + height, clip.getBottom());
  62148. int cy = 0;
  62149. while (y < bottom)
  62150. {
  62151. int cx = cy;
  62152. for (int xx = x; xx < right; xx += checkWidth)
  62153. context->fillRectWithColour (xx, y,
  62154. jmin (checkWidth, right - xx),
  62155. jmin (checkHeight, bottom - y),
  62156. ((cx++ & 1) == 0) ? colour1 : colour2,
  62157. false);
  62158. ++cy;
  62159. y += checkHeight;
  62160. }
  62161. }
  62162. }
  62163. }
  62164. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  62165. {
  62166. SolidColourBrush colourBrush (state->colour);
  62167. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  62168. }
  62169. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  62170. {
  62171. SolidColourBrush colourBrush (state->colour);
  62172. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  62173. }
  62174. void Graphics::drawLine (float x1, float y1,
  62175. float x2, float y2) const throw()
  62176. {
  62177. if (! context->isClipEmpty())
  62178. {
  62179. SolidColourBrush colourBrush (state->colour);
  62180. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  62181. }
  62182. }
  62183. void Graphics::drawLine (const float startX,
  62184. const float startY,
  62185. const float endX,
  62186. const float endY,
  62187. const float lineThickness) const throw()
  62188. {
  62189. Path p;
  62190. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  62191. fillPath (p);
  62192. }
  62193. void Graphics::drawLine (const Line& line) const throw()
  62194. {
  62195. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  62196. }
  62197. void Graphics::drawLine (const Line& line,
  62198. const float lineThickness) const throw()
  62199. {
  62200. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  62201. }
  62202. void Graphics::drawDashedLine (const float startX,
  62203. const float startY,
  62204. const float endX,
  62205. const float endY,
  62206. const float* const dashLengths,
  62207. const int numDashLengths,
  62208. const float lineThickness) const throw()
  62209. {
  62210. const double dx = endX - startX;
  62211. const double dy = endY - startY;
  62212. const double totalLen = juce_hypot (dx, dy);
  62213. if (totalLen >= 0.5)
  62214. {
  62215. const double onePixAlpha = 1.0 / totalLen;
  62216. double alpha = 0.0;
  62217. float x = startX;
  62218. float y = startY;
  62219. int n = 0;
  62220. while (alpha < 1.0f)
  62221. {
  62222. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  62223. n = n % numDashLengths;
  62224. const float oldX = x;
  62225. const float oldY = y;
  62226. x = (float) (startX + dx * alpha);
  62227. y = (float) (startY + dy * alpha);
  62228. if ((n & 1) != 0)
  62229. {
  62230. if (lineThickness != 1.0f)
  62231. drawLine (oldX, oldY, x, y, lineThickness);
  62232. else
  62233. drawLine (oldX, oldY, x, y);
  62234. }
  62235. }
  62236. }
  62237. }
  62238. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  62239. {
  62240. saveStateIfPending();
  62241. state->quality = newQuality;
  62242. }
  62243. void Graphics::drawImageAt (const Image* const imageToDraw,
  62244. const int topLeftX,
  62245. const int topLeftY,
  62246. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62247. {
  62248. if (imageToDraw != 0)
  62249. {
  62250. const int imageW = imageToDraw->getWidth();
  62251. const int imageH = imageToDraw->getHeight();
  62252. drawImage (imageToDraw,
  62253. topLeftX, topLeftY, imageW, imageH,
  62254. 0, 0, imageW, imageH,
  62255. fillAlphaChannelWithCurrentBrush);
  62256. }
  62257. }
  62258. void Graphics::drawImageWithin (const Image* const imageToDraw,
  62259. const int destX,
  62260. const int destY,
  62261. const int destW,
  62262. const int destH,
  62263. const RectanglePlacement& placementWithinTarget,
  62264. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62265. {
  62266. // passing in a silly number can cause maths problems in rendering!
  62267. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  62268. if (imageToDraw != 0)
  62269. {
  62270. const int imageW = imageToDraw->getWidth();
  62271. const int imageH = imageToDraw->getHeight();
  62272. if (imageW > 0 && imageH > 0)
  62273. {
  62274. double newX = 0.0, newY = 0.0;
  62275. double newW = imageW;
  62276. double newH = imageH;
  62277. placementWithinTarget.applyTo (newX, newY, newW, newH,
  62278. destX, destY, destW, destH);
  62279. if (newW > 0 && newH > 0)
  62280. {
  62281. drawImage (imageToDraw,
  62282. roundDoubleToInt (newX), roundDoubleToInt (newY),
  62283. roundDoubleToInt (newW), roundDoubleToInt (newH),
  62284. 0, 0, imageW, imageH,
  62285. fillAlphaChannelWithCurrentBrush);
  62286. }
  62287. }
  62288. }
  62289. }
  62290. void Graphics::drawImage (const Image* const imageToDraw,
  62291. int dx, int dy, int dw, int dh,
  62292. int sx, int sy, int sw, int sh,
  62293. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62294. {
  62295. // passing in a silly number can cause maths problems in rendering!
  62296. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  62297. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  62298. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  62299. return;
  62300. if (sw == dw && sh == dh)
  62301. {
  62302. if (sx < 0)
  62303. {
  62304. dx -= sx;
  62305. dw += sx;
  62306. sw += sx;
  62307. sx = 0;
  62308. }
  62309. if (sx + sw > imageToDraw->getWidth())
  62310. {
  62311. const int amount = sx + sw - imageToDraw->getWidth();
  62312. dw -= amount;
  62313. sw -= amount;
  62314. }
  62315. if (sy < 0)
  62316. {
  62317. dy -= sy;
  62318. dh += sy;
  62319. sh += sy;
  62320. sy = 0;
  62321. }
  62322. if (sy + sh > imageToDraw->getHeight())
  62323. {
  62324. const int amount = sy + sh - imageToDraw->getHeight();
  62325. dh -= amount;
  62326. sh -= amount;
  62327. }
  62328. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62329. return;
  62330. if (fillAlphaChannelWithCurrentBrush)
  62331. {
  62332. SolidColourBrush colourBrush (state->colour);
  62333. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62334. .paintAlphaChannel (*context, *imageToDraw,
  62335. dx - sx, dy - sy,
  62336. dx, dy,
  62337. dw, dh);
  62338. }
  62339. else
  62340. {
  62341. context->blendImage (*imageToDraw,
  62342. dx, dy, dw, dh, sx, sy,
  62343. state->colour.getFloatAlpha());
  62344. }
  62345. }
  62346. else
  62347. {
  62348. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62349. return;
  62350. if (fillAlphaChannelWithCurrentBrush)
  62351. {
  62352. if (imageToDraw->isRGB())
  62353. {
  62354. fillRect (dx, dy, dw, dh);
  62355. }
  62356. else
  62357. {
  62358. int tx = dx;
  62359. int ty = dy;
  62360. int tw = dw;
  62361. int th = dh;
  62362. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62363. {
  62364. Image temp (imageToDraw->getFormat(), tw, th, true);
  62365. Graphics g (temp);
  62366. g.setImageResamplingQuality (state->quality);
  62367. g.setOrigin (dx - tx, dy - ty);
  62368. g.drawImage (imageToDraw,
  62369. 0, 0, dw, dh,
  62370. sx, sy, sw, sh,
  62371. false);
  62372. SolidColourBrush colourBrush (state->colour);
  62373. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62374. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62375. }
  62376. }
  62377. }
  62378. else
  62379. {
  62380. context->blendImageRescaling (*imageToDraw,
  62381. dx, dy, dw, dh,
  62382. sx, sy, sw, sh,
  62383. state->colour.getFloatAlpha(),
  62384. state->quality);
  62385. }
  62386. }
  62387. }
  62388. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  62389. int sourceClipX,
  62390. int sourceClipY,
  62391. int sourceClipWidth,
  62392. int sourceClipHeight,
  62393. const AffineTransform& transform,
  62394. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62395. {
  62396. if (imageToDraw != 0
  62397. && (! context->isClipEmpty())
  62398. && ! transform.isSingularity())
  62399. {
  62400. if (transform.isIdentity())
  62401. {
  62402. drawImage (imageToDraw,
  62403. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62404. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62405. fillAlphaChannelWithCurrentBrush);
  62406. }
  62407. else if (fillAlphaChannelWithCurrentBrush)
  62408. {
  62409. Path p;
  62410. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  62411. (float) sourceClipWidth, (float) sourceClipHeight);
  62412. p.applyTransform (transform);
  62413. float dx, dy, dw, dh;
  62414. p.getBounds (dx, dy, dw, dh);
  62415. int tx = (int) dx;
  62416. int ty = (int) dy;
  62417. int tw = roundFloatToInt (dw) + 2;
  62418. int th = roundFloatToInt (dh) + 2;
  62419. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62420. {
  62421. Image temp (imageToDraw->getFormat(), tw, th, true);
  62422. Graphics g (temp);
  62423. g.setImageResamplingQuality (state->quality);
  62424. g.drawImageTransformed (imageToDraw,
  62425. sourceClipX,
  62426. sourceClipY,
  62427. sourceClipWidth,
  62428. sourceClipHeight,
  62429. transform.translated ((float) -tx, (float) -ty),
  62430. false);
  62431. SolidColourBrush colourBrush (state->colour);
  62432. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62433. }
  62434. }
  62435. else
  62436. {
  62437. context->blendImageWarping (*imageToDraw,
  62438. sourceClipX,
  62439. sourceClipY,
  62440. sourceClipWidth,
  62441. sourceClipHeight,
  62442. transform,
  62443. state->colour.getFloatAlpha(),
  62444. state->quality);
  62445. }
  62446. }
  62447. }
  62448. END_JUCE_NAMESPACE
  62449. /********* End of inlined file: juce_Graphics.cpp *********/
  62450. /********* Start of inlined file: juce_Justification.cpp *********/
  62451. BEGIN_JUCE_NAMESPACE
  62452. Justification::Justification (const Justification& other) throw()
  62453. : flags (other.flags)
  62454. {
  62455. }
  62456. const Justification& Justification::operator= (const Justification& other) throw()
  62457. {
  62458. flags = other.flags;
  62459. return *this;
  62460. }
  62461. int Justification::getOnlyVerticalFlags() const throw()
  62462. {
  62463. return flags & (top | bottom | verticallyCentred);
  62464. }
  62465. int Justification::getOnlyHorizontalFlags() const throw()
  62466. {
  62467. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  62468. }
  62469. void Justification::applyToRectangle (int& x, int& y,
  62470. const int w, const int h,
  62471. const int spaceX, const int spaceY,
  62472. const int spaceW, const int spaceH) const throw()
  62473. {
  62474. if ((flags & horizontallyCentred) != 0)
  62475. {
  62476. x = spaceX + ((spaceW - w) >> 1);
  62477. }
  62478. else if ((flags & right) != 0)
  62479. {
  62480. x = spaceX + spaceW - w;
  62481. }
  62482. else
  62483. {
  62484. x = spaceX;
  62485. }
  62486. if ((flags & verticallyCentred) != 0)
  62487. {
  62488. y = spaceY + ((spaceH - h) >> 1);
  62489. }
  62490. else if ((flags & bottom) != 0)
  62491. {
  62492. y = spaceY + spaceH - h;
  62493. }
  62494. else
  62495. {
  62496. y = spaceY;
  62497. }
  62498. }
  62499. END_JUCE_NAMESPACE
  62500. /********* End of inlined file: juce_Justification.cpp *********/
  62501. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62502. BEGIN_JUCE_NAMESPACE
  62503. #if JUCE_MSVC
  62504. #pragma warning (disable: 4996) // deprecated sprintf warning
  62505. #endif
  62506. // this will throw an assertion if you try to draw something that's not
  62507. // possible in postscript
  62508. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  62509. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  62510. #define notPossibleInPostscriptAssert jassertfalse
  62511. #else
  62512. #define notPossibleInPostscriptAssert
  62513. #endif
  62514. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  62515. const String& documentTitle,
  62516. const int totalWidth_,
  62517. const int totalHeight_)
  62518. : out (resultingPostScript),
  62519. totalWidth (totalWidth_),
  62520. totalHeight (totalHeight_),
  62521. xOffset (0),
  62522. yOffset (0),
  62523. needToClip (true)
  62524. {
  62525. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  62526. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  62527. out << "%!PS-Adobe-3.0 EPSF-3.0"
  62528. "\n%%BoundingBox: 0 0 600 824"
  62529. "\n%%Pages: 0"
  62530. "\n%%Creator: Raw Material Software JUCE"
  62531. "\n%%Title: " << documentTitle <<
  62532. "\n%%CreationDate: none"
  62533. "\n%%LanguageLevel: 2"
  62534. "\n%%EndComments"
  62535. "\n%%BeginProlog"
  62536. "\n%%BeginResource: JRes"
  62537. "\n/bd {bind def} bind def"
  62538. "\n/c {setrgbcolor} bd"
  62539. "\n/m {moveto} bd"
  62540. "\n/l {lineto} bd"
  62541. "\n/rl {rlineto} bd"
  62542. "\n/ct {curveto} bd"
  62543. "\n/cp {closepath} bd"
  62544. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  62545. "\n/doclip {initclip newpath} bd"
  62546. "\n/endclip {clip newpath} bd"
  62547. "\n%%EndResource"
  62548. "\n%%EndProlog"
  62549. "\n%%BeginSetup"
  62550. "\n%%EndSetup"
  62551. "\n%%Page: 1 1"
  62552. "\n%%BeginPageSetup"
  62553. "\n%%EndPageSetup\n\n"
  62554. << "40 800 translate\n"
  62555. << scale << ' ' << scale << " scale\n\n";
  62556. }
  62557. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  62558. {
  62559. delete clip;
  62560. }
  62561. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  62562. {
  62563. return true;
  62564. }
  62565. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  62566. {
  62567. if (x != 0 || y != 0)
  62568. {
  62569. xOffset += x;
  62570. yOffset += y;
  62571. needToClip = true;
  62572. }
  62573. }
  62574. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  62575. {
  62576. needToClip = true;
  62577. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62578. }
  62579. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62580. {
  62581. needToClip = true;
  62582. return clip->clipTo (clipRegion);
  62583. }
  62584. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  62585. {
  62586. needToClip = true;
  62587. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62588. }
  62589. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62590. {
  62591. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62592. }
  62593. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  62594. {
  62595. return clip->getBounds().translated (-xOffset, -yOffset);
  62596. }
  62597. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  62598. {
  62599. return clip->isEmpty();
  62600. }
  62601. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  62602. const int xOffset_, const int yOffset_)
  62603. : clip (clip_),
  62604. xOffset (xOffset_),
  62605. yOffset (yOffset_)
  62606. {
  62607. }
  62608. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  62609. {
  62610. delete clip;
  62611. }
  62612. void LowLevelGraphicsPostScriptRenderer::saveState()
  62613. {
  62614. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62615. }
  62616. void LowLevelGraphicsPostScriptRenderer::restoreState()
  62617. {
  62618. SavedState* const top = stateStack.getLast();
  62619. if (top != 0)
  62620. {
  62621. clip->swapWith (*top->clip);
  62622. xOffset = top->xOffset;
  62623. yOffset = top->yOffset;
  62624. stateStack.removeLast();
  62625. needToClip = true;
  62626. }
  62627. else
  62628. {
  62629. jassertfalse // trying to pop with an empty stack!
  62630. }
  62631. }
  62632. void LowLevelGraphicsPostScriptRenderer::writeClip()
  62633. {
  62634. if (needToClip)
  62635. {
  62636. needToClip = false;
  62637. out << "doclip ";
  62638. int itemsOnLine = 0;
  62639. for (RectangleList::Iterator i (*clip); i.next();)
  62640. {
  62641. if (++itemsOnLine == 6)
  62642. {
  62643. itemsOnLine = 0;
  62644. out << '\n';
  62645. }
  62646. const Rectangle& r = *i.getRectangle();
  62647. out << r.getX() << ' ' << -r.getY() << ' '
  62648. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  62649. }
  62650. out << "endclip\n";
  62651. }
  62652. }
  62653. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  62654. {
  62655. Colour c (Colours::white.overlaidWith (colour));
  62656. if (lastColour != c)
  62657. {
  62658. lastColour = c;
  62659. out << String (c.getFloatRed(), 3) << ' '
  62660. << String (c.getFloatGreen(), 3) << ' '
  62661. << String (c.getFloatBlue(), 3) << " c\n";
  62662. }
  62663. }
  62664. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  62665. {
  62666. out << String (x, 2) << ' '
  62667. << String (-y, 2) << ' ';
  62668. }
  62669. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  62670. {
  62671. out << "newpath ";
  62672. float lastX = 0.0f;
  62673. float lastY = 0.0f;
  62674. int itemsOnLine = 0;
  62675. Path::Iterator i (path);
  62676. while (i.next())
  62677. {
  62678. if (++itemsOnLine == 4)
  62679. {
  62680. itemsOnLine = 0;
  62681. out << '\n';
  62682. }
  62683. switch (i.elementType)
  62684. {
  62685. case Path::Iterator::startNewSubPath:
  62686. writeXY (i.x1, i.y1);
  62687. lastX = i.x1;
  62688. lastY = i.y1;
  62689. out << "m ";
  62690. break;
  62691. case Path::Iterator::lineTo:
  62692. writeXY (i.x1, i.y1);
  62693. lastX = i.x1;
  62694. lastY = i.y1;
  62695. out << "l ";
  62696. break;
  62697. case Path::Iterator::quadraticTo:
  62698. {
  62699. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  62700. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  62701. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  62702. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  62703. writeXY (cp1x, cp1y);
  62704. writeXY (cp2x, cp2y);
  62705. writeXY (i.x2, i.y2);
  62706. out << "ct ";
  62707. lastX = i.x2;
  62708. lastY = i.y2;
  62709. }
  62710. break;
  62711. case Path::Iterator::cubicTo:
  62712. writeXY (i.x1, i.y1);
  62713. writeXY (i.x2, i.y2);
  62714. writeXY (i.x3, i.y3);
  62715. out << "ct ";
  62716. lastX = i.x3;
  62717. lastY = i.y3;
  62718. break;
  62719. case Path::Iterator::closePath:
  62720. out << "cp ";
  62721. break;
  62722. default:
  62723. jassertfalse
  62724. break;
  62725. }
  62726. }
  62727. out << '\n';
  62728. }
  62729. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  62730. {
  62731. out << "[ "
  62732. << trans.mat00 << ' '
  62733. << trans.mat10 << ' '
  62734. << trans.mat01 << ' '
  62735. << trans.mat11 << ' '
  62736. << trans.mat02 << ' '
  62737. << trans.mat12 << " ] concat ";
  62738. }
  62739. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  62740. {
  62741. writeClip();
  62742. writeColour (colour);
  62743. x += xOffset;
  62744. y += yOffset;
  62745. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  62746. }
  62747. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62748. {
  62749. Path p;
  62750. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62751. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  62752. }
  62753. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62754. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  62755. {
  62756. writeClip();
  62757. Path p (path);
  62758. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62759. writePath (p);
  62760. writeColour (colour);
  62761. out << "fill\n";
  62762. }
  62763. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  62764. {
  62765. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  62766. // postscript can't do semi-transparent ones.
  62767. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62768. writeClip();
  62769. out << "gsave ";
  62770. {
  62771. Path p (path);
  62772. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62773. writePath (p);
  62774. out << "clip\n";
  62775. }
  62776. int numColours = 256;
  62777. PixelARGB* const colours = gradient.createLookupTable (numColours);
  62778. for (int i = numColours; --i >= 0;)
  62779. colours[i].unpremultiply();
  62780. const Rectangle bounds (clip->getBounds());
  62781. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  62782. // time-being, this just fills it with the average colour..
  62783. writeColour (Colour (colours [numColours / 2].getARGB()));
  62784. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  62785. juce_free (colours);
  62786. out << "grestore\n";
  62787. }
  62788. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62789. const Image& sourceImage,
  62790. int imageX, int imageY,
  62791. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  62792. {
  62793. writeClip();
  62794. out << "gsave ";
  62795. Path p (path);
  62796. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  62797. writePath (p);
  62798. out << "clip\n";
  62799. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  62800. out << "grestore\n";
  62801. }
  62802. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  62803. {
  62804. x += xOffset;
  62805. y += yOffset;
  62806. writeClip();
  62807. writeColour (colour);
  62808. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62809. }
  62810. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  62811. {
  62812. imageX += xOffset;
  62813. imageY += yOffset;
  62814. writeClip();
  62815. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62816. }
  62817. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  62818. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  62819. {
  62820. alphaImageX += xOffset;
  62821. alphaImageY += yOffset;
  62822. fillerImageX += xOffset;
  62823. fillerImageY += yOffset;
  62824. writeClip();
  62825. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62826. }
  62827. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  62828. int dx, int dy, int dw, int dh,
  62829. int sx, int sy, int sw, int sh,
  62830. float alpha,
  62831. const Graphics::ResamplingQuality quality)
  62832. {
  62833. if (sw > 0 && sh > 0)
  62834. {
  62835. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  62836. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  62837. if (sw == dw && sh == dh)
  62838. {
  62839. blendImage (sourceImage,
  62840. dx, dy, dw, dh,
  62841. sx, sy, alpha);
  62842. }
  62843. else
  62844. {
  62845. blendImageWarping (sourceImage,
  62846. sx, sy, sw, sh,
  62847. AffineTransform::scale (dw / (float) sw,
  62848. dh / (float) sh)
  62849. .translated ((float) (dx - sx),
  62850. (float) (dy - sy)),
  62851. alpha,
  62852. quality);
  62853. }
  62854. }
  62855. }
  62856. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62857. {
  62858. blendImageWarping (sourceImage,
  62859. sx, sy, dw, dh,
  62860. AffineTransform::translation ((float) dx, (float) dy),
  62861. opacity, Graphics::highResamplingQuality);
  62862. }
  62863. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  62864. const int sx, const int sy,
  62865. const int maxW, const int maxH) const
  62866. {
  62867. out << "{<\n";
  62868. const int w = jmin (maxW, im.getWidth());
  62869. const int h = jmin (maxH, im.getHeight());
  62870. int charsOnLine = 0;
  62871. int lineStride, pixelStride;
  62872. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  62873. Colour pixel;
  62874. for (int y = h; --y >= 0;)
  62875. {
  62876. for (int x = 0; x < w; ++x)
  62877. {
  62878. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  62879. if (x >= sx && y >= sy)
  62880. {
  62881. if (im.isARGB())
  62882. {
  62883. PixelARGB p (*(const PixelARGB*) pixelData);
  62884. p.unpremultiply();
  62885. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  62886. }
  62887. else if (im.isRGB())
  62888. {
  62889. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  62890. }
  62891. else
  62892. {
  62893. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  62894. }
  62895. }
  62896. else
  62897. {
  62898. pixel = Colours::transparentWhite;
  62899. }
  62900. char colourString [16];
  62901. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  62902. out << (const char*) colourString;
  62903. charsOnLine += 3;
  62904. if (charsOnLine > 100)
  62905. {
  62906. out << '\n';
  62907. charsOnLine = 0;
  62908. }
  62909. }
  62910. }
  62911. im.releasePixelDataReadOnly (data);
  62912. out << "\n>}\n";
  62913. }
  62914. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  62915. int srcClipX, int srcClipY,
  62916. int srcClipW, int srcClipH,
  62917. const AffineTransform& t,
  62918. float /*opacity*/,
  62919. const Graphics::ResamplingQuality /*quality*/)
  62920. {
  62921. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  62922. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  62923. writeClip();
  62924. out << "gsave ";
  62925. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  62926. .scaled (1.0f, -1.0f));
  62927. RectangleList imageClip;
  62928. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  62929. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  62930. out << "newpath ";
  62931. int itemsOnLine = 0;
  62932. for (RectangleList::Iterator i (imageClip); i.next();)
  62933. {
  62934. if (++itemsOnLine == 6)
  62935. {
  62936. out << '\n';
  62937. itemsOnLine = 0;
  62938. }
  62939. const Rectangle& r = *i.getRectangle();
  62940. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  62941. }
  62942. out << " clip newpath\n";
  62943. out << w << ' ' << h << " scale\n";
  62944. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  62945. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  62946. out << "false 3 colorimage grestore\n";
  62947. needToClip = true;
  62948. }
  62949. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62950. {
  62951. Path p;
  62952. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  62953. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  62954. }
  62955. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62956. {
  62957. drawLine (x, top, x, bottom, col);
  62958. }
  62959. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62960. {
  62961. drawLine (left, y, right, y, col);
  62962. }
  62963. END_JUCE_NAMESPACE
  62964. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62965. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62966. BEGIN_JUCE_NAMESPACE
  62967. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  62968. #define JUCE_USE_SSE_INSTRUCTIONS 1
  62969. #endif
  62970. #if JUCE_DEBUG && JUCE_MSVC
  62971. #pragma warning (disable: 4714)
  62972. #endif
  62973. #define MINIMUM_COORD -0x3fffffff
  62974. #define MAXIMUM_COORD 0x3fffffff
  62975. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  62976. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  62977. jassert ((int) x >= MINIMUM_COORD \
  62978. && (int) x <= MAXIMUM_COORD \
  62979. && (int) y >= MINIMUM_COORD \
  62980. && (int) y <= MAXIMUM_COORD \
  62981. && (int) w >= 0 \
  62982. && (int) w < MAXIMUM_COORD \
  62983. && (int) h >= 0 \
  62984. && (int) h < MAXIMUM_COORD);
  62985. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62986. {
  62987. const PixelARGB blendColour (colour.getPixelARGB());
  62988. if (w < 32)
  62989. {
  62990. while (--h >= 0)
  62991. {
  62992. PixelRGB* dest = (PixelRGB*) pixels;
  62993. for (int i = w; --i >= 0;)
  62994. (dest++)->set (blendColour);
  62995. pixels += stride;
  62996. }
  62997. }
  62998. else
  62999. {
  63000. // for wider fills, it's worth using some optimisations..
  63001. const uint8 r = blendColour.getRed();
  63002. const uint8 g = blendColour.getGreen();
  63003. const uint8 b = blendColour.getBlue();
  63004. if (r == g && r == b) // if all the component values are the same, we can cheat..
  63005. {
  63006. while (--h >= 0)
  63007. {
  63008. memset (pixels, r, w * 3);
  63009. pixels += stride;
  63010. }
  63011. }
  63012. else
  63013. {
  63014. PixelRGB filler [4];
  63015. filler[0].set (blendColour);
  63016. filler[1].set (blendColour);
  63017. filler[2].set (blendColour);
  63018. filler[3].set (blendColour);
  63019. const int* const intFiller = (const int*) filler;
  63020. while (--h >= 0)
  63021. {
  63022. uint8* dest = (uint8*) pixels;
  63023. int i = w;
  63024. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  63025. {
  63026. ((PixelRGB*) dest)->set (blendColour);
  63027. dest += 3;
  63028. --i;
  63029. }
  63030. while (i >= 4)
  63031. {
  63032. ((int*) dest) [0] = intFiller[0];
  63033. ((int*) dest) [1] = intFiller[1];
  63034. ((int*) dest) [2] = intFiller[2];
  63035. dest += 12;
  63036. i -= 4;
  63037. }
  63038. while (--i >= 0)
  63039. {
  63040. ((PixelRGB*) dest)->set (blendColour);
  63041. dest += 3;
  63042. }
  63043. pixels += stride;
  63044. }
  63045. }
  63046. }
  63047. }
  63048. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63049. {
  63050. const PixelARGB blendColour (colour.getPixelARGB());
  63051. while (--h >= 0)
  63052. {
  63053. PixelARGB* const dest = (PixelARGB*) pixels;
  63054. for (int i = 0; i < w; ++i)
  63055. dest[i] = blendColour;
  63056. pixels += stride;
  63057. }
  63058. }
  63059. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63060. {
  63061. if (colour.isOpaque())
  63062. {
  63063. replaceRectRGB (pixels, w, h, stride, colour);
  63064. }
  63065. else
  63066. {
  63067. const PixelARGB blendColour (colour.getPixelARGB());
  63068. const int alpha = blendColour.getAlpha();
  63069. if (alpha <= 0)
  63070. return;
  63071. #if JUCE_USE_SSE_INSTRUCTIONS
  63072. if (SystemStats::hasSSE())
  63073. {
  63074. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  63075. | (int64) ((blendColour.getGreen() << 16)
  63076. | blendColour.getBlue());
  63077. const int invAlpha = 0xff - alpha;
  63078. int64 aaaa = (invAlpha << 16) | invAlpha;
  63079. aaaa = (aaaa << 16) | aaaa;
  63080. #ifndef JUCE_GCC
  63081. __asm
  63082. {
  63083. movq mm1, aaaa
  63084. movq mm2, rgb0
  63085. pxor mm7, mm7
  63086. }
  63087. while (--h >= 0)
  63088. {
  63089. __asm
  63090. {
  63091. mov edx, pixels
  63092. mov ebx, w
  63093. pixloop:
  63094. prefetchnta [edx]
  63095. mov ax, [edx + 1]
  63096. shl eax, 8
  63097. mov al, [edx]
  63098. movd mm0, eax
  63099. punpcklbw mm0, mm7
  63100. pmullw mm0, mm1
  63101. psrlw mm0, 8
  63102. paddw mm0, mm2
  63103. packuswb mm0, mm7
  63104. movd eax, mm0
  63105. mov [edx], al
  63106. inc edx
  63107. shr eax, 8
  63108. mov [edx], ax
  63109. add edx, 2
  63110. dec ebx
  63111. jg pixloop
  63112. }
  63113. pixels += stride;
  63114. }
  63115. __asm emms
  63116. #else
  63117. __asm__ __volatile__ (
  63118. "\tpush %%ebx \n"
  63119. "\tmovq %[aaaa], %%mm1 \n"
  63120. "\tmovq %[rgb0], %%mm2 \n"
  63121. "\tpxor %%mm7, %%mm7 \n"
  63122. ".lineLoop2: \n"
  63123. "\tmovl %%esi,%%edx \n"
  63124. "\tmovl %[w], %%ebx \n"
  63125. ".pixLoop2: \n"
  63126. "\tprefetchnta (%%edx) \n"
  63127. "\tmov (%%edx), %%ax \n"
  63128. "\tshl $8, %%eax \n"
  63129. "\tmov 2(%%edx), %%al \n"
  63130. "\tmovd %%eax, %%mm0 \n"
  63131. "\tpunpcklbw %%mm7, %%mm0 \n"
  63132. "\tpmullw %%mm1, %%mm0 \n"
  63133. "\tpsrlw $8, %%mm0 \n"
  63134. "\tpaddw %%mm2, %%mm0 \n"
  63135. "\tpackuswb %%mm7, %%mm0 \n"
  63136. "\tmovd %%mm0, %%eax \n"
  63137. "\tmovb %%al, (%%edx) \n"
  63138. "\tinc %%edx \n"
  63139. "\tshr $8, %%eax \n"
  63140. "\tmovw %%ax, (%%edx) \n"
  63141. "\tadd $2, %%edx \n"
  63142. "\tdec %%ebx \n"
  63143. "\tjg .pixLoop2 \n"
  63144. "\tadd %%edi, %%esi \n"
  63145. "\tdec %%ecx \n"
  63146. "\tjg .lineLoop2 \n"
  63147. "\tpop %%ebx \n"
  63148. "\temms \n"
  63149. : /* No output registers */
  63150. : [aaaa] "m" (aaaa), /* Input registers */
  63151. [rgb0] "m" (rgb0),
  63152. [w] "m" (w),
  63153. "c" (h),
  63154. [stride] "D" (stride),
  63155. [pixels] "S" (pixels)
  63156. : "cc", "eax", "edx", "memory" /* Clobber list */
  63157. );
  63158. #endif
  63159. }
  63160. else
  63161. #endif
  63162. {
  63163. while (--h >= 0)
  63164. {
  63165. PixelRGB* dest = (PixelRGB*) pixels;
  63166. for (int i = w; --i >= 0;)
  63167. (dest++)->blend (blendColour);
  63168. pixels += stride;
  63169. }
  63170. }
  63171. }
  63172. }
  63173. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63174. {
  63175. if (colour.isOpaque())
  63176. {
  63177. replaceRectARGB (pixels, w, h, stride, colour);
  63178. }
  63179. else
  63180. {
  63181. const PixelARGB blendColour (colour.getPixelARGB());
  63182. const int alpha = blendColour.getAlpha();
  63183. if (alpha <= 0)
  63184. return;
  63185. while (--h >= 0)
  63186. {
  63187. PixelARGB* dest = (PixelARGB*) pixels;
  63188. for (int i = w; --i >= 0;)
  63189. (dest++)->blend (blendColour);
  63190. pixels += stride;
  63191. }
  63192. }
  63193. }
  63194. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  63195. const uint8* alphaValues, const int w, int h,
  63196. const int pixelStride, const int lineStride,
  63197. const Colour& colour) throw()
  63198. {
  63199. const PixelARGB srcPix (colour.getPixelARGB());
  63200. while (--h >= 0)
  63201. {
  63202. PixelARGB* dest = (PixelARGB*) destPixel;
  63203. const uint8* src = alphaValues;
  63204. int i = w;
  63205. while (--i >= 0)
  63206. {
  63207. unsigned int srcAlpha = *src;
  63208. src += pixelStride;
  63209. if (srcAlpha > 0)
  63210. dest->blend (srcPix, srcAlpha);
  63211. ++dest;
  63212. }
  63213. alphaValues += lineStride;
  63214. destPixel += imageStride;
  63215. }
  63216. }
  63217. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  63218. const uint8* alphaValues, int const width, int height,
  63219. const int pixelStride, const int lineStride,
  63220. const Colour& colour) throw()
  63221. {
  63222. const PixelARGB srcPix (colour.getPixelARGB());
  63223. while (--height >= 0)
  63224. {
  63225. PixelRGB* dest = (PixelRGB*) destPixel;
  63226. const uint8* src = alphaValues;
  63227. int i = width;
  63228. while (--i >= 0)
  63229. {
  63230. unsigned int srcAlpha = *src;
  63231. src += pixelStride;
  63232. if (srcAlpha > 0)
  63233. dest->blend (srcPix, srcAlpha);
  63234. ++dest;
  63235. }
  63236. alphaValues += lineStride;
  63237. destPixel += imageStride;
  63238. }
  63239. }
  63240. template <class PixelType>
  63241. class SolidColourEdgeTableRenderer
  63242. {
  63243. uint8* const data;
  63244. const int stride;
  63245. PixelType* linePixels;
  63246. PixelARGB sourceColour;
  63247. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  63248. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  63249. public:
  63250. SolidColourEdgeTableRenderer (uint8* const data_,
  63251. const int stride_,
  63252. const Colour& colour) throw()
  63253. : data (data_),
  63254. stride (stride_),
  63255. sourceColour (colour.getPixelARGB())
  63256. {
  63257. }
  63258. forcedinline void setEdgeTableYPos (const int y) throw()
  63259. {
  63260. linePixels = (PixelType*) (data + stride * y);
  63261. }
  63262. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63263. {
  63264. linePixels[x].blend (sourceColour, alphaLevel);
  63265. }
  63266. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63267. {
  63268. PixelARGB p (sourceColour);
  63269. p.multiplyAlpha (alphaLevel);
  63270. PixelType* dest = linePixels + x;
  63271. if (p.getAlpha() < 0xff)
  63272. {
  63273. do
  63274. {
  63275. dest->blend (p);
  63276. ++dest;
  63277. } while (--width > 0);
  63278. }
  63279. else
  63280. {
  63281. do
  63282. {
  63283. dest->set (p);
  63284. ++dest;
  63285. } while (--width > 0);
  63286. }
  63287. }
  63288. };
  63289. class AlphaBitmapRenderer
  63290. {
  63291. uint8* data;
  63292. int stride;
  63293. uint8* lineStart;
  63294. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  63295. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  63296. public:
  63297. AlphaBitmapRenderer (uint8* const data_,
  63298. const int stride_) throw()
  63299. : data (data_),
  63300. stride (stride_)
  63301. {
  63302. }
  63303. forcedinline void setEdgeTableYPos (const int y) throw()
  63304. {
  63305. lineStart = data + (stride * y);
  63306. }
  63307. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63308. {
  63309. lineStart [x] = (uint8) alphaLevel;
  63310. }
  63311. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63312. {
  63313. uint8* d = lineStart + x;
  63314. while (--width >= 0)
  63315. *d++ = (uint8) alphaLevel;
  63316. }
  63317. };
  63318. static const int numScaleBits = 12;
  63319. class LinearGradientPixelGenerator
  63320. {
  63321. const PixelARGB* const lookupTable;
  63322. const int numEntries;
  63323. PixelARGB linePix;
  63324. int start, scale;
  63325. double grad, yTerm;
  63326. bool vertical, horizontal;
  63327. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  63328. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  63329. public:
  63330. LinearGradientPixelGenerator (const ColourGradient& gradient,
  63331. const PixelARGB* const lookupTable_, const int numEntries_)
  63332. : lookupTable (lookupTable_),
  63333. numEntries (numEntries_)
  63334. {
  63335. jassert (numEntries_ >= 0);
  63336. float x1 = gradient.x1;
  63337. float y1 = gradient.y1;
  63338. float x2 = gradient.x2;
  63339. float y2 = gradient.y2;
  63340. if (! gradient.transform.isIdentity())
  63341. {
  63342. Line l (x2, y2, x1, y1);
  63343. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  63344. float x3 = p3.getX();
  63345. float y3 = p3.getY();
  63346. gradient.transform.transformPoint (x1, y1);
  63347. gradient.transform.transformPoint (x2, y2);
  63348. gradient.transform.transformPoint (x3, y3);
  63349. Line l2 (x2, y2, x3, y3);
  63350. float prop = l2.findNearestPointTo (x1, y1);
  63351. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  63352. x2 = newP2.getX();
  63353. y2 = newP2.getY();
  63354. }
  63355. vertical = fabs (x1 - x2) < 0.001f;
  63356. horizontal = fabs (y1 - y2) < 0.001f;
  63357. if (vertical)
  63358. {
  63359. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  63360. start = roundDoubleToInt (y1 * scale);
  63361. }
  63362. else if (horizontal)
  63363. {
  63364. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  63365. start = roundDoubleToInt (x1 * scale);
  63366. }
  63367. else
  63368. {
  63369. grad = (y2 - y1) / (double) (x1 - x2);
  63370. yTerm = y1 - x1 / grad;
  63371. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  63372. grad *= scale;
  63373. }
  63374. }
  63375. forcedinline void setY (const int y) throw()
  63376. {
  63377. if (vertical)
  63378. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  63379. else if (! horizontal)
  63380. start = roundDoubleToInt ((y - yTerm) * grad);
  63381. }
  63382. forcedinline const PixelARGB getPixel (const int x) const throw()
  63383. {
  63384. if (vertical)
  63385. return linePix;
  63386. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  63387. }
  63388. };
  63389. class RadialGradientPixelGenerator
  63390. {
  63391. protected:
  63392. const PixelARGB* const lookupTable;
  63393. const int numEntries;
  63394. const double gx1, gy1;
  63395. double maxDist, invScale;
  63396. double dy;
  63397. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  63398. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  63399. public:
  63400. RadialGradientPixelGenerator (const ColourGradient& gradient,
  63401. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63402. : lookupTable (lookupTable_),
  63403. numEntries (numEntries_),
  63404. gx1 (gradient.x1),
  63405. gy1 (gradient.y1)
  63406. {
  63407. jassert (numEntries_ >= 0);
  63408. const float dx = gradient.x1 - gradient.x2;
  63409. const float dy = gradient.y1 - gradient.y2;
  63410. maxDist = dx * dx + dy * dy;
  63411. invScale = (numEntries + 1) / sqrt (maxDist);
  63412. }
  63413. forcedinline void setY (const int y) throw()
  63414. {
  63415. dy = y - gy1;
  63416. dy *= dy;
  63417. }
  63418. forcedinline const PixelARGB getPixel (const int px) const throw()
  63419. {
  63420. double x = px - gx1;
  63421. x *= x;
  63422. x += dy;
  63423. if (x >= maxDist)
  63424. return lookupTable [numEntries];
  63425. else
  63426. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63427. }
  63428. };
  63429. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  63430. {
  63431. double tM10, tM00, lineYM01, lineYM11;
  63432. AffineTransform inverseTransform;
  63433. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  63434. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  63435. public:
  63436. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  63437. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63438. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  63439. inverseTransform (gradient.transform.inverted())
  63440. {
  63441. tM10 = inverseTransform.mat10;
  63442. tM00 = inverseTransform.mat00;
  63443. }
  63444. forcedinline void setY (const int y) throw()
  63445. {
  63446. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  63447. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  63448. }
  63449. forcedinline const PixelARGB getPixel (const int px) const throw()
  63450. {
  63451. double x = px;
  63452. const double y = tM10 * x + lineYM11;
  63453. x = tM00 * x + lineYM01;
  63454. x *= x;
  63455. x += y * y;
  63456. if (x >= maxDist)
  63457. return lookupTable [numEntries];
  63458. else
  63459. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63460. }
  63461. };
  63462. template <class PixelType, class GradientType>
  63463. class GradientEdgeTableRenderer : public GradientType
  63464. {
  63465. uint8* const data;
  63466. const int stride;
  63467. PixelType* linePixels;
  63468. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  63469. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  63470. public:
  63471. GradientEdgeTableRenderer (uint8* const data_,
  63472. const int stride_,
  63473. const ColourGradient& gradient,
  63474. const PixelARGB* const lookupTable, const int numEntries) throw()
  63475. : GradientType (gradient, lookupTable, numEntries - 1),
  63476. data (data_),
  63477. stride (stride_)
  63478. {
  63479. }
  63480. forcedinline void setEdgeTableYPos (const int y) throw()
  63481. {
  63482. linePixels = (PixelType*) (data + stride * y);
  63483. GradientType::setY (y);
  63484. }
  63485. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63486. {
  63487. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  63488. }
  63489. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  63490. {
  63491. PixelType* dest = linePixels + x;
  63492. if (alphaLevel < 0xff)
  63493. {
  63494. do
  63495. {
  63496. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  63497. } while (--width > 0);
  63498. }
  63499. else
  63500. {
  63501. do
  63502. {
  63503. (dest++)->blend (GradientType::getPixel (x++));
  63504. } while (--width > 0);
  63505. }
  63506. }
  63507. };
  63508. template <class DestPixelType, class SrcPixelType>
  63509. class ImageFillEdgeTableRenderer
  63510. {
  63511. uint8* const destImageData;
  63512. const uint8* srcImageData;
  63513. int stride, srcStride, extraAlpha;
  63514. DestPixelType* linePixels;
  63515. SrcPixelType* sourceLineStart;
  63516. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  63517. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  63518. public:
  63519. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  63520. const int stride_,
  63521. const uint8* srcImageData_,
  63522. const int srcStride_,
  63523. int extraAlpha_,
  63524. SrcPixelType*) throw() // dummy param to avoid compiler error
  63525. : destImageData (destImageData_),
  63526. srcImageData (srcImageData_),
  63527. stride (stride_),
  63528. srcStride (srcStride_),
  63529. extraAlpha (extraAlpha_)
  63530. {
  63531. }
  63532. forcedinline void setEdgeTableYPos (int y) throw()
  63533. {
  63534. linePixels = (DestPixelType*) (destImageData + stride * y);
  63535. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  63536. }
  63537. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  63538. {
  63539. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63540. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  63541. }
  63542. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  63543. {
  63544. DestPixelType* dest = linePixels + x;
  63545. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63546. if (alphaLevel < 0xfe)
  63547. {
  63548. do
  63549. {
  63550. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  63551. } while (--width > 0);
  63552. }
  63553. else
  63554. {
  63555. do
  63556. {
  63557. dest++ ->blend (sourceLineStart [x++]);
  63558. } while (--width > 0);
  63559. }
  63560. }
  63561. };
  63562. static void blendRowOfPixels (PixelARGB* dst,
  63563. const PixelRGB* src,
  63564. int width) throw()
  63565. {
  63566. while (--width >= 0)
  63567. (dst++)->set (*src++);
  63568. }
  63569. static void blendRowOfPixels (PixelRGB* dst,
  63570. const PixelRGB* src,
  63571. int width) throw()
  63572. {
  63573. memcpy (dst, src, 3 * width);
  63574. }
  63575. static void blendRowOfPixels (PixelRGB* dst,
  63576. const PixelARGB* src,
  63577. int width) throw()
  63578. {
  63579. while (--width >= 0)
  63580. (dst++)->blend (*src++);
  63581. }
  63582. static void blendRowOfPixels (PixelARGB* dst,
  63583. const PixelARGB* src,
  63584. int width) throw()
  63585. {
  63586. while (--width >= 0)
  63587. (dst++)->blend (*src++);
  63588. }
  63589. static void blendRowOfPixels (PixelARGB* dst,
  63590. const PixelRGB* src,
  63591. int width,
  63592. const uint8 alpha) throw()
  63593. {
  63594. while (--width >= 0)
  63595. (dst++)->blend (*src++, alpha);
  63596. }
  63597. static void blendRowOfPixels (PixelRGB* dst,
  63598. const PixelRGB* src,
  63599. int width,
  63600. const uint8 alpha) throw()
  63601. {
  63602. uint8* d = (uint8*) dst;
  63603. const uint8* s = (const uint8*) src;
  63604. const int inverseAlpha = 0xff - alpha;
  63605. while (--width >= 0)
  63606. {
  63607. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  63608. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  63609. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  63610. d += 3;
  63611. s += 3;
  63612. }
  63613. }
  63614. static void blendRowOfPixels (PixelRGB* dst,
  63615. const PixelARGB* src,
  63616. int width,
  63617. const uint8 alpha) throw()
  63618. {
  63619. while (--width >= 0)
  63620. (dst++)->blend (*src++, alpha);
  63621. }
  63622. static void blendRowOfPixels (PixelARGB* dst,
  63623. const PixelARGB* src,
  63624. int width,
  63625. const uint8 alpha) throw()
  63626. {
  63627. while (--width >= 0)
  63628. (dst++)->blend (*src++, alpha);
  63629. }
  63630. template <class DestPixelType, class SrcPixelType>
  63631. static void overlayImage (DestPixelType* dest,
  63632. const int destStride,
  63633. const SrcPixelType* src,
  63634. const int srcStride,
  63635. const int width,
  63636. int height,
  63637. const uint8 alpha) throw()
  63638. {
  63639. if (alpha < 0xff)
  63640. {
  63641. while (--height >= 0)
  63642. {
  63643. blendRowOfPixels (dest, src, width, alpha);
  63644. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63645. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63646. }
  63647. }
  63648. else
  63649. {
  63650. while (--height >= 0)
  63651. {
  63652. blendRowOfPixels (dest, src, width);
  63653. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63654. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63655. }
  63656. }
  63657. }
  63658. template <class DestPixelType, class SrcPixelType>
  63659. static void transformedImageRender (Image& destImage,
  63660. const Image& sourceImage,
  63661. const int destClipX, const int destClipY,
  63662. const int destClipW, const int destClipH,
  63663. const int srcClipX, const int srcClipY,
  63664. const int srcClipWidth, const int srcClipHeight,
  63665. double srcX, double srcY,
  63666. const double lineDX, const double lineDY,
  63667. const double pixelDX, const double pixelDY,
  63668. const uint8 alpha,
  63669. const Graphics::ResamplingQuality quality,
  63670. DestPixelType*,
  63671. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  63672. // parameters of the templated classes to
  63673. // make it use the correct instance of this function..
  63674. {
  63675. int destStride, destPixelStride;
  63676. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  63677. int srcStride, srcPixelStride;
  63678. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  63679. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  63680. {
  63681. if (alpha == 255)
  63682. {
  63683. for (int y = 0; y < destClipH; ++y)
  63684. {
  63685. double sx = srcX;
  63686. double sy = srcY;
  63687. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63688. for (int x = destClipW; --x >= 0;)
  63689. {
  63690. const int ix = ((int) sx) - srcClipX;
  63691. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63692. {
  63693. const int iy = ((int) sy) - srcClipY;
  63694. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63695. {
  63696. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63697. dest->set (*src);
  63698. }
  63699. }
  63700. ++dest;
  63701. sx += pixelDX;
  63702. sy += pixelDY;
  63703. }
  63704. srcX += lineDX;
  63705. srcY += lineDY;
  63706. }
  63707. }
  63708. else
  63709. {
  63710. for (int y = 0; y < destClipH; ++y)
  63711. {
  63712. double sx = srcX;
  63713. double sy = srcY;
  63714. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63715. for (int x = destClipW; --x >= 0;)
  63716. {
  63717. const int ix = ((int) sx) - srcClipX;
  63718. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63719. {
  63720. const int iy = ((int) sy) - srcClipY;
  63721. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63722. {
  63723. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63724. dest->blend (*src, alpha);
  63725. }
  63726. }
  63727. ++dest;
  63728. sx += pixelDX;
  63729. sy += pixelDY;
  63730. }
  63731. srcX += lineDX;
  63732. srcY += lineDY;
  63733. }
  63734. }
  63735. }
  63736. else
  63737. {
  63738. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  63739. for (int y = 0; y < destClipH; ++y)
  63740. {
  63741. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  63742. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  63743. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63744. for (int x = 0; x < destClipW; ++x)
  63745. {
  63746. const double fx = floor (sx);
  63747. const double fy = floor (sy);
  63748. const int ix = roundDoubleToInt (fx) - srcClipX;
  63749. const int iy = roundDoubleToInt (fy) - srcClipY;
  63750. if (ix < srcClipWidth && iy < srcClipHeight)
  63751. {
  63752. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  63753. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63754. if (iy >= 0)
  63755. {
  63756. if (ix >= 0)
  63757. p1.set (src[0]);
  63758. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63759. p2.set (src[1]);
  63760. }
  63761. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  63762. {
  63763. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63764. if (ix >= 0)
  63765. p3.set (src[0]);
  63766. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63767. p4.set (src[1]);
  63768. }
  63769. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  63770. p1.tween (p2, dx);
  63771. p3.tween (p4, dx);
  63772. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  63773. if (p1.getAlpha() > 0)
  63774. dest->blend (p1, alpha);
  63775. }
  63776. ++dest;
  63777. sx += pixelDX;
  63778. sy += pixelDY;
  63779. }
  63780. srcX += lineDX;
  63781. srcY += lineDY;
  63782. }
  63783. }
  63784. destImage.releasePixelDataReadWrite (destPixels);
  63785. sourceImage.releasePixelDataReadOnly (srcPixels);
  63786. }
  63787. template <class SrcPixelType, class DestPixelType>
  63788. static void renderAlphaMap (DestPixelType* destPixels,
  63789. int destStride,
  63790. SrcPixelType* srcPixels,
  63791. int srcStride,
  63792. const uint8* alphaValues,
  63793. const int lineStride, const int pixelStride,
  63794. int width, int height,
  63795. const int extraAlpha) throw()
  63796. {
  63797. while (--height >= 0)
  63798. {
  63799. SrcPixelType* srcPix = srcPixels;
  63800. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  63801. DestPixelType* destPix = destPixels;
  63802. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  63803. const uint8* alpha = alphaValues;
  63804. alphaValues += lineStride;
  63805. if (extraAlpha < 0x100)
  63806. {
  63807. for (int i = width; --i >= 0;)
  63808. {
  63809. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  63810. alpha += pixelStride;
  63811. }
  63812. }
  63813. else
  63814. {
  63815. for (int i = width; --i >= 0;)
  63816. {
  63817. destPix++ ->blend (*srcPix++, *alpha);
  63818. alpha += pixelStride;
  63819. }
  63820. }
  63821. }
  63822. }
  63823. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  63824. : image (image_),
  63825. xOffset (0),
  63826. yOffset (0),
  63827. stateStack (20)
  63828. {
  63829. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  63830. }
  63831. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  63832. {
  63833. delete clip;
  63834. }
  63835. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  63836. {
  63837. return false;
  63838. }
  63839. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  63840. {
  63841. xOffset += x;
  63842. yOffset += y;
  63843. }
  63844. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  63845. {
  63846. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  63847. }
  63848. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  63849. {
  63850. RectangleList temp (clipRegion);
  63851. temp.offsetAll (xOffset, yOffset);
  63852. return clip->clipTo (temp);
  63853. }
  63854. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  63855. {
  63856. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  63857. }
  63858. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  63859. {
  63860. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  63861. }
  63862. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  63863. {
  63864. return clip->getBounds().translated (-xOffset, -yOffset);
  63865. }
  63866. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  63867. {
  63868. return clip->isEmpty();
  63869. }
  63870. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  63871. const int xOffset_, const int yOffset_)
  63872. : clip (clip_),
  63873. xOffset (xOffset_),
  63874. yOffset (yOffset_)
  63875. {
  63876. }
  63877. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  63878. {
  63879. delete clip;
  63880. }
  63881. void LowLevelGraphicsSoftwareRenderer::saveState()
  63882. {
  63883. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  63884. }
  63885. void LowLevelGraphicsSoftwareRenderer::restoreState()
  63886. {
  63887. SavedState* const top = stateStack.getLast();
  63888. if (top != 0)
  63889. {
  63890. clip->swapWith (*top->clip);
  63891. xOffset = top->xOffset;
  63892. yOffset = top->yOffset;
  63893. stateStack.removeLast();
  63894. }
  63895. else
  63896. {
  63897. jassertfalse // trying to pop with an empty stack!
  63898. }
  63899. }
  63900. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63901. {
  63902. x += xOffset;
  63903. y += yOffset;
  63904. for (RectangleList::Iterator i (*clip); i.next();)
  63905. {
  63906. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  63907. }
  63908. }
  63909. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  63910. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63911. {
  63912. if (clipRect.intersectRectangle (x, y, w, h))
  63913. {
  63914. int stride, pixelStride;
  63915. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63916. if (image.getFormat() == Image::RGB)
  63917. {
  63918. if (replaceExistingContents)
  63919. replaceRectRGB (pixels, w, h, stride, colour);
  63920. else
  63921. blendRectRGB (pixels, w, h, stride, colour);
  63922. }
  63923. else if (image.getFormat() == Image::ARGB)
  63924. {
  63925. if (replaceExistingContents)
  63926. replaceRectARGB (pixels, w, h, stride, colour);
  63927. else
  63928. blendRectARGB (pixels, w, h, stride, colour);
  63929. }
  63930. else
  63931. {
  63932. jassertfalse // not done!
  63933. }
  63934. image.releasePixelDataReadWrite (pixels);
  63935. }
  63936. }
  63937. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  63938. {
  63939. Path p;
  63940. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  63941. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  63942. }
  63943. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  63944. const Path& path, const AffineTransform& transform,
  63945. int& x, int& y, int& w, int& h) const
  63946. {
  63947. float tx, ty, tw, th;
  63948. path.getBoundsTransformed (transform, tx, ty, tw, th);
  63949. x = roundDoubleToInt (tx) - 1;
  63950. y = roundDoubleToInt (ty) - 1;
  63951. w = roundDoubleToInt (tw) + 2;
  63952. h = roundDoubleToInt (th) + 2;
  63953. // seems like this operation is using some crazy out-of-range numbers..
  63954. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  63955. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  63956. }
  63957. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  63958. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63959. {
  63960. for (RectangleList::Iterator i (*clip); i.next();)
  63961. {
  63962. const Rectangle& r = *i.getRectangle();
  63963. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  63964. }
  63965. }
  63966. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63967. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63968. {
  63969. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63970. int cx, cy, cw, ch;
  63971. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63972. {
  63973. EdgeTable edgeTable (0, ch, quality);
  63974. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63975. int stride, pixelStride;
  63976. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63977. if (image.getFormat() == Image::RGB)
  63978. {
  63979. jassert (pixelStride == 3);
  63980. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  63981. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63982. }
  63983. else if (image.getFormat() == Image::ARGB)
  63984. {
  63985. jassert (pixelStride == 4);
  63986. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  63987. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63988. }
  63989. else if (image.getFormat() == Image::SingleChannel)
  63990. {
  63991. jassert (pixelStride == 1);
  63992. AlphaBitmapRenderer renderer (pixels, stride);
  63993. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63994. }
  63995. image.releasePixelDataReadWrite (pixels);
  63996. }
  63997. }
  63998. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63999. {
  64000. for (RectangleList::Iterator i (*clip); i.next();)
  64001. {
  64002. const Rectangle& r = *i.getRectangle();
  64003. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64004. path, t, gradient, quality);
  64005. }
  64006. }
  64007. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  64008. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  64009. {
  64010. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64011. int cx, cy, cw, ch;
  64012. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  64013. {
  64014. int stride, pixelStride;
  64015. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  64016. ColourGradient g2 (gradient);
  64017. const bool isIdentity = g2.transform.isIdentity();
  64018. if (isIdentity)
  64019. {
  64020. g2.x1 += xOffset - cx;
  64021. g2.x2 += xOffset - cx;
  64022. g2.y1 += yOffset - cy;
  64023. g2.y2 += yOffset - cy;
  64024. }
  64025. else
  64026. {
  64027. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  64028. (float) (yOffset - cy));
  64029. }
  64030. int numLookupEntries;
  64031. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  64032. jassert (numLookupEntries > 0);
  64033. EdgeTable edgeTable (0, ch, quality);
  64034. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  64035. if (image.getFormat() == Image::RGB)
  64036. {
  64037. jassert (pixelStride == 3);
  64038. if (g2.isRadial)
  64039. {
  64040. if (isIdentity)
  64041. {
  64042. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64043. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64044. }
  64045. else
  64046. {
  64047. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64048. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64049. }
  64050. }
  64051. else
  64052. {
  64053. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64054. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64055. }
  64056. }
  64057. else if (image.getFormat() == Image::ARGB)
  64058. {
  64059. jassert (pixelStride == 4);
  64060. if (g2.isRadial)
  64061. {
  64062. if (isIdentity)
  64063. {
  64064. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64065. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64066. }
  64067. else
  64068. {
  64069. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64070. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64071. }
  64072. }
  64073. else
  64074. {
  64075. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64076. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64077. }
  64078. }
  64079. else if (image.getFormat() == Image::SingleChannel)
  64080. {
  64081. jassertfalse // not done!
  64082. }
  64083. juce_free (lookupTable);
  64084. image.releasePixelDataReadWrite (pixels);
  64085. }
  64086. }
  64087. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  64088. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  64089. {
  64090. imageX += xOffset;
  64091. imageY += yOffset;
  64092. for (RectangleList::Iterator i (*clip); i.next();)
  64093. {
  64094. const Rectangle& r = *i.getRectangle();
  64095. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64096. path, transform, sourceImage, imageX, imageY, opacity, quality);
  64097. }
  64098. }
  64099. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  64100. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  64101. {
  64102. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  64103. {
  64104. EdgeTable edgeTable (0, h, quality);
  64105. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  64106. int stride, pixelStride;
  64107. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64108. int srcStride, srcPixelStride;
  64109. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  64110. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  64111. if (image.getFormat() == Image::RGB)
  64112. {
  64113. if (sourceImage.getFormat() == Image::RGB)
  64114. {
  64115. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  64116. srcPix, srcStride,
  64117. alpha, (PixelRGB*) 0);
  64118. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64119. }
  64120. else if (sourceImage.getFormat() == Image::ARGB)
  64121. {
  64122. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  64123. srcPix, srcStride,
  64124. alpha, (PixelARGB*) 0);
  64125. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64126. }
  64127. else
  64128. {
  64129. jassertfalse // not done!
  64130. }
  64131. }
  64132. else if (image.getFormat() == Image::ARGB)
  64133. {
  64134. if (sourceImage.getFormat() == Image::RGB)
  64135. {
  64136. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  64137. srcPix, srcStride,
  64138. alpha, (PixelRGB*) 0);
  64139. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64140. }
  64141. else if (sourceImage.getFormat() == Image::ARGB)
  64142. {
  64143. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  64144. srcPix, srcStride,
  64145. alpha, (PixelARGB*) 0);
  64146. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64147. }
  64148. else
  64149. {
  64150. jassertfalse // not done!
  64151. }
  64152. }
  64153. else
  64154. {
  64155. jassertfalse // not done!
  64156. }
  64157. sourceImage.releasePixelDataReadOnly (srcPix);
  64158. image.releasePixelDataReadWrite (pixels);
  64159. }
  64160. }
  64161. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  64162. {
  64163. x += xOffset;
  64164. y += yOffset;
  64165. for (RectangleList::Iterator i (*clip); i.next();)
  64166. {
  64167. const Rectangle& r = *i.getRectangle();
  64168. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64169. clipImage, x, y, colour);
  64170. }
  64171. }
  64172. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  64173. {
  64174. int w = clipImage.getWidth();
  64175. int h = clipImage.getHeight();
  64176. int sx = 0;
  64177. int sy = 0;
  64178. if (x < clipX)
  64179. {
  64180. sx = clipX - x;
  64181. w -= clipX - x;
  64182. x = clipX;
  64183. }
  64184. if (y < clipY)
  64185. {
  64186. sy = clipY - y;
  64187. h -= clipY - y;
  64188. y = clipY;
  64189. }
  64190. if (x + w > clipX + clipW)
  64191. w = clipX + clipW - x;
  64192. if (y + h > clipY + clipH)
  64193. h = clipY + clipH - y;
  64194. if (w > 0 && h > 0)
  64195. {
  64196. int stride, alphaStride, pixelStride;
  64197. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64198. const uint8* const alphaValues
  64199. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  64200. #if JUCE_BIG_ENDIAN
  64201. const uint8* const alphas = alphaValues;
  64202. #else
  64203. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  64204. #endif
  64205. if (image.getFormat() == Image::RGB)
  64206. {
  64207. blendAlphaMapRGB (pixels, stride,
  64208. alphas, w, h,
  64209. pixelStride, alphaStride,
  64210. colour);
  64211. }
  64212. else if (image.getFormat() == Image::ARGB)
  64213. {
  64214. blendAlphaMapARGB (pixels, stride,
  64215. alphas, w, h,
  64216. pixelStride, alphaStride,
  64217. colour);
  64218. }
  64219. else
  64220. {
  64221. jassertfalse // not done!
  64222. }
  64223. clipImage.releasePixelDataReadOnly (alphaValues);
  64224. image.releasePixelDataReadWrite (pixels);
  64225. }
  64226. }
  64227. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  64228. {
  64229. imageX += xOffset;
  64230. imageY += yOffset;
  64231. for (RectangleList::Iterator i (*clip); i.next();)
  64232. {
  64233. const Rectangle& r = *i.getRectangle();
  64234. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64235. alphaChannelImage, imageX, imageY, gradient);
  64236. }
  64237. }
  64238. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  64239. const Image& alphaChannelImage,
  64240. int imageX, int imageY, const ColourGradient& gradient)
  64241. {
  64242. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  64243. {
  64244. ColourGradient g2 (gradient);
  64245. g2.x1 += xOffset - x;
  64246. g2.x2 += xOffset - x;
  64247. g2.y1 += yOffset - y;
  64248. g2.y2 += yOffset - y;
  64249. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  64250. LowLevelGraphicsSoftwareRenderer tempG (temp);
  64251. tempG.fillRectWithGradient (0, 0, w, h, g2);
  64252. clippedFillAlphaChannelWithImage (x, y, w, h,
  64253. alphaChannelImage, imageX, imageY,
  64254. temp, x, y, 1.0f);
  64255. }
  64256. }
  64257. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  64258. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64259. {
  64260. alphaImageX += xOffset;
  64261. alphaImageY += yOffset;
  64262. fillerImageX += xOffset;
  64263. fillerImageY += yOffset;
  64264. for (RectangleList::Iterator i (*clip); i.next();)
  64265. {
  64266. const Rectangle& r = *i.getRectangle();
  64267. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64268. alphaImage, alphaImageX, alphaImageY,
  64269. fillerImage, fillerImageX, fillerImageY, opacity);
  64270. }
  64271. }
  64272. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  64273. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64274. {
  64275. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  64276. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  64277. {
  64278. int dstStride, dstPixStride;
  64279. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  64280. int srcStride, srcPixStride;
  64281. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  64282. int maskStride, maskPixStride;
  64283. const uint8* const alpha
  64284. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  64285. #if JUCE_BIG_ENDIAN
  64286. const uint8* const alphaValues = alpha;
  64287. #else
  64288. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  64289. #endif
  64290. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  64291. if (image.getFormat() == Image::RGB)
  64292. {
  64293. if (fillerImage.getFormat() == Image::RGB)
  64294. {
  64295. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64296. }
  64297. else if (fillerImage.getFormat() == Image::ARGB)
  64298. {
  64299. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64300. }
  64301. else
  64302. {
  64303. jassertfalse // not done!
  64304. }
  64305. }
  64306. else if (image.getFormat() == Image::ARGB)
  64307. {
  64308. if (fillerImage.getFormat() == Image::RGB)
  64309. {
  64310. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64311. }
  64312. else if (fillerImage.getFormat() == Image::ARGB)
  64313. {
  64314. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64315. }
  64316. else
  64317. {
  64318. jassertfalse // not done!
  64319. }
  64320. }
  64321. else
  64322. {
  64323. jassertfalse // not done!
  64324. }
  64325. alphaImage.releasePixelDataReadOnly (alphaValues);
  64326. fillerImage.releasePixelDataReadOnly (srcPix);
  64327. image.releasePixelDataReadWrite (dstPix);
  64328. }
  64329. }
  64330. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64331. {
  64332. dx += xOffset;
  64333. dy += yOffset;
  64334. for (RectangleList::Iterator i (*clip); i.next();)
  64335. {
  64336. const Rectangle& r = *i.getRectangle();
  64337. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64338. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  64339. }
  64340. }
  64341. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  64342. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64343. {
  64344. if (dx < clipX)
  64345. {
  64346. sx += clipX - dx;
  64347. dw -= clipX - dx;
  64348. dx = clipX;
  64349. }
  64350. if (dy < clipY)
  64351. {
  64352. sy += clipY - dy;
  64353. dh -= clipY - dy;
  64354. dy = clipY;
  64355. }
  64356. if (dx + dw > clipX + clipW)
  64357. dw = clipX + clipW - dx;
  64358. if (dy + dh > clipY + clipH)
  64359. dh = clipY + clipH - dy;
  64360. if (dw <= 0 || dh <= 0)
  64361. return;
  64362. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64363. if (alpha == 0)
  64364. return;
  64365. int dstStride, dstPixelStride;
  64366. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  64367. int srcStride, srcPixelStride;
  64368. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  64369. if (image.getFormat() == Image::ARGB)
  64370. {
  64371. if (sourceImage.getFormat() == Image::ARGB)
  64372. {
  64373. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64374. (PixelARGB*) srcPixels, srcStride,
  64375. dw, dh, alpha);
  64376. }
  64377. else if (sourceImage.getFormat() == Image::RGB)
  64378. {
  64379. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64380. (PixelRGB*) srcPixels, srcStride,
  64381. dw, dh, alpha);
  64382. }
  64383. else
  64384. {
  64385. jassertfalse
  64386. }
  64387. }
  64388. else if (image.getFormat() == Image::RGB)
  64389. {
  64390. if (sourceImage.getFormat() == Image::ARGB)
  64391. {
  64392. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64393. (PixelARGB*) srcPixels, srcStride,
  64394. dw, dh, alpha);
  64395. }
  64396. else if (sourceImage.getFormat() == Image::RGB)
  64397. {
  64398. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64399. (PixelRGB*) srcPixels, srcStride,
  64400. dw, dh, alpha);
  64401. }
  64402. else
  64403. {
  64404. jassertfalse
  64405. }
  64406. }
  64407. else
  64408. {
  64409. jassertfalse
  64410. }
  64411. image.releasePixelDataReadWrite (dstPixels);
  64412. sourceImage.releasePixelDataReadOnly (srcPixels);
  64413. }
  64414. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  64415. int dx, int dy, int dw, int dh,
  64416. int sx, int sy, int sw, int sh,
  64417. float alpha,
  64418. const Graphics::ResamplingQuality quality)
  64419. {
  64420. if (sw > 0 && sh > 0)
  64421. {
  64422. if (sw == dw && sh == dh)
  64423. {
  64424. blendImage (sourceImage,
  64425. dx, dy, dw, dh,
  64426. sx, sy, alpha);
  64427. }
  64428. else
  64429. {
  64430. blendImageWarping (sourceImage,
  64431. sx, sy, sw, sh,
  64432. AffineTransform::translation ((float) -sx,
  64433. (float) -sy)
  64434. .scaled (dw / (float) sw,
  64435. dh / (float) sh)
  64436. .translated ((float) dx,
  64437. (float) dy),
  64438. alpha,
  64439. quality);
  64440. }
  64441. }
  64442. }
  64443. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  64444. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64445. const AffineTransform& t,
  64446. float opacity,
  64447. const Graphics::ResamplingQuality quality)
  64448. {
  64449. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64450. for (RectangleList::Iterator i (*clip); i.next();)
  64451. {
  64452. const Rectangle& r = *i.getRectangle();
  64453. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64454. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  64455. transform, opacity, quality);
  64456. }
  64457. }
  64458. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  64459. const Image& sourceImage,
  64460. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64461. const AffineTransform& transform,
  64462. float opacity,
  64463. const Graphics::ResamplingQuality quality)
  64464. {
  64465. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  64466. {
  64467. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  64468. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  64469. if (srcClipW <= 0 || srcClipH <= 0)
  64470. return;
  64471. jassert (srcClipX >= 0 && srcClipY >= 0);
  64472. Path imageBounds;
  64473. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  64474. imageBounds.applyTransform (transform);
  64475. float imX, imY, imW, imH;
  64476. imageBounds.getBounds (imX, imY, imW, imH);
  64477. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  64478. (int) floorf (imX),
  64479. (int) floorf (imY),
  64480. 1 + roundDoubleToInt (imW),
  64481. 1 + roundDoubleToInt (imH)))
  64482. {
  64483. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64484. float srcX1 = (float) destClipX;
  64485. float srcY1 = (float) destClipY;
  64486. float srcX2 = (float) (destClipX + destClipW);
  64487. float srcY2 = srcY1;
  64488. float srcX3 = srcX1;
  64489. float srcY3 = (float) (destClipY + destClipH);
  64490. AffineTransform inverse (transform.inverted());
  64491. inverse.transformPoint (srcX1, srcY1);
  64492. inverse.transformPoint (srcX2, srcY2);
  64493. inverse.transformPoint (srcX3, srcY3);
  64494. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  64495. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  64496. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  64497. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  64498. if (image.getFormat() == Image::ARGB)
  64499. {
  64500. if (sourceImage.getFormat() == Image::ARGB)
  64501. {
  64502. transformedImageRender (image, sourceImage,
  64503. destClipX, destClipY, destClipW, destClipH,
  64504. srcClipX, srcClipY, srcClipW, srcClipH,
  64505. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64506. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  64507. }
  64508. else if (sourceImage.getFormat() == Image::RGB)
  64509. {
  64510. transformedImageRender (image, sourceImage,
  64511. destClipX, destClipY, destClipW, destClipH,
  64512. srcClipX, srcClipY, srcClipW, srcClipH,
  64513. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64514. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  64515. }
  64516. else
  64517. {
  64518. jassertfalse
  64519. }
  64520. }
  64521. else if (image.getFormat() == Image::RGB)
  64522. {
  64523. if (sourceImage.getFormat() == Image::ARGB)
  64524. {
  64525. transformedImageRender (image, sourceImage,
  64526. destClipX, destClipY, destClipW, destClipH,
  64527. srcClipX, srcClipY, srcClipW, srcClipH,
  64528. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64529. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  64530. }
  64531. else if (sourceImage.getFormat() == Image::RGB)
  64532. {
  64533. transformedImageRender (image, sourceImage,
  64534. destClipX, destClipY, destClipW, destClipH,
  64535. srcClipX, srcClipY, srcClipW, srcClipH,
  64536. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64537. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  64538. }
  64539. else
  64540. {
  64541. jassertfalse
  64542. }
  64543. }
  64544. else
  64545. {
  64546. jassertfalse
  64547. }
  64548. }
  64549. }
  64550. }
  64551. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  64552. {
  64553. x1 += xOffset;
  64554. y1 += yOffset;
  64555. x2 += xOffset;
  64556. y2 += yOffset;
  64557. for (RectangleList::Iterator i (*clip); i.next();)
  64558. {
  64559. const Rectangle& r = *i.getRectangle();
  64560. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64561. x1, y1, x2, y2, colour);
  64562. }
  64563. }
  64564. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  64565. {
  64566. if (clipW > 0 && clipH > 0)
  64567. {
  64568. if (x1 == x2)
  64569. {
  64570. if (y2 < y1)
  64571. swapVariables (y1, y2);
  64572. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  64573. }
  64574. else if (y1 == y2)
  64575. {
  64576. if (x2 < x1)
  64577. swapVariables (x1, x2);
  64578. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  64579. }
  64580. else
  64581. {
  64582. double gradient = (y2 - y1) / (x2 - x1);
  64583. if (fabs (gradient) > 1.0)
  64584. {
  64585. gradient = 1.0 / gradient;
  64586. int y = roundDoubleToInt (y1);
  64587. const int startY = y;
  64588. int endY = roundDoubleToInt (y2);
  64589. if (y > endY)
  64590. swapVariables (y, endY);
  64591. while (y < endY)
  64592. {
  64593. const double x = x1 + gradient * (y - startY);
  64594. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  64595. ++y;
  64596. }
  64597. }
  64598. else
  64599. {
  64600. int x = roundDoubleToInt (x1);
  64601. const int startX = x;
  64602. int endX = roundDoubleToInt (x2);
  64603. if (x > endX)
  64604. swapVariables (x, endX);
  64605. while (x < endX)
  64606. {
  64607. const double y = y1 + gradient * (x - startX);
  64608. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  64609. ++x;
  64610. }
  64611. }
  64612. }
  64613. }
  64614. }
  64615. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  64616. {
  64617. for (RectangleList::Iterator i (*clip); i.next();)
  64618. {
  64619. const Rectangle& r = *i.getRectangle();
  64620. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64621. x + xOffset, top + yOffset, bottom + yOffset, col);
  64622. }
  64623. }
  64624. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  64625. const int x, double top, double bottom, const Colour& col)
  64626. {
  64627. jassert (top <= bottom);
  64628. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  64629. && top < clipY + clipH
  64630. && bottom > clipY
  64631. && clipW > 0)
  64632. {
  64633. if (top < clipY)
  64634. top = clipY;
  64635. if (bottom > clipY + clipH)
  64636. bottom = clipY + clipH;
  64637. if (bottom > top)
  64638. drawVertical (x, top, bottom, col);
  64639. }
  64640. }
  64641. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  64642. {
  64643. for (RectangleList::Iterator i (*clip); i.next();)
  64644. {
  64645. const Rectangle& r = *i.getRectangle();
  64646. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64647. y + yOffset, left + xOffset, right + xOffset, col);
  64648. }
  64649. }
  64650. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  64651. const int y, double left, double right, const Colour& col)
  64652. {
  64653. jassert (left <= right);
  64654. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  64655. && left < clipX + clipW
  64656. && right > clipX
  64657. && clipW > 0)
  64658. {
  64659. if (left < clipX)
  64660. left = clipX;
  64661. if (right > clipX + clipW)
  64662. right = clipX + clipW;
  64663. if (right > left)
  64664. drawHorizontal (y, left, right, col);
  64665. }
  64666. }
  64667. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  64668. const double top,
  64669. const double bottom,
  64670. const Colour& col)
  64671. {
  64672. int wholeStart = (int) top;
  64673. const int wholeEnd = (int) bottom;
  64674. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64675. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64676. if (totalPixels <= 0)
  64677. return;
  64678. int lineStride, dstPixelStride;
  64679. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  64680. uint8* dest = dstPixels;
  64681. PixelARGB colour (col.getPixelARGB());
  64682. if (wholeEnd == wholeStart)
  64683. {
  64684. if (image.getFormat() == Image::ARGB)
  64685. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64686. else if (image.getFormat() == Image::RGB)
  64687. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64688. else
  64689. {
  64690. jassertfalse
  64691. }
  64692. }
  64693. else
  64694. {
  64695. if (image.getFormat() == Image::ARGB)
  64696. {
  64697. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64698. ++wholeStart;
  64699. dest += lineStride;
  64700. if (colour.getAlpha() == 0xff)
  64701. {
  64702. while (wholeEnd > wholeStart)
  64703. {
  64704. ((PixelARGB*) dest)->set (colour);
  64705. ++wholeStart;
  64706. dest += lineStride;
  64707. }
  64708. }
  64709. else
  64710. {
  64711. while (wholeEnd > wholeStart)
  64712. {
  64713. ((PixelARGB*) dest)->blend (colour);
  64714. ++wholeStart;
  64715. dest += lineStride;
  64716. }
  64717. }
  64718. if (lastAlpha > 0)
  64719. {
  64720. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64721. }
  64722. }
  64723. else if (image.getFormat() == Image::RGB)
  64724. {
  64725. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64726. ++wholeStart;
  64727. dest += lineStride;
  64728. if (colour.getAlpha() == 0xff)
  64729. {
  64730. while (wholeEnd > wholeStart)
  64731. {
  64732. ((PixelRGB*) dest)->set (colour);
  64733. ++wholeStart;
  64734. dest += lineStride;
  64735. }
  64736. }
  64737. else
  64738. {
  64739. while (wholeEnd > wholeStart)
  64740. {
  64741. ((PixelRGB*) dest)->blend (colour);
  64742. ++wholeStart;
  64743. dest += lineStride;
  64744. }
  64745. }
  64746. if (lastAlpha > 0)
  64747. {
  64748. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64749. }
  64750. }
  64751. else
  64752. {
  64753. jassertfalse
  64754. }
  64755. }
  64756. image.releasePixelDataReadWrite (dstPixels);
  64757. }
  64758. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  64759. const double top,
  64760. const double bottom,
  64761. const Colour& col)
  64762. {
  64763. int wholeStart = (int) top;
  64764. const int wholeEnd = (int) bottom;
  64765. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64766. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64767. if (totalPixels <= 0)
  64768. return;
  64769. int lineStride, dstPixelStride;
  64770. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  64771. uint8* dest = dstPixels;
  64772. PixelARGB colour (col.getPixelARGB());
  64773. if (wholeEnd == wholeStart)
  64774. {
  64775. if (image.getFormat() == Image::ARGB)
  64776. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64777. else if (image.getFormat() == Image::RGB)
  64778. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64779. else
  64780. {
  64781. jassertfalse
  64782. }
  64783. }
  64784. else
  64785. {
  64786. if (image.getFormat() == Image::ARGB)
  64787. {
  64788. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64789. dest += dstPixelStride;
  64790. ++wholeStart;
  64791. if (colour.getAlpha() == 0xff)
  64792. {
  64793. while (wholeEnd > wholeStart)
  64794. {
  64795. ((PixelARGB*) dest)->set (colour);
  64796. dest += dstPixelStride;
  64797. ++wholeStart;
  64798. }
  64799. }
  64800. else
  64801. {
  64802. while (wholeEnd > wholeStart)
  64803. {
  64804. ((PixelARGB*) dest)->blend (colour);
  64805. dest += dstPixelStride;
  64806. ++wholeStart;
  64807. }
  64808. }
  64809. if (lastAlpha > 0)
  64810. {
  64811. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64812. }
  64813. }
  64814. else if (image.getFormat() == Image::RGB)
  64815. {
  64816. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64817. dest += dstPixelStride;
  64818. ++wholeStart;
  64819. if (colour.getAlpha() == 0xff)
  64820. {
  64821. while (wholeEnd > wholeStart)
  64822. {
  64823. ((PixelRGB*) dest)->set (colour);
  64824. dest += dstPixelStride;
  64825. ++wholeStart;
  64826. }
  64827. }
  64828. else
  64829. {
  64830. while (wholeEnd > wholeStart)
  64831. {
  64832. ((PixelRGB*) dest)->blend (colour);
  64833. dest += dstPixelStride;
  64834. ++wholeStart;
  64835. }
  64836. }
  64837. if (lastAlpha > 0)
  64838. {
  64839. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64840. }
  64841. }
  64842. else
  64843. {
  64844. jassertfalse
  64845. }
  64846. }
  64847. image.releasePixelDataReadWrite (dstPixels);
  64848. }
  64849. END_JUCE_NAMESPACE
  64850. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  64851. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  64852. BEGIN_JUCE_NAMESPACE
  64853. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  64854. : flags (other.flags)
  64855. {
  64856. }
  64857. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  64858. {
  64859. flags = other.flags;
  64860. return *this;
  64861. }
  64862. void RectanglePlacement::applyTo (double& x, double& y,
  64863. double& w, double& h,
  64864. const double dx, const double dy,
  64865. const double dw, const double dh) const throw()
  64866. {
  64867. if (w == 0 || h == 0)
  64868. return;
  64869. if ((flags & stretchToFit) != 0)
  64870. {
  64871. x = dx;
  64872. y = dy;
  64873. w = dw;
  64874. h = dh;
  64875. }
  64876. else
  64877. {
  64878. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  64879. : jmin (dw / w, dh / h);
  64880. if ((flags & onlyReduceInSize) != 0)
  64881. scale = jmin (scale, 1.0);
  64882. if ((flags & onlyIncreaseInSize) != 0)
  64883. scale = jmax (scale, 1.0);
  64884. w *= scale;
  64885. h *= scale;
  64886. if ((flags & xLeft) != 0)
  64887. x = dx;
  64888. else if ((flags & xRight) != 0)
  64889. x = dx + dw - w;
  64890. else
  64891. x = dx + (dw - w) * 0.5;
  64892. if ((flags & yTop) != 0)
  64893. y = dy;
  64894. else if ((flags & yBottom) != 0)
  64895. y = dy + dh - h;
  64896. else
  64897. y = dy + (dh - h) * 0.5;
  64898. }
  64899. }
  64900. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  64901. float w, float h,
  64902. const float dx, const float dy,
  64903. const float dw, const float dh) const throw()
  64904. {
  64905. if (w == 0 || h == 0)
  64906. return AffineTransform::identity;
  64907. const float scaleX = dw / w;
  64908. const float scaleY = dh / h;
  64909. if ((flags & stretchToFit) != 0)
  64910. return AffineTransform::translation (-x, -y)
  64911. .scaled (scaleX, scaleY)
  64912. .translated (dx, dy);
  64913. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  64914. : jmin (scaleX, scaleY);
  64915. if ((flags & onlyReduceInSize) != 0)
  64916. scale = jmin (scale, 1.0f);
  64917. if ((flags & onlyIncreaseInSize) != 0)
  64918. scale = jmax (scale, 1.0f);
  64919. w *= scale;
  64920. h *= scale;
  64921. float newX = dx;
  64922. if ((flags & xRight) != 0)
  64923. newX += dw - w; // right
  64924. else if ((flags & xLeft) == 0)
  64925. newX += (dw - w) / 2.0f; // centre
  64926. float newY = dy;
  64927. if ((flags & yBottom) != 0)
  64928. newY += dh - h; // bottom
  64929. else if ((flags & yTop) == 0)
  64930. newY += (dh - h) / 2.0f; // centre
  64931. return AffineTransform::translation (-x, -y)
  64932. .scaled (scale, scale)
  64933. .translated (newX, newY);
  64934. }
  64935. END_JUCE_NAMESPACE
  64936. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  64937. /********* Start of inlined file: juce_Drawable.cpp *********/
  64938. BEGIN_JUCE_NAMESPACE
  64939. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  64940. const AffineTransform& transform_,
  64941. const float opacity_) throw()
  64942. : g (g_),
  64943. transform (transform_),
  64944. opacity (opacity_)
  64945. {
  64946. }
  64947. Drawable::Drawable()
  64948. {
  64949. }
  64950. Drawable::~Drawable()
  64951. {
  64952. }
  64953. void Drawable::draw (Graphics& g,
  64954. const AffineTransform& transform) const
  64955. {
  64956. const RenderingContext context (g, transform, g.getCurrentColour().getFloatAlpha());
  64957. render (context);
  64958. }
  64959. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  64960. {
  64961. draw (g, AffineTransform::translation (x, y));
  64962. }
  64963. void Drawable::drawWithin (Graphics& g,
  64964. const int destX,
  64965. const int destY,
  64966. const int destW,
  64967. const int destH,
  64968. const RectanglePlacement& placement) const
  64969. {
  64970. if (destW > 0 && destH > 0)
  64971. {
  64972. float x, y, w, h;
  64973. getBounds (x, y, w, h);
  64974. draw (g, placement.getTransformToFit (x, y, w, h,
  64975. (float) destX, (float) destY,
  64976. (float) destW, (float) destH));
  64977. }
  64978. }
  64979. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  64980. {
  64981. Drawable* result = 0;
  64982. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  64983. if (image != 0)
  64984. {
  64985. DrawableImage* const di = new DrawableImage();
  64986. di->setImage (image, true);
  64987. result = di;
  64988. }
  64989. else
  64990. {
  64991. const String asString (String::createStringFromData (data, numBytes));
  64992. XmlDocument doc (asString);
  64993. XmlElement* const outer = doc.getDocumentElement (true);
  64994. if (outer != 0 && outer->hasTagName (T("svg")))
  64995. {
  64996. XmlElement* const svg = doc.getDocumentElement();
  64997. if (svg != 0)
  64998. {
  64999. result = Drawable::createFromSVG (*svg);
  65000. delete svg;
  65001. }
  65002. }
  65003. delete outer;
  65004. }
  65005. return result;
  65006. }
  65007. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  65008. {
  65009. MemoryBlock mb;
  65010. dataSource.readIntoMemoryBlock (mb);
  65011. return createFromImageData (mb.getData(), mb.getSize());
  65012. }
  65013. Drawable* Drawable::createFromImageFile (const File& file)
  65014. {
  65015. FileInputStream* fin = file.createInputStream();
  65016. if (fin == 0)
  65017. return 0;
  65018. Drawable* d = createFromImageDataStream (*fin);
  65019. delete fin;
  65020. return d;
  65021. }
  65022. Drawable* Drawable::readFromBinaryStream (InputStream& input)
  65023. {
  65024. char header[8];
  65025. if (input.read (header, sizeof (header)) != sizeof (header))
  65026. return 0;
  65027. DrawableComposite* result = 0;
  65028. if (memcmp (header, "JuceDrw1", sizeof (header)) == 0)
  65029. {
  65030. result = new DrawableComposite();
  65031. if (! result->readBinary (input))
  65032. deleteAndZero (result);
  65033. }
  65034. return result;
  65035. }
  65036. bool Drawable::writeToBinaryStream (OutputStream& output) const
  65037. {
  65038. output.write ("JuceDrw1", 8);
  65039. return writeBinary (output);
  65040. }
  65041. Drawable* Drawable::readFromXml (const XmlElement& xml)
  65042. {
  65043. DrawableComposite* result = 0;
  65044. if (xml.hasTagName (T("JuceDrawable")))
  65045. {
  65046. result = new DrawableComposite();
  65047. if (! result->readXml (xml))
  65048. deleteAndZero (result);
  65049. }
  65050. return result;
  65051. }
  65052. XmlElement* Drawable::createXml() const
  65053. {
  65054. if (dynamic_cast <const DrawableComposite*> (this) == 0)
  65055. {
  65056. DrawableComposite tempDC;
  65057. tempDC.insertDrawable (const_cast <Drawable*> (this));
  65058. XmlElement* result = tempDC.createXml();
  65059. tempDC.removeDrawable (0, false);
  65060. return result;
  65061. }
  65062. else
  65063. {
  65064. XmlElement* e = new XmlElement (T("JuceDrawable"));
  65065. writeXml (*e);
  65066. return e;
  65067. }
  65068. }
  65069. END_JUCE_NAMESPACE
  65070. /********* End of inlined file: juce_Drawable.cpp *********/
  65071. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  65072. BEGIN_JUCE_NAMESPACE
  65073. DrawableComposite::DrawableComposite()
  65074. {
  65075. }
  65076. DrawableComposite::~DrawableComposite()
  65077. {
  65078. }
  65079. void DrawableComposite::insertDrawable (Drawable* drawable,
  65080. const AffineTransform& transform,
  65081. const int index)
  65082. {
  65083. if (drawable != 0)
  65084. {
  65085. if (! drawables.contains (drawable))
  65086. {
  65087. drawables.insert (index, drawable);
  65088. if (transform.isIdentity())
  65089. transforms.insert (index, 0);
  65090. else
  65091. transforms.insert (index, new AffineTransform (transform));
  65092. }
  65093. else
  65094. {
  65095. jassertfalse // trying to add a drawable that's already in here!
  65096. }
  65097. }
  65098. }
  65099. void DrawableComposite::insertDrawable (const Drawable& drawable,
  65100. const AffineTransform& transform,
  65101. const int index)
  65102. {
  65103. insertDrawable (drawable.createCopy(), transform, index);
  65104. }
  65105. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  65106. {
  65107. drawables.remove (index, deleteDrawable);
  65108. transforms.remove (index);
  65109. }
  65110. void DrawableComposite::bringToFront (const int index)
  65111. {
  65112. if (index >= 0 && index < drawables.size() - 1)
  65113. {
  65114. drawables.move (index, -1);
  65115. transforms.move (index, -1);
  65116. }
  65117. }
  65118. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  65119. {
  65120. if (drawables.size() > 0 && context.opacity > 0)
  65121. {
  65122. if (context.opacity >= 1.0f || drawables.size() == 1)
  65123. {
  65124. Drawable::RenderingContext contextCopy (context);
  65125. for (int i = 0; i < drawables.size(); ++i)
  65126. {
  65127. const AffineTransform* const t = transforms.getUnchecked(i);
  65128. contextCopy.transform = (t == 0) ? context.transform
  65129. : t->followedBy (context.transform);
  65130. drawables.getUnchecked(i)->render (contextCopy);
  65131. }
  65132. }
  65133. else
  65134. {
  65135. // To correctly render a whole composite layer with an overall transparency,
  65136. // we need to render everything opaquely into a temp buffer, then blend that
  65137. // with the target opacity...
  65138. const Rectangle clipBounds (context.g.getClipBounds());
  65139. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  65140. {
  65141. Graphics tempG (tempImage);
  65142. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  65143. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  65144. render (tempContext);
  65145. }
  65146. context.g.setOpacity (context.opacity);
  65147. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  65148. }
  65149. }
  65150. }
  65151. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  65152. {
  65153. Path totalPath;
  65154. for (int i = 0; i < drawables.size(); ++i)
  65155. {
  65156. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  65157. if (width > 0.0f && height > 0.0f)
  65158. {
  65159. Path outline;
  65160. outline.addRectangle (x, y, width, height);
  65161. const AffineTransform* const t = transforms.getUnchecked(i);
  65162. if (t == 0)
  65163. totalPath.addPath (outline);
  65164. else
  65165. totalPath.addPath (outline, *t);
  65166. }
  65167. }
  65168. totalPath.getBounds (x, y, width, height);
  65169. }
  65170. bool DrawableComposite::hitTest (float x, float y) const
  65171. {
  65172. for (int i = 0; i < drawables.size(); ++i)
  65173. {
  65174. float tx = x;
  65175. float ty = y;
  65176. const AffineTransform* const t = transforms.getUnchecked(i);
  65177. if (t != 0)
  65178. t->inverted().transformPoint (tx, ty);
  65179. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  65180. return true;
  65181. }
  65182. return false;
  65183. }
  65184. Drawable* DrawableComposite::createCopy() const
  65185. {
  65186. DrawableComposite* const dc = new DrawableComposite();
  65187. for (int i = 0; i < drawables.size(); ++i)
  65188. {
  65189. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  65190. const AffineTransform* const t = transforms.getUnchecked(i);
  65191. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  65192. }
  65193. return dc;
  65194. }
  65195. const char juce_drawableCompositeTransformFlag = 't';
  65196. const char juce_drawableCompositeBinaryType = 'C';
  65197. const char juce_drawablePathBinaryType = 'P';
  65198. const char juce_drawableImageBinaryType = 'I';
  65199. const char juce_drawableTextBinaryType = 'T';
  65200. bool DrawableComposite::readBinary (InputStream& input)
  65201. {
  65202. AffineTransform transform;
  65203. while (! input.isExhausted())
  65204. {
  65205. const int n = input.readByte();
  65206. if (n == 0)
  65207. break;
  65208. if (n == juce_drawableCompositeTransformFlag)
  65209. {
  65210. float f[6];
  65211. for (int i = 0; i < 6; ++i)
  65212. f[i] = input.readFloat();
  65213. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65214. }
  65215. else
  65216. {
  65217. Drawable* d = 0;
  65218. switch (n)
  65219. {
  65220. case juce_drawableCompositeBinaryType: d = new DrawableComposite(); break;
  65221. case juce_drawablePathBinaryType: d = new DrawablePath(); break;
  65222. case juce_drawableImageBinaryType: d = new DrawableImage(); break;
  65223. case juce_drawableTextBinaryType: d = new DrawableText(); break;
  65224. default: jassertfalse; return false;
  65225. }
  65226. d->setName (input.readString());
  65227. if (! d->readBinary (input))
  65228. {
  65229. delete d;
  65230. return false;
  65231. }
  65232. insertDrawable (d, transform);
  65233. transform = AffineTransform::identity;
  65234. }
  65235. }
  65236. return true;
  65237. }
  65238. bool DrawableComposite::writeBinary (OutputStream& output) const
  65239. {
  65240. for (int i = 0; i < drawables.size(); ++i)
  65241. {
  65242. AffineTransform* transform = transforms.getUnchecked(i);
  65243. if (transform != 0)
  65244. {
  65245. output.writeByte (juce_drawableCompositeTransformFlag);
  65246. output.writeFloat (transform->mat00);
  65247. output.writeFloat (transform->mat01);
  65248. output.writeFloat (transform->mat02);
  65249. output.writeFloat (transform->mat10);
  65250. output.writeFloat (transform->mat11);
  65251. output.writeFloat (transform->mat12);
  65252. }
  65253. Drawable* const d = drawables.getUnchecked(i);
  65254. char typeFlag;
  65255. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65256. typeFlag = juce_drawableCompositeBinaryType;
  65257. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65258. typeFlag = juce_drawablePathBinaryType;
  65259. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65260. typeFlag = juce_drawableImageBinaryType;
  65261. else if (dynamic_cast <DrawableText*> (d) != 0)
  65262. typeFlag = juce_drawableTextBinaryType;
  65263. else
  65264. {
  65265. jassertfalse;
  65266. continue;
  65267. }
  65268. output.writeByte (typeFlag);
  65269. output.writeString (d->getName());
  65270. d->writeBinary (output);
  65271. }
  65272. output.writeByte (0);
  65273. return true;
  65274. }
  65275. const tchar* juce_drawableCompositeXmlTag = T("Group");
  65276. const tchar* juce_drawablePathXmlTag = T("Path");
  65277. const tchar* juce_drawableImageXmlTag = T("Image");
  65278. const tchar* juce_drawableTextXmlTag = T("Text");
  65279. bool DrawableComposite::readXml (const XmlElement& xml)
  65280. {
  65281. forEachXmlChildElement (xml, e)
  65282. {
  65283. Drawable* d = 0;
  65284. if (e->hasTagName (juce_drawableCompositeXmlTag))
  65285. d = new DrawableComposite();
  65286. else if (e->hasTagName (juce_drawablePathXmlTag))
  65287. d = new DrawablePath();
  65288. else if (e->hasTagName (juce_drawableImageXmlTag))
  65289. d = new DrawableImage();
  65290. else if (e->hasTagName (juce_drawableTextXmlTag))
  65291. d = new DrawableText();
  65292. else
  65293. {
  65294. jassertfalse;
  65295. return false;
  65296. }
  65297. d->setName (e->getStringAttribute (T("id")));
  65298. if (! d->readXml (*e))
  65299. {
  65300. jassertfalse;
  65301. delete d;
  65302. return false;
  65303. }
  65304. AffineTransform transform;
  65305. const String transformAtt (e->getStringAttribute (T("transform")));
  65306. if (transformAtt.isNotEmpty())
  65307. {
  65308. StringArray tokens;
  65309. tokens.addTokens (transformAtt.trim(), false);
  65310. tokens.removeEmptyStrings (true);
  65311. if (tokens.size() == 6)
  65312. {
  65313. float f[6];
  65314. for (int i = 0; i < 6; ++i)
  65315. f[i] = (float) tokens[i].getDoubleValue();
  65316. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65317. }
  65318. }
  65319. insertDrawable (d, transform);
  65320. }
  65321. return true;
  65322. }
  65323. void DrawableComposite::writeXml (XmlElement& xml) const
  65324. {
  65325. for (int i = 0; i < drawables.size(); ++i)
  65326. {
  65327. XmlElement* e = 0;
  65328. Drawable* const d = drawables.getUnchecked(i);
  65329. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65330. e = new XmlElement (juce_drawableCompositeXmlTag);
  65331. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65332. e = new XmlElement (juce_drawablePathXmlTag);
  65333. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65334. e = new XmlElement (juce_drawableImageXmlTag);
  65335. else if (dynamic_cast <DrawableText*> (d) != 0)
  65336. e = new XmlElement (juce_drawableTextXmlTag);
  65337. else
  65338. {
  65339. jassertfalse;
  65340. continue;
  65341. }
  65342. AffineTransform* transform = transforms.getUnchecked(i);
  65343. if (transform != 0)
  65344. {
  65345. String t;
  65346. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  65347. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  65348. e->setAttribute (T("transform"), t);
  65349. }
  65350. if (d->getName().isNotEmpty())
  65351. e->setAttribute (T("id"), d->getName());
  65352. d->writeXml (*e);
  65353. xml.addChildElement (e);
  65354. }
  65355. }
  65356. END_JUCE_NAMESPACE
  65357. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  65358. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  65359. BEGIN_JUCE_NAMESPACE
  65360. DrawableImage::DrawableImage()
  65361. : image (0),
  65362. canDeleteImage (false),
  65363. opacity (1.0f),
  65364. overlayColour (0x00000000)
  65365. {
  65366. }
  65367. DrawableImage::~DrawableImage()
  65368. {
  65369. clearImage();
  65370. }
  65371. void DrawableImage::clearImage()
  65372. {
  65373. if (canDeleteImage && image != 0)
  65374. {
  65375. if (ImageCache::isImageInCache (image))
  65376. ImageCache::release (image);
  65377. else
  65378. delete image;
  65379. }
  65380. image = 0;
  65381. }
  65382. void DrawableImage::setImage (const Image& imageToCopy)
  65383. {
  65384. clearImage();
  65385. image = new Image (imageToCopy);
  65386. canDeleteImage = true;
  65387. }
  65388. void DrawableImage::setImage (Image* imageToUse,
  65389. const bool releaseWhenNotNeeded)
  65390. {
  65391. clearImage();
  65392. image = imageToUse;
  65393. canDeleteImage = releaseWhenNotNeeded;
  65394. }
  65395. void DrawableImage::setOpacity (const float newOpacity)
  65396. {
  65397. opacity = newOpacity;
  65398. }
  65399. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  65400. {
  65401. overlayColour = newOverlayColour;
  65402. }
  65403. void DrawableImage::render (const Drawable::RenderingContext& context) const
  65404. {
  65405. if (image != 0)
  65406. {
  65407. if (opacity > 0.0f && ! overlayColour.isOpaque())
  65408. {
  65409. context.g.setOpacity (context.opacity * opacity);
  65410. context.g.drawImageTransformed (image,
  65411. 0, 0, image->getWidth(), image->getHeight(),
  65412. context.transform, false);
  65413. }
  65414. if (! overlayColour.isTransparent())
  65415. {
  65416. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  65417. context.g.drawImageTransformed (image,
  65418. 0, 0, image->getWidth(), image->getHeight(),
  65419. context.transform, true);
  65420. }
  65421. }
  65422. }
  65423. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  65424. {
  65425. x = 0.0f;
  65426. y = 0.0f;
  65427. width = 0.0f;
  65428. height = 0.0f;
  65429. if (image != 0)
  65430. {
  65431. width = (float) image->getWidth();
  65432. height = (float) image->getHeight();
  65433. }
  65434. }
  65435. bool DrawableImage::hitTest (float x, float y) const
  65436. {
  65437. return image != 0
  65438. && x >= 0.0f
  65439. && y >= 0.0f
  65440. && x < image->getWidth()
  65441. && y < image->getHeight()
  65442. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  65443. }
  65444. Drawable* DrawableImage::createCopy() const
  65445. {
  65446. DrawableImage* const di = new DrawableImage();
  65447. di->opacity = opacity;
  65448. di->overlayColour = overlayColour;
  65449. if (image != 0)
  65450. {
  65451. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  65452. {
  65453. di->setImage (*image);
  65454. }
  65455. else
  65456. {
  65457. ImageCache::incReferenceCount (image);
  65458. di->setImage (image, true);
  65459. }
  65460. }
  65461. return di;
  65462. }
  65463. bool DrawableImage::readBinary (InputStream& input)
  65464. {
  65465. opacity = input.readFloat();
  65466. overlayColour = Colour (input.readInt());
  65467. const int dataLen = input.readInt();
  65468. if (dataLen > 0)
  65469. {
  65470. MemoryBlock imageData;
  65471. input.readIntoMemoryBlock (imageData, dataLen);
  65472. Image* im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65473. if (im == 0)
  65474. return false;
  65475. setImage (im, true);
  65476. }
  65477. return true;
  65478. }
  65479. bool DrawableImage::writeBinary (OutputStream& output) const
  65480. {
  65481. MemoryOutputStream imageData;
  65482. if (image != 0)
  65483. {
  65484. PNGImageFormat pngFormat;
  65485. if (! pngFormat.writeImageToStream (*image, imageData))
  65486. return false;
  65487. }
  65488. output.writeFloat (opacity);
  65489. output.writeInt (overlayColour.getARGB());
  65490. output.writeInt (imageData.getDataSize());
  65491. output.write (imageData.getData(), imageData.getDataSize());
  65492. return true;
  65493. }
  65494. bool DrawableImage::readXml (const XmlElement& xml)
  65495. {
  65496. opacity = (float) xml.getDoubleAttribute (T("opacity"), 1.0);
  65497. overlayColour = Colour (xml.getStringAttribute (T("overlay"), T("0")).getHexValue32());
  65498. MemoryBlock imageData;
  65499. if (imageData.fromBase64Encoding (xml.getAllSubText()))
  65500. {
  65501. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65502. if (im == 0)
  65503. return false;
  65504. setImage (im, true);
  65505. }
  65506. return true;
  65507. }
  65508. void DrawableImage::writeXml (XmlElement& xml) const
  65509. {
  65510. if (opacity < 1.0f)
  65511. xml.setAttribute (T("opacity"), (double) opacity);
  65512. if (! overlayColour.isTransparent())
  65513. xml.setAttribute (T("overlay"), String::toHexString ((int) overlayColour.getARGB()));
  65514. if (image != 0)
  65515. {
  65516. MemoryOutputStream imageData;
  65517. PNGImageFormat pngFormat;
  65518. if (pngFormat.writeImageToStream (*image, imageData))
  65519. {
  65520. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  65521. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  65522. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  65523. xml.addTextElement (base64);
  65524. }
  65525. }
  65526. }
  65527. END_JUCE_NAMESPACE
  65528. /********* End of inlined file: juce_DrawableImage.cpp *********/
  65529. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  65530. BEGIN_JUCE_NAMESPACE
  65531. DrawablePath::DrawablePath()
  65532. : fillBrush (new SolidColourBrush (Colours::black)),
  65533. strokeBrush (0),
  65534. strokeType (0.0f)
  65535. {
  65536. }
  65537. DrawablePath::~DrawablePath()
  65538. {
  65539. delete fillBrush;
  65540. delete strokeBrush;
  65541. }
  65542. void DrawablePath::setPath (const Path& newPath)
  65543. {
  65544. path = newPath;
  65545. updateOutline();
  65546. }
  65547. void DrawablePath::setSolidFill (const Colour& newColour)
  65548. {
  65549. delete fillBrush;
  65550. fillBrush = new SolidColourBrush (newColour);
  65551. }
  65552. void DrawablePath::setFillBrush (const Brush& newBrush)
  65553. {
  65554. delete fillBrush;
  65555. fillBrush = newBrush.createCopy();
  65556. }
  65557. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  65558. {
  65559. strokeType = PathStrokeType (thickness);
  65560. delete strokeBrush;
  65561. strokeBrush = new SolidColourBrush (colour);
  65562. updateOutline();
  65563. }
  65564. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  65565. {
  65566. strokeType = strokeType_;
  65567. delete strokeBrush;
  65568. strokeBrush = newStrokeBrush.createCopy();
  65569. updateOutline();
  65570. }
  65571. void DrawablePath::render (const Drawable::RenderingContext& context) const
  65572. {
  65573. {
  65574. Brush* const tempBrush = fillBrush->createCopy();
  65575. tempBrush->applyTransform (context.transform);
  65576. tempBrush->multiplyOpacity (context.opacity);
  65577. context.g.setBrush (tempBrush);
  65578. context.g.fillPath (path, context.transform);
  65579. delete tempBrush;
  65580. }
  65581. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  65582. {
  65583. Brush* const tempBrush = strokeBrush->createCopy();
  65584. tempBrush->applyTransform (context.transform);
  65585. tempBrush->multiplyOpacity (context.opacity);
  65586. context.g.setBrush (tempBrush);
  65587. context.g.fillPath (outline, context.transform);
  65588. delete tempBrush;
  65589. }
  65590. }
  65591. void DrawablePath::updateOutline()
  65592. {
  65593. outline.clear();
  65594. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  65595. }
  65596. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  65597. {
  65598. if (strokeType.getStrokeThickness() > 0.0f)
  65599. outline.getBounds (x, y, width, height);
  65600. else
  65601. path.getBounds (x, y, width, height);
  65602. }
  65603. bool DrawablePath::hitTest (float x, float y) const
  65604. {
  65605. return path.contains (x, y)
  65606. || outline.contains (x, y);
  65607. }
  65608. Drawable* DrawablePath::createCopy() const
  65609. {
  65610. DrawablePath* const dp = new DrawablePath();
  65611. dp->path = path;
  65612. dp->setFillBrush (*fillBrush);
  65613. if (strokeBrush != 0)
  65614. dp->setOutline (strokeType, *strokeBrush);
  65615. return dp;
  65616. }
  65617. static Brush* readBrushFromBinary (InputStream& input)
  65618. {
  65619. switch (input.readByte())
  65620. {
  65621. case 1:
  65622. return new SolidColourBrush (Colour ((uint32) input.readInt()));
  65623. case 2:
  65624. {
  65625. ColourGradient gradient;
  65626. gradient.x1 = input.readFloat();
  65627. gradient.y1 = input.readFloat();
  65628. gradient.x2 = input.readFloat();
  65629. gradient.y2 = input.readFloat();
  65630. gradient.isRadial = input.readByte() != 0;
  65631. const int numColours = input.readCompressedInt();
  65632. for (int i = 0; i < numColours; ++i)
  65633. {
  65634. double proportion = (double) input.readFloat();
  65635. const Colour colour ((uint32) input.readInt());
  65636. gradient.addColour (proportion, colour);
  65637. }
  65638. return new GradientBrush (gradient);
  65639. }
  65640. case 3:
  65641. {
  65642. jassertfalse; //xxx TODO
  65643. return new ImageBrush (0, 0, 0, 0);
  65644. }
  65645. default:
  65646. break;
  65647. }
  65648. return 0;
  65649. }
  65650. static void writeBrushToBinary (OutputStream& output, const Brush* const brush)
  65651. {
  65652. if (brush == 0)
  65653. {
  65654. output.writeByte (0);
  65655. return;
  65656. }
  65657. const SolidColourBrush* cb;
  65658. const GradientBrush* gb;
  65659. const ImageBrush* ib;
  65660. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65661. {
  65662. output.writeByte (1);
  65663. output.writeInt ((int) cb->getColour().getARGB());
  65664. }
  65665. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65666. {
  65667. output.writeByte (2);
  65668. const ColourGradient& g = gb->getGradient();
  65669. output.writeFloat (g.x1);
  65670. output.writeFloat (g.y1);
  65671. output.writeFloat (g.x2);
  65672. output.writeFloat (g.y2);
  65673. output.writeByte (g.isRadial ? 1 : 0);
  65674. output.writeCompressedInt (g.getNumColours());
  65675. for (int i = 0; i < g.getNumColours(); ++i)
  65676. {
  65677. output.writeFloat ((float) g.getColourPosition (i));
  65678. output.writeInt ((int) g.getColour (i).getARGB());
  65679. }
  65680. }
  65681. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65682. {
  65683. output.writeByte (3);
  65684. jassertfalse; //xxx TODO
  65685. }
  65686. }
  65687. static Brush* readBrushFromXml (const XmlElement* xml)
  65688. {
  65689. if (xml == 0)
  65690. return 0;
  65691. const String type (xml->getStringAttribute (T("type")));
  65692. if (type.equalsIgnoreCase (T("solid")))
  65693. return new SolidColourBrush (Colour ((uint32) xml->getStringAttribute (T("colour"), T("ff000000")).getHexValue32()));
  65694. if (type.equalsIgnoreCase (T("gradient")))
  65695. {
  65696. ColourGradient gradient;
  65697. gradient.x1 = (float) xml->getDoubleAttribute (T("x1"));
  65698. gradient.y1 = (float) xml->getDoubleAttribute (T("y1"));
  65699. gradient.x2 = (float) xml->getDoubleAttribute (T("x2"));
  65700. gradient.y2 = (float) xml->getDoubleAttribute (T("y2"));
  65701. gradient.isRadial = xml->getBoolAttribute (T("radial"), false);
  65702. StringArray colours;
  65703. colours.addTokens (xml->getStringAttribute (T("colours")), false);
  65704. for (int i = 0; i < colours.size() / 2; ++i)
  65705. gradient.addColour (colours[i * 2].getDoubleValue(),
  65706. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  65707. return new GradientBrush (gradient);
  65708. }
  65709. if (type.equalsIgnoreCase (T("image")))
  65710. {
  65711. jassertfalse; //xxx TODO
  65712. return new ImageBrush (0, 0, 0, 0);
  65713. }
  65714. return 0;
  65715. }
  65716. static XmlElement* writeBrushToXml (const String& tagName, const Brush* brush)
  65717. {
  65718. if (brush == 0)
  65719. return 0;
  65720. XmlElement* const xml = new XmlElement (tagName);
  65721. const SolidColourBrush* cb;
  65722. const GradientBrush* gb;
  65723. const ImageBrush* ib;
  65724. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65725. {
  65726. xml->setAttribute (T("type"), T("solid"));
  65727. xml->setAttribute (T("colour"), String::toHexString ((int) cb->getColour().getARGB()));
  65728. }
  65729. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65730. {
  65731. xml->setAttribute (T("type"), T("gradient"));
  65732. const ColourGradient& g = gb->getGradient();
  65733. xml->setAttribute (T("x1"), g.x1);
  65734. xml->setAttribute (T("y1"), g.y1);
  65735. xml->setAttribute (T("x2"), g.x2);
  65736. xml->setAttribute (T("y2"), g.y2);
  65737. xml->setAttribute (T("radial"), g.isRadial);
  65738. String s;
  65739. for (int i = 0; i < g.getNumColours(); ++i)
  65740. s << " " << g.getColourPosition (i) << " " << String::toHexString ((int) g.getColour(i).getARGB());
  65741. xml->setAttribute (T("colours"), s.trimStart());
  65742. }
  65743. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65744. {
  65745. xml->setAttribute (T("type"), T("image"));
  65746. jassertfalse; //xxx TODO
  65747. }
  65748. return xml;
  65749. }
  65750. bool DrawablePath::readBinary (InputStream& input)
  65751. {
  65752. delete fillBrush;
  65753. fillBrush = readBrushFromBinary (input);
  65754. delete strokeBrush;
  65755. strokeBrush = readBrushFromBinary (input);
  65756. const float strokeThickness = input.readFloat();
  65757. const int jointStyle = input.readByte();
  65758. const int endStyle = input.readByte();
  65759. strokeType = PathStrokeType (strokeThickness,
  65760. jointStyle == 1 ? PathStrokeType::curved
  65761. : (jointStyle == 2 ? PathStrokeType::beveled
  65762. : PathStrokeType::mitered),
  65763. endStyle == 1 ? PathStrokeType::square
  65764. : (endStyle == 2 ? PathStrokeType::rounded
  65765. : PathStrokeType::butt));
  65766. const int pathSize = input.readInt();
  65767. MemoryBlock pathData;
  65768. input.readIntoMemoryBlock (pathData, pathSize);
  65769. if (pathData.getSize() != pathSize)
  65770. return false;
  65771. path.clear();
  65772. path.loadPathFromData ((const uint8*) pathData.getData(), pathSize);
  65773. updateOutline();
  65774. return true;
  65775. }
  65776. bool DrawablePath::writeBinary (OutputStream& output) const
  65777. {
  65778. writeBrushToBinary (output, fillBrush);
  65779. writeBrushToBinary (output, strokeBrush);
  65780. output.writeFloat (strokeType.getStrokeThickness());
  65781. output.writeByte (strokeType.getJointStyle() == PathStrokeType::mitered ? 0
  65782. : (strokeType.getJointStyle() == PathStrokeType::curved ? 1 : 2));
  65783. output.writeByte (strokeType.getEndStyle() == PathStrokeType::butt ? 0
  65784. : (strokeType.getEndStyle() == PathStrokeType::square ? 1 : 2));
  65785. MemoryOutputStream out;
  65786. path.writePathToStream (out);
  65787. output.writeInt (out.getDataSize());
  65788. output.write (out.getData(), out.getDataSize());
  65789. return true;
  65790. }
  65791. bool DrawablePath::readXml (const XmlElement& xml)
  65792. {
  65793. delete fillBrush;
  65794. fillBrush = readBrushFromXml (xml.getChildByName (T("fill")));
  65795. delete strokeBrush;
  65796. strokeBrush = readBrushFromXml (xml.getChildByName (T("stroke")));
  65797. const String jointStyle (xml.getStringAttribute (T("jointStyle"), String::empty));
  65798. const String endStyle (xml.getStringAttribute (T("capStyle"), String::empty));
  65799. strokeType = PathStrokeType ((float) xml.getDoubleAttribute (T("strokeWidth"), 0.0),
  65800. jointStyle.equalsIgnoreCase (T("curved")) ? PathStrokeType::curved
  65801. : (jointStyle.equalsIgnoreCase (T("bevel")) ? PathStrokeType::beveled
  65802. : PathStrokeType::mitered),
  65803. endStyle.equalsIgnoreCase (T("square")) ? PathStrokeType::square
  65804. : (endStyle.equalsIgnoreCase (T("round")) ? PathStrokeType::rounded
  65805. : PathStrokeType::butt));
  65806. path.clear();
  65807. path.restoreFromString (xml.getAllSubText());
  65808. updateOutline();
  65809. return true;
  65810. }
  65811. void DrawablePath::writeXml (XmlElement& xml) const
  65812. {
  65813. xml.addChildElement (writeBrushToXml (T("fill"), fillBrush));
  65814. xml.addChildElement (writeBrushToXml (T("stroke"), strokeBrush));
  65815. xml.setAttribute (T("strokeWidth"), (double) strokeType.getStrokeThickness());
  65816. xml.setAttribute (T("jointStyle"),
  65817. strokeType.getJointStyle() == PathStrokeType::mitered ? T("miter")
  65818. : (strokeType.getJointStyle() == PathStrokeType::curved ? T("curved") : T("bevel")));
  65819. xml.setAttribute (T("capStyle"),
  65820. strokeType.getEndStyle() == PathStrokeType::butt ? T("butt")
  65821. : (strokeType.getEndStyle() == PathStrokeType::square ? T("square") : T("round")));
  65822. xml.addTextElement (path.toString());
  65823. }
  65824. END_JUCE_NAMESPACE
  65825. /********* End of inlined file: juce_DrawablePath.cpp *********/
  65826. /********* Start of inlined file: juce_DrawableText.cpp *********/
  65827. BEGIN_JUCE_NAMESPACE
  65828. DrawableText::DrawableText()
  65829. : colour (Colours::white)
  65830. {
  65831. }
  65832. DrawableText::~DrawableText()
  65833. {
  65834. }
  65835. void DrawableText::setText (const GlyphArrangement& newText)
  65836. {
  65837. text = newText;
  65838. }
  65839. void DrawableText::setText (const String& newText, const Font& fontToUse)
  65840. {
  65841. text.clear();
  65842. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  65843. }
  65844. void DrawableText::setColour (const Colour& newColour)
  65845. {
  65846. colour = newColour;
  65847. }
  65848. void DrawableText::render (const Drawable::RenderingContext& context) const
  65849. {
  65850. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  65851. text.draw (context.g, context.transform);
  65852. }
  65853. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  65854. {
  65855. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  65856. width -= x;
  65857. height -= y;
  65858. }
  65859. bool DrawableText::hitTest (float x, float y) const
  65860. {
  65861. return text.findGlyphIndexAt (x, y) >= 0;
  65862. }
  65863. Drawable* DrawableText::createCopy() const
  65864. {
  65865. DrawableText* const dt = new DrawableText();
  65866. dt->text = text;
  65867. dt->colour = colour;
  65868. return dt;
  65869. }
  65870. bool DrawableText::readBinary (InputStream& input)
  65871. {
  65872. jassertfalse; //xxx TODO
  65873. return false;
  65874. }
  65875. bool DrawableText::writeBinary (OutputStream& output) const
  65876. {
  65877. jassertfalse; //xxx TODO
  65878. return false;
  65879. }
  65880. bool DrawableText::readXml (const XmlElement& xml)
  65881. {
  65882. jassertfalse; //xxx TODO
  65883. return false;
  65884. }
  65885. void DrawableText::writeXml (XmlElement& xml) const
  65886. {
  65887. jassertfalse; //xxx TODO
  65888. }
  65889. END_JUCE_NAMESPACE
  65890. /********* End of inlined file: juce_DrawableText.cpp *********/
  65891. /********* Start of inlined file: juce_SVGParser.cpp *********/
  65892. BEGIN_JUCE_NAMESPACE
  65893. class SVGState
  65894. {
  65895. public:
  65896. SVGState (const XmlElement* const topLevel)
  65897. : topLevelXml (topLevel),
  65898. x (0), y (0),
  65899. width (512), height (512),
  65900. viewBoxW (0), viewBoxH (0)
  65901. {
  65902. }
  65903. ~SVGState()
  65904. {
  65905. }
  65906. Drawable* parseSVGElement (const XmlElement& xml)
  65907. {
  65908. if (! xml.hasTagName (T("svg")))
  65909. return 0;
  65910. DrawableComposite* const drawable = new DrawableComposite();
  65911. drawable->setName (xml.getStringAttribute (T("id")));
  65912. SVGState newState (*this);
  65913. if (xml.hasAttribute (T("transform")))
  65914. newState.addTransform (xml);
  65915. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  65916. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  65917. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  65918. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  65919. if (xml.hasAttribute (T("viewBox")))
  65920. {
  65921. const String viewParams (xml.getStringAttribute (T("viewBox")));
  65922. int i = 0;
  65923. float vx, vy, vw, vh;
  65924. if (parseCoords (viewParams, vx, vy, i, true)
  65925. && parseCoords (viewParams, vw, vh, i, true)
  65926. && vw > 0
  65927. && vh > 0)
  65928. {
  65929. newState.viewBoxW = vw;
  65930. newState.viewBoxH = vh;
  65931. int placementFlags = 0;
  65932. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  65933. if (aspect.containsIgnoreCase (T("none")))
  65934. {
  65935. placementFlags = RectanglePlacement::stretchToFit;
  65936. }
  65937. else
  65938. {
  65939. if (aspect.containsIgnoreCase (T("slice")))
  65940. placementFlags |= RectanglePlacement::fillDestination;
  65941. if (aspect.containsIgnoreCase (T("xMin")))
  65942. placementFlags |= RectanglePlacement::xLeft;
  65943. else if (aspect.containsIgnoreCase (T("xMax")))
  65944. placementFlags |= RectanglePlacement::xRight;
  65945. else
  65946. placementFlags |= RectanglePlacement::xMid;
  65947. if (aspect.containsIgnoreCase (T("yMin")))
  65948. placementFlags |= RectanglePlacement::yTop;
  65949. else if (aspect.containsIgnoreCase (T("yMax")))
  65950. placementFlags |= RectanglePlacement::yBottom;
  65951. else
  65952. placementFlags |= RectanglePlacement::yMid;
  65953. }
  65954. const RectanglePlacement placement (placementFlags);
  65955. newState.transform
  65956. = placement.getTransformToFit (vx, vy, vw, vh,
  65957. 0.0f, 0.0f, newState.width, newState.height)
  65958. .followedBy (newState.transform);
  65959. }
  65960. }
  65961. else
  65962. {
  65963. if (viewBoxW == 0)
  65964. newState.viewBoxW = newState.width;
  65965. if (viewBoxH == 0)
  65966. newState.viewBoxH = newState.height;
  65967. }
  65968. newState.parseSubElements (xml, drawable);
  65969. return drawable;
  65970. }
  65971. private:
  65972. const XmlElement* const topLevelXml;
  65973. float x, y, width, height, viewBoxW, viewBoxH;
  65974. AffineTransform transform;
  65975. String cssStyleText;
  65976. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  65977. {
  65978. forEachXmlChildElement (xml, e)
  65979. {
  65980. Drawable* d = 0;
  65981. if (e->hasTagName (T("g")))
  65982. d = parseGroupElement (*e);
  65983. else if (e->hasTagName (T("svg")))
  65984. d = parseSVGElement (*e);
  65985. else if (e->hasTagName (T("path")))
  65986. d = parsePath (*e);
  65987. else if (e->hasTagName (T("rect")))
  65988. d = parseRect (*e);
  65989. else if (e->hasTagName (T("circle")))
  65990. d = parseCircle (*e);
  65991. else if (e->hasTagName (T("ellipse")))
  65992. d = parseEllipse (*e);
  65993. else if (e->hasTagName (T("line")))
  65994. d = parseLine (*e);
  65995. else if (e->hasTagName (T("polyline")))
  65996. d = parsePolygon (*e, true);
  65997. else if (e->hasTagName (T("polygon")))
  65998. d = parsePolygon (*e, false);
  65999. else if (e->hasTagName (T("text")))
  66000. d = parseText (*e);
  66001. else if (e->hasTagName (T("switch")))
  66002. d = parseSwitch (*e);
  66003. else if (e->hasTagName (T("style")))
  66004. parseCSSStyle (*e);
  66005. parentDrawable->insertDrawable (d);
  66006. }
  66007. }
  66008. DrawableComposite* parseSwitch (const XmlElement& xml)
  66009. {
  66010. const XmlElement* const group = xml.getChildByName (T("g"));
  66011. if (group != 0)
  66012. return parseGroupElement (*group);
  66013. return 0;
  66014. }
  66015. DrawableComposite* parseGroupElement (const XmlElement& xml)
  66016. {
  66017. DrawableComposite* const drawable = new DrawableComposite();
  66018. drawable->setName (xml.getStringAttribute (T("id")));
  66019. if (xml.hasAttribute (T("transform")))
  66020. {
  66021. SVGState newState (*this);
  66022. newState.addTransform (xml);
  66023. newState.parseSubElements (xml, drawable);
  66024. }
  66025. else
  66026. {
  66027. parseSubElements (xml, drawable);
  66028. }
  66029. return drawable;
  66030. }
  66031. Drawable* parsePath (const XmlElement& xml) const
  66032. {
  66033. const String d (xml.getStringAttribute (T("d")).trimStart());
  66034. Path path;
  66035. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  66036. path.setUsingNonZeroWinding (false);
  66037. int index = 0;
  66038. float lastX = 0, lastY = 0;
  66039. float lastX2 = 0, lastY2 = 0;
  66040. tchar lastCommandChar = 0;
  66041. bool carryOn = true;
  66042. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  66043. for (;;)
  66044. {
  66045. float x, y, x2, y2, x3, y3;
  66046. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  66047. if (validCommandChars.containsChar (d[index]))
  66048. lastCommandChar = d [index++];
  66049. switch (lastCommandChar)
  66050. {
  66051. case T('M'):
  66052. case T('m'):
  66053. case T('L'):
  66054. case T('l'):
  66055. if (parseCoords (d, x, y, index, false))
  66056. {
  66057. if (isRelative)
  66058. {
  66059. x += lastX;
  66060. y += lastY;
  66061. }
  66062. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  66063. path.startNewSubPath (x, y);
  66064. else
  66065. path.lineTo (x, y);
  66066. lastX2 = lastX;
  66067. lastY2 = lastY;
  66068. lastX = x;
  66069. lastY = y;
  66070. }
  66071. else
  66072. {
  66073. ++index;
  66074. }
  66075. break;
  66076. case T('H'):
  66077. case T('h'):
  66078. if (parseCoord (d, x, index, false, true))
  66079. {
  66080. if (isRelative)
  66081. x += lastX;
  66082. path.lineTo (x, lastY);
  66083. lastX2 = lastX;
  66084. lastX = x;
  66085. }
  66086. else
  66087. {
  66088. ++index;
  66089. }
  66090. break;
  66091. case T('V'):
  66092. case T('v'):
  66093. if (parseCoord (d, y, index, false, false))
  66094. {
  66095. if (isRelative)
  66096. y += lastY;
  66097. path.lineTo (lastX, y);
  66098. lastY2 = lastY;
  66099. lastY = y;
  66100. }
  66101. else
  66102. {
  66103. ++index;
  66104. }
  66105. break;
  66106. case T('C'):
  66107. case T('c'):
  66108. if (parseCoords (d, x, y, index, false)
  66109. && parseCoords (d, x2, y2, index, false)
  66110. && parseCoords (d, x3, y3, index, false))
  66111. {
  66112. if (isRelative)
  66113. {
  66114. x += lastX;
  66115. y += lastY;
  66116. x2 += lastX;
  66117. y2 += lastY;
  66118. x3 += lastX;
  66119. y3 += lastY;
  66120. }
  66121. path.cubicTo (x, y, x2, y2, x3, y3);
  66122. lastX2 = x2;
  66123. lastY2 = y2;
  66124. lastX = x3;
  66125. lastY = y3;
  66126. }
  66127. else
  66128. {
  66129. ++index;
  66130. }
  66131. break;
  66132. case T('S'):
  66133. case T('s'):
  66134. if (parseCoords (d, x, y, index, false)
  66135. && parseCoords (d, x3, y3, index, false))
  66136. {
  66137. if (isRelative)
  66138. {
  66139. x += lastX;
  66140. y += lastY;
  66141. x3 += lastX;
  66142. y3 += lastY;
  66143. }
  66144. x2 = lastX + (lastX - lastX2);
  66145. y2 = lastY + (lastY - lastY2);
  66146. path.cubicTo (x2, y2, x, y, x3, y3);
  66147. lastX2 = x;
  66148. lastY2 = y;
  66149. lastX = x3;
  66150. lastY = y3;
  66151. }
  66152. else
  66153. {
  66154. ++index;
  66155. }
  66156. break;
  66157. case T('Q'):
  66158. case T('q'):
  66159. if (parseCoords (d, x, y, index, false)
  66160. && parseCoords (d, x2, y2, index, false))
  66161. {
  66162. if (isRelative)
  66163. {
  66164. x += lastX;
  66165. y += lastY;
  66166. x2 += lastX;
  66167. y2 += lastY;
  66168. }
  66169. path.quadraticTo (x, y, x2, y2);
  66170. lastX2 = x;
  66171. lastY2 = y;
  66172. lastX = x2;
  66173. lastY = y2;
  66174. }
  66175. else
  66176. {
  66177. ++index;
  66178. }
  66179. break;
  66180. case T('T'):
  66181. case T('t'):
  66182. if (parseCoords (d, x, y, index, false))
  66183. {
  66184. if (isRelative)
  66185. {
  66186. x += lastX;
  66187. y += lastY;
  66188. }
  66189. x2 = lastX + (lastX - lastX2);
  66190. y2 = lastY + (lastY - lastY2);
  66191. path.quadraticTo (x2, y2, x, y);
  66192. lastX2 = x2;
  66193. lastY2 = y2;
  66194. lastX = x;
  66195. lastY = y;
  66196. }
  66197. else
  66198. {
  66199. ++index;
  66200. }
  66201. break;
  66202. case T('A'):
  66203. case T('a'):
  66204. if (parseCoords (d, x, y, index, false))
  66205. {
  66206. String num;
  66207. if (parseNextNumber (d, num, index, false))
  66208. {
  66209. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  66210. if (parseNextNumber (d, num, index, false))
  66211. {
  66212. const bool largeArc = num.getIntValue() != 0;
  66213. if (parseNextNumber (d, num, index, false))
  66214. {
  66215. const bool sweep = num.getIntValue() != 0;
  66216. if (parseCoords (d, x2, y2, index, false))
  66217. {
  66218. if (isRelative)
  66219. {
  66220. x2 += lastX;
  66221. y2 += lastY;
  66222. }
  66223. if (lastX != x2 || lastY != y2)
  66224. {
  66225. double centreX, centreY, startAngle, deltaAngle;
  66226. double rx = x, ry = y;
  66227. endpointToCentreParameters (lastX, lastY, x2, y2,
  66228. angle, largeArc, sweep,
  66229. rx, ry, centreX, centreY,
  66230. startAngle, deltaAngle);
  66231. path.addCentredArc ((float) centreX, (float) centreY,
  66232. (float) rx, (float) ry,
  66233. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  66234. false);
  66235. path.lineTo (x2, y2);
  66236. }
  66237. lastX2 = lastX;
  66238. lastY2 = lastY;
  66239. lastX = x2;
  66240. lastY = y2;
  66241. }
  66242. }
  66243. }
  66244. }
  66245. }
  66246. else
  66247. {
  66248. ++index;
  66249. }
  66250. break;
  66251. case T('Z'):
  66252. case T('z'):
  66253. path.closeSubPath();
  66254. while (CharacterFunctions::isWhitespace (d [index]))
  66255. ++index;
  66256. break;
  66257. default:
  66258. carryOn = false;
  66259. break;
  66260. }
  66261. if (! carryOn)
  66262. break;
  66263. }
  66264. return parseShape (xml, path);
  66265. }
  66266. Drawable* parseRect (const XmlElement& xml) const
  66267. {
  66268. Path rect;
  66269. const bool hasRX = xml.hasAttribute (T("rx"));
  66270. const bool hasRY = xml.hasAttribute (T("ry"));
  66271. if (hasRX || hasRY)
  66272. {
  66273. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66274. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66275. if (! hasRX)
  66276. rx = ry;
  66277. else if (! hasRY)
  66278. ry = rx;
  66279. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66280. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66281. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66282. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  66283. rx, ry);
  66284. }
  66285. else
  66286. {
  66287. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66288. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66289. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66290. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  66291. }
  66292. return parseShape (xml, rect);
  66293. }
  66294. Drawable* parseCircle (const XmlElement& xml) const
  66295. {
  66296. Path circle;
  66297. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66298. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66299. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  66300. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  66301. return parseShape (xml, circle);
  66302. }
  66303. Drawable* parseEllipse (const XmlElement& xml) const
  66304. {
  66305. Path ellipse;
  66306. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66307. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66308. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66309. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66310. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  66311. return parseShape (xml, ellipse);
  66312. }
  66313. Drawable* parseLine (const XmlElement& xml) const
  66314. {
  66315. Path line;
  66316. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  66317. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  66318. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  66319. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  66320. line.startNewSubPath (x1, y1);
  66321. line.lineTo (x2, y2);
  66322. return parseShape (xml, line);
  66323. }
  66324. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  66325. {
  66326. const String points (xml.getStringAttribute (T("points")));
  66327. Path path;
  66328. int index = 0;
  66329. float x, y;
  66330. if (parseCoords (points, x, y, index, true))
  66331. {
  66332. float firstX = x;
  66333. float firstY = y;
  66334. float lastX = 0, lastY = 0;
  66335. path.startNewSubPath (x, y);
  66336. while (parseCoords (points, x, y, index, true))
  66337. {
  66338. lastX = x;
  66339. lastY = y;
  66340. path.lineTo (x, y);
  66341. }
  66342. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  66343. path.closeSubPath();
  66344. }
  66345. return parseShape (xml, path);
  66346. }
  66347. Drawable* parseShape (const XmlElement& xml, Path& path,
  66348. const bool parseTransform = true) const
  66349. {
  66350. if (parseTransform && xml.hasAttribute (T("transform")))
  66351. {
  66352. SVGState newState (*this);
  66353. newState.addTransform (xml);
  66354. return newState.parseShape (xml, path, false);
  66355. }
  66356. DrawablePath* dp = new DrawablePath();
  66357. dp->setName (xml.getStringAttribute (T("id")));
  66358. dp->setSolidFill (Colours::transparentBlack);
  66359. path.applyTransform (transform);
  66360. dp->setPath (path);
  66361. Path::Iterator iter (path);
  66362. bool containsClosedSubPath = false;
  66363. while (iter.next())
  66364. {
  66365. if (iter.elementType == Path::Iterator::closePath)
  66366. {
  66367. containsClosedSubPath = true;
  66368. break;
  66369. }
  66370. }
  66371. Brush* const fillBrush
  66372. = getBrushForFill (path,
  66373. getStyleAttribute (&xml, T("fill")),
  66374. getStyleAttribute (&xml, T("fill-opacity")),
  66375. getStyleAttribute (&xml, T("opacity")),
  66376. containsClosedSubPath ? Colours::black
  66377. : Colours::transparentBlack);
  66378. if (fillBrush != 0)
  66379. {
  66380. if (! fillBrush->isInvisible())
  66381. {
  66382. fillBrush->applyTransform (transform);
  66383. dp->setFillBrush (*fillBrush);
  66384. }
  66385. delete fillBrush;
  66386. }
  66387. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  66388. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  66389. {
  66390. Brush* const strokeBrush
  66391. = getBrushForFill (path, strokeType,
  66392. getStyleAttribute (&xml, T("stroke-opacity")),
  66393. getStyleAttribute (&xml, T("opacity")),
  66394. Colours::transparentBlack);
  66395. if (strokeBrush != 0)
  66396. {
  66397. const PathStrokeType stroke (getStrokeFor (&xml));
  66398. if (! strokeBrush->isInvisible())
  66399. {
  66400. strokeBrush->applyTransform (transform);
  66401. dp->setOutline (stroke, *strokeBrush);
  66402. }
  66403. delete strokeBrush;
  66404. }
  66405. }
  66406. return dp;
  66407. }
  66408. const XmlElement* findLinkedElement (const XmlElement* e) const
  66409. {
  66410. const String id (e->getStringAttribute (T("xlink:href")));
  66411. if (! id.startsWithChar (T('#')))
  66412. return 0;
  66413. return findElementForId (topLevelXml, id.substring (1));
  66414. }
  66415. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  66416. {
  66417. if (fillXml == 0)
  66418. return;
  66419. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  66420. {
  66421. int index = 0;
  66422. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  66423. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  66424. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  66425. double offset = e->getDoubleAttribute (T("offset"));
  66426. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  66427. offset *= 0.01;
  66428. cg.addColour (jlimit (0.0, 1.0, offset), col);
  66429. }
  66430. }
  66431. Brush* getBrushForFill (const Path& path,
  66432. const String& fill,
  66433. const String& fillOpacity,
  66434. const String& overallOpacity,
  66435. const Colour& defaultColour) const
  66436. {
  66437. float opacity = 1.0f;
  66438. if (overallOpacity.isNotEmpty())
  66439. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  66440. if (fillOpacity.isNotEmpty())
  66441. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  66442. if (fill.startsWithIgnoreCase (T("url")))
  66443. {
  66444. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  66445. .upToLastOccurrenceOf (T(")"), false, false).trim());
  66446. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  66447. if (fillXml != 0
  66448. && (fillXml->hasTagName (T("linearGradient"))
  66449. || fillXml->hasTagName (T("radialGradient"))))
  66450. {
  66451. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  66452. ColourGradient cg;
  66453. addGradientStopsIn (cg, inheritedFrom);
  66454. addGradientStopsIn (cg, fillXml);
  66455. if (cg.getNumColours() > 0)
  66456. {
  66457. cg.addColour (0.0, cg.getColour (0));
  66458. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  66459. }
  66460. else
  66461. {
  66462. cg.addColour (0.0, Colours::black);
  66463. cg.addColour (1.0, Colours::black);
  66464. }
  66465. if (overallOpacity.isNotEmpty())
  66466. cg.multiplyOpacity (overallOpacity.getFloatValue());
  66467. jassert (cg.getNumColours() > 0);
  66468. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  66469. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  66470. float width = viewBoxW;
  66471. float height = viewBoxH;
  66472. float dx = 0.0;
  66473. float dy = 0.0;
  66474. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  66475. if (! userSpace)
  66476. path.getBounds (dx, dy, width, height);
  66477. if (cg.isRadial)
  66478. {
  66479. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  66480. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  66481. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  66482. cg.x2 = cg.x1 + radius;
  66483. cg.y2 = cg.y1;
  66484. //xxx (the fx, fy focal point isn't handled properly here..)
  66485. }
  66486. else
  66487. {
  66488. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  66489. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  66490. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  66491. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  66492. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  66493. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  66494. }
  66495. return new GradientBrush (cg);
  66496. }
  66497. }
  66498. if (fill.equalsIgnoreCase (T("none")))
  66499. return new SolidColourBrush (Colours::transparentBlack);
  66500. int i = 0;
  66501. Colour colour (parseColour (fill, i, defaultColour));
  66502. colour = colour.withMultipliedAlpha (opacity);
  66503. return new SolidColourBrush (colour);
  66504. }
  66505. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  66506. {
  66507. const String width (getStyleAttribute (xml, T("stroke-width")));
  66508. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  66509. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  66510. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  66511. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  66512. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  66513. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  66514. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  66515. if (join.equalsIgnoreCase (T("round")))
  66516. joinStyle = PathStrokeType::curved;
  66517. else if (join.equalsIgnoreCase (T("bevel")))
  66518. joinStyle = PathStrokeType::beveled;
  66519. if (cap.equalsIgnoreCase (T("round")))
  66520. capStyle = PathStrokeType::rounded;
  66521. else if (cap.equalsIgnoreCase (T("square")))
  66522. capStyle = PathStrokeType::square;
  66523. float ox = 0.0f, oy = 0.0f;
  66524. transform.transformPoint (ox, oy);
  66525. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  66526. transform.transformPoint (x, y);
  66527. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  66528. joinStyle, capStyle);
  66529. }
  66530. Drawable* parseText (const XmlElement& xml)
  66531. {
  66532. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  66533. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  66534. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  66535. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  66536. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  66537. //xxx not done text yet!
  66538. forEachXmlChildElement (xml, e)
  66539. {
  66540. if (e->isTextElement())
  66541. {
  66542. const String text (e->getText());
  66543. Path path;
  66544. Drawable* s = parseShape (*e, path);
  66545. delete s;
  66546. }
  66547. else if (e->hasTagName (T("tspan")))
  66548. {
  66549. Drawable* s = parseText (*e);
  66550. delete s;
  66551. }
  66552. }
  66553. return 0;
  66554. }
  66555. void addTransform (const XmlElement& xml)
  66556. {
  66557. transform = parseTransform (xml.getStringAttribute (T("transform")))
  66558. .followedBy (transform);
  66559. }
  66560. bool parseCoord (const String& s, float& value, int& index,
  66561. const bool allowUnits, const bool isX) const
  66562. {
  66563. String number;
  66564. if (! parseNextNumber (s, number, index, allowUnits))
  66565. {
  66566. value = 0;
  66567. return false;
  66568. }
  66569. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  66570. return true;
  66571. }
  66572. bool parseCoords (const String& s, float& x, float& y,
  66573. int& index, const bool allowUnits) const
  66574. {
  66575. return parseCoord (s, x, index, allowUnits, true)
  66576. && parseCoord (s, y, index, allowUnits, false);
  66577. }
  66578. float getCoordLength (const String& s, const float sizeForProportions) const
  66579. {
  66580. float n = s.getFloatValue();
  66581. const int len = s.length();
  66582. if (len > 2)
  66583. {
  66584. const float dpi = 96.0f;
  66585. const tchar n1 = s [len - 2];
  66586. const tchar n2 = s [len - 1];
  66587. if (n1 == T('i') && n2 == T('n'))
  66588. n *= dpi;
  66589. else if (n1 == T('m') && n2 == T('m'))
  66590. n *= dpi / 25.4f;
  66591. else if (n1 == T('c') && n2 == T('m'))
  66592. n *= dpi / 2.54f;
  66593. else if (n1 == T('p') && n2 == T('c'))
  66594. n *= 15.0f;
  66595. else if (n2 == T('%'))
  66596. n *= 0.01f * sizeForProportions;
  66597. }
  66598. return n;
  66599. }
  66600. void getCoordList (Array <float>& coords, const String& list,
  66601. const bool allowUnits, const bool isX) const
  66602. {
  66603. int index = 0;
  66604. float value;
  66605. while (parseCoord (list, value, index, allowUnits, isX))
  66606. coords.add (value);
  66607. }
  66608. void parseCSSStyle (const XmlElement& xml)
  66609. {
  66610. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  66611. }
  66612. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  66613. const String& defaultValue = String::empty) const
  66614. {
  66615. if (xml->hasAttribute (attributeName))
  66616. return xml->getStringAttribute (attributeName, defaultValue);
  66617. const String styleAtt (xml->getStringAttribute (T("style")));
  66618. if (styleAtt.isNotEmpty())
  66619. {
  66620. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  66621. if (value.isNotEmpty())
  66622. return value;
  66623. }
  66624. else if (xml->hasAttribute (T("class")))
  66625. {
  66626. const String className (T(".") + xml->getStringAttribute (T("class")));
  66627. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  66628. if (index < 0)
  66629. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  66630. if (index >= 0)
  66631. {
  66632. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  66633. if (openBracket > index)
  66634. {
  66635. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  66636. if (closeBracket > openBracket)
  66637. {
  66638. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  66639. if (value.isNotEmpty())
  66640. return value;
  66641. }
  66642. }
  66643. }
  66644. }
  66645. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66646. if (xml != 0)
  66647. return getStyleAttribute (xml, attributeName, defaultValue);
  66648. return defaultValue;
  66649. }
  66650. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  66651. {
  66652. if (xml->hasAttribute (attributeName))
  66653. return xml->getStringAttribute (attributeName);
  66654. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66655. if (xml != 0)
  66656. return getInheritedAttribute (xml, attributeName);
  66657. return String::empty;
  66658. }
  66659. static bool isIdentifierChar (const tchar c)
  66660. {
  66661. return CharacterFunctions::isLetter (c) || c == T('-');
  66662. }
  66663. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  66664. {
  66665. int i = 0;
  66666. for (;;)
  66667. {
  66668. i = list.indexOf (i, attributeName);
  66669. if (i < 0)
  66670. break;
  66671. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  66672. && ! isIdentifierChar (list [i + attributeName.length()]))
  66673. {
  66674. i = list.indexOfChar (i, T(':'));
  66675. if (i < 0)
  66676. break;
  66677. int end = list.indexOfChar (i, T(';'));
  66678. if (end < 0)
  66679. end = 0x7ffff;
  66680. return list.substring (i + 1, end).trim();
  66681. }
  66682. ++i;
  66683. }
  66684. return defaultValue;
  66685. }
  66686. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  66687. {
  66688. const tchar* const s = (const tchar*) source;
  66689. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66690. ++index;
  66691. int start = index;
  66692. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  66693. ++index;
  66694. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  66695. ++index;
  66696. if ((s[index] == T('e') || s[index] == T('E'))
  66697. && (CharacterFunctions::isDigit (s[index + 1])
  66698. || s[index + 1] == T('-')
  66699. || s[index + 1] == T('+')))
  66700. {
  66701. index += 2;
  66702. while (CharacterFunctions::isDigit (s[index]))
  66703. ++index;
  66704. }
  66705. if (allowUnits)
  66706. {
  66707. while (CharacterFunctions::isLetter (s[index]))
  66708. ++index;
  66709. }
  66710. if (index == start)
  66711. return false;
  66712. value = String (s + start, index - start);
  66713. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66714. ++index;
  66715. return true;
  66716. }
  66717. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  66718. {
  66719. if (s [index] == T('#'))
  66720. {
  66721. uint32 hex [6];
  66722. zeromem (hex, sizeof (hex));
  66723. int numChars = 0;
  66724. for (int i = 6; --i >= 0;)
  66725. {
  66726. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  66727. if (hexValue >= 0)
  66728. hex [numChars++] = hexValue;
  66729. else
  66730. break;
  66731. }
  66732. if (numChars <= 3)
  66733. return Colour ((uint8) (hex [0] * 0x11),
  66734. (uint8) (hex [1] * 0x11),
  66735. (uint8) (hex [2] * 0x11));
  66736. else
  66737. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  66738. (uint8) ((hex [2] << 4) + hex [3]),
  66739. (uint8) ((hex [4] << 4) + hex [5]));
  66740. }
  66741. else if (s [index] == T('r')
  66742. && s [index + 1] == T('g')
  66743. && s [index + 2] == T('b'))
  66744. {
  66745. const int openBracket = s.indexOfChar (index, T('('));
  66746. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  66747. if (openBracket >= 3 && closeBracket > openBracket)
  66748. {
  66749. index = closeBracket;
  66750. StringArray tokens;
  66751. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  66752. tokens.trim();
  66753. tokens.removeEmptyStrings();
  66754. if (tokens[0].containsChar (T('%')))
  66755. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  66756. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  66757. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  66758. else
  66759. return Colour ((uint8) tokens[0].getIntValue(),
  66760. (uint8) tokens[1].getIntValue(),
  66761. (uint8) tokens[2].getIntValue());
  66762. }
  66763. }
  66764. return Colours::findColourForName (s, defaultColour);
  66765. }
  66766. static const AffineTransform parseTransform (String t)
  66767. {
  66768. AffineTransform result;
  66769. while (t.isNotEmpty())
  66770. {
  66771. StringArray tokens;
  66772. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  66773. .upToFirstOccurrenceOf (T(")"), false, false),
  66774. T(", "), 0);
  66775. tokens.removeEmptyStrings (true);
  66776. float numbers [6];
  66777. for (int i = 0; i < 6; ++i)
  66778. numbers[i] = tokens[i].getFloatValue();
  66779. AffineTransform trans;
  66780. if (t.startsWithIgnoreCase (T("matrix")))
  66781. {
  66782. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  66783. numbers[1], numbers[3], numbers[5]);
  66784. }
  66785. else if (t.startsWithIgnoreCase (T("translate")))
  66786. {
  66787. trans = trans.translated (numbers[0], numbers[1]);
  66788. }
  66789. else if (t.startsWithIgnoreCase (T("scale")))
  66790. {
  66791. if (tokens.size() == 1)
  66792. trans = trans.scaled (numbers[0], numbers[0]);
  66793. else
  66794. trans = trans.scaled (numbers[0], numbers[1]);
  66795. }
  66796. else if (t.startsWithIgnoreCase (T("rotate")))
  66797. {
  66798. if (tokens.size() != 3)
  66799. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  66800. else
  66801. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  66802. numbers[1], numbers[2]);
  66803. }
  66804. else if (t.startsWithIgnoreCase (T("skewX")))
  66805. {
  66806. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  66807. 0.0f, 1.0f, 0.0f);
  66808. }
  66809. else if (t.startsWithIgnoreCase (T("skewY")))
  66810. {
  66811. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  66812. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  66813. }
  66814. result = trans.followedBy (result);
  66815. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  66816. }
  66817. return result;
  66818. }
  66819. static void endpointToCentreParameters (const double x1, const double y1,
  66820. const double x2, const double y2,
  66821. const double angle,
  66822. const bool largeArc, const bool sweep,
  66823. double& rx, double& ry,
  66824. double& centreX, double& centreY,
  66825. double& startAngle, double& deltaAngle)
  66826. {
  66827. const double midX = (x1 - x2) * 0.5;
  66828. const double midY = (y1 - y2) * 0.5;
  66829. const double cosAngle = cos (angle);
  66830. const double sinAngle = sin (angle);
  66831. const double xp = cosAngle * midX + sinAngle * midY;
  66832. const double yp = cosAngle * midY - sinAngle * midX;
  66833. const double xp2 = xp * xp;
  66834. const double yp2 = yp * yp;
  66835. double rx2 = rx * rx;
  66836. double ry2 = ry * ry;
  66837. const double s = (xp2 / rx2) + (yp2 / ry2);
  66838. double c;
  66839. if (s <= 1.0)
  66840. {
  66841. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  66842. / (( rx2 * yp2) + (ry2 * xp2))));
  66843. if (largeArc == sweep)
  66844. c = -c;
  66845. }
  66846. else
  66847. {
  66848. const double s2 = sqrt (s);
  66849. rx *= s2;
  66850. ry *= s2;
  66851. rx2 = rx * rx;
  66852. ry2 = ry * ry;
  66853. c = 0;
  66854. }
  66855. const double cpx = ((rx * yp) / ry) * c;
  66856. const double cpy = ((-ry * xp) / rx) * c;
  66857. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  66858. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  66859. const double ux = (xp - cpx) / rx;
  66860. const double uy = (yp - cpy) / ry;
  66861. const double vx = (-xp - cpx) / rx;
  66862. const double vy = (-yp - cpy) / ry;
  66863. const double length = juce_hypot (ux, uy);
  66864. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  66865. if (uy < 0)
  66866. startAngle = -startAngle;
  66867. startAngle += double_Pi * 0.5;
  66868. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  66869. / (length * juce_hypot (vx, vy))));
  66870. if ((ux * vy) - (uy * vx) < 0)
  66871. deltaAngle = -deltaAngle;
  66872. if (sweep)
  66873. {
  66874. if (deltaAngle < 0)
  66875. deltaAngle += double_Pi * 2.0;
  66876. }
  66877. else
  66878. {
  66879. if (deltaAngle > 0)
  66880. deltaAngle -= double_Pi * 2.0;
  66881. }
  66882. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  66883. }
  66884. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  66885. {
  66886. forEachXmlChildElement (*parent, e)
  66887. {
  66888. if (e->compareAttribute (T("id"), id))
  66889. return e;
  66890. const XmlElement* const found = findElementForId (e, id);
  66891. if (found != 0)
  66892. return found;
  66893. }
  66894. return 0;
  66895. }
  66896. const SVGState& operator= (const SVGState&);
  66897. };
  66898. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  66899. {
  66900. SVGState state (&svgDocument);
  66901. return state.parseSVGElement (svgDocument);
  66902. }
  66903. END_JUCE_NAMESPACE
  66904. /********* End of inlined file: juce_SVGParser.cpp *********/
  66905. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  66906. BEGIN_JUCE_NAMESPACE
  66907. #if JUCE_MSVC
  66908. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  66909. #endif
  66910. DropShadowEffect::DropShadowEffect()
  66911. : offsetX (0),
  66912. offsetY (0),
  66913. radius (4),
  66914. opacity (0.6f)
  66915. {
  66916. }
  66917. DropShadowEffect::~DropShadowEffect()
  66918. {
  66919. }
  66920. void DropShadowEffect::setShadowProperties (const float newRadius,
  66921. const float newOpacity,
  66922. const int newShadowOffsetX,
  66923. const int newShadowOffsetY)
  66924. {
  66925. radius = jmax (1.1f, newRadius);
  66926. offsetX = newShadowOffsetX;
  66927. offsetY = newShadowOffsetY;
  66928. opacity = newOpacity;
  66929. }
  66930. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  66931. {
  66932. const int w = image.getWidth();
  66933. const int h = image.getHeight();
  66934. int lineStride, pixelStride;
  66935. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  66936. Image shadowImage (Image::SingleChannel, w, h, false);
  66937. int destStride, destPixelStride;
  66938. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  66939. const int filter = roundFloatToInt (63.0f / radius);
  66940. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  66941. for (int x = w; --x >= 0;)
  66942. {
  66943. int shadowAlpha = 0;
  66944. const PixelARGB* src = srcPixels + x;
  66945. uint8* shadowPix = shadowChannel + x;
  66946. for (int y = h; --y >= 0;)
  66947. {
  66948. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  66949. *shadowPix = (uint8) shadowAlpha;
  66950. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  66951. shadowPix += destStride;
  66952. }
  66953. }
  66954. for (int y = h; --y >= 0;)
  66955. {
  66956. int shadowAlpha = 0;
  66957. uint8* shadowPix = shadowChannel + y * destStride;
  66958. for (int x = w; --x >= 0;)
  66959. {
  66960. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  66961. *shadowPix++ = (uint8) shadowAlpha;
  66962. }
  66963. }
  66964. image.releasePixelDataReadOnly (srcPixels);
  66965. shadowImage.releasePixelDataReadWrite (shadowChannel);
  66966. g.setColour (Colours::black.withAlpha (opacity));
  66967. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  66968. g.setOpacity (1.0f);
  66969. g.drawImageAt (&image, 0, 0);
  66970. }
  66971. END_JUCE_NAMESPACE
  66972. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  66973. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  66974. BEGIN_JUCE_NAMESPACE
  66975. GlowEffect::GlowEffect()
  66976. : radius (2.0f),
  66977. colour (Colours::white)
  66978. {
  66979. }
  66980. GlowEffect::~GlowEffect()
  66981. {
  66982. }
  66983. void GlowEffect::setGlowProperties (const float newRadius,
  66984. const Colour& newColour)
  66985. {
  66986. radius = newRadius;
  66987. colour = newColour;
  66988. }
  66989. void GlowEffect::applyEffect (Image& image, Graphics& g)
  66990. {
  66991. const int w = image.getWidth();
  66992. const int h = image.getHeight();
  66993. Image temp (image.getFormat(), w, h, true);
  66994. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  66995. blurKernel.createGaussianBlur (radius);
  66996. blurKernel.rescaleAllValues (radius);
  66997. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  66998. g.setColour (colour);
  66999. g.drawImageAt (&temp, 0, 0, true);
  67000. g.setOpacity (1.0f);
  67001. g.drawImageAt (&image, 0, 0, false);
  67002. }
  67003. END_JUCE_NAMESPACE
  67004. /********* End of inlined file: juce_GlowEffect.cpp *********/
  67005. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  67006. BEGIN_JUCE_NAMESPACE
  67007. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  67008. : opacity (opacity_)
  67009. {
  67010. }
  67011. ReduceOpacityEffect::~ReduceOpacityEffect()
  67012. {
  67013. }
  67014. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  67015. {
  67016. opacity = jlimit (0.0f, 1.0f, newOpacity);
  67017. }
  67018. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  67019. {
  67020. g.setOpacity (opacity);
  67021. g.drawImageAt (&image, 0, 0);
  67022. }
  67023. END_JUCE_NAMESPACE
  67024. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  67025. /********* Start of inlined file: juce_Font.cpp *********/
  67026. BEGIN_JUCE_NAMESPACE
  67027. static const float minFontHeight = 0.1f;
  67028. static const float maxFontHeight = 10000.0f;
  67029. static const float defaultFontHeight = 14.0f;
  67030. Font::Font() throw()
  67031. : typefaceName (Typeface::defaultTypefaceNameSans),
  67032. height (defaultFontHeight),
  67033. horizontalScale (1.0f),
  67034. kerning (0),
  67035. ascent (0),
  67036. styleFlags (Font::plain)
  67037. {
  67038. }
  67039. void Font::resetToDefaultState() throw()
  67040. {
  67041. typefaceName = Typeface::defaultTypefaceNameSans;
  67042. height = defaultFontHeight;
  67043. horizontalScale = 1.0f;
  67044. kerning = 0;
  67045. ascent = 0;
  67046. styleFlags = Font::plain;
  67047. typeface = 0;
  67048. }
  67049. Font::Font (const float fontHeight,
  67050. const int styleFlags_) throw()
  67051. : typefaceName (Typeface::defaultTypefaceNameSans),
  67052. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  67053. horizontalScale (1.0f),
  67054. kerning (0),
  67055. ascent (0),
  67056. styleFlags (styleFlags_)
  67057. {
  67058. }
  67059. Font::Font (const String& typefaceName_,
  67060. const float fontHeight,
  67061. const int styleFlags_) throw()
  67062. : typefaceName (typefaceName_),
  67063. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  67064. horizontalScale (1.0f),
  67065. kerning (0),
  67066. ascent (0),
  67067. styleFlags (styleFlags_)
  67068. {
  67069. }
  67070. Font::Font (const Font& other) throw()
  67071. : typefaceName (other.typefaceName),
  67072. height (other.height),
  67073. horizontalScale (other.horizontalScale),
  67074. kerning (other.kerning),
  67075. ascent (other.ascent),
  67076. styleFlags (other.styleFlags),
  67077. typeface (other.typeface)
  67078. {
  67079. }
  67080. const Font& Font::operator= (const Font& other) throw()
  67081. {
  67082. if (this != &other)
  67083. {
  67084. typefaceName = other.typefaceName;
  67085. height = other.height;
  67086. styleFlags = other.styleFlags;
  67087. horizontalScale = other.horizontalScale;
  67088. kerning = other.kerning;
  67089. ascent = other.ascent;
  67090. typeface = other.typeface;
  67091. }
  67092. return *this;
  67093. }
  67094. Font::~Font() throw()
  67095. {
  67096. }
  67097. Font::Font (const Typeface& face) throw()
  67098. : height (11.0f),
  67099. horizontalScale (1.0f),
  67100. kerning (0),
  67101. ascent (0),
  67102. styleFlags (plain)
  67103. {
  67104. typefaceName = face.getName();
  67105. setBold (face.isBold());
  67106. setItalic (face.isItalic());
  67107. typeface = new Typeface (face);
  67108. }
  67109. bool Font::operator== (const Font& other) const throw()
  67110. {
  67111. return height == other.height
  67112. && horizontalScale == other.horizontalScale
  67113. && kerning == other.kerning
  67114. && styleFlags == other.styleFlags
  67115. && typefaceName == other.typefaceName;
  67116. }
  67117. bool Font::operator!= (const Font& other) const throw()
  67118. {
  67119. return ! operator== (other);
  67120. }
  67121. void Font::setTypefaceName (const String& faceName) throw()
  67122. {
  67123. typefaceName = faceName;
  67124. typeface = 0;
  67125. ascent = 0;
  67126. }
  67127. static String fallbackFont;
  67128. const String Font::getFallbackFontName() throw()
  67129. {
  67130. return fallbackFont;
  67131. }
  67132. void Font::setFallbackFontName (const String& name) throw()
  67133. {
  67134. fallbackFont = name;
  67135. }
  67136. void Font::setHeight (float newHeight) throw()
  67137. {
  67138. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67139. }
  67140. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  67141. {
  67142. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  67143. horizontalScale *= (height / newHeight);
  67144. height = newHeight;
  67145. }
  67146. void Font::setStyleFlags (const int newFlags) throw()
  67147. {
  67148. if (styleFlags != newFlags)
  67149. {
  67150. styleFlags = newFlags;
  67151. typeface = 0;
  67152. ascent = 0;
  67153. }
  67154. }
  67155. void Font::setSizeAndStyle (const float newHeight,
  67156. const int newStyleFlags,
  67157. const float newHorizontalScale,
  67158. const float newKerningAmount) throw()
  67159. {
  67160. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67161. horizontalScale = newHorizontalScale;
  67162. kerning = newKerningAmount;
  67163. setStyleFlags (newStyleFlags);
  67164. }
  67165. void Font::setHorizontalScale (const float scaleFactor) throw()
  67166. {
  67167. horizontalScale = scaleFactor;
  67168. }
  67169. void Font::setExtraKerningFactor (const float extraKerning) throw()
  67170. {
  67171. kerning = extraKerning;
  67172. }
  67173. void Font::setBold (const bool shouldBeBold) throw()
  67174. {
  67175. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  67176. : (styleFlags & ~bold));
  67177. }
  67178. bool Font::isBold() const throw()
  67179. {
  67180. return (styleFlags & bold) != 0;
  67181. }
  67182. void Font::setItalic (const bool shouldBeItalic) throw()
  67183. {
  67184. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  67185. : (styleFlags & ~italic));
  67186. }
  67187. bool Font::isItalic() const throw()
  67188. {
  67189. return (styleFlags & italic) != 0;
  67190. }
  67191. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  67192. {
  67193. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  67194. : (styleFlags & ~underlined));
  67195. }
  67196. bool Font::isUnderlined() const throw()
  67197. {
  67198. return (styleFlags & underlined) != 0;
  67199. }
  67200. float Font::getAscent() const throw()
  67201. {
  67202. if (ascent == 0)
  67203. ascent = getTypeface()->getAscent();
  67204. return height * ascent;
  67205. }
  67206. float Font::getDescent() const throw()
  67207. {
  67208. return height - getAscent();
  67209. }
  67210. int Font::getStringWidth (const String& text) const throw()
  67211. {
  67212. return roundFloatToInt (getStringWidthFloat (text));
  67213. }
  67214. float Font::getStringWidthFloat (const String& text) const throw()
  67215. {
  67216. float x = 0.0f;
  67217. if (text.isNotEmpty())
  67218. {
  67219. Typeface* const typeface = getTypeface();
  67220. const juce_wchar* t = (const juce_wchar*) text;
  67221. do
  67222. {
  67223. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  67224. if (glyph != 0)
  67225. x += kerning + glyph->getHorizontalSpacing (*t);
  67226. }
  67227. while (*t != 0);
  67228. x *= height;
  67229. x *= horizontalScale;
  67230. }
  67231. return x;
  67232. }
  67233. Typeface* Font::getTypeface() const throw()
  67234. {
  67235. if (typeface == 0)
  67236. typeface = Typeface::getTypefaceFor (*this);
  67237. return typeface;
  67238. }
  67239. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  67240. {
  67241. const StringArray names (findAllTypefaceNames());
  67242. for (int i = 0; i < names.size(); ++i)
  67243. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  67244. }
  67245. END_JUCE_NAMESPACE
  67246. /********* End of inlined file: juce_Font.cpp *********/
  67247. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  67248. BEGIN_JUCE_NAMESPACE
  67249. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  67250. class FontGlyphAlphaMap
  67251. {
  67252. public:
  67253. bool draw (const Graphics& g, float x, const float y) const throw()
  67254. {
  67255. if (bitmap1 == 0)
  67256. return false;
  67257. x += xOrigin;
  67258. const float xFloor = floorf (x);
  67259. const int intX = (int) xFloor;
  67260. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  67261. intX, (int) floorf (y + yOrigin), true);
  67262. return true;
  67263. }
  67264. juce_UseDebuggingNewOperator
  67265. private:
  67266. Image* bitmap1;
  67267. Image* bitmap2;
  67268. float xOrigin, yOrigin;
  67269. int lastAccessCount;
  67270. Typeface::Ptr typeface;
  67271. float height, horizontalScale;
  67272. juce_wchar character;
  67273. friend class GlyphCache;
  67274. FontGlyphAlphaMap() throw()
  67275. : bitmap1 (0),
  67276. bitmap2 (0),
  67277. lastAccessCount (0),
  67278. height (0),
  67279. horizontalScale (0),
  67280. character (0)
  67281. {
  67282. }
  67283. ~FontGlyphAlphaMap() throw()
  67284. {
  67285. delete bitmap1;
  67286. delete bitmap2;
  67287. }
  67288. class AlphaBitmapRenderer
  67289. {
  67290. uint8* const data;
  67291. const int stride;
  67292. uint8* lineStart;
  67293. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  67294. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  67295. public:
  67296. AlphaBitmapRenderer (uint8* const data_,
  67297. const int stride_) throw()
  67298. : data (data_),
  67299. stride (stride_)
  67300. {
  67301. }
  67302. forcedinline void setEdgeTableYPos (const int y) throw()
  67303. {
  67304. lineStart = data + (stride * y);
  67305. }
  67306. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67307. {
  67308. lineStart [x] = (uint8) alphaLevel;
  67309. }
  67310. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  67311. {
  67312. uint8* d = lineStart + x;
  67313. while (--width >= 0)
  67314. *d++ = (uint8) alphaLevel;
  67315. }
  67316. };
  67317. Image* createAlphaMapFromPath (const Path& path,
  67318. float& topLeftX, float& topLeftY,
  67319. float xScale, float yScale,
  67320. const float subPixelOffsetX) throw()
  67321. {
  67322. Image* im = 0;
  67323. float px, py, pw, ph;
  67324. path.getBounds (px, py, pw, ph);
  67325. topLeftX = floorf (px * xScale);
  67326. topLeftY = floorf (py * yScale);
  67327. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  67328. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  67329. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  67330. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  67331. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  67332. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  67333. int stride, pixelStride;
  67334. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  67335. jassert (pixelStride == 1);
  67336. AlphaBitmapRenderer renderer (pixels, stride);
  67337. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  67338. im->releasePixelDataReadWrite (pixels);
  67339. return im;
  67340. }
  67341. void generate (Typeface* const face,
  67342. const juce_wchar character_,
  67343. const float fontHeight,
  67344. const float fontHorizontalScale) throw()
  67345. {
  67346. character = character_;
  67347. typeface = face;
  67348. height = fontHeight;
  67349. horizontalScale = fontHorizontalScale;
  67350. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  67351. deleteAndZero (bitmap1);
  67352. deleteAndZero (bitmap2);
  67353. const float fontHScale = fontHeight * fontHorizontalScale;
  67354. if (glyphPath != 0 && ! glyphPath->isEmpty())
  67355. {
  67356. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  67357. if (fontHScale < 24.0f)
  67358. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  67359. }
  67360. else
  67361. {
  67362. xOrigin = yOrigin = 0;
  67363. }
  67364. }
  67365. };
  67366. static const int defaultNumGlyphsToCache = 120;
  67367. class GlyphCache;
  67368. static GlyphCache* cacheInstance = 0;
  67369. class GlyphCache : private DeletedAtShutdown
  67370. {
  67371. public:
  67372. static GlyphCache* getInstance() throw()
  67373. {
  67374. if (cacheInstance == 0)
  67375. cacheInstance = new GlyphCache();
  67376. return cacheInstance;
  67377. }
  67378. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  67379. const float fontHeight,
  67380. const float fontHorizontalScale,
  67381. const juce_wchar character) throw()
  67382. {
  67383. ++accessCounter;
  67384. int oldestCounter = INT_MAX;
  67385. int oldestIndex = 0;
  67386. for (int i = numGlyphs; --i >= 0;)
  67387. {
  67388. FontGlyphAlphaMap& g = glyphs[i];
  67389. if (g.character == character
  67390. && g.height == fontHeight
  67391. && g.typeface->hashCode() == typeface->hashCode()
  67392. && g.horizontalScale == fontHorizontalScale)
  67393. {
  67394. g.lastAccessCount = accessCounter;
  67395. ++hits;
  67396. return g;
  67397. }
  67398. if (oldestCounter > g.lastAccessCount)
  67399. {
  67400. oldestCounter = g.lastAccessCount;
  67401. oldestIndex = i;
  67402. }
  67403. }
  67404. ++misses;
  67405. if (hits + misses > (numGlyphs << 4))
  67406. {
  67407. if (misses * 2 > hits)
  67408. setCacheSize (numGlyphs + 32);
  67409. hits = 0;
  67410. misses = 0;
  67411. oldestIndex = 0;
  67412. }
  67413. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  67414. oldest.lastAccessCount = accessCounter;
  67415. oldest.generate (typeface,
  67416. character,
  67417. fontHeight,
  67418. fontHorizontalScale);
  67419. return oldest;
  67420. }
  67421. void setCacheSize (const int num) throw()
  67422. {
  67423. if (numGlyphs != num)
  67424. {
  67425. numGlyphs = num;
  67426. if (glyphs != 0)
  67427. delete[] glyphs;
  67428. glyphs = new FontGlyphAlphaMap [numGlyphs];
  67429. hits = 0;
  67430. misses = 0;
  67431. }
  67432. }
  67433. juce_UseDebuggingNewOperator
  67434. private:
  67435. FontGlyphAlphaMap* glyphs;
  67436. int numGlyphs, accessCounter;
  67437. int hits, misses;
  67438. GlyphCache() throw()
  67439. : glyphs (0),
  67440. numGlyphs (0),
  67441. accessCounter (0)
  67442. {
  67443. setCacheSize (defaultNumGlyphsToCache);
  67444. }
  67445. ~GlyphCache() throw()
  67446. {
  67447. delete[] glyphs;
  67448. jassert (cacheInstance == this);
  67449. cacheInstance = 0;
  67450. }
  67451. GlyphCache (const GlyphCache&);
  67452. const GlyphCache& operator= (const GlyphCache&);
  67453. };
  67454. PositionedGlyph::PositionedGlyph() throw()
  67455. {
  67456. }
  67457. void PositionedGlyph::draw (const Graphics& g) const throw()
  67458. {
  67459. if (! glyphInfo->isWhitespace())
  67460. {
  67461. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  67462. {
  67463. const FontGlyphAlphaMap& alphaMap
  67464. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  67465. fontHeight,
  67466. fontHorizontalScale,
  67467. getCharacter());
  67468. alphaMap.draw (g, x, y);
  67469. }
  67470. else
  67471. {
  67472. // that's a bit of a dodgy size, isn't it??
  67473. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  67474. draw (g, AffineTransform::identity);
  67475. }
  67476. }
  67477. }
  67478. void PositionedGlyph::draw (const Graphics& g,
  67479. const AffineTransform& transform) const throw()
  67480. {
  67481. if (! glyphInfo->isWhitespace())
  67482. {
  67483. g.fillPath (glyphInfo->getPath(),
  67484. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67485. .translated (x, y)
  67486. .followedBy (transform));
  67487. }
  67488. }
  67489. void PositionedGlyph::createPath (Path& path) const throw()
  67490. {
  67491. if (! glyphInfo->isWhitespace())
  67492. {
  67493. path.addPath (glyphInfo->getPath(),
  67494. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67495. .translated (x, y));
  67496. }
  67497. }
  67498. bool PositionedGlyph::hitTest (float px, float py) const throw()
  67499. {
  67500. if (px >= getLeft() && px < getRight()
  67501. && py >= getTop() && py < getBottom()
  67502. && fontHeight > 0.0f
  67503. && ! glyphInfo->isWhitespace())
  67504. {
  67505. AffineTransform::translation (-x, -y)
  67506. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  67507. .transformPoint (px, py);
  67508. return glyphInfo->getPath().contains (px, py);
  67509. }
  67510. return false;
  67511. }
  67512. void PositionedGlyph::moveBy (const float deltaX,
  67513. const float deltaY) throw()
  67514. {
  67515. x += deltaX;
  67516. y += deltaY;
  67517. }
  67518. GlyphArrangement::GlyphArrangement() throw()
  67519. : numGlyphs (0),
  67520. numAllocated (0),
  67521. glyphs (0)
  67522. {
  67523. }
  67524. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  67525. : numGlyphs (0),
  67526. numAllocated (0),
  67527. glyphs (0)
  67528. {
  67529. addGlyphArrangement (other);
  67530. }
  67531. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  67532. {
  67533. if (this != &other)
  67534. {
  67535. clear();
  67536. addGlyphArrangement (other);
  67537. }
  67538. return *this;
  67539. }
  67540. GlyphArrangement::~GlyphArrangement() throw()
  67541. {
  67542. clear();
  67543. juce_free (glyphs);
  67544. }
  67545. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  67546. {
  67547. if (numAllocated <= minGlyphs)
  67548. {
  67549. numAllocated = minGlyphs + 2;
  67550. if (glyphs == 0)
  67551. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  67552. else
  67553. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  67554. }
  67555. }
  67556. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  67557. {
  67558. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  67559. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67560. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  67561. }
  67562. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  67563. {
  67564. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67565. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  67566. }
  67567. void GlyphArrangement::clear() throw()
  67568. {
  67569. for (int i = numGlyphs; --i >= 0;)
  67570. decGlyphRefCount (i);
  67571. numGlyphs = 0;
  67572. }
  67573. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  67574. {
  67575. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  67576. return glyphs [index];
  67577. }
  67578. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  67579. {
  67580. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  67581. memcpy (glyphs + numGlyphs, other.glyphs,
  67582. other.numGlyphs * sizeof (PositionedGlyph));
  67583. for (int i = other.numGlyphs; --i >= 0;)
  67584. incGlyphRefCount (numGlyphs++);
  67585. }
  67586. void GlyphArrangement::removeLast() throw()
  67587. {
  67588. if (numGlyphs > 0)
  67589. decGlyphRefCount (--numGlyphs);
  67590. }
  67591. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  67592. {
  67593. jassert (startIndex >= 0);
  67594. if (startIndex < 0)
  67595. startIndex = 0;
  67596. if (num < 0 || startIndex + num >= numGlyphs)
  67597. {
  67598. while (numGlyphs > startIndex)
  67599. removeLast();
  67600. }
  67601. else if (num > 0)
  67602. {
  67603. int i;
  67604. for (i = startIndex; i < startIndex + num; ++i)
  67605. decGlyphRefCount (i);
  67606. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  67607. {
  67608. glyphs [startIndex] = glyphs [startIndex + num];
  67609. ++startIndex;
  67610. }
  67611. numGlyphs -= num;
  67612. }
  67613. }
  67614. void GlyphArrangement::addLineOfText (const Font& font,
  67615. const String& text,
  67616. const float xOffset,
  67617. const float yOffset) throw()
  67618. {
  67619. addCurtailedLineOfText (font, text,
  67620. xOffset, yOffset,
  67621. 1.0e10f, false);
  67622. }
  67623. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  67624. const String& text,
  67625. float xOffset,
  67626. const float yOffset,
  67627. const float maxWidthPixels,
  67628. const bool useEllipsis) throw()
  67629. {
  67630. const int textLen = text.length();
  67631. if (textLen > 0)
  67632. {
  67633. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  67634. Typeface* const typeface = font.getTypeface();
  67635. const float fontHeight = font.getHeight();
  67636. const float ascent = font.getAscent();
  67637. const float fontHorizontalScale = font.getHorizontalScale();
  67638. const float heightTimesScale = fontHorizontalScale * fontHeight;
  67639. const float kerningFactor = font.getExtraKerningFactor();
  67640. const float startX = xOffset;
  67641. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  67642. for (int i = 0; i < textLen; ++i)
  67643. {
  67644. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  67645. if (glyph != 0)
  67646. {
  67647. jassert (numAllocated > numGlyphs);
  67648. ensureNumGlyphsAllocated (numGlyphs);
  67649. PositionedGlyph& pg = glyphs [numGlyphs];
  67650. pg.glyphInfo = glyph;
  67651. pg.x = xOffset;
  67652. pg.y = yOffset;
  67653. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  67654. pg.fontHeight = fontHeight;
  67655. pg.fontAscent = ascent;
  67656. pg.fontHorizontalScale = fontHorizontalScale;
  67657. pg.isUnderlined = font.isUnderlined();
  67658. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  67659. if (xOffset - startX > maxWidthPixels + 1.0f)
  67660. {
  67661. // curtail the string if it's too wide..
  67662. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  67663. appendEllipsis (font, startX + maxWidthPixels);
  67664. break;
  67665. }
  67666. else
  67667. {
  67668. if (glyph->getTypeface() != 0)
  67669. glyph->getTypeface()->incReferenceCount();
  67670. ++numGlyphs;
  67671. }
  67672. }
  67673. }
  67674. }
  67675. }
  67676. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  67677. {
  67678. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  67679. if (dotGlyph != 0)
  67680. {
  67681. if (numGlyphs > 0)
  67682. {
  67683. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  67684. const float fontHeight = glyph.fontHeight;
  67685. const float fontHorizontalScale = glyph.fontHorizontalScale;
  67686. const float fontAscent = glyph.fontAscent;
  67687. const float dx = fontHeight * fontHorizontalScale
  67688. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  67689. float xOffset = 0.0f, yOffset = 0.0f;
  67690. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  67691. {
  67692. removeLast();
  67693. jassert (numAllocated > numGlyphs);
  67694. PositionedGlyph& pg = glyphs [numGlyphs];
  67695. xOffset = pg.x;
  67696. yOffset = pg.y;
  67697. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  67698. break;
  67699. }
  67700. for (int i = 3; --i >= 0;)
  67701. {
  67702. jassert (numAllocated > numGlyphs);
  67703. ensureNumGlyphsAllocated (numGlyphs);
  67704. PositionedGlyph& pg = glyphs [numGlyphs];
  67705. pg.glyphInfo = dotGlyph;
  67706. pg.x = xOffset;
  67707. pg.y = yOffset;
  67708. pg.w = dx;
  67709. pg.fontHeight = fontHeight;
  67710. pg.fontAscent = fontAscent;
  67711. pg.fontHorizontalScale = fontHorizontalScale;
  67712. pg.isUnderlined = font.isUnderlined();
  67713. xOffset += dx;
  67714. if (dotGlyph->getTypeface() != 0)
  67715. dotGlyph->getTypeface()->incReferenceCount();
  67716. ++numGlyphs;
  67717. }
  67718. }
  67719. }
  67720. }
  67721. void GlyphArrangement::addJustifiedText (const Font& font,
  67722. const String& text,
  67723. float x, float y,
  67724. const float maxLineWidth,
  67725. const Justification& horizontalLayout) throw()
  67726. {
  67727. int lineStartIndex = numGlyphs;
  67728. addLineOfText (font, text, x, y);
  67729. const float originalY = y;
  67730. while (lineStartIndex < numGlyphs)
  67731. {
  67732. int i = lineStartIndex;
  67733. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  67734. ++i;
  67735. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  67736. int lastWordBreakIndex = -1;
  67737. while (i < numGlyphs)
  67738. {
  67739. PositionedGlyph& pg = glyphs[i];
  67740. const juce_wchar c = pg.getCharacter();
  67741. if (c == T('\r') || c == T('\n'))
  67742. {
  67743. ++i;
  67744. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  67745. ++i;
  67746. break;
  67747. }
  67748. else if (pg.isWhitespace())
  67749. {
  67750. lastWordBreakIndex = i + 1;
  67751. }
  67752. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  67753. {
  67754. if (lastWordBreakIndex >= 0)
  67755. i = lastWordBreakIndex;
  67756. break;
  67757. }
  67758. ++i;
  67759. }
  67760. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  67761. float currentLineEndX = currentLineStartX;
  67762. for (int j = i; --j >= lineStartIndex;)
  67763. {
  67764. if (! glyphs[j].isWhitespace())
  67765. {
  67766. currentLineEndX = glyphs[j].getRight();
  67767. break;
  67768. }
  67769. }
  67770. float deltaX = 0.0f;
  67771. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  67772. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  67773. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  67774. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  67775. else if (horizontalLayout.testFlags (Justification::right))
  67776. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  67777. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  67778. x + deltaX - currentLineStartX, y - originalY);
  67779. lineStartIndex = i;
  67780. y += font.getHeight();
  67781. }
  67782. }
  67783. void GlyphArrangement::addFittedText (const Font& f,
  67784. const String& text,
  67785. float x, float y,
  67786. float width, float height,
  67787. const Justification& layout,
  67788. int maximumLines,
  67789. const float minimumHorizontalScale) throw()
  67790. {
  67791. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  67792. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  67793. if (text.containsAnyOf (T("\r\n")))
  67794. {
  67795. GlyphArrangement ga;
  67796. ga.addJustifiedText (f, text, x, y, width, layout);
  67797. float l, t, r, b;
  67798. ga.getBoundingBox (0, -1, l, t, r, b, false);
  67799. float dy = y - t;
  67800. if (layout.testFlags (Justification::verticallyCentred))
  67801. dy += (height - (b - t)) * 0.5f;
  67802. else if (layout.testFlags (Justification::bottom))
  67803. dy += height - (b - t);
  67804. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  67805. addGlyphArrangement (ga);
  67806. return;
  67807. }
  67808. int startIndex = numGlyphs;
  67809. addLineOfText (f, text.trim(), x, y);
  67810. if (numGlyphs > startIndex)
  67811. {
  67812. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67813. if (lineWidth <= 0)
  67814. return;
  67815. if (lineWidth * minimumHorizontalScale < width)
  67816. {
  67817. if (lineWidth > width)
  67818. {
  67819. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  67820. width / lineWidth);
  67821. }
  67822. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67823. x, y, width, height, layout);
  67824. }
  67825. else if (maximumLines <= 1)
  67826. {
  67827. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  67828. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  67829. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  67830. removeLast();
  67831. appendEllipsis (f, x + width);
  67832. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67833. x, y, width, height, layout);
  67834. }
  67835. else
  67836. {
  67837. Font font (f);
  67838. String txt (text.trim());
  67839. const int length = txt.length();
  67840. int numLines = 1;
  67841. const int originalStartIndex = startIndex;
  67842. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  67843. maximumLines = 1;
  67844. maximumLines = jmin (maximumLines, length);
  67845. while (numLines < maximumLines)
  67846. {
  67847. ++numLines;
  67848. const float newFontHeight = height / (float)numLines;
  67849. if (newFontHeight < 8.0f)
  67850. break;
  67851. if (newFontHeight < font.getHeight())
  67852. {
  67853. font.setHeight (newFontHeight);
  67854. while (numGlyphs > startIndex)
  67855. removeLast();
  67856. addLineOfText (font, txt, x, y);
  67857. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67858. }
  67859. if (numLines > lineWidth / width)
  67860. break;
  67861. }
  67862. if (numLines < 1)
  67863. numLines = 1;
  67864. float lineY = y;
  67865. float widthPerLine = lineWidth / numLines;
  67866. int lastLineStartIndex = 0;
  67867. for (int line = 0; line < numLines; ++line)
  67868. {
  67869. int i = startIndex;
  67870. lastLineStartIndex = i;
  67871. float lineStartX = glyphs[startIndex].getLeft();
  67872. while (i < numGlyphs)
  67873. {
  67874. lineWidth = (glyphs[i].getRight() - lineStartX);
  67875. if (lineWidth > widthPerLine)
  67876. {
  67877. // got to a point where the line's too long, so skip forward to find a
  67878. // good place to break it..
  67879. const int searchStartIndex = i;
  67880. while (i < numGlyphs)
  67881. {
  67882. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  67883. {
  67884. if (glyphs[i].isWhitespace()
  67885. || glyphs[i].getCharacter() == T('-'))
  67886. {
  67887. ++i;
  67888. break;
  67889. }
  67890. }
  67891. else
  67892. {
  67893. // can't find a suitable break, so try looking backwards..
  67894. i = searchStartIndex;
  67895. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  67896. {
  67897. if (glyphs[i - back].isWhitespace()
  67898. || glyphs[i - back].getCharacter() == T('-'))
  67899. {
  67900. i -= back - 1;
  67901. break;
  67902. }
  67903. }
  67904. break;
  67905. }
  67906. ++i;
  67907. }
  67908. break;
  67909. }
  67910. ++i;
  67911. }
  67912. int wsStart = i;
  67913. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  67914. --wsStart;
  67915. int wsEnd = i;
  67916. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  67917. ++wsEnd;
  67918. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  67919. i = jmax (wsStart, startIndex + 1);
  67920. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  67921. if (lineWidth > width)
  67922. {
  67923. stretchRangeOfGlyphs (startIndex, i - startIndex,
  67924. width / lineWidth);
  67925. }
  67926. justifyGlyphs (startIndex, i - startIndex,
  67927. x, lineY, width, font.getHeight(),
  67928. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67929. startIndex = i;
  67930. lineY += font.getHeight();
  67931. if (startIndex >= numGlyphs)
  67932. break;
  67933. }
  67934. if (startIndex < numGlyphs)
  67935. {
  67936. while (numGlyphs > startIndex)
  67937. removeLast();
  67938. if (startIndex - originalStartIndex > 4)
  67939. {
  67940. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  67941. appendEllipsis (font, lineStartX + width);
  67942. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  67943. if (lineWidth > width)
  67944. {
  67945. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67946. width / lineWidth);
  67947. }
  67948. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67949. x, lineY - font.getHeight(), width, font.getHeight(),
  67950. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67951. }
  67952. startIndex = numGlyphs;
  67953. }
  67954. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  67955. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  67956. }
  67957. }
  67958. }
  67959. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  67960. const float dx, const float dy) throw()
  67961. {
  67962. jassert (startIndex >= 0);
  67963. if (dx != 0.0f || dy != 0.0f)
  67964. {
  67965. if (num < 0 || startIndex + num > numGlyphs)
  67966. num = numGlyphs - startIndex;
  67967. while (--num >= 0)
  67968. {
  67969. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67970. glyphs [startIndex++].moveBy (dx, dy);
  67971. }
  67972. }
  67973. }
  67974. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  67975. const float horizontalScaleFactor) throw()
  67976. {
  67977. jassert (startIndex >= 0);
  67978. if (num < 0 || startIndex + num > numGlyphs)
  67979. num = numGlyphs - startIndex;
  67980. if (num > 0)
  67981. {
  67982. const float xAnchor = glyphs[startIndex].getLeft();
  67983. while (--num >= 0)
  67984. {
  67985. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67986. PositionedGlyph& pg = glyphs[startIndex++];
  67987. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  67988. pg.fontHorizontalScale *= horizontalScaleFactor;
  67989. pg.w *= horizontalScaleFactor;
  67990. }
  67991. }
  67992. }
  67993. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  67994. float& left,
  67995. float& top,
  67996. float& right,
  67997. float& bottom,
  67998. const bool includeWhitespace) const throw()
  67999. {
  68000. jassert (startIndex >= 0);
  68001. if (num < 0 || startIndex + num > numGlyphs)
  68002. num = numGlyphs - startIndex;
  68003. left = 0.0f;
  68004. top = 0.0f;
  68005. right = 0.0f;
  68006. bottom = 0.0f;
  68007. bool isFirst = true;
  68008. while (--num >= 0)
  68009. {
  68010. const PositionedGlyph& pg = glyphs [startIndex++];
  68011. if (includeWhitespace || ! pg.isWhitespace())
  68012. {
  68013. if (isFirst)
  68014. {
  68015. isFirst = false;
  68016. left = pg.getLeft();
  68017. top = pg.getTop();
  68018. right = pg.getRight();
  68019. bottom = pg.getBottom();
  68020. }
  68021. else
  68022. {
  68023. left = jmin (left, pg.getLeft());
  68024. top = jmin (top, pg.getTop());
  68025. right = jmax (right, pg.getRight());
  68026. bottom = jmax (bottom, pg.getBottom());
  68027. }
  68028. }
  68029. }
  68030. }
  68031. void GlyphArrangement::justifyGlyphs (const int startIndex,
  68032. const int num,
  68033. const float x, const float y,
  68034. const float width, const float height,
  68035. const Justification& justification) throw()
  68036. {
  68037. jassert (num >= 0 && startIndex >= 0);
  68038. if (numGlyphs > 0 && num > 0)
  68039. {
  68040. float left, top, right, bottom;
  68041. getBoundingBox (startIndex, num, left, top, right, bottom,
  68042. ! justification.testFlags (Justification::horizontallyJustified
  68043. | Justification::horizontallyCentred));
  68044. float deltaX = 0.0f;
  68045. if (justification.testFlags (Justification::horizontallyJustified))
  68046. deltaX = x - left;
  68047. else if (justification.testFlags (Justification::horizontallyCentred))
  68048. deltaX = x + (width - (right - left)) * 0.5f - left;
  68049. else if (justification.testFlags (Justification::right))
  68050. deltaX = (x + width) - right;
  68051. else
  68052. deltaX = x - left;
  68053. float deltaY = 0.0f;
  68054. if (justification.testFlags (Justification::top))
  68055. deltaY = y - top;
  68056. else if (justification.testFlags (Justification::bottom))
  68057. deltaY = (y + height) - bottom;
  68058. else
  68059. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  68060. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  68061. if (justification.testFlags (Justification::horizontallyJustified))
  68062. {
  68063. int lineStart = 0;
  68064. float baseY = glyphs [startIndex].getBaselineY();
  68065. int i;
  68066. for (i = 0; i < num; ++i)
  68067. {
  68068. const float glyphY = glyphs [startIndex + i].getBaselineY();
  68069. if (glyphY != baseY)
  68070. {
  68071. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  68072. lineStart = i;
  68073. baseY = glyphY;
  68074. }
  68075. }
  68076. if (i > lineStart)
  68077. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  68078. }
  68079. }
  68080. }
  68081. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  68082. {
  68083. if (start + num < numGlyphs
  68084. && glyphs [start + num - 1].getCharacter() != T('\r')
  68085. && glyphs [start + num - 1].getCharacter() != T('\n'))
  68086. {
  68087. int numSpaces = 0;
  68088. int spacesAtEnd = 0;
  68089. for (int i = 0; i < num; ++i)
  68090. {
  68091. if (glyphs [start + i].isWhitespace())
  68092. {
  68093. ++spacesAtEnd;
  68094. ++numSpaces;
  68095. }
  68096. else
  68097. {
  68098. spacesAtEnd = 0;
  68099. }
  68100. }
  68101. numSpaces -= spacesAtEnd;
  68102. if (numSpaces > 0)
  68103. {
  68104. const float startX = glyphs [start].getLeft();
  68105. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  68106. const float extraPaddingBetweenWords
  68107. = (targetWidth - (endX - startX)) / (float) numSpaces;
  68108. float deltaX = 0.0f;
  68109. for (int i = 0; i < num; ++i)
  68110. {
  68111. glyphs [start + i].moveBy (deltaX, 0.0);
  68112. if (glyphs [start + i].isWhitespace())
  68113. deltaX += extraPaddingBetweenWords;
  68114. }
  68115. }
  68116. }
  68117. }
  68118. void GlyphArrangement::draw (const Graphics& g) const throw()
  68119. {
  68120. for (int i = 0; i < numGlyphs; ++i)
  68121. {
  68122. glyphs[i].draw (g);
  68123. if (glyphs[i].isUnderlined)
  68124. {
  68125. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  68126. juce_wchar nextChar = 0;
  68127. if (i < numGlyphs - 1
  68128. && glyphs[i + 1].y == glyphs[i].y)
  68129. {
  68130. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68131. }
  68132. g.fillRect (glyphs[i].x,
  68133. glyphs[i].y + lineThickness * 2.0f,
  68134. glyphs[i].fontHeight
  68135. * glyphs[i].fontHorizontalScale
  68136. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68137. lineThickness);
  68138. }
  68139. }
  68140. }
  68141. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  68142. {
  68143. for (int i = 0; i < numGlyphs; ++i)
  68144. {
  68145. glyphs[i].draw (g, transform);
  68146. if (glyphs[i].isUnderlined)
  68147. {
  68148. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  68149. juce_wchar nextChar = 0;
  68150. if (i < numGlyphs - 1
  68151. && glyphs[i + 1].y == glyphs[i].y)
  68152. {
  68153. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68154. }
  68155. Path p;
  68156. p.addLineSegment (glyphs[i].x,
  68157. glyphs[i].y + lineThickness * 2.5f,
  68158. glyphs[i].x + glyphs[i].fontHeight
  68159. * glyphs[i].fontHorizontalScale
  68160. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68161. glyphs[i].y + lineThickness * 2.5f,
  68162. lineThickness);
  68163. g.fillPath (p, transform);
  68164. }
  68165. }
  68166. }
  68167. void GlyphArrangement::createPath (Path& path) const throw()
  68168. {
  68169. for (int i = 0; i < numGlyphs; ++i)
  68170. glyphs[i].createPath (path);
  68171. }
  68172. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  68173. {
  68174. for (int i = 0; i < numGlyphs; ++i)
  68175. if (glyphs[i].hitTest (x, y))
  68176. return i;
  68177. return -1;
  68178. }
  68179. END_JUCE_NAMESPACE
  68180. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  68181. /********* Start of inlined file: juce_TextLayout.cpp *********/
  68182. BEGIN_JUCE_NAMESPACE
  68183. class TextLayoutToken
  68184. {
  68185. public:
  68186. String text;
  68187. Font font;
  68188. int x, y, w, h;
  68189. int line, lineHeight;
  68190. bool isWhitespace, isNewLine;
  68191. TextLayoutToken (const String& t,
  68192. const Font& f,
  68193. const bool isWhitespace_) throw()
  68194. : text (t),
  68195. font (f),
  68196. x(0),
  68197. y(0),
  68198. isWhitespace (isWhitespace_)
  68199. {
  68200. w = font.getStringWidth (t);
  68201. h = roundFloatToInt (f.getHeight());
  68202. isNewLine = t.containsAnyOf (T("\r\n"));
  68203. }
  68204. TextLayoutToken (const TextLayoutToken& other) throw()
  68205. : text (other.text),
  68206. font (other.font),
  68207. x (other.x),
  68208. y (other.y),
  68209. w (other.w),
  68210. h (other.h),
  68211. line (other.line),
  68212. lineHeight (other.lineHeight),
  68213. isWhitespace (other.isWhitespace),
  68214. isNewLine (other.isNewLine)
  68215. {
  68216. }
  68217. ~TextLayoutToken() throw()
  68218. {
  68219. }
  68220. void draw (Graphics& g,
  68221. const int xOffset,
  68222. const int yOffset) throw()
  68223. {
  68224. if (! isWhitespace)
  68225. {
  68226. g.setFont (font);
  68227. g.drawSingleLineText (text.trimEnd(),
  68228. xOffset + x,
  68229. yOffset + y + (lineHeight - h)
  68230. + roundFloatToInt (font.getAscent()));
  68231. }
  68232. }
  68233. juce_UseDebuggingNewOperator
  68234. };
  68235. TextLayout::TextLayout() throw()
  68236. : tokens (64),
  68237. totalLines (0)
  68238. {
  68239. }
  68240. TextLayout::TextLayout (const String& text,
  68241. const Font& font) throw()
  68242. : tokens (64),
  68243. totalLines (0)
  68244. {
  68245. appendText (text, font);
  68246. }
  68247. TextLayout::TextLayout (const TextLayout& other) throw()
  68248. : tokens (64),
  68249. totalLines (0)
  68250. {
  68251. *this = other;
  68252. }
  68253. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  68254. {
  68255. if (this != &other)
  68256. {
  68257. clear();
  68258. totalLines = other.totalLines;
  68259. for (int i = 0; i < other.tokens.size(); ++i)
  68260. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  68261. }
  68262. return *this;
  68263. }
  68264. TextLayout::~TextLayout() throw()
  68265. {
  68266. clear();
  68267. }
  68268. void TextLayout::clear() throw()
  68269. {
  68270. for (int i = tokens.size(); --i >= 0;)
  68271. {
  68272. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68273. delete t;
  68274. }
  68275. tokens.clear();
  68276. totalLines = 0;
  68277. }
  68278. void TextLayout::appendText (const String& text,
  68279. const Font& font) throw()
  68280. {
  68281. const tchar* t = text;
  68282. String currentString;
  68283. int lastCharType = 0;
  68284. for (;;)
  68285. {
  68286. const tchar c = *t++;
  68287. if (c == 0)
  68288. break;
  68289. int charType;
  68290. if (c == T('\r') || c == T('\n'))
  68291. {
  68292. charType = 0;
  68293. }
  68294. else if (CharacterFunctions::isWhitespace (c))
  68295. {
  68296. charType = 2;
  68297. }
  68298. else
  68299. {
  68300. charType = 1;
  68301. }
  68302. if (charType == 0 || charType != lastCharType)
  68303. {
  68304. if (currentString.isNotEmpty())
  68305. {
  68306. tokens.add (new TextLayoutToken (currentString, font,
  68307. lastCharType == 2 || lastCharType == 0));
  68308. }
  68309. currentString = String::charToString (c);
  68310. if (c == T('\r') && *t == T('\n'))
  68311. currentString += *t++;
  68312. }
  68313. else
  68314. {
  68315. currentString += c;
  68316. }
  68317. lastCharType = charType;
  68318. }
  68319. if (currentString.isNotEmpty())
  68320. tokens.add (new TextLayoutToken (currentString,
  68321. font,
  68322. lastCharType == 2));
  68323. }
  68324. void TextLayout::setText (const String& text, const Font& font) throw()
  68325. {
  68326. clear();
  68327. appendText (text, font);
  68328. }
  68329. void TextLayout::layout (int maxWidth,
  68330. const Justification& justification,
  68331. const bool attemptToBalanceLineLengths) throw()
  68332. {
  68333. if (attemptToBalanceLineLengths)
  68334. {
  68335. const int originalW = maxWidth;
  68336. int bestWidth = maxWidth;
  68337. float bestLineProportion = 0.0f;
  68338. while (maxWidth > originalW / 2)
  68339. {
  68340. layout (maxWidth, justification, false);
  68341. if (getNumLines() <= 1)
  68342. return;
  68343. const int lastLineW = getLineWidth (getNumLines() - 1);
  68344. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  68345. const float prop = lastLineW / (float) lastButOneLineW;
  68346. if (prop > 0.9f)
  68347. return;
  68348. if (prop > bestLineProportion)
  68349. {
  68350. bestLineProportion = prop;
  68351. bestWidth = maxWidth;
  68352. }
  68353. maxWidth -= 10;
  68354. }
  68355. layout (bestWidth, justification, false);
  68356. }
  68357. else
  68358. {
  68359. int x = 0;
  68360. int y = 0;
  68361. int h = 0;
  68362. totalLines = 0;
  68363. int i;
  68364. for (i = 0; i < tokens.size(); ++i)
  68365. {
  68366. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68367. t->x = x;
  68368. t->y = y;
  68369. t->line = totalLines;
  68370. x += t->w;
  68371. h = jmax (h, t->h);
  68372. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  68373. if (nextTok == 0)
  68374. break;
  68375. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  68376. {
  68377. // finished a line, so go back and update the heights of the things on it
  68378. for (int j = i; j >= 0; --j)
  68379. {
  68380. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  68381. if (tok->line == totalLines)
  68382. tok->lineHeight = h;
  68383. else
  68384. break;
  68385. }
  68386. x = 0;
  68387. y += h;
  68388. h = 0;
  68389. ++totalLines;
  68390. }
  68391. }
  68392. // finished a line, so go back and update the heights of the things on it
  68393. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  68394. {
  68395. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  68396. if (t->line == totalLines)
  68397. t->lineHeight = h;
  68398. else
  68399. break;
  68400. }
  68401. ++totalLines;
  68402. if (! justification.testFlags (Justification::left))
  68403. {
  68404. int totalW = getWidth();
  68405. for (i = totalLines; --i >= 0;)
  68406. {
  68407. const int lineW = getLineWidth (i);
  68408. int dx = 0;
  68409. if (justification.testFlags (Justification::horizontallyCentred))
  68410. dx = (totalW - lineW) / 2;
  68411. else if (justification.testFlags (Justification::right))
  68412. dx = totalW - lineW;
  68413. for (int j = tokens.size(); --j >= 0;)
  68414. {
  68415. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  68416. if (t->line == i)
  68417. t->x += dx;
  68418. }
  68419. }
  68420. }
  68421. }
  68422. }
  68423. int TextLayout::getLineWidth (const int lineNumber) const throw()
  68424. {
  68425. int maxW = 0;
  68426. for (int i = tokens.size(); --i >= 0;)
  68427. {
  68428. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68429. if (t->line == lineNumber && ! t->isWhitespace)
  68430. maxW = jmax (maxW, t->x + t->w);
  68431. }
  68432. return maxW;
  68433. }
  68434. int TextLayout::getWidth() const throw()
  68435. {
  68436. int maxW = 0;
  68437. for (int i = tokens.size(); --i >= 0;)
  68438. {
  68439. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68440. if (! t->isWhitespace)
  68441. maxW = jmax (maxW, t->x + t->w);
  68442. }
  68443. return maxW;
  68444. }
  68445. int TextLayout::getHeight() const throw()
  68446. {
  68447. int maxH = 0;
  68448. for (int i = tokens.size(); --i >= 0;)
  68449. {
  68450. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68451. if (! t->isWhitespace)
  68452. maxH = jmax (maxH, t->y + t->h);
  68453. }
  68454. return maxH;
  68455. }
  68456. void TextLayout::draw (Graphics& g,
  68457. const int xOffset,
  68458. const int yOffset) const throw()
  68459. {
  68460. for (int i = tokens.size(); --i >= 0;)
  68461. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  68462. }
  68463. void TextLayout::drawWithin (Graphics& g,
  68464. int x, int y, int w, int h,
  68465. const Justification& justification) const throw()
  68466. {
  68467. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  68468. x, y, w, h);
  68469. draw (g, x, y);
  68470. }
  68471. END_JUCE_NAMESPACE
  68472. /********* End of inlined file: juce_TextLayout.cpp *********/
  68473. /********* Start of inlined file: juce_Typeface.cpp *********/
  68474. BEGIN_JUCE_NAMESPACE
  68475. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  68476. const Path& shape,
  68477. const float horizontalSeparation,
  68478. Typeface* const typeface_) throw()
  68479. : character (character_),
  68480. path (shape),
  68481. width (horizontalSeparation),
  68482. typeface (typeface_)
  68483. {
  68484. }
  68485. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  68486. {
  68487. }
  68488. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  68489. {
  68490. if (subsequentCharacter != 0)
  68491. {
  68492. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  68493. const int numPairs = getNumKerningPairs();
  68494. for (int i = 0; i < numPairs; ++i)
  68495. if (pairs [i].character2 == subsequentCharacter)
  68496. return width + pairs [i].kerningAmount;
  68497. }
  68498. return width;
  68499. }
  68500. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  68501. const float extraKerningAmount) throw()
  68502. {
  68503. const int numPairs = getNumKerningPairs();
  68504. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  68505. KerningPair& p = getKerningPair (numPairs);
  68506. p.character2 = subsequentCharacter;
  68507. p.kerningAmount = extraKerningAmount;
  68508. }
  68509. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  68510. {
  68511. return ((KerningPair*) kerningPairs.getData()) [index];
  68512. }
  68513. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  68514. {
  68515. return kerningPairs.getSize() / sizeof (KerningPair);
  68516. }
  68517. const tchar* Typeface::defaultTypefaceNameSans = T("<Sans-Serif>");
  68518. const tchar* Typeface::defaultTypefaceNameSerif = T("<Serif>");
  68519. const tchar* Typeface::defaultTypefaceNameMono = T("<Monospaced>");
  68520. Typeface::Typeface() throw()
  68521. : hash (0),
  68522. isFullyPopulated (false)
  68523. {
  68524. zeromem (lookupTable, sizeof (lookupTable));
  68525. }
  68526. Typeface::Typeface (const Typeface& other)
  68527. : typefaceName (other.typefaceName),
  68528. ascent (other.ascent),
  68529. bold (other.bold),
  68530. italic (other.italic),
  68531. isFullyPopulated (other.isFullyPopulated),
  68532. defaultCharacter (other.defaultCharacter)
  68533. {
  68534. zeromem (lookupTable, sizeof (lookupTable));
  68535. for (int i = 0; i < other.glyphs.size(); ++i)
  68536. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68537. updateHashCode();
  68538. }
  68539. Typeface::Typeface (const String& faceName,
  68540. const bool bold,
  68541. const bool italic)
  68542. : isFullyPopulated (false)
  68543. {
  68544. zeromem (lookupTable, sizeof (lookupTable));
  68545. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  68546. updateHashCode();
  68547. }
  68548. Typeface::~Typeface()
  68549. {
  68550. clear();
  68551. }
  68552. const Typeface& Typeface::operator= (const Typeface& other) throw()
  68553. {
  68554. if (this != &other)
  68555. {
  68556. clear();
  68557. typefaceName = other.typefaceName;
  68558. ascent = other.ascent;
  68559. bold = other.bold;
  68560. italic = other.italic;
  68561. isFullyPopulated = other.isFullyPopulated;
  68562. defaultCharacter = other.defaultCharacter;
  68563. for (int i = 0; i < other.glyphs.size(); ++i)
  68564. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68565. updateHashCode();
  68566. }
  68567. return *this;
  68568. }
  68569. void Typeface::updateHashCode() throw()
  68570. {
  68571. hash = typefaceName.hashCode();
  68572. if (bold)
  68573. hash ^= 0xffff;
  68574. if (italic)
  68575. hash ^= 0xffff0000;
  68576. }
  68577. void Typeface::clear() throw()
  68578. {
  68579. zeromem (lookupTable, sizeof (lookupTable));
  68580. typefaceName = String::empty;
  68581. bold = false;
  68582. italic = false;
  68583. for (int i = glyphs.size(); --i >= 0;)
  68584. {
  68585. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  68586. delete g;
  68587. }
  68588. glyphs.clear();
  68589. updateHashCode();
  68590. }
  68591. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  68592. {
  68593. zeromem (lookupTable, sizeof (lookupTable));
  68594. isFullyPopulated = true;
  68595. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  68596. BufferedInputStream in (&gzin, 32768, false);
  68597. typefaceName = in.readString();
  68598. bold = in.readBool();
  68599. italic = in.readBool();
  68600. ascent = in.readFloat();
  68601. defaultCharacter = (juce_wchar) in.readShort();
  68602. int i, numChars = in.readInt();
  68603. for (i = 0; i < numChars; ++i)
  68604. {
  68605. const juce_wchar c = (juce_wchar) in.readShort();
  68606. const float width = in.readFloat();
  68607. Path p;
  68608. p.loadPathFromStream (in);
  68609. addGlyph (c, p, width);
  68610. }
  68611. const int numKerningPairs = in.readInt();
  68612. for (i = 0; i < numKerningPairs; ++i)
  68613. {
  68614. const juce_wchar char1 = (juce_wchar) in.readShort();
  68615. const juce_wchar char2 = (juce_wchar) in.readShort();
  68616. addKerningPair (char1, char2, in.readFloat());
  68617. }
  68618. updateHashCode();
  68619. }
  68620. void Typeface::serialise (OutputStream& outputStream)
  68621. {
  68622. GZIPCompressorOutputStream out (&outputStream);
  68623. out.writeString (typefaceName);
  68624. out.writeBool (bold);
  68625. out.writeBool (italic);
  68626. out.writeFloat (ascent);
  68627. out.writeShort ((short) (unsigned short) defaultCharacter);
  68628. out.writeInt (glyphs.size());
  68629. int i, numKerningPairs = 0;
  68630. for (i = 0; i < glyphs.size(); ++i)
  68631. {
  68632. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68633. out.writeShort ((short) (unsigned short) g.character);
  68634. out.writeFloat (g.width);
  68635. g.path.writePathToStream (out);
  68636. numKerningPairs += g.getNumKerningPairs();
  68637. }
  68638. out.writeInt (numKerningPairs);
  68639. for (i = 0; i < glyphs.size(); ++i)
  68640. {
  68641. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68642. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  68643. {
  68644. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  68645. out.writeShort ((short) (unsigned short) g.character);
  68646. out.writeShort ((short) (unsigned short) p.character2);
  68647. out.writeFloat (p.kerningAmount);
  68648. }
  68649. }
  68650. }
  68651. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  68652. {
  68653. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  68654. if (g != 0)
  68655. return &(g->path);
  68656. else
  68657. return 0;
  68658. }
  68659. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  68660. {
  68661. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  68662. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68663. for (int i = 0; i < glyphs.size(); ++i)
  68664. {
  68665. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68666. if (g->character == character)
  68667. return g;
  68668. }
  68669. if ((! isFullyPopulated)
  68670. && findAndAddSystemGlyph (character))
  68671. {
  68672. for (int i = 0; i < glyphs.size(); ++i)
  68673. {
  68674. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68675. if (g->character == character)
  68676. return g;
  68677. }
  68678. }
  68679. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  68680. {
  68681. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  68682. if (spaceGlyph != 0)
  68683. {
  68684. // Add a copy of the empty glyph, mapped onto this character
  68685. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  68686. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68687. }
  68688. return spaceGlyph;
  68689. }
  68690. else if (character != defaultCharacter)
  68691. {
  68692. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  68693. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  68694. if (fallbackTypeface != 0 && fallbackTypeface != this)
  68695. return fallbackTypeface->getGlyph (character);
  68696. return getGlyph (defaultCharacter);
  68697. }
  68698. return 0;
  68699. }
  68700. void Typeface::addGlyph (const juce_wchar character,
  68701. const Path& path,
  68702. const float horizontalSpacing) throw()
  68703. {
  68704. #ifdef JUCE_DEBUG
  68705. for (int i = 0; i < glyphs.size(); ++i)
  68706. {
  68707. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68708. if (g->character == character)
  68709. jassertfalse;
  68710. }
  68711. #endif
  68712. if (((unsigned int) character) < 128)
  68713. lookupTable [character] = (short) glyphs.size();
  68714. glyphs.add (new TypefaceGlyphInfo (character,
  68715. path,
  68716. horizontalSpacing,
  68717. this));
  68718. }
  68719. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  68720. {
  68721. if (glyphInfoToCopy != 0)
  68722. {
  68723. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  68724. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  68725. TypefaceGlyphInfo* const newOne
  68726. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  68727. glyphInfoToCopy->path,
  68728. glyphInfoToCopy->width,
  68729. this);
  68730. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  68731. glyphs.add (newOne);
  68732. }
  68733. }
  68734. void Typeface::addKerningPair (const juce_wchar char1,
  68735. const juce_wchar char2,
  68736. const float extraAmount) throw()
  68737. {
  68738. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  68739. if (g != 0)
  68740. g->addKerningPair (char2, extraAmount);
  68741. }
  68742. void Typeface::setName (const String& name) throw()
  68743. {
  68744. typefaceName = name;
  68745. updateHashCode();
  68746. }
  68747. void Typeface::setAscent (const float newAscent) throw()
  68748. {
  68749. ascent = newAscent;
  68750. }
  68751. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  68752. {
  68753. defaultCharacter = newDefaultCharacter;
  68754. }
  68755. void Typeface::setBold (const bool shouldBeBold) throw()
  68756. {
  68757. bold = shouldBeBold;
  68758. updateHashCode();
  68759. }
  68760. void Typeface::setItalic (const bool shouldBeItalic) throw()
  68761. {
  68762. italic = shouldBeItalic;
  68763. updateHashCode();
  68764. }
  68765. class TypefaceCache;
  68766. static TypefaceCache* typefaceCacheInstance = 0;
  68767. void clearUpDefaultFontNames() throw(); // in juce_LookAndFeel.cpp
  68768. class TypefaceCache : private DeletedAtShutdown
  68769. {
  68770. private:
  68771. struct CachedFace
  68772. {
  68773. CachedFace() throw()
  68774. : lastUsageCount (0),
  68775. flags (0)
  68776. {
  68777. }
  68778. String typefaceName;
  68779. int lastUsageCount;
  68780. int flags;
  68781. Typeface::Ptr typeFace;
  68782. };
  68783. int counter;
  68784. OwnedArray <CachedFace> faces;
  68785. TypefaceCache (const TypefaceCache&);
  68786. const TypefaceCache& operator= (const TypefaceCache&);
  68787. public:
  68788. TypefaceCache (int numToCache = 10)
  68789. : counter (1),
  68790. faces (2)
  68791. {
  68792. while (--numToCache >= 0)
  68793. {
  68794. CachedFace* const face = new CachedFace();
  68795. face->typeFace = new Typeface();
  68796. faces.add (face);
  68797. }
  68798. }
  68799. ~TypefaceCache()
  68800. {
  68801. faces.clear();
  68802. jassert (typefaceCacheInstance == this);
  68803. typefaceCacheInstance = 0;
  68804. clearUpDefaultFontNames();
  68805. }
  68806. static TypefaceCache* getInstance() throw()
  68807. {
  68808. if (typefaceCacheInstance == 0)
  68809. typefaceCacheInstance = new TypefaceCache();
  68810. return typefaceCacheInstance;
  68811. }
  68812. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  68813. {
  68814. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  68815. int i;
  68816. for (i = faces.size(); --i >= 0;)
  68817. {
  68818. CachedFace* const face = faces.getUnchecked(i);
  68819. if (face->flags == flags
  68820. && face->typefaceName == font.getTypefaceName())
  68821. {
  68822. face->lastUsageCount = ++counter;
  68823. return face->typeFace;
  68824. }
  68825. }
  68826. int replaceIndex = 0;
  68827. int bestLastUsageCount = INT_MAX;
  68828. for (i = faces.size(); --i >= 0;)
  68829. {
  68830. const int lu = faces.getUnchecked(i)->lastUsageCount;
  68831. if (bestLastUsageCount > lu)
  68832. {
  68833. bestLastUsageCount = lu;
  68834. replaceIndex = i;
  68835. }
  68836. }
  68837. CachedFace* const face = faces.getUnchecked (replaceIndex);
  68838. face->typefaceName = font.getTypefaceName();
  68839. face->flags = flags;
  68840. face->lastUsageCount = ++counter;
  68841. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  68842. return face->typeFace;
  68843. }
  68844. };
  68845. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  68846. {
  68847. return TypefaceCache::getInstance()->findTypefaceFor (font);
  68848. }
  68849. END_JUCE_NAMESPACE
  68850. /********* End of inlined file: juce_Typeface.cpp *********/
  68851. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  68852. BEGIN_JUCE_NAMESPACE
  68853. AffineTransform::AffineTransform() throw()
  68854. : mat00 (1.0f),
  68855. mat01 (0),
  68856. mat02 (0),
  68857. mat10 (0),
  68858. mat11 (1.0f),
  68859. mat12 (0)
  68860. {
  68861. }
  68862. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  68863. : mat00 (other.mat00),
  68864. mat01 (other.mat01),
  68865. mat02 (other.mat02),
  68866. mat10 (other.mat10),
  68867. mat11 (other.mat11),
  68868. mat12 (other.mat12)
  68869. {
  68870. }
  68871. AffineTransform::AffineTransform (const float mat00_,
  68872. const float mat01_,
  68873. const float mat02_,
  68874. const float mat10_,
  68875. const float mat11_,
  68876. const float mat12_) throw()
  68877. : mat00 (mat00_),
  68878. mat01 (mat01_),
  68879. mat02 (mat02_),
  68880. mat10 (mat10_),
  68881. mat11 (mat11_),
  68882. mat12 (mat12_)
  68883. {
  68884. }
  68885. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  68886. {
  68887. mat00 = other.mat00;
  68888. mat01 = other.mat01;
  68889. mat02 = other.mat02;
  68890. mat10 = other.mat10;
  68891. mat11 = other.mat11;
  68892. mat12 = other.mat12;
  68893. return *this;
  68894. }
  68895. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  68896. {
  68897. return mat00 == other.mat00
  68898. && mat01 == other.mat01
  68899. && mat02 == other.mat02
  68900. && mat10 == other.mat10
  68901. && mat11 == other.mat11
  68902. && mat12 == other.mat12;
  68903. }
  68904. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  68905. {
  68906. return ! operator== (other);
  68907. }
  68908. bool AffineTransform::isIdentity() const throw()
  68909. {
  68910. return (mat01 == 0)
  68911. && (mat02 == 0)
  68912. && (mat10 == 0)
  68913. && (mat12 == 0)
  68914. && (mat00 == 1.0f)
  68915. && (mat11 == 1.0f);
  68916. }
  68917. const AffineTransform AffineTransform::identity;
  68918. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  68919. {
  68920. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  68921. other.mat00 * mat01 + other.mat01 * mat11,
  68922. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  68923. other.mat10 * mat00 + other.mat11 * mat10,
  68924. other.mat10 * mat01 + other.mat11 * mat11,
  68925. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  68926. }
  68927. const AffineTransform AffineTransform::followedBy (const float omat00,
  68928. const float omat01,
  68929. const float omat02,
  68930. const float omat10,
  68931. const float omat11,
  68932. const float omat12) const throw()
  68933. {
  68934. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  68935. omat00 * mat01 + omat01 * mat11,
  68936. omat00 * mat02 + omat01 * mat12 + omat02,
  68937. omat10 * mat00 + omat11 * mat10,
  68938. omat10 * mat01 + omat11 * mat11,
  68939. omat10 * mat02 + omat11 * mat12 + omat12);
  68940. }
  68941. const AffineTransform AffineTransform::translated (const float dx,
  68942. const float dy) const throw()
  68943. {
  68944. return followedBy (1.0f, 0, dx,
  68945. 0, 1.0f, dy);
  68946. }
  68947. const AffineTransform AffineTransform::translation (const float dx,
  68948. const float dy) throw()
  68949. {
  68950. return AffineTransform (1.0f, 0, dx,
  68951. 0, 1.0f, dy);
  68952. }
  68953. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  68954. {
  68955. const float cosRad = cosf (rad);
  68956. const float sinRad = sinf (rad);
  68957. return followedBy (cosRad, -sinRad, 0,
  68958. sinRad, cosRad, 0);
  68959. }
  68960. const AffineTransform AffineTransform::rotation (const float rad) throw()
  68961. {
  68962. const float cosRad = cosf (rad);
  68963. const float sinRad = sinf (rad);
  68964. return AffineTransform (cosRad, -sinRad, 0,
  68965. sinRad, cosRad, 0);
  68966. }
  68967. const AffineTransform AffineTransform::rotated (const float angle,
  68968. const float pivotX,
  68969. const float pivotY) const throw()
  68970. {
  68971. return translated (-pivotX, -pivotY)
  68972. .rotated (angle)
  68973. .translated (pivotX, pivotY);
  68974. }
  68975. const AffineTransform AffineTransform::rotation (const float angle,
  68976. const float pivotX,
  68977. const float pivotY) throw()
  68978. {
  68979. return translation (-pivotX, -pivotY)
  68980. .rotated (angle)
  68981. .translated (pivotX, pivotY);
  68982. }
  68983. const AffineTransform AffineTransform::scaled (const float factorX,
  68984. const float factorY) const throw()
  68985. {
  68986. return followedBy (factorX, 0, 0,
  68987. 0, factorY, 0);
  68988. }
  68989. const AffineTransform AffineTransform::scale (const float factorX,
  68990. const float factorY) throw()
  68991. {
  68992. return AffineTransform (factorX, 0, 0,
  68993. 0, factorY, 0);
  68994. }
  68995. const AffineTransform AffineTransform::sheared (const float shearX,
  68996. const float shearY) const throw()
  68997. {
  68998. return followedBy (1.0f, shearX, 0,
  68999. shearY, 1.0f, 0);
  69000. }
  69001. const AffineTransform AffineTransform::inverted() const throw()
  69002. {
  69003. double determinant = (mat00 * mat11 - mat10 * mat01);
  69004. if (determinant != 0.0)
  69005. {
  69006. determinant = 1.0 / determinant;
  69007. const float dst00 = (float) (mat11 * determinant);
  69008. const float dst10 = (float) (-mat10 * determinant);
  69009. const float dst01 = (float) (-mat01 * determinant);
  69010. const float dst11 = (float) (mat00 * determinant);
  69011. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  69012. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  69013. }
  69014. else
  69015. {
  69016. // singularity..
  69017. return *this;
  69018. }
  69019. }
  69020. bool AffineTransform::isSingularity() const throw()
  69021. {
  69022. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  69023. }
  69024. void AffineTransform::transformPoint (float& x,
  69025. float& y) const throw()
  69026. {
  69027. const float oldX = x;
  69028. x = mat00 * oldX + mat01 * y + mat02;
  69029. y = mat10 * oldX + mat11 * y + mat12;
  69030. }
  69031. void AffineTransform::transformPoint (double& x,
  69032. double& y) const throw()
  69033. {
  69034. const double oldX = x;
  69035. x = mat00 * oldX + mat01 * y + mat02;
  69036. y = mat10 * oldX + mat11 * y + mat12;
  69037. }
  69038. END_JUCE_NAMESPACE
  69039. /********* End of inlined file: juce_AffineTransform.cpp *********/
  69040. /********* Start of inlined file: juce_BorderSize.cpp *********/
  69041. BEGIN_JUCE_NAMESPACE
  69042. BorderSize::BorderSize() throw()
  69043. : top (0),
  69044. left (0),
  69045. bottom (0),
  69046. right (0)
  69047. {
  69048. }
  69049. BorderSize::BorderSize (const BorderSize& other) throw()
  69050. : top (other.top),
  69051. left (other.left),
  69052. bottom (other.bottom),
  69053. right (other.right)
  69054. {
  69055. }
  69056. BorderSize::BorderSize (const int topGap,
  69057. const int leftGap,
  69058. const int bottomGap,
  69059. const int rightGap) throw()
  69060. : top (topGap),
  69061. left (leftGap),
  69062. bottom (bottomGap),
  69063. right (rightGap)
  69064. {
  69065. }
  69066. BorderSize::BorderSize (const int allGaps) throw()
  69067. : top (allGaps),
  69068. left (allGaps),
  69069. bottom (allGaps),
  69070. right (allGaps)
  69071. {
  69072. }
  69073. BorderSize::~BorderSize() throw()
  69074. {
  69075. }
  69076. void BorderSize::setTop (const int newTopGap) throw()
  69077. {
  69078. top = newTopGap;
  69079. }
  69080. void BorderSize::setLeft (const int newLeftGap) throw()
  69081. {
  69082. left = newLeftGap;
  69083. }
  69084. void BorderSize::setBottom (const int newBottomGap) throw()
  69085. {
  69086. bottom = newBottomGap;
  69087. }
  69088. void BorderSize::setRight (const int newRightGap) throw()
  69089. {
  69090. right = newRightGap;
  69091. }
  69092. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  69093. {
  69094. return Rectangle (r.getX() + left,
  69095. r.getY() + top,
  69096. r.getWidth() - (left + right),
  69097. r.getHeight() - (top + bottom));
  69098. }
  69099. void BorderSize::subtractFrom (Rectangle& r) const throw()
  69100. {
  69101. r.setBounds (r.getX() + left,
  69102. r.getY() + top,
  69103. r.getWidth() - (left + right),
  69104. r.getHeight() - (top + bottom));
  69105. }
  69106. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  69107. {
  69108. return Rectangle (r.getX() - left,
  69109. r.getY() - top,
  69110. r.getWidth() + (left + right),
  69111. r.getHeight() + (top + bottom));
  69112. }
  69113. void BorderSize::addTo (Rectangle& r) const throw()
  69114. {
  69115. r.setBounds (r.getX() - left,
  69116. r.getY() - top,
  69117. r.getWidth() + (left + right),
  69118. r.getHeight() + (top + bottom));
  69119. }
  69120. bool BorderSize::operator== (const BorderSize& other) const throw()
  69121. {
  69122. return top == other.top
  69123. && left == other.left
  69124. && bottom == other.bottom
  69125. && right == other.right;
  69126. }
  69127. bool BorderSize::operator!= (const BorderSize& other) const throw()
  69128. {
  69129. return ! operator== (other);
  69130. }
  69131. END_JUCE_NAMESPACE
  69132. /********* End of inlined file: juce_BorderSize.cpp *********/
  69133. /********* Start of inlined file: juce_Line.cpp *********/
  69134. BEGIN_JUCE_NAMESPACE
  69135. static bool juce_lineIntersection (const float x1, const float y1,
  69136. const float x2, const float y2,
  69137. const float x3, const float y3,
  69138. const float x4, const float y4,
  69139. float& intersectionX,
  69140. float& intersectionY) throw()
  69141. {
  69142. if (x2 != x3 || y2 != y3)
  69143. {
  69144. const float dx1 = x2 - x1;
  69145. const float dy1 = y2 - y1;
  69146. const float dx2 = x4 - x3;
  69147. const float dy2 = y4 - y3;
  69148. const float divisor = dx1 * dy2 - dx2 * dy1;
  69149. if (divisor == 0)
  69150. {
  69151. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  69152. {
  69153. if (dy1 == 0 && dy2 != 0)
  69154. {
  69155. const float along = (y1 - y3) / dy2;
  69156. intersectionX = x3 + along * dx2;
  69157. intersectionY = y1;
  69158. return along >= 0 && along <= 1.0f;
  69159. }
  69160. else if (dy2 == 0 && dy1 != 0)
  69161. {
  69162. const float along = (y3 - y1) / dy1;
  69163. intersectionX = x1 + along * dx1;
  69164. intersectionY = y3;
  69165. return along >= 0 && along <= 1.0f;
  69166. }
  69167. else if (dx1 == 0 && dx2 != 0)
  69168. {
  69169. const float along = (x1 - x3) / dx2;
  69170. intersectionX = x1;
  69171. intersectionY = y3 + along * dy2;
  69172. return along >= 0 && along <= 1.0f;
  69173. }
  69174. else if (dx2 == 0 && dx1 != 0)
  69175. {
  69176. const float along = (x3 - x1) / dx1;
  69177. intersectionX = x3;
  69178. intersectionY = y1 + along * dy1;
  69179. return along >= 0 && along <= 1.0f;
  69180. }
  69181. }
  69182. intersectionX = 0.5f * (x2 + x3);
  69183. intersectionY = 0.5f * (y2 + y3);
  69184. return false;
  69185. }
  69186. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  69187. intersectionX = x1 + along1 * dx1;
  69188. intersectionY = y1 + along1 * dy1;
  69189. if (along1 < 0 || along1 > 1.0f)
  69190. return false;
  69191. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  69192. return along2 >= 0 && along2 <= 1.0f;
  69193. }
  69194. intersectionX = x2;
  69195. intersectionY = y2;
  69196. return true;
  69197. }
  69198. Line::Line() throw()
  69199. : startX (0.0f),
  69200. startY (0.0f),
  69201. endX (0.0f),
  69202. endY (0.0f)
  69203. {
  69204. }
  69205. Line::Line (const Line& other) throw()
  69206. : startX (other.startX),
  69207. startY (other.startY),
  69208. endX (other.endX),
  69209. endY (other.endY)
  69210. {
  69211. }
  69212. Line::Line (const float startX_, const float startY_,
  69213. const float endX_, const float endY_) throw()
  69214. : startX (startX_),
  69215. startY (startY_),
  69216. endX (endX_),
  69217. endY (endY_)
  69218. {
  69219. }
  69220. Line::Line (const Point& start,
  69221. const Point& end) throw()
  69222. : startX (start.getX()),
  69223. startY (start.getY()),
  69224. endX (end.getX()),
  69225. endY (end.getY())
  69226. {
  69227. }
  69228. const Line& Line::operator= (const Line& other) throw()
  69229. {
  69230. startX = other.startX;
  69231. startY = other.startY;
  69232. endX = other.endX;
  69233. endY = other.endY;
  69234. return *this;
  69235. }
  69236. Line::~Line() throw()
  69237. {
  69238. }
  69239. const Point Line::getStart() const throw()
  69240. {
  69241. return Point (startX, startY);
  69242. }
  69243. const Point Line::getEnd() const throw()
  69244. {
  69245. return Point (endX, endY);
  69246. }
  69247. void Line::setStart (const float newStartX,
  69248. const float newStartY) throw()
  69249. {
  69250. startX = newStartX;
  69251. startY = newStartY;
  69252. }
  69253. void Line::setStart (const Point& newStart) throw()
  69254. {
  69255. startX = newStart.getX();
  69256. startY = newStart.getY();
  69257. }
  69258. void Line::setEnd (const float newEndX,
  69259. const float newEndY) throw()
  69260. {
  69261. endX = newEndX;
  69262. endY = newEndY;
  69263. }
  69264. void Line::setEnd (const Point& newEnd) throw()
  69265. {
  69266. endX = newEnd.getX();
  69267. endY = newEnd.getY();
  69268. }
  69269. bool Line::operator== (const Line& other) const throw()
  69270. {
  69271. return startX == other.startX
  69272. && startY == other.startY
  69273. && endX == other.endX
  69274. && endY == other.endY;
  69275. }
  69276. bool Line::operator!= (const Line& other) const throw()
  69277. {
  69278. return startX != other.startX
  69279. || startY != other.startY
  69280. || endX != other.endX
  69281. || endY != other.endY;
  69282. }
  69283. void Line::applyTransform (const AffineTransform& transform) throw()
  69284. {
  69285. transform.transformPoint (startX, startY);
  69286. transform.transformPoint (endX, endY);
  69287. }
  69288. float Line::getLength() const throw()
  69289. {
  69290. return (float) juce_hypot (startX - endX,
  69291. startY - endY);
  69292. }
  69293. float Line::getAngle() const throw()
  69294. {
  69295. return atan2f (endX - startX,
  69296. endY - startY);
  69297. }
  69298. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  69299. {
  69300. const float alpha = distanceFromStart / getLength();
  69301. return Point (startX + (endX - startX) * alpha,
  69302. startY + (endY - startY) * alpha);
  69303. }
  69304. const Point Line::getPointAlongLine (const float offsetX,
  69305. const float offsetY) const throw()
  69306. {
  69307. const float dx = endX - startX;
  69308. const float dy = endY - startY;
  69309. const double length = juce_hypot (dx, dy);
  69310. if (length == 0)
  69311. return Point (startX, startY);
  69312. else
  69313. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  69314. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  69315. }
  69316. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  69317. {
  69318. return Point (startX + (endX - startX) * alpha,
  69319. startY + (endY - startY) * alpha);
  69320. }
  69321. float Line::getDistanceFromLine (const float x,
  69322. const float y) const throw()
  69323. {
  69324. const double dx = endX - startX;
  69325. const double dy = endY - startY;
  69326. const double length = dx * dx + dy * dy;
  69327. if (length > 0)
  69328. {
  69329. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  69330. if (prop >= 0.0f && prop < 1.0f)
  69331. {
  69332. return (float) juce_hypot (x - (startX + prop * dx),
  69333. y - (startY + prop * dy));
  69334. }
  69335. }
  69336. return (float) jmin (juce_hypot (x - startX, y - startY),
  69337. juce_hypot (x - endX, y - endY));
  69338. }
  69339. float Line::findNearestPointTo (const float x,
  69340. const float y) const throw()
  69341. {
  69342. const double dx = endX - startX;
  69343. const double dy = endY - startY;
  69344. const double length = dx * dx + dy * dy;
  69345. if (length <= 0.0)
  69346. return 0.0f;
  69347. return jlimit (0.0f, 1.0f,
  69348. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  69349. }
  69350. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  69351. {
  69352. const float length = getLength();
  69353. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  69354. getEnd());
  69355. }
  69356. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  69357. {
  69358. const float length = getLength();
  69359. return Line (getStart(),
  69360. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  69361. }
  69362. bool Line::clipToPath (const Path& path,
  69363. const bool keepSectionOutsidePath) throw()
  69364. {
  69365. const bool startInside = path.contains (startX, startY);
  69366. const bool endInside = path.contains (endX, endY);
  69367. if (startInside == endInside)
  69368. {
  69369. if (keepSectionOutsidePath != startInside)
  69370. {
  69371. // entirely outside the path
  69372. return false;
  69373. }
  69374. else
  69375. {
  69376. // entirely inside the path
  69377. startX = 0.0f;
  69378. startY = 0.0f;
  69379. endX = 0.0f;
  69380. endY = 0.0f;
  69381. return true;
  69382. }
  69383. }
  69384. else
  69385. {
  69386. bool changed = false;
  69387. PathFlatteningIterator iter (path, AffineTransform::identity);
  69388. while (iter.next())
  69389. {
  69390. float ix, iy;
  69391. if (intersects (Line (iter.x1, iter.y1,
  69392. iter.x2, iter.y2),
  69393. ix, iy))
  69394. {
  69395. if ((startInside && keepSectionOutsidePath)
  69396. || (endInside && ! keepSectionOutsidePath))
  69397. {
  69398. setStart (ix, iy);
  69399. }
  69400. else
  69401. {
  69402. setEnd (ix, iy);
  69403. }
  69404. changed = true;
  69405. }
  69406. }
  69407. return changed;
  69408. }
  69409. }
  69410. bool Line::intersects (const Line& line,
  69411. float& intersectionX,
  69412. float& intersectionY) const throw()
  69413. {
  69414. return juce_lineIntersection (startX, startY,
  69415. endX, endY,
  69416. line.startX, line.startY,
  69417. line.endX, line.endY,
  69418. intersectionX,
  69419. intersectionY);
  69420. }
  69421. bool Line::isVertical() const throw()
  69422. {
  69423. return startX == endX;
  69424. }
  69425. bool Line::isHorizontal() const throw()
  69426. {
  69427. return startY == endY;
  69428. }
  69429. bool Line::isPointAbove (const float x, const float y) const throw()
  69430. {
  69431. return startX != endX
  69432. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  69433. }
  69434. END_JUCE_NAMESPACE
  69435. /********* End of inlined file: juce_Line.cpp *********/
  69436. /********* Start of inlined file: juce_Path.cpp *********/
  69437. BEGIN_JUCE_NAMESPACE
  69438. // tests that some co-ords aren't NaNs
  69439. #define CHECK_COORDS_ARE_VALID(x, y) \
  69440. jassert (x == x && y == y);
  69441. const float Path::lineMarker = 100001.0f;
  69442. const float Path::moveMarker = 100002.0f;
  69443. const float Path::quadMarker = 100003.0f;
  69444. const float Path::cubicMarker = 100004.0f;
  69445. const float Path::closeSubPathMarker = 100005.0f;
  69446. static const int defaultGranularity = 32;
  69447. Path::Path() throw()
  69448. : ArrayAllocationBase <float> (defaultGranularity),
  69449. numElements (0),
  69450. pathXMin (0),
  69451. pathXMax (0),
  69452. pathYMin (0),
  69453. pathYMax (0),
  69454. useNonZeroWinding (true)
  69455. {
  69456. }
  69457. Path::~Path() throw()
  69458. {
  69459. }
  69460. Path::Path (const Path& other) throw()
  69461. : ArrayAllocationBase <float> (defaultGranularity),
  69462. numElements (other.numElements),
  69463. pathXMin (other.pathXMin),
  69464. pathXMax (other.pathXMax),
  69465. pathYMin (other.pathYMin),
  69466. pathYMax (other.pathYMax),
  69467. useNonZeroWinding (other.useNonZeroWinding)
  69468. {
  69469. if (numElements > 0)
  69470. {
  69471. setAllocatedSize (numElements);
  69472. memcpy (elements, other.elements, numElements * sizeof (float));
  69473. }
  69474. }
  69475. const Path& Path::operator= (const Path& other) throw()
  69476. {
  69477. if (this != &other)
  69478. {
  69479. ensureAllocatedSize (other.numElements);
  69480. numElements = other.numElements;
  69481. pathXMin = other.pathXMin;
  69482. pathXMax = other.pathXMax;
  69483. pathYMin = other.pathYMin;
  69484. pathYMax = other.pathYMax;
  69485. useNonZeroWinding = other.useNonZeroWinding;
  69486. if (numElements > 0)
  69487. memcpy (elements, other.elements, numElements * sizeof (float));
  69488. }
  69489. return *this;
  69490. }
  69491. void Path::clear() throw()
  69492. {
  69493. numElements = 0;
  69494. pathXMin = 0;
  69495. pathYMin = 0;
  69496. pathYMax = 0;
  69497. pathXMax = 0;
  69498. }
  69499. void Path::swapWithPath (Path& other)
  69500. {
  69501. swapVariables <int> (this->numAllocated, other.numAllocated);
  69502. swapVariables <float*> (this->elements, other.elements);
  69503. swapVariables <int> (this->numElements, other.numElements);
  69504. swapVariables <float> (this->pathXMin, other.pathXMin);
  69505. swapVariables <float> (this->pathXMax, other.pathXMax);
  69506. swapVariables <float> (this->pathYMin, other.pathYMin);
  69507. swapVariables <float> (this->pathYMax, other.pathYMax);
  69508. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  69509. }
  69510. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  69511. {
  69512. useNonZeroWinding = isNonZero;
  69513. }
  69514. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  69515. const bool preserveProportions) throw()
  69516. {
  69517. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  69518. }
  69519. bool Path::isEmpty() const throw()
  69520. {
  69521. int i = 0;
  69522. while (i < numElements)
  69523. {
  69524. const float type = elements [i++];
  69525. if (type == moveMarker)
  69526. {
  69527. i += 2;
  69528. }
  69529. else if (type == lineMarker
  69530. || type == quadMarker
  69531. || type == cubicMarker)
  69532. {
  69533. return false;
  69534. }
  69535. }
  69536. return true;
  69537. }
  69538. void Path::getBounds (float& x, float& y,
  69539. float& w, float& h) const throw()
  69540. {
  69541. x = pathXMin;
  69542. y = pathYMin;
  69543. w = pathXMax - pathXMin;
  69544. h = pathYMax - pathYMin;
  69545. }
  69546. void Path::getBoundsTransformed (const AffineTransform& transform,
  69547. float& x, float& y,
  69548. float& w, float& h) const throw()
  69549. {
  69550. float x1 = pathXMin;
  69551. float y1 = pathYMin;
  69552. transform.transformPoint (x1, y1);
  69553. float x2 = pathXMax;
  69554. float y2 = pathYMin;
  69555. transform.transformPoint (x2, y2);
  69556. float x3 = pathXMin;
  69557. float y3 = pathYMax;
  69558. transform.transformPoint (x3, y3);
  69559. float x4 = pathXMax;
  69560. float y4 = pathYMax;
  69561. transform.transformPoint (x4, y4);
  69562. x = jmin (x1, x2, x3, x4);
  69563. y = jmin (y1, y2, y3, y4);
  69564. w = jmax (x1, x2, x3, x4) - x;
  69565. h = jmax (y1, y2, y3, y4) - y;
  69566. }
  69567. void Path::startNewSubPath (const float x,
  69568. const float y) throw()
  69569. {
  69570. CHECK_COORDS_ARE_VALID (x, y);
  69571. if (numElements == 0)
  69572. {
  69573. pathXMin = pathXMax = x;
  69574. pathYMin = pathYMax = y;
  69575. }
  69576. else
  69577. {
  69578. pathXMin = jmin (pathXMin, x);
  69579. pathXMax = jmax (pathXMax, x);
  69580. pathYMin = jmin (pathYMin, y);
  69581. pathYMax = jmax (pathYMax, y);
  69582. }
  69583. ensureAllocatedSize (numElements + 3);
  69584. elements [numElements++] = moveMarker;
  69585. elements [numElements++] = x;
  69586. elements [numElements++] = y;
  69587. }
  69588. void Path::lineTo (const float x, const float y) throw()
  69589. {
  69590. CHECK_COORDS_ARE_VALID (x, y);
  69591. if (numElements == 0)
  69592. startNewSubPath (0, 0);
  69593. ensureAllocatedSize (numElements + 3);
  69594. elements [numElements++] = lineMarker;
  69595. elements [numElements++] = x;
  69596. elements [numElements++] = y;
  69597. pathXMin = jmin (pathXMin, x);
  69598. pathXMax = jmax (pathXMax, x);
  69599. pathYMin = jmin (pathYMin, y);
  69600. pathYMax = jmax (pathYMax, y);
  69601. }
  69602. void Path::quadraticTo (const float x1, const float y1,
  69603. const float x2, const float y2) throw()
  69604. {
  69605. CHECK_COORDS_ARE_VALID (x1, y1);
  69606. CHECK_COORDS_ARE_VALID (x2, y2);
  69607. if (numElements == 0)
  69608. startNewSubPath (0, 0);
  69609. ensureAllocatedSize (numElements + 5);
  69610. elements [numElements++] = quadMarker;
  69611. elements [numElements++] = x1;
  69612. elements [numElements++] = y1;
  69613. elements [numElements++] = x2;
  69614. elements [numElements++] = y2;
  69615. pathXMin = jmin (pathXMin, x1, x2);
  69616. pathXMax = jmax (pathXMax, x1, x2);
  69617. pathYMin = jmin (pathYMin, y1, y2);
  69618. pathYMax = jmax (pathYMax, y1, y2);
  69619. }
  69620. void Path::cubicTo (const float x1, const float y1,
  69621. const float x2, const float y2,
  69622. const float x3, const float y3) throw()
  69623. {
  69624. CHECK_COORDS_ARE_VALID (x1, y1);
  69625. CHECK_COORDS_ARE_VALID (x2, y2);
  69626. CHECK_COORDS_ARE_VALID (x3, y3);
  69627. if (numElements == 0)
  69628. startNewSubPath (0, 0);
  69629. ensureAllocatedSize (numElements + 7);
  69630. elements [numElements++] = cubicMarker;
  69631. elements [numElements++] = x1;
  69632. elements [numElements++] = y1;
  69633. elements [numElements++] = x2;
  69634. elements [numElements++] = y2;
  69635. elements [numElements++] = x3;
  69636. elements [numElements++] = y3;
  69637. pathXMin = jmin (pathXMin, x1, x2, x3);
  69638. pathXMax = jmax (pathXMax, x1, x2, x3);
  69639. pathYMin = jmin (pathYMin, y1, y2, y3);
  69640. pathYMax = jmax (pathYMax, y1, y2, y3);
  69641. }
  69642. void Path::closeSubPath() throw()
  69643. {
  69644. if (numElements > 0
  69645. && elements [numElements - 1] != closeSubPathMarker)
  69646. {
  69647. ensureAllocatedSize (numElements + 1);
  69648. elements [numElements++] = closeSubPathMarker;
  69649. }
  69650. }
  69651. const Point Path::getCurrentPosition() const
  69652. {
  69653. int i = numElements - 1;
  69654. if (i > 0 && elements[i] == closeSubPathMarker)
  69655. {
  69656. while (i >= 0)
  69657. {
  69658. if (elements[i] == moveMarker)
  69659. {
  69660. i += 2;
  69661. break;
  69662. }
  69663. --i;
  69664. }
  69665. }
  69666. if (i > 0)
  69667. return Point (elements [i - 1], elements [i]);
  69668. return Point (0.0f, 0.0f);
  69669. }
  69670. void Path::addRectangle (const float x, const float y,
  69671. const float w, const float h) throw()
  69672. {
  69673. startNewSubPath (x, y + h);
  69674. lineTo (x, y);
  69675. lineTo (x + w, y);
  69676. lineTo (x + w, y + h);
  69677. closeSubPath();
  69678. }
  69679. void Path::addRoundedRectangle (const float x, const float y,
  69680. const float w, const float h,
  69681. float csx,
  69682. float csy) throw()
  69683. {
  69684. csx = jmin (csx, w * 0.5f);
  69685. csy = jmin (csy, h * 0.5f);
  69686. const float cs45x = csx * 0.45f;
  69687. const float cs45y = csy * 0.45f;
  69688. const float x2 = x + w;
  69689. const float y2 = y + h;
  69690. startNewSubPath (x + csx, y);
  69691. lineTo (x2 - csx, y);
  69692. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  69693. lineTo (x2, y2 - csy);
  69694. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  69695. lineTo (x + csx, y2);
  69696. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  69697. lineTo (x, y + csy);
  69698. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  69699. closeSubPath();
  69700. }
  69701. void Path::addRoundedRectangle (const float x, const float y,
  69702. const float w, const float h,
  69703. float cs) throw()
  69704. {
  69705. addRoundedRectangle (x, y, w, h, cs, cs);
  69706. }
  69707. void Path::addTriangle (const float x1, const float y1,
  69708. const float x2, const float y2,
  69709. const float x3, const float y3) throw()
  69710. {
  69711. startNewSubPath (x1, y1);
  69712. lineTo (x2, y2);
  69713. lineTo (x3, y3);
  69714. closeSubPath();
  69715. }
  69716. void Path::addQuadrilateral (const float x1, const float y1,
  69717. const float x2, const float y2,
  69718. const float x3, const float y3,
  69719. const float x4, const float y4) throw()
  69720. {
  69721. startNewSubPath (x1, y1);
  69722. lineTo (x2, y2);
  69723. lineTo (x3, y3);
  69724. lineTo (x4, y4);
  69725. closeSubPath();
  69726. }
  69727. void Path::addEllipse (const float x, const float y,
  69728. const float w, const float h) throw()
  69729. {
  69730. const float hw = w * 0.5f;
  69731. const float hw55 = hw * 0.55f;
  69732. const float hh = h * 0.5f;
  69733. const float hh45 = hh * 0.55f;
  69734. const float cx = x + hw;
  69735. const float cy = y + hh;
  69736. startNewSubPath (cx, cy - hh);
  69737. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  69738. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  69739. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  69740. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  69741. closeSubPath();
  69742. }
  69743. void Path::addArc (const float x, const float y,
  69744. const float w, const float h,
  69745. const float fromRadians,
  69746. const float toRadians,
  69747. const bool startAsNewSubPath) throw()
  69748. {
  69749. const float radiusX = w / 2.0f;
  69750. const float radiusY = h / 2.0f;
  69751. addCentredArc (x + radiusX,
  69752. y + radiusY,
  69753. radiusX, radiusY,
  69754. 0.0f,
  69755. fromRadians, toRadians,
  69756. startAsNewSubPath);
  69757. }
  69758. static const float ellipseAngularIncrement = 0.05f;
  69759. void Path::addCentredArc (const float centreX, const float centreY,
  69760. const float radiusX, const float radiusY,
  69761. const float rotationOfEllipse,
  69762. const float fromRadians,
  69763. const float toRadians,
  69764. const bool startAsNewSubPath) throw()
  69765. {
  69766. if (radiusX > 0.0f && radiusY > 0.0f)
  69767. {
  69768. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  69769. float angle = fromRadians;
  69770. if (startAsNewSubPath)
  69771. {
  69772. float x = centreX + radiusX * sinf (angle);
  69773. float y = centreY - radiusY * cosf (angle);
  69774. if (rotationOfEllipse != 0)
  69775. rotation.transformPoint (x, y);
  69776. startNewSubPath (x, y);
  69777. }
  69778. if (fromRadians < toRadians)
  69779. {
  69780. if (startAsNewSubPath)
  69781. angle += ellipseAngularIncrement;
  69782. while (angle < toRadians)
  69783. {
  69784. float x = centreX + radiusX * sinf (angle);
  69785. float y = centreY - radiusY * cosf (angle);
  69786. if (rotationOfEllipse != 0)
  69787. rotation.transformPoint (x, y);
  69788. lineTo (x, y);
  69789. angle += ellipseAngularIncrement;
  69790. }
  69791. }
  69792. else
  69793. {
  69794. if (startAsNewSubPath)
  69795. angle -= ellipseAngularIncrement;
  69796. while (angle > toRadians)
  69797. {
  69798. float x = centreX + radiusX * sinf (angle);
  69799. float y = centreY - radiusY * cosf (angle);
  69800. if (rotationOfEllipse != 0)
  69801. rotation.transformPoint (x, y);
  69802. lineTo (x, y);
  69803. angle -= ellipseAngularIncrement;
  69804. }
  69805. }
  69806. float x = centreX + radiusX * sinf (toRadians);
  69807. float y = centreY - radiusY * cosf (toRadians);
  69808. if (rotationOfEllipse != 0)
  69809. rotation.transformPoint (x, y);
  69810. lineTo (x, y);
  69811. }
  69812. }
  69813. void Path::addPieSegment (const float x, const float y,
  69814. const float width, const float height,
  69815. const float fromRadians,
  69816. const float toRadians,
  69817. const float innerCircleProportionalSize)
  69818. {
  69819. float hw = width * 0.5f;
  69820. float hh = height * 0.5f;
  69821. const float centreX = x + hw;
  69822. const float centreY = y + hh;
  69823. startNewSubPath (centreX + hw * sinf (fromRadians),
  69824. centreY - hh * cosf (fromRadians));
  69825. addArc (x, y, width, height, fromRadians, toRadians);
  69826. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  69827. {
  69828. closeSubPath();
  69829. if (innerCircleProportionalSize > 0)
  69830. {
  69831. hw *= innerCircleProportionalSize;
  69832. hh *= innerCircleProportionalSize;
  69833. startNewSubPath (centreX + hw * sinf (toRadians),
  69834. centreY - hh * cosf (toRadians));
  69835. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69836. toRadians, fromRadians);
  69837. }
  69838. }
  69839. else
  69840. {
  69841. if (innerCircleProportionalSize > 0)
  69842. {
  69843. hw *= innerCircleProportionalSize;
  69844. hh *= innerCircleProportionalSize;
  69845. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69846. toRadians, fromRadians);
  69847. }
  69848. else
  69849. {
  69850. lineTo (centreX, centreY);
  69851. }
  69852. }
  69853. closeSubPath();
  69854. }
  69855. static void perpendicularOffset (const float x1, const float y1,
  69856. const float x2, const float y2,
  69857. const float offsetX, const float offsetY,
  69858. float& resultX, float& resultY) throw()
  69859. {
  69860. const float dx = x2 - x1;
  69861. const float dy = y2 - y1;
  69862. const float len = juce_hypotf (dx, dy);
  69863. if (len == 0)
  69864. {
  69865. resultX = x1;
  69866. resultY = y1;
  69867. }
  69868. else
  69869. {
  69870. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  69871. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  69872. }
  69873. }
  69874. void Path::addLineSegment (const float startX, const float startY,
  69875. const float endX, const float endY,
  69876. float lineThickness) throw()
  69877. {
  69878. lineThickness *= 0.5f;
  69879. float x, y;
  69880. perpendicularOffset (startX, startY, endX, endY,
  69881. 0, lineThickness, x, y);
  69882. startNewSubPath (x, y);
  69883. perpendicularOffset (startX, startY, endX, endY,
  69884. 0, -lineThickness, x, y);
  69885. lineTo (x, y);
  69886. perpendicularOffset (endX, endY, startX, startY,
  69887. 0, lineThickness, x, y);
  69888. lineTo (x, y);
  69889. perpendicularOffset (endX, endY, startX, startY,
  69890. 0, -lineThickness, x, y);
  69891. lineTo (x, y);
  69892. closeSubPath();
  69893. }
  69894. void Path::addArrow (const float startX, const float startY,
  69895. const float endX, const float endY,
  69896. float lineThickness,
  69897. float arrowheadWidth,
  69898. float arrowheadLength) throw()
  69899. {
  69900. lineThickness *= 0.5f;
  69901. arrowheadWidth *= 0.5f;
  69902. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  69903. startY - endY));
  69904. float x, y;
  69905. perpendicularOffset (startX, startY, endX, endY,
  69906. 0, lineThickness, x, y);
  69907. startNewSubPath (x, y);
  69908. perpendicularOffset (startX, startY, endX, endY,
  69909. 0, -lineThickness, x, y);
  69910. lineTo (x, y);
  69911. perpendicularOffset (endX, endY, startX, startY,
  69912. arrowheadLength, lineThickness, x, y);
  69913. lineTo (x, y);
  69914. perpendicularOffset (endX, endY, startX, startY,
  69915. arrowheadLength, arrowheadWidth, x, y);
  69916. lineTo (x, y);
  69917. perpendicularOffset (endX, endY, startX, startY,
  69918. 0, 0, x, y);
  69919. lineTo (x, y);
  69920. perpendicularOffset (endX, endY, startX, startY,
  69921. arrowheadLength, -arrowheadWidth, x, y);
  69922. lineTo (x, y);
  69923. perpendicularOffset (endX, endY, startX, startY,
  69924. arrowheadLength, -lineThickness, x, y);
  69925. lineTo (x, y);
  69926. closeSubPath();
  69927. }
  69928. void Path::addStar (const float centreX,
  69929. const float centreY,
  69930. const int numberOfPoints,
  69931. const float innerRadius,
  69932. const float outerRadius,
  69933. const float startAngle)
  69934. {
  69935. jassert (numberOfPoints > 1); // this would be silly.
  69936. if (numberOfPoints > 1)
  69937. {
  69938. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  69939. for (int i = 0; i < numberOfPoints; ++i)
  69940. {
  69941. float angle = startAngle + i * angleBetweenPoints;
  69942. const float x = centreX + outerRadius * sinf (angle);
  69943. const float y = centreY - outerRadius * cosf (angle);
  69944. if (i == 0)
  69945. startNewSubPath (x, y);
  69946. else
  69947. lineTo (x, y);
  69948. angle += angleBetweenPoints * 0.5f;
  69949. lineTo (centreX + innerRadius * sinf (angle),
  69950. centreY - innerRadius * cosf (angle));
  69951. }
  69952. closeSubPath();
  69953. }
  69954. }
  69955. void Path::addBubble (float x, float y,
  69956. float w, float h,
  69957. float cs,
  69958. float tipX,
  69959. float tipY,
  69960. int whichSide,
  69961. float arrowPos,
  69962. float arrowWidth)
  69963. {
  69964. if (w > 1.0f && h > 1.0f)
  69965. {
  69966. cs = jmin (cs, w * 0.5f, h * 0.5f);
  69967. const float cs2 = 2.0f * cs;
  69968. startNewSubPath (x + cs, y);
  69969. if (whichSide == 0)
  69970. {
  69971. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69972. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69973. lineTo (arrowX1, y);
  69974. lineTo (tipX, tipY);
  69975. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  69976. }
  69977. lineTo (x + w - cs, y);
  69978. if (cs > 0.0f)
  69979. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  69980. if (whichSide == 3)
  69981. {
  69982. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69983. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69984. lineTo (x + w, arrowY1);
  69985. lineTo (tipX, tipY);
  69986. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  69987. }
  69988. lineTo (x + w, y + h - cs);
  69989. if (cs > 0.0f)
  69990. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  69991. if (whichSide == 2)
  69992. {
  69993. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69994. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69995. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  69996. lineTo (tipX, tipY);
  69997. lineTo (arrowX1, y + h);
  69998. }
  69999. lineTo (x + cs, y + h);
  70000. if (cs > 0.0f)
  70001. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  70002. if (whichSide == 1)
  70003. {
  70004. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  70005. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  70006. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  70007. lineTo (tipX, tipY);
  70008. lineTo (x, arrowY1);
  70009. }
  70010. lineTo (x, y + cs);
  70011. if (cs > 0.0f)
  70012. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  70013. closeSubPath();
  70014. }
  70015. }
  70016. void Path::addPath (const Path& other) throw()
  70017. {
  70018. int i = 0;
  70019. while (i < other.numElements)
  70020. {
  70021. const float type = other.elements [i++];
  70022. if (type == moveMarker)
  70023. {
  70024. startNewSubPath (other.elements [i],
  70025. other.elements [i + 1]);
  70026. i += 2;
  70027. }
  70028. else if (type == lineMarker)
  70029. {
  70030. lineTo (other.elements [i],
  70031. other.elements [i + 1]);
  70032. i += 2;
  70033. }
  70034. else if (type == quadMarker)
  70035. {
  70036. quadraticTo (other.elements [i],
  70037. other.elements [i + 1],
  70038. other.elements [i + 2],
  70039. other.elements [i + 3]);
  70040. i += 4;
  70041. }
  70042. else if (type == cubicMarker)
  70043. {
  70044. cubicTo (other.elements [i],
  70045. other.elements [i + 1],
  70046. other.elements [i + 2],
  70047. other.elements [i + 3],
  70048. other.elements [i + 4],
  70049. other.elements [i + 5]);
  70050. i += 6;
  70051. }
  70052. else if (type == closeSubPathMarker)
  70053. {
  70054. closeSubPath();
  70055. }
  70056. else
  70057. {
  70058. // something's gone wrong with the element list!
  70059. jassertfalse
  70060. }
  70061. }
  70062. }
  70063. void Path::addPath (const Path& other,
  70064. const AffineTransform& transformToApply) throw()
  70065. {
  70066. int i = 0;
  70067. while (i < other.numElements)
  70068. {
  70069. const float type = other.elements [i++];
  70070. if (type == closeSubPathMarker)
  70071. {
  70072. closeSubPath();
  70073. }
  70074. else
  70075. {
  70076. float x = other.elements [i++];
  70077. float y = other.elements [i++];
  70078. transformToApply.transformPoint (x, y);
  70079. if (type == moveMarker)
  70080. {
  70081. startNewSubPath (x, y);
  70082. }
  70083. else if (type == lineMarker)
  70084. {
  70085. lineTo (x, y);
  70086. }
  70087. else if (type == quadMarker)
  70088. {
  70089. float x2 = other.elements [i++];
  70090. float y2 = other.elements [i++];
  70091. transformToApply.transformPoint (x2, y2);
  70092. quadraticTo (x, y, x2, y2);
  70093. }
  70094. else if (type == cubicMarker)
  70095. {
  70096. float x2 = other.elements [i++];
  70097. float y2 = other.elements [i++];
  70098. float x3 = other.elements [i++];
  70099. float y3 = other.elements [i++];
  70100. transformToApply.transformPoint (x2, y2);
  70101. transformToApply.transformPoint (x3, y3);
  70102. cubicTo (x, y, x2, y2, x3, y3);
  70103. }
  70104. else
  70105. {
  70106. // something's gone wrong with the element list!
  70107. jassertfalse
  70108. }
  70109. }
  70110. }
  70111. }
  70112. void Path::applyTransform (const AffineTransform& transform) throw()
  70113. {
  70114. int i = 0;
  70115. pathYMin = pathXMin = 0;
  70116. pathYMax = pathXMax = 0;
  70117. bool setMaxMin = false;
  70118. while (i < numElements)
  70119. {
  70120. const float type = elements [i++];
  70121. if (type == moveMarker)
  70122. {
  70123. transform.transformPoint (elements [i],
  70124. elements [i + 1]);
  70125. if (setMaxMin)
  70126. {
  70127. pathXMin = jmin (pathXMin, elements [i]);
  70128. pathXMax = jmax (pathXMax, elements [i]);
  70129. pathYMin = jmin (pathYMin, elements [i + 1]);
  70130. pathYMax = jmax (pathYMax, elements [i + 1]);
  70131. }
  70132. else
  70133. {
  70134. pathXMin = pathXMax = elements [i];
  70135. pathYMin = pathYMax = elements [i + 1];
  70136. setMaxMin = true;
  70137. }
  70138. i += 2;
  70139. }
  70140. else if (type == lineMarker)
  70141. {
  70142. transform.transformPoint (elements [i],
  70143. elements [i + 1]);
  70144. pathXMin = jmin (pathXMin, elements [i]);
  70145. pathXMax = jmax (pathXMax, elements [i]);
  70146. pathYMin = jmin (pathYMin, elements [i + 1]);
  70147. pathYMax = jmax (pathYMax, elements [i + 1]);
  70148. i += 2;
  70149. }
  70150. else if (type == quadMarker)
  70151. {
  70152. transform.transformPoint (elements [i],
  70153. elements [i + 1]);
  70154. transform.transformPoint (elements [i + 2],
  70155. elements [i + 3]);
  70156. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  70157. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  70158. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  70159. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  70160. i += 4;
  70161. }
  70162. else if (type == cubicMarker)
  70163. {
  70164. transform.transformPoint (elements [i],
  70165. elements [i + 1]);
  70166. transform.transformPoint (elements [i + 2],
  70167. elements [i + 3]);
  70168. transform.transformPoint (elements [i + 4],
  70169. elements [i + 5]);
  70170. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  70171. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  70172. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  70173. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  70174. i += 6;
  70175. }
  70176. }
  70177. }
  70178. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  70179. const float w, const float h,
  70180. const bool preserveProportions,
  70181. const Justification& justification) const throw()
  70182. {
  70183. float sx, sy, sw, sh;
  70184. getBounds (sx, sy, sw, sh);
  70185. if (preserveProportions)
  70186. {
  70187. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  70188. return AffineTransform::identity;
  70189. float newW, newH;
  70190. const float srcRatio = sh / sw;
  70191. if (srcRatio > h / w)
  70192. {
  70193. newW = h / srcRatio;
  70194. newH = h;
  70195. }
  70196. else
  70197. {
  70198. newW = w;
  70199. newH = w * srcRatio;
  70200. }
  70201. float newXCentre = x;
  70202. float newYCentre = y;
  70203. if (justification.testFlags (Justification::left))
  70204. newXCentre += newW * 0.5f;
  70205. else if (justification.testFlags (Justification::right))
  70206. newXCentre += w - newW * 0.5f;
  70207. else
  70208. newXCentre += w * 0.5f;
  70209. if (justification.testFlags (Justification::top))
  70210. newYCentre += newH * 0.5f;
  70211. else if (justification.testFlags (Justification::bottom))
  70212. newYCentre += h - newH * 0.5f;
  70213. else
  70214. newYCentre += h * 0.5f;
  70215. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  70216. .scaled (newW / sw, newH / sh)
  70217. .translated (newXCentre, newYCentre);
  70218. }
  70219. else
  70220. {
  70221. return AffineTransform::translation (-sx, -sy)
  70222. .scaled (w / sw, h / sh)
  70223. .translated (x, y);
  70224. }
  70225. }
  70226. bool Path::contains (const float x, const float y, const float tolerence) const throw()
  70227. {
  70228. if (x <= pathXMin || x >= pathXMax
  70229. || y <= pathYMin || y >= pathYMax)
  70230. return false;
  70231. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70232. int positiveCrossings = 0;
  70233. int negativeCrossings = 0;
  70234. while (i.next())
  70235. {
  70236. if ((i.y1 <= y && i.y2 > y)
  70237. || (i.y2 <= y && i.y1 > y))
  70238. {
  70239. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  70240. if (intersectX <= x)
  70241. {
  70242. if (i.y1 < i.y2)
  70243. ++positiveCrossings;
  70244. else
  70245. ++negativeCrossings;
  70246. }
  70247. }
  70248. }
  70249. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  70250. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  70251. }
  70252. bool Path::intersectsLine (const float x1, const float y1,
  70253. const float x2, const float y2,
  70254. const float tolerence) throw()
  70255. {
  70256. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70257. const Line line1 (x1, y1, x2, y2);
  70258. while (i.next())
  70259. {
  70260. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  70261. float ix, iy;
  70262. if (line1.intersects (line2, ix, iy))
  70263. return true;
  70264. }
  70265. return false;
  70266. }
  70267. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  70268. {
  70269. if (cornerRadius <= 0.01f)
  70270. return *this;
  70271. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  70272. int n = 0;
  70273. bool lastWasLine = false, firstWasLine = false;
  70274. Path p;
  70275. while (n < numElements)
  70276. {
  70277. const float type = elements [n++];
  70278. if (type == moveMarker)
  70279. {
  70280. indexOfPathStart = p.numElements;
  70281. indexOfPathStartThis = n - 1;
  70282. const float x = elements [n++];
  70283. const float y = elements [n++];
  70284. p.startNewSubPath (x, y);
  70285. lastWasLine = false;
  70286. firstWasLine = (elements [n] == lineMarker);
  70287. }
  70288. else if (type == lineMarker || type == closeSubPathMarker)
  70289. {
  70290. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  70291. if (type == lineMarker)
  70292. {
  70293. endX = elements [n++];
  70294. endY = elements [n++];
  70295. if (n > 8)
  70296. {
  70297. startX = elements [n - 8];
  70298. startY = elements [n - 7];
  70299. joinX = elements [n - 5];
  70300. joinY = elements [n - 4];
  70301. }
  70302. }
  70303. else
  70304. {
  70305. endX = elements [indexOfPathStartThis + 1];
  70306. endY = elements [indexOfPathStartThis + 2];
  70307. if (n > 6)
  70308. {
  70309. startX = elements [n - 6];
  70310. startY = elements [n - 5];
  70311. joinX = elements [n - 3];
  70312. joinY = elements [n - 2];
  70313. }
  70314. }
  70315. if (lastWasLine)
  70316. {
  70317. const double len1 = juce_hypot (startX - joinX,
  70318. startY - joinY);
  70319. if (len1 > 0)
  70320. {
  70321. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70322. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70323. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70324. }
  70325. const double len2 = juce_hypot (endX - joinX,
  70326. endY - joinY);
  70327. if (len2 > 0)
  70328. {
  70329. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70330. p.quadraticTo (joinX, joinY,
  70331. (float) (joinX + (endX - joinX) * propNeeded),
  70332. (float) (joinY + (endY - joinY) * propNeeded));
  70333. }
  70334. p.lineTo (endX, endY);
  70335. }
  70336. else if (type == lineMarker)
  70337. {
  70338. p.lineTo (endX, endY);
  70339. lastWasLine = true;
  70340. }
  70341. if (type == closeSubPathMarker)
  70342. {
  70343. if (firstWasLine)
  70344. {
  70345. startX = elements [n - 3];
  70346. startY = elements [n - 2];
  70347. joinX = endX;
  70348. joinY = endY;
  70349. endX = elements [indexOfPathStartThis + 4];
  70350. endY = elements [indexOfPathStartThis + 5];
  70351. const double len1 = juce_hypot (startX - joinX,
  70352. startY - joinY);
  70353. if (len1 > 0)
  70354. {
  70355. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70356. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70357. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70358. }
  70359. const double len2 = juce_hypot (endX - joinX,
  70360. endY - joinY);
  70361. if (len2 > 0)
  70362. {
  70363. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70364. endX = (float) (joinX + (endX - joinX) * propNeeded);
  70365. endY = (float) (joinY + (endY - joinY) * propNeeded);
  70366. p.quadraticTo (joinX, joinY, endX, endY);
  70367. p.elements [indexOfPathStart + 1] = endX;
  70368. p.elements [indexOfPathStart + 2] = endY;
  70369. }
  70370. }
  70371. p.closeSubPath();
  70372. }
  70373. }
  70374. else if (type == quadMarker)
  70375. {
  70376. lastWasLine = false;
  70377. const float x1 = elements [n++];
  70378. const float y1 = elements [n++];
  70379. const float x2 = elements [n++];
  70380. const float y2 = elements [n++];
  70381. p.quadraticTo (x1, y1, x2, y2);
  70382. }
  70383. else if (type == cubicMarker)
  70384. {
  70385. lastWasLine = false;
  70386. const float x1 = elements [n++];
  70387. const float y1 = elements [n++];
  70388. const float x2 = elements [n++];
  70389. const float y2 = elements [n++];
  70390. const float x3 = elements [n++];
  70391. const float y3 = elements [n++];
  70392. p.cubicTo (x1, y1, x2, y2, x3, y3);
  70393. }
  70394. }
  70395. return p;
  70396. }
  70397. void Path::loadPathFromStream (InputStream& source)
  70398. {
  70399. while (! source.isExhausted())
  70400. {
  70401. switch (source.readByte())
  70402. {
  70403. case 'm':
  70404. {
  70405. const float x = source.readFloat();
  70406. const float y = source.readFloat();
  70407. startNewSubPath (x, y);
  70408. break;
  70409. }
  70410. case 'l':
  70411. {
  70412. const float x = source.readFloat();
  70413. const float y = source.readFloat();
  70414. lineTo (x, y);
  70415. break;
  70416. }
  70417. case 'q':
  70418. {
  70419. const float x1 = source.readFloat();
  70420. const float y1 = source.readFloat();
  70421. const float x2 = source.readFloat();
  70422. const float y2 = source.readFloat();
  70423. quadraticTo (x1, y1, x2, y2);
  70424. break;
  70425. }
  70426. case 'b':
  70427. {
  70428. const float x1 = source.readFloat();
  70429. const float y1 = source.readFloat();
  70430. const float x2 = source.readFloat();
  70431. const float y2 = source.readFloat();
  70432. const float x3 = source.readFloat();
  70433. const float y3 = source.readFloat();
  70434. cubicTo (x1, y1, x2, y2, x3, y3);
  70435. break;
  70436. }
  70437. case 'c':
  70438. closeSubPath();
  70439. break;
  70440. case 'n':
  70441. useNonZeroWinding = true;
  70442. break;
  70443. case 'z':
  70444. useNonZeroWinding = false;
  70445. break;
  70446. case 'e':
  70447. return; // end of path marker
  70448. default:
  70449. jassertfalse // illegal char in the stream
  70450. break;
  70451. }
  70452. }
  70453. }
  70454. void Path::loadPathFromData (const unsigned char* const data,
  70455. const int numberOfBytes) throw()
  70456. {
  70457. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  70458. loadPathFromStream (in);
  70459. }
  70460. void Path::writePathToStream (OutputStream& dest) const
  70461. {
  70462. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  70463. int i = 0;
  70464. while (i < numElements)
  70465. {
  70466. const float type = elements [i++];
  70467. if (type == moveMarker)
  70468. {
  70469. dest.writeByte ('m');
  70470. dest.writeFloat (elements [i++]);
  70471. dest.writeFloat (elements [i++]);
  70472. }
  70473. else if (type == lineMarker)
  70474. {
  70475. dest.writeByte ('l');
  70476. dest.writeFloat (elements [i++]);
  70477. dest.writeFloat (elements [i++]);
  70478. }
  70479. else if (type == quadMarker)
  70480. {
  70481. dest.writeByte ('q');
  70482. dest.writeFloat (elements [i++]);
  70483. dest.writeFloat (elements [i++]);
  70484. dest.writeFloat (elements [i++]);
  70485. dest.writeFloat (elements [i++]);
  70486. }
  70487. else if (type == cubicMarker)
  70488. {
  70489. dest.writeByte ('b');
  70490. dest.writeFloat (elements [i++]);
  70491. dest.writeFloat (elements [i++]);
  70492. dest.writeFloat (elements [i++]);
  70493. dest.writeFloat (elements [i++]);
  70494. dest.writeFloat (elements [i++]);
  70495. dest.writeFloat (elements [i++]);
  70496. }
  70497. else if (type == closeSubPathMarker)
  70498. {
  70499. dest.writeByte ('c');
  70500. }
  70501. }
  70502. dest.writeByte ('e'); // marks the end-of-path
  70503. }
  70504. const String Path::toString() const
  70505. {
  70506. String s;
  70507. s.preallocateStorage (numElements * 4);
  70508. if (! useNonZeroWinding)
  70509. s << T("a ");
  70510. int i = 0;
  70511. float lastMarker = 0.0f;
  70512. while (i < numElements)
  70513. {
  70514. const float marker = elements [i++];
  70515. tchar markerChar = 0;
  70516. int numCoords = 0;
  70517. if (marker == moveMarker)
  70518. {
  70519. markerChar = T('m');
  70520. numCoords = 2;
  70521. }
  70522. else if (marker == lineMarker)
  70523. {
  70524. markerChar = T('l');
  70525. numCoords = 2;
  70526. }
  70527. else if (marker == quadMarker)
  70528. {
  70529. markerChar = T('q');
  70530. numCoords = 4;
  70531. }
  70532. else if (marker == cubicMarker)
  70533. {
  70534. markerChar = T('c');
  70535. numCoords = 6;
  70536. }
  70537. else
  70538. {
  70539. jassert (marker == closeSubPathMarker);
  70540. markerChar = T('z');
  70541. }
  70542. if (marker != lastMarker)
  70543. {
  70544. s << markerChar << T(' ');
  70545. lastMarker = marker;
  70546. }
  70547. while (--numCoords >= 0 && i < numElements)
  70548. {
  70549. String n (elements [i++], 3);
  70550. while (n.endsWithChar (T('0')))
  70551. n = n.dropLastCharacters (1);
  70552. if (n.endsWithChar (T('.')))
  70553. n = n.dropLastCharacters (1);
  70554. s << n << T(' ');
  70555. }
  70556. }
  70557. return s.trimEnd();
  70558. }
  70559. static const String nextToken (const tchar*& t)
  70560. {
  70561. while (CharacterFunctions::isWhitespace (*t))
  70562. ++t;
  70563. const tchar* const start = t;
  70564. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  70565. ++t;
  70566. const int length = (int) (t - start);
  70567. while (CharacterFunctions::isWhitespace (*t))
  70568. ++t;
  70569. return String (start, length);
  70570. }
  70571. void Path::restoreFromString (const String& stringVersion)
  70572. {
  70573. clear();
  70574. setUsingNonZeroWinding (true);
  70575. const tchar* t = stringVersion;
  70576. tchar marker = T('m');
  70577. int numValues = 2;
  70578. float values [6];
  70579. while (*t != 0)
  70580. {
  70581. const String token (nextToken (t));
  70582. const tchar firstChar = token[0];
  70583. int startNum = 0;
  70584. if (firstChar == T('m') || firstChar == T('l'))
  70585. {
  70586. marker = firstChar;
  70587. numValues = 2;
  70588. }
  70589. else if (firstChar == T('q'))
  70590. {
  70591. marker = firstChar;
  70592. numValues = 4;
  70593. }
  70594. else if (firstChar == T('c'))
  70595. {
  70596. marker = firstChar;
  70597. numValues = 6;
  70598. }
  70599. else if (firstChar == T('z'))
  70600. {
  70601. marker = firstChar;
  70602. numValues = 0;
  70603. }
  70604. else if (firstChar == T('a'))
  70605. {
  70606. setUsingNonZeroWinding (false);
  70607. continue;
  70608. }
  70609. else
  70610. {
  70611. ++startNum;
  70612. values [0] = token.getFloatValue();
  70613. }
  70614. for (int i = startNum; i < numValues; ++i)
  70615. values [i] = nextToken (t).getFloatValue();
  70616. switch (marker)
  70617. {
  70618. case T('m'):
  70619. startNewSubPath (values[0], values[1]);
  70620. break;
  70621. case T('l'):
  70622. lineTo (values[0], values[1]);
  70623. break;
  70624. case T('q'):
  70625. quadraticTo (values[0], values[1],
  70626. values[2], values[3]);
  70627. break;
  70628. case T('c'):
  70629. cubicTo (values[0], values[1],
  70630. values[2], values[3],
  70631. values[4], values[5]);
  70632. break;
  70633. case T('z'):
  70634. closeSubPath();
  70635. break;
  70636. default:
  70637. jassertfalse // illegal string format?
  70638. break;
  70639. }
  70640. }
  70641. }
  70642. Path::Iterator::Iterator (const Path& path_)
  70643. : path (path_),
  70644. index (0)
  70645. {
  70646. }
  70647. Path::Iterator::~Iterator()
  70648. {
  70649. }
  70650. bool Path::Iterator::next()
  70651. {
  70652. const float* const elements = path.elements;
  70653. if (index < path.numElements)
  70654. {
  70655. const float type = elements [index++];
  70656. if (type == moveMarker)
  70657. {
  70658. elementType = startNewSubPath;
  70659. x1 = elements [index++];
  70660. y1 = elements [index++];
  70661. }
  70662. else if (type == lineMarker)
  70663. {
  70664. elementType = lineTo;
  70665. x1 = elements [index++];
  70666. y1 = elements [index++];
  70667. }
  70668. else if (type == quadMarker)
  70669. {
  70670. elementType = quadraticTo;
  70671. x1 = elements [index++];
  70672. y1 = elements [index++];
  70673. x2 = elements [index++];
  70674. y2 = elements [index++];
  70675. }
  70676. else if (type == cubicMarker)
  70677. {
  70678. elementType = cubicTo;
  70679. x1 = elements [index++];
  70680. y1 = elements [index++];
  70681. x2 = elements [index++];
  70682. y2 = elements [index++];
  70683. x3 = elements [index++];
  70684. y3 = elements [index++];
  70685. }
  70686. else if (type == closeSubPathMarker)
  70687. {
  70688. elementType = closePath;
  70689. }
  70690. return true;
  70691. }
  70692. return false;
  70693. }
  70694. END_JUCE_NAMESPACE
  70695. /********* End of inlined file: juce_Path.cpp *********/
  70696. /********* Start of inlined file: juce_PathIterator.cpp *********/
  70697. BEGIN_JUCE_NAMESPACE
  70698. #if JUCE_MSVC
  70699. #pragma optimize ("t", on)
  70700. #endif
  70701. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  70702. const AffineTransform& transform_,
  70703. float tolerence_) throw()
  70704. : x2 (0),
  70705. y2 (0),
  70706. closesSubPath (false),
  70707. subPathIndex (-1),
  70708. path (path_),
  70709. transform (transform_),
  70710. points (path_.elements),
  70711. tolerence (tolerence_ * tolerence_),
  70712. subPathCloseX (0),
  70713. subPathCloseY (0),
  70714. index (0),
  70715. stackSize (32)
  70716. {
  70717. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  70718. isIdentityTransform = transform.isIdentity();
  70719. stackPos = stackBase;
  70720. }
  70721. PathFlatteningIterator::~PathFlatteningIterator() throw()
  70722. {
  70723. juce_free (stackBase);
  70724. }
  70725. bool PathFlatteningIterator::next() throw()
  70726. {
  70727. x1 = x2;
  70728. y1 = y2;
  70729. float x3 = 0;
  70730. float y3 = 0;
  70731. float x4 = 0;
  70732. float y4 = 0;
  70733. float type;
  70734. for (;;)
  70735. {
  70736. if (stackPos == stackBase)
  70737. {
  70738. if (index >= path.numElements)
  70739. {
  70740. return false;
  70741. }
  70742. else
  70743. {
  70744. type = points [index++];
  70745. if (type != Path::closeSubPathMarker)
  70746. {
  70747. x2 = points [index++];
  70748. y2 = points [index++];
  70749. if (! isIdentityTransform)
  70750. transform.transformPoint (x2, y2);
  70751. if (type == Path::quadMarker)
  70752. {
  70753. x3 = points [index++];
  70754. y3 = points [index++];
  70755. if (! isIdentityTransform)
  70756. transform.transformPoint (x3, y3);
  70757. }
  70758. else if (type == Path::cubicMarker)
  70759. {
  70760. x3 = points [index++];
  70761. y3 = points [index++];
  70762. x4 = points [index++];
  70763. y4 = points [index++];
  70764. if (! isIdentityTransform)
  70765. {
  70766. transform.transformPoint (x3, y3);
  70767. transform.transformPoint (x4, y4);
  70768. }
  70769. }
  70770. }
  70771. }
  70772. }
  70773. else
  70774. {
  70775. type = *--stackPos;
  70776. if (type != Path::closeSubPathMarker)
  70777. {
  70778. x2 = *--stackPos;
  70779. y2 = *--stackPos;
  70780. if (type == Path::quadMarker)
  70781. {
  70782. x3 = *--stackPos;
  70783. y3 = *--stackPos;
  70784. }
  70785. else if (type == Path::cubicMarker)
  70786. {
  70787. x3 = *--stackPos;
  70788. y3 = *--stackPos;
  70789. x4 = *--stackPos;
  70790. y4 = *--stackPos;
  70791. }
  70792. }
  70793. }
  70794. if (type == Path::lineMarker)
  70795. {
  70796. ++subPathIndex;
  70797. closesSubPath = (stackPos == stackBase)
  70798. && (index < path.numElements)
  70799. && (points [index] == Path::closeSubPathMarker)
  70800. && x2 == subPathCloseX
  70801. && y2 == subPathCloseY;
  70802. return true;
  70803. }
  70804. else if (type == Path::quadMarker)
  70805. {
  70806. const int offset = (int) (stackPos - stackBase);
  70807. if (offset >= stackSize - 10)
  70808. {
  70809. stackSize <<= 1;
  70810. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70811. stackPos = stackBase + offset;
  70812. }
  70813. const float dx1 = x1 - x2;
  70814. const float dy1 = y1 - y2;
  70815. const float dx2 = x2 - x3;
  70816. const float dy2 = y2 - y3;
  70817. const float m1x = (x1 + x2) * 0.5f;
  70818. const float m1y = (y1 + y2) * 0.5f;
  70819. const float m2x = (x2 + x3) * 0.5f;
  70820. const float m2y = (y2 + y3) * 0.5f;
  70821. const float m3x = (m1x + m2x) * 0.5f;
  70822. const float m3y = (m1y + m2y) * 0.5f;
  70823. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  70824. {
  70825. *stackPos++ = y3;
  70826. *stackPos++ = x3;
  70827. *stackPos++ = m2y;
  70828. *stackPos++ = m2x;
  70829. *stackPos++ = Path::quadMarker;
  70830. *stackPos++ = m3y;
  70831. *stackPos++ = m3x;
  70832. *stackPos++ = m1y;
  70833. *stackPos++ = m1x;
  70834. *stackPos++ = Path::quadMarker;
  70835. }
  70836. else
  70837. {
  70838. *stackPos++ = y3;
  70839. *stackPos++ = x3;
  70840. *stackPos++ = Path::lineMarker;
  70841. *stackPos++ = m3y;
  70842. *stackPos++ = m3x;
  70843. *stackPos++ = Path::lineMarker;
  70844. }
  70845. jassert (stackPos < stackBase + stackSize);
  70846. }
  70847. else if (type == Path::cubicMarker)
  70848. {
  70849. const int offset = (int) (stackPos - stackBase);
  70850. if (offset >= stackSize - 16)
  70851. {
  70852. stackSize <<= 1;
  70853. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70854. stackPos = stackBase + offset;
  70855. }
  70856. const float dx1 = x1 - x2;
  70857. const float dy1 = y1 - y2;
  70858. const float dx2 = x2 - x3;
  70859. const float dy2 = y2 - y3;
  70860. const float dx3 = x3 - x4;
  70861. const float dy3 = y3 - y4;
  70862. const float m1x = (x1 + x2) * 0.5f;
  70863. const float m1y = (y1 + y2) * 0.5f;
  70864. const float m2x = (x3 + x2) * 0.5f;
  70865. const float m2y = (y3 + y2) * 0.5f;
  70866. const float m3x = (x3 + x4) * 0.5f;
  70867. const float m3y = (y3 + y4) * 0.5f;
  70868. const float m4x = (m1x + m2x) * 0.5f;
  70869. const float m4y = (m1y + m2y) * 0.5f;
  70870. const float m5x = (m3x + m2x) * 0.5f;
  70871. const float m5y = (m3y + m2y) * 0.5f;
  70872. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  70873. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  70874. {
  70875. *stackPos++ = y4;
  70876. *stackPos++ = x4;
  70877. *stackPos++ = m3y;
  70878. *stackPos++ = m3x;
  70879. *stackPos++ = m5y;
  70880. *stackPos++ = m5x;
  70881. *stackPos++ = Path::cubicMarker;
  70882. *stackPos++ = (m4y + m5y) * 0.5f;
  70883. *stackPos++ = (m4x + m5x) * 0.5f;
  70884. *stackPos++ = m4y;
  70885. *stackPos++ = m4x;
  70886. *stackPos++ = m1y;
  70887. *stackPos++ = m1x;
  70888. *stackPos++ = Path::cubicMarker;
  70889. }
  70890. else
  70891. {
  70892. *stackPos++ = y4;
  70893. *stackPos++ = x4;
  70894. *stackPos++ = Path::lineMarker;
  70895. *stackPos++ = m5y;
  70896. *stackPos++ = m5x;
  70897. *stackPos++ = Path::lineMarker;
  70898. *stackPos++ = m4y;
  70899. *stackPos++ = m4x;
  70900. *stackPos++ = Path::lineMarker;
  70901. }
  70902. }
  70903. else if (type == Path::closeSubPathMarker)
  70904. {
  70905. if (x2 != subPathCloseX || y2 != subPathCloseY)
  70906. {
  70907. x1 = x2;
  70908. y1 = y2;
  70909. x2 = subPathCloseX;
  70910. y2 = subPathCloseY;
  70911. closesSubPath = true;
  70912. return true;
  70913. }
  70914. }
  70915. else
  70916. {
  70917. jassert (type == Path::moveMarker);
  70918. subPathIndex = -1;
  70919. subPathCloseX = x1 = x2;
  70920. subPathCloseY = y1 = y2;
  70921. }
  70922. }
  70923. }
  70924. END_JUCE_NAMESPACE
  70925. /********* End of inlined file: juce_PathIterator.cpp *********/
  70926. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  70927. BEGIN_JUCE_NAMESPACE
  70928. PathStrokeType::PathStrokeType (const float strokeThickness,
  70929. const JointStyle jointStyle_,
  70930. const EndCapStyle endStyle_) throw()
  70931. : thickness (strokeThickness),
  70932. jointStyle (jointStyle_),
  70933. endStyle (endStyle_)
  70934. {
  70935. }
  70936. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  70937. : thickness (other.thickness),
  70938. jointStyle (other.jointStyle),
  70939. endStyle (other.endStyle)
  70940. {
  70941. }
  70942. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  70943. {
  70944. thickness = other.thickness;
  70945. jointStyle = other.jointStyle;
  70946. endStyle = other.endStyle;
  70947. return *this;
  70948. }
  70949. PathStrokeType::~PathStrokeType() throw()
  70950. {
  70951. }
  70952. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  70953. {
  70954. return thickness == other.thickness
  70955. && jointStyle == other.jointStyle
  70956. && endStyle == other.endStyle;
  70957. }
  70958. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  70959. {
  70960. return ! operator== (other);
  70961. }
  70962. static bool lineIntersection (const float x1, const float y1,
  70963. const float x2, const float y2,
  70964. const float x3, const float y3,
  70965. const float x4, const float y4,
  70966. float& intersectionX,
  70967. float& intersectionY,
  70968. float& distanceBeyondLine1EndSquared) throw()
  70969. {
  70970. if (x2 != x3 || y2 != y3)
  70971. {
  70972. const float dx1 = x2 - x1;
  70973. const float dy1 = y2 - y1;
  70974. const float dx2 = x4 - x3;
  70975. const float dy2 = y4 - y3;
  70976. const float divisor = dx1 * dy2 - dx2 * dy1;
  70977. if (divisor == 0)
  70978. {
  70979. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  70980. {
  70981. if (dy1 == 0 && dy2 != 0)
  70982. {
  70983. const float along = (y1 - y3) / dy2;
  70984. intersectionX = x3 + along * dx2;
  70985. intersectionY = y1;
  70986. distanceBeyondLine1EndSquared = intersectionX - x2;
  70987. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70988. if ((x2 > x1) == (intersectionX < x2))
  70989. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70990. return along >= 0 && along <= 1.0f;
  70991. }
  70992. else if (dy2 == 0 && dy1 != 0)
  70993. {
  70994. const float along = (y3 - y1) / dy1;
  70995. intersectionX = x1 + along * dx1;
  70996. intersectionY = y3;
  70997. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  70998. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70999. if (along < 1.0f)
  71000. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71001. return along >= 0 && along <= 1.0f;
  71002. }
  71003. else if (dx1 == 0 && dx2 != 0)
  71004. {
  71005. const float along = (x1 - x3) / dx2;
  71006. intersectionX = x1;
  71007. intersectionY = y3 + along * dy2;
  71008. distanceBeyondLine1EndSquared = intersectionY - y2;
  71009. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71010. if ((y2 > y1) == (intersectionY < y2))
  71011. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71012. return along >= 0 && along <= 1.0f;
  71013. }
  71014. else if (dx2 == 0 && dx1 != 0)
  71015. {
  71016. const float along = (x3 - x1) / dx1;
  71017. intersectionX = x3;
  71018. intersectionY = y1 + along * dy1;
  71019. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  71020. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71021. if (along < 1.0f)
  71022. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71023. return along >= 0 && along <= 1.0f;
  71024. }
  71025. }
  71026. intersectionX = 0.5f * (x2 + x3);
  71027. intersectionY = 0.5f * (y2 + y3);
  71028. distanceBeyondLine1EndSquared = 0.0f;
  71029. return false;
  71030. }
  71031. else
  71032. {
  71033. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  71034. intersectionX = x1 + along1 * dx1;
  71035. intersectionY = y1 + along1 * dy1;
  71036. if (along1 >= 0 && along1 <= 1.0f)
  71037. {
  71038. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  71039. if (along2 >= 0 && along2 <= divisor)
  71040. {
  71041. distanceBeyondLine1EndSquared = 0.0f;
  71042. return true;
  71043. }
  71044. }
  71045. distanceBeyondLine1EndSquared = along1 - 1.0f;
  71046. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71047. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  71048. if (along1 < 1.0f)
  71049. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71050. return false;
  71051. }
  71052. }
  71053. intersectionX = x2;
  71054. intersectionY = y2;
  71055. distanceBeyondLine1EndSquared = 0.0f;
  71056. return true;
  71057. }
  71058. // part of stroke drawing stuff
  71059. static void addEdgeAndJoint (Path& destPath,
  71060. const PathStrokeType::JointStyle style,
  71061. const float maxMiterExtensionSquared, const float width,
  71062. const float x1, const float y1,
  71063. const float x2, const float y2,
  71064. const float x3, const float y3,
  71065. const float x4, const float y4,
  71066. const float midX, const float midY) throw()
  71067. {
  71068. if (style == PathStrokeType::beveled
  71069. || (x3 == x4 && y3 == y4)
  71070. || (x1 == x2 && y1 == y2))
  71071. {
  71072. destPath.lineTo (x2, y2);
  71073. destPath.lineTo (x3, y3);
  71074. }
  71075. else
  71076. {
  71077. float jx, jy, distanceBeyondLine1EndSquared;
  71078. // if they intersect, use this point..
  71079. if (lineIntersection (x1, y1, x2, y2,
  71080. x3, y3, x4, y4,
  71081. jx, jy, distanceBeyondLine1EndSquared))
  71082. {
  71083. destPath.lineTo (jx, jy);
  71084. }
  71085. else
  71086. {
  71087. if (style == PathStrokeType::mitered)
  71088. {
  71089. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  71090. && distanceBeyondLine1EndSquared > 0.0f)
  71091. {
  71092. destPath.lineTo (jx, jy);
  71093. }
  71094. else
  71095. {
  71096. // the end sticks out too far, so just use a blunt joint
  71097. destPath.lineTo (x2, y2);
  71098. destPath.lineTo (x3, y3);
  71099. }
  71100. }
  71101. else
  71102. {
  71103. // curved joints
  71104. float angle = atan2f (x2 - midX, y2 - midY);
  71105. float angle2 = atan2f (x3 - midX, y3 - midY);
  71106. while (angle < angle2 - 0.01f)
  71107. angle2 -= float_Pi * 2.0f;
  71108. destPath.lineTo (x2, y2);
  71109. while (angle > angle2)
  71110. {
  71111. destPath.lineTo (midX + width * sinf (angle),
  71112. midY + width * cosf (angle));
  71113. angle -= 0.1f;
  71114. }
  71115. destPath.lineTo (x3, y3);
  71116. }
  71117. }
  71118. }
  71119. }
  71120. static inline void addLineEnd (Path& destPath,
  71121. const PathStrokeType::EndCapStyle style,
  71122. const float x1, const float y1,
  71123. const float x2, const float y2,
  71124. const float width) throw()
  71125. {
  71126. if (style == PathStrokeType::butt)
  71127. {
  71128. destPath.lineTo (x2, y2);
  71129. }
  71130. else
  71131. {
  71132. float offx1, offy1, offx2, offy2;
  71133. float dx = x2 - x1;
  71134. float dy = y2 - y1;
  71135. const float len = juce_hypotf (dx, dy);
  71136. if (len == 0)
  71137. {
  71138. offx1 = offx2 = x1;
  71139. offy1 = offy2 = y1;
  71140. }
  71141. else
  71142. {
  71143. const float offset = width / len;
  71144. dx *= offset;
  71145. dy *= offset;
  71146. offx1 = x1 + dy;
  71147. offy1 = y1 - dx;
  71148. offx2 = x2 + dy;
  71149. offy2 = y2 - dx;
  71150. }
  71151. if (style == PathStrokeType::square)
  71152. {
  71153. // sqaure ends
  71154. destPath.lineTo (offx1, offy1);
  71155. destPath.lineTo (offx2, offy2);
  71156. destPath.lineTo (x2, y2);
  71157. }
  71158. else
  71159. {
  71160. // rounded ends
  71161. const float midx = (offx1 + offx2) * 0.5f;
  71162. const float midy = (offy1 + offy2) * 0.5f;
  71163. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  71164. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  71165. midx, midy);
  71166. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  71167. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  71168. x2, y2);
  71169. }
  71170. }
  71171. }
  71172. struct LineSection
  71173. {
  71174. LineSection() throw() {}
  71175. LineSection (int) throw() {}
  71176. float x1, y1, x2, y2; // original line
  71177. float lx1, ly1, lx2, ly2; // the left-hand stroke
  71178. float rx1, ry1, rx2, ry2; // the right-hand stroke
  71179. };
  71180. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  71181. const bool isClosed,
  71182. const float width, const float maxMiterExtensionSquared,
  71183. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  71184. {
  71185. jassert (subPath.size() > 0);
  71186. const LineSection& firstLine = subPath.getReference (0);
  71187. float lastX1 = firstLine.lx1;
  71188. float lastY1 = firstLine.ly1;
  71189. float lastX2 = firstLine.lx2;
  71190. float lastY2 = firstLine.ly2;
  71191. if (isClosed)
  71192. {
  71193. destPath.startNewSubPath (lastX1, lastY1);
  71194. }
  71195. else
  71196. {
  71197. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  71198. addLineEnd (destPath, endStyle,
  71199. firstLine.rx2, firstLine.ry2,
  71200. lastX1, lastY1,
  71201. width);
  71202. }
  71203. int i;
  71204. for (i = 1; i < subPath.size(); ++i)
  71205. {
  71206. const LineSection& l = subPath.getReference (i);
  71207. addEdgeAndJoint (destPath, jointStyle,
  71208. maxMiterExtensionSquared, width,
  71209. lastX1, lastY1, lastX2, lastY2,
  71210. l.lx1, l.ly1, l.lx2, l.ly2,
  71211. l.x1, l.y1);
  71212. lastX1 = l.lx1;
  71213. lastY1 = l.ly1;
  71214. lastX2 = l.lx2;
  71215. lastY2 = l.ly2;
  71216. }
  71217. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  71218. if (isClosed)
  71219. {
  71220. const LineSection& l = subPath.getReference (0);
  71221. addEdgeAndJoint (destPath, jointStyle,
  71222. maxMiterExtensionSquared, width,
  71223. lastX1, lastY1, lastX2, lastY2,
  71224. l.lx1, l.ly1, l.lx2, l.ly2,
  71225. l.x1, l.y1);
  71226. destPath.closeSubPath();
  71227. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  71228. }
  71229. else
  71230. {
  71231. destPath.lineTo (lastX2, lastY2);
  71232. addLineEnd (destPath, endStyle,
  71233. lastX2, lastY2,
  71234. lastLine.rx1, lastLine.ry1,
  71235. width);
  71236. }
  71237. lastX1 = lastLine.rx1;
  71238. lastY1 = lastLine.ry1;
  71239. lastX2 = lastLine.rx2;
  71240. lastY2 = lastLine.ry2;
  71241. for (i = subPath.size() - 1; --i >= 0;)
  71242. {
  71243. const LineSection& l = subPath.getReference (i);
  71244. addEdgeAndJoint (destPath, jointStyle,
  71245. maxMiterExtensionSquared, width,
  71246. lastX1, lastY1, lastX2, lastY2,
  71247. l.rx1, l.ry1, l.rx2, l.ry2,
  71248. l.x2, l.y2);
  71249. lastX1 = l.rx1;
  71250. lastY1 = l.ry1;
  71251. lastX2 = l.rx2;
  71252. lastY2 = l.ry2;
  71253. }
  71254. if (isClosed)
  71255. {
  71256. addEdgeAndJoint (destPath, jointStyle,
  71257. maxMiterExtensionSquared, width,
  71258. lastX1, lastY1, lastX2, lastY2,
  71259. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  71260. lastLine.x2, lastLine.y2);
  71261. }
  71262. else
  71263. {
  71264. // do the last line
  71265. destPath.lineTo (lastX2, lastY2);
  71266. }
  71267. destPath.closeSubPath();
  71268. }
  71269. void PathStrokeType::createStrokedPath (Path& destPath,
  71270. const Path& source,
  71271. const AffineTransform& transform,
  71272. const float extraAccuracy) const throw()
  71273. {
  71274. if (thickness <= 0)
  71275. {
  71276. destPath.clear();
  71277. return;
  71278. }
  71279. const Path* sourcePath = &source;
  71280. Path temp;
  71281. if (sourcePath == &destPath)
  71282. {
  71283. destPath.swapWithPath (temp);
  71284. sourcePath = &temp;
  71285. }
  71286. else
  71287. {
  71288. destPath.clear();
  71289. }
  71290. destPath.setUsingNonZeroWinding (true);
  71291. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  71292. const float width = 0.5f * thickness;
  71293. // Iterate the path, creating a list of the
  71294. // left/right-hand lines along either side of it...
  71295. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  71296. Array <LineSection> subPath;
  71297. LineSection l;
  71298. l.x1 = 0;
  71299. l.y1 = 0;
  71300. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  71301. while (it.next())
  71302. {
  71303. if (it.subPathIndex == 0)
  71304. {
  71305. if (subPath.size() > 0)
  71306. {
  71307. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71308. subPath.clearQuick();
  71309. }
  71310. l.x1 = it.x1;
  71311. l.y1 = it.y1;
  71312. }
  71313. l.x2 = it.x2;
  71314. l.y2 = it.y2;
  71315. float dx = l.x2 - l.x1;
  71316. float dy = l.y2 - l.y1;
  71317. const float hypotSquared = dx*dx + dy*dy;
  71318. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  71319. {
  71320. const float len = sqrtf (hypotSquared);
  71321. if (len == 0)
  71322. {
  71323. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  71324. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  71325. }
  71326. else
  71327. {
  71328. const float offset = width / len;
  71329. dx *= offset;
  71330. dy *= offset;
  71331. l.rx2 = l.x1 - dy;
  71332. l.ry2 = l.y1 + dx;
  71333. l.lx1 = l.x1 + dy;
  71334. l.ly1 = l.y1 - dx;
  71335. l.lx2 = l.x2 + dy;
  71336. l.ly2 = l.y2 - dx;
  71337. l.rx1 = l.x2 - dy;
  71338. l.ry1 = l.y2 + dx;
  71339. }
  71340. subPath.add (l);
  71341. if (it.closesSubPath)
  71342. {
  71343. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71344. subPath.clearQuick();
  71345. }
  71346. else
  71347. {
  71348. l.x1 = it.x2;
  71349. l.y1 = it.y2;
  71350. }
  71351. }
  71352. }
  71353. if (subPath.size() > 0)
  71354. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71355. }
  71356. void PathStrokeType::createDashedStroke (Path& destPath,
  71357. const Path& sourcePath,
  71358. const float* dashLengths,
  71359. int numDashLengths,
  71360. const AffineTransform& transform,
  71361. const float extraAccuracy) const throw()
  71362. {
  71363. if (thickness <= 0)
  71364. return;
  71365. // this should really be an even number..
  71366. jassert ((numDashLengths & 1) == 0);
  71367. Path newDestPath;
  71368. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  71369. bool first = true;
  71370. int dashNum = 0;
  71371. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  71372. float dx = 0.0f, dy = 0.0f;
  71373. for (;;)
  71374. {
  71375. const bool isSolid = ((dashNum & 1) == 0);
  71376. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  71377. jassert (dashLen > 0); // must be a positive increment!
  71378. if (dashLen <= 0)
  71379. break;
  71380. pos += dashLen;
  71381. while (pos > lineEndPos)
  71382. {
  71383. if (! it.next())
  71384. {
  71385. if (isSolid && ! first)
  71386. newDestPath.lineTo (it.x2, it.y2);
  71387. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  71388. return;
  71389. }
  71390. if (isSolid && ! first)
  71391. newDestPath.lineTo (it.x1, it.y1);
  71392. else
  71393. newDestPath.startNewSubPath (it.x1, it.y1);
  71394. dx = it.x2 - it.x1;
  71395. dy = it.y2 - it.y1;
  71396. lineLen = juce_hypotf (dx, dy);
  71397. lineEndPos += lineLen;
  71398. first = it.closesSubPath;
  71399. }
  71400. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  71401. if (isSolid)
  71402. newDestPath.lineTo (it.x1 + dx * alpha,
  71403. it.y1 + dy * alpha);
  71404. else
  71405. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  71406. it.y1 + dy * alpha);
  71407. }
  71408. }
  71409. END_JUCE_NAMESPACE
  71410. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  71411. /********* Start of inlined file: juce_Point.cpp *********/
  71412. BEGIN_JUCE_NAMESPACE
  71413. Point::Point() throw()
  71414. : x (0.0f),
  71415. y (0.0f)
  71416. {
  71417. }
  71418. Point::Point (const Point& other) throw()
  71419. : x (other.x),
  71420. y (other.y)
  71421. {
  71422. }
  71423. const Point& Point::operator= (const Point& other) throw()
  71424. {
  71425. x = other.x;
  71426. y = other.y;
  71427. return *this;
  71428. }
  71429. Point::Point (const float x_,
  71430. const float y_) throw()
  71431. : x (x_),
  71432. y (y_)
  71433. {
  71434. }
  71435. Point::~Point() throw()
  71436. {
  71437. }
  71438. void Point::setXY (const float x_,
  71439. const float y_) throw()
  71440. {
  71441. x = x_;
  71442. y = y_;
  71443. }
  71444. void Point::applyTransform (const AffineTransform& transform) throw()
  71445. {
  71446. transform.transformPoint (x, y);
  71447. }
  71448. END_JUCE_NAMESPACE
  71449. /********* End of inlined file: juce_Point.cpp *********/
  71450. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  71451. BEGIN_JUCE_NAMESPACE
  71452. PositionedRectangle::PositionedRectangle() throw()
  71453. : x (0.0),
  71454. y (0.0),
  71455. w (0.0),
  71456. h (0.0),
  71457. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71458. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71459. wMode (absoluteSize),
  71460. hMode (absoluteSize)
  71461. {
  71462. }
  71463. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  71464. : x (other.x),
  71465. y (other.y),
  71466. w (other.w),
  71467. h (other.h),
  71468. xMode (other.xMode),
  71469. yMode (other.yMode),
  71470. wMode (other.wMode),
  71471. hMode (other.hMode)
  71472. {
  71473. }
  71474. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  71475. {
  71476. if (this != &other)
  71477. {
  71478. x = other.x;
  71479. y = other.y;
  71480. w = other.w;
  71481. h = other.h;
  71482. xMode = other.xMode;
  71483. yMode = other.yMode;
  71484. wMode = other.wMode;
  71485. hMode = other.hMode;
  71486. }
  71487. return *this;
  71488. }
  71489. PositionedRectangle::~PositionedRectangle() throw()
  71490. {
  71491. }
  71492. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  71493. {
  71494. return x == other.x
  71495. && y == other.y
  71496. && w == other.w
  71497. && h == other.h
  71498. && xMode == other.xMode
  71499. && yMode == other.yMode
  71500. && wMode == other.wMode
  71501. && hMode == other.hMode;
  71502. }
  71503. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  71504. {
  71505. return ! operator== (other);
  71506. }
  71507. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  71508. {
  71509. StringArray tokens;
  71510. tokens.addTokens (stringVersion, false);
  71511. decodePosString (tokens [0], xMode, x);
  71512. decodePosString (tokens [1], yMode, y);
  71513. decodeSizeString (tokens [2], wMode, w);
  71514. decodeSizeString (tokens [3], hMode, h);
  71515. }
  71516. const String PositionedRectangle::toString() const throw()
  71517. {
  71518. String s;
  71519. s.preallocateStorage (12);
  71520. addPosDescription (s, xMode, x);
  71521. s << T(' ');
  71522. addPosDescription (s, yMode, y);
  71523. s << T(' ');
  71524. addSizeDescription (s, wMode, w);
  71525. s << T(' ');
  71526. addSizeDescription (s, hMode, h);
  71527. return s;
  71528. }
  71529. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  71530. {
  71531. jassert (! target.isEmpty());
  71532. double x_, y_, w_, h_;
  71533. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71534. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71535. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  71536. roundDoubleToInt (w_), roundDoubleToInt (h_));
  71537. }
  71538. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  71539. double& x_, double& y_,
  71540. double& w_, double& h_) const throw()
  71541. {
  71542. jassert (! target.isEmpty());
  71543. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71544. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71545. }
  71546. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  71547. {
  71548. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  71549. }
  71550. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  71551. const Rectangle& target) throw()
  71552. {
  71553. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  71554. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  71555. }
  71556. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  71557. const double newW, const double newH,
  71558. const Rectangle& target) throw()
  71559. {
  71560. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  71561. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  71562. }
  71563. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  71564. {
  71565. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  71566. updateFrom (comp.getBounds(), Rectangle());
  71567. else
  71568. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  71569. }
  71570. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  71571. {
  71572. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71573. }
  71574. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  71575. {
  71576. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  71577. | absoluteFromParentBottomRight
  71578. | absoluteFromParentCentre
  71579. | proportionOfParentSize));
  71580. }
  71581. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  71582. {
  71583. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71584. }
  71585. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  71586. {
  71587. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  71588. | absoluteFromParentBottomRight
  71589. | absoluteFromParentCentre
  71590. | proportionOfParentSize));
  71591. }
  71592. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  71593. {
  71594. return (SizeMode) wMode;
  71595. }
  71596. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  71597. {
  71598. return (SizeMode) hMode;
  71599. }
  71600. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  71601. const PositionMode xMode_,
  71602. const AnchorPoint yAnchor,
  71603. const PositionMode yMode_,
  71604. const SizeMode widthMode,
  71605. const SizeMode heightMode,
  71606. const Rectangle& target) throw()
  71607. {
  71608. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  71609. {
  71610. double tx, tw;
  71611. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  71612. xMode = (uint8) (xAnchor | xMode_);
  71613. wMode = (uint8) widthMode;
  71614. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  71615. }
  71616. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  71617. {
  71618. double ty, th;
  71619. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  71620. yMode = (uint8) (yAnchor | yMode_);
  71621. hMode = (uint8) heightMode;
  71622. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  71623. }
  71624. }
  71625. bool PositionedRectangle::isPositionAbsolute() const throw()
  71626. {
  71627. return xMode == absoluteFromParentTopLeft
  71628. && yMode == absoluteFromParentTopLeft
  71629. && wMode == absoluteSize
  71630. && hMode == absoluteSize;
  71631. }
  71632. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  71633. {
  71634. if ((mode & proportionOfParentSize) != 0)
  71635. {
  71636. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71637. }
  71638. else
  71639. {
  71640. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71641. if ((mode & absoluteFromParentBottomRight) != 0)
  71642. s << T('R');
  71643. else if ((mode & absoluteFromParentCentre) != 0)
  71644. s << T('C');
  71645. }
  71646. if ((mode & anchorAtRightOrBottom) != 0)
  71647. s << T('r');
  71648. else if ((mode & anchorAtCentre) != 0)
  71649. s << T('c');
  71650. }
  71651. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  71652. {
  71653. if (mode == proportionalSize)
  71654. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71655. else if (mode == parentSizeMinusAbsolute)
  71656. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  71657. else
  71658. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71659. }
  71660. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  71661. {
  71662. if (s.containsChar (T('r')))
  71663. mode = anchorAtRightOrBottom;
  71664. else if (s.containsChar (T('c')))
  71665. mode = anchorAtCentre;
  71666. else
  71667. mode = anchorAtLeftOrTop;
  71668. if (s.containsChar (T('%')))
  71669. {
  71670. mode |= proportionOfParentSize;
  71671. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  71672. }
  71673. else
  71674. {
  71675. if (s.containsChar (T('R')))
  71676. mode |= absoluteFromParentBottomRight;
  71677. else if (s.containsChar (T('C')))
  71678. mode |= absoluteFromParentCentre;
  71679. else
  71680. mode |= absoluteFromParentTopLeft;
  71681. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  71682. }
  71683. }
  71684. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  71685. {
  71686. if (s.containsChar (T('%')))
  71687. {
  71688. mode = proportionalSize;
  71689. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  71690. }
  71691. else if (s.containsChar (T('M')))
  71692. {
  71693. mode = parentSizeMinusAbsolute;
  71694. value = s.getDoubleValue();
  71695. }
  71696. else
  71697. {
  71698. mode = absoluteSize;
  71699. value = s.getDoubleValue();
  71700. }
  71701. }
  71702. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  71703. const double x_, const double w_,
  71704. const uint8 xMode_, const uint8 wMode_,
  71705. const int parentPos,
  71706. const int parentSize) const throw()
  71707. {
  71708. if (wMode_ == proportionalSize)
  71709. wOut = roundDoubleToInt (w_ * parentSize);
  71710. else if (wMode_ == parentSizeMinusAbsolute)
  71711. wOut = jmax (0, parentSize - roundDoubleToInt (w_));
  71712. else
  71713. wOut = roundDoubleToInt (w_);
  71714. if ((xMode_ & proportionOfParentSize) != 0)
  71715. xOut = parentPos + x_ * parentSize;
  71716. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71717. xOut = (parentPos + parentSize) - x_;
  71718. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71719. xOut = x_ + (parentPos + parentSize / 2);
  71720. else
  71721. xOut = x_ + parentPos;
  71722. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71723. xOut -= wOut;
  71724. else if ((xMode_ & anchorAtCentre) != 0)
  71725. xOut -= wOut / 2;
  71726. }
  71727. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  71728. double x_, const double w_,
  71729. const uint8 xMode_, const uint8 wMode_,
  71730. const int parentPos,
  71731. const int parentSize) const throw()
  71732. {
  71733. if (wMode_ == proportionalSize)
  71734. {
  71735. if (parentSize > 0)
  71736. wOut = w_ / parentSize;
  71737. }
  71738. else if (wMode_ == parentSizeMinusAbsolute)
  71739. wOut = parentSize - w_;
  71740. else
  71741. wOut = w_;
  71742. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71743. x_ += w_;
  71744. else if ((xMode_ & anchorAtCentre) != 0)
  71745. x_ += w_ / 2;
  71746. if ((xMode_ & proportionOfParentSize) != 0)
  71747. {
  71748. if (parentSize > 0)
  71749. xOut = (x_ - parentPos) / parentSize;
  71750. }
  71751. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71752. xOut = (parentPos + parentSize) - x_;
  71753. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71754. xOut = x_ - (parentPos + parentSize / 2);
  71755. else
  71756. xOut = x_ - parentPos;
  71757. }
  71758. END_JUCE_NAMESPACE
  71759. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  71760. /********* Start of inlined file: juce_Rectangle.cpp *********/
  71761. BEGIN_JUCE_NAMESPACE
  71762. Rectangle::Rectangle() throw()
  71763. : x (0),
  71764. y (0),
  71765. w (0),
  71766. h (0)
  71767. {
  71768. }
  71769. Rectangle::Rectangle (const int x_, const int y_,
  71770. const int w_, const int h_) throw()
  71771. : x (x_),
  71772. y (y_),
  71773. w (w_),
  71774. h (h_)
  71775. {
  71776. }
  71777. Rectangle::Rectangle (const int w_, const int h_) throw()
  71778. : x (0),
  71779. y (0),
  71780. w (w_),
  71781. h (h_)
  71782. {
  71783. }
  71784. Rectangle::Rectangle (const Rectangle& other) throw()
  71785. : x (other.x),
  71786. y (other.y),
  71787. w (other.w),
  71788. h (other.h)
  71789. {
  71790. }
  71791. Rectangle::~Rectangle() throw()
  71792. {
  71793. }
  71794. bool Rectangle::isEmpty() const throw()
  71795. {
  71796. return w <= 0 || h <= 0;
  71797. }
  71798. void Rectangle::setBounds (const int x_,
  71799. const int y_,
  71800. const int w_,
  71801. const int h_) throw()
  71802. {
  71803. x = x_;
  71804. y = y_;
  71805. w = w_;
  71806. h = h_;
  71807. }
  71808. void Rectangle::setPosition (const int x_,
  71809. const int y_) throw()
  71810. {
  71811. x = x_;
  71812. y = y_;
  71813. }
  71814. void Rectangle::setSize (const int w_,
  71815. const int h_) throw()
  71816. {
  71817. w = w_;
  71818. h = h_;
  71819. }
  71820. void Rectangle::setLeft (const int newLeft) throw()
  71821. {
  71822. w = jmax (0, x + w - newLeft);
  71823. x = newLeft;
  71824. }
  71825. void Rectangle::setTop (const int newTop) throw()
  71826. {
  71827. h = jmax (0, y + h - newTop);
  71828. y = newTop;
  71829. }
  71830. void Rectangle::setRight (const int newRight) throw()
  71831. {
  71832. x = jmin (x, newRight);
  71833. w = newRight - x;
  71834. }
  71835. void Rectangle::setBottom (const int newBottom) throw()
  71836. {
  71837. y = jmin (y, newBottom);
  71838. h = newBottom - y;
  71839. }
  71840. void Rectangle::translate (const int dx,
  71841. const int dy) throw()
  71842. {
  71843. x += dx;
  71844. y += dy;
  71845. }
  71846. const Rectangle Rectangle::translated (const int dx,
  71847. const int dy) const throw()
  71848. {
  71849. return Rectangle (x + dx, y + dy, w, h);
  71850. }
  71851. void Rectangle::expand (const int deltaX,
  71852. const int deltaY) throw()
  71853. {
  71854. const int nw = jmax (0, w + deltaX + deltaX);
  71855. const int nh = jmax (0, h + deltaY + deltaY);
  71856. setBounds (x - deltaX,
  71857. y - deltaY,
  71858. nw, nh);
  71859. }
  71860. const Rectangle Rectangle::expanded (const int deltaX,
  71861. const int deltaY) const throw()
  71862. {
  71863. const int nw = jmax (0, w + deltaX + deltaX);
  71864. const int nh = jmax (0, h + deltaY + deltaY);
  71865. return Rectangle (x - deltaX,
  71866. y - deltaY,
  71867. nw, nh);
  71868. }
  71869. void Rectangle::reduce (const int deltaX,
  71870. const int deltaY) throw()
  71871. {
  71872. expand (-deltaX, -deltaY);
  71873. }
  71874. const Rectangle Rectangle::reduced (const int deltaX,
  71875. const int deltaY) const throw()
  71876. {
  71877. return expanded (-deltaX, -deltaY);
  71878. }
  71879. bool Rectangle::operator== (const Rectangle& other) const throw()
  71880. {
  71881. return x == other.x
  71882. && y == other.y
  71883. && w == other.w
  71884. && h == other.h;
  71885. }
  71886. bool Rectangle::operator!= (const Rectangle& other) const throw()
  71887. {
  71888. return x != other.x
  71889. || y != other.y
  71890. || w != other.w
  71891. || h != other.h;
  71892. }
  71893. bool Rectangle::contains (const int px,
  71894. const int py) const throw()
  71895. {
  71896. return px >= x
  71897. && py >= y
  71898. && px < x + w
  71899. && py < y + h;
  71900. }
  71901. bool Rectangle::contains (const Rectangle& other) const throw()
  71902. {
  71903. return x <= other.x
  71904. && y <= other.y
  71905. && x + w >= other.x + other.w
  71906. && y + h >= other.y + other.h;
  71907. }
  71908. bool Rectangle::intersects (const Rectangle& other) const throw()
  71909. {
  71910. return x + w > other.x
  71911. && y + h > other.y
  71912. && x < other.x + other.w
  71913. && y < other.y + other.h
  71914. && w > 0
  71915. && h > 0;
  71916. }
  71917. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  71918. {
  71919. const int nx = jmax (x, other.x);
  71920. const int ny = jmax (y, other.y);
  71921. const int nw = jmin (x + w, other.x + other.w) - nx;
  71922. const int nh = jmin (y + h, other.y + other.h) - ny;
  71923. if (nw >= 0 && nh >= 0)
  71924. return Rectangle (nx, ny, nw, nh);
  71925. else
  71926. return Rectangle();
  71927. }
  71928. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  71929. {
  71930. const int maxX = jmax (x1, x);
  71931. w1 = jmin (x1 + w1, x + w) - maxX;
  71932. if (w1 > 0)
  71933. {
  71934. const int maxY = jmax (y1, y);
  71935. h1 = jmin (y1 + h1, y + h) - maxY;
  71936. if (h1 > 0)
  71937. {
  71938. x1 = maxX;
  71939. y1 = maxY;
  71940. return true;
  71941. }
  71942. }
  71943. return false;
  71944. }
  71945. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  71946. int x2, int y2, int w2, int h2) throw()
  71947. {
  71948. const int x = jmax (x1, x2);
  71949. w1 = jmin (x1 + w1, x2 + w2) - x;
  71950. if (w1 > 0)
  71951. {
  71952. const int y = jmax (y1, y2);
  71953. h1 = jmin (y1 + h1, y2 + h2) - y;
  71954. if (h1 > 0)
  71955. {
  71956. x1 = x;
  71957. y1 = y;
  71958. return true;
  71959. }
  71960. }
  71961. return false;
  71962. }
  71963. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  71964. {
  71965. const int newX = jmin (x, other.x);
  71966. const int newY = jmin (y, other.y);
  71967. return Rectangle (newX, newY,
  71968. jmax (x + w, other.x + other.w) - newX,
  71969. jmax (y + h, other.y + other.h) - newY);
  71970. }
  71971. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  71972. {
  71973. if (x == other.x && getRight() == other.getRight()
  71974. && (other.getBottom() >= y && other.y <= getBottom()))
  71975. {
  71976. const int newY = jmin (y, other.y);
  71977. h = jmax (getBottom(), other.getBottom()) - newY;
  71978. y = newY;
  71979. return true;
  71980. }
  71981. else if (y == other.y && getBottom() == other.getBottom()
  71982. && (other.getRight() >= x && other.x <= getRight()))
  71983. {
  71984. const int newX = jmin (x, other.x);
  71985. w = jmax (getRight(), other.getRight()) - newX;
  71986. x = newX;
  71987. return true;
  71988. }
  71989. return false;
  71990. }
  71991. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  71992. {
  71993. int inside = 0;
  71994. const int otherR = other.getRight();
  71995. if (x >= other.x && x < otherR)
  71996. inside = 1;
  71997. const int otherB = other.getBottom();
  71998. if (y >= other.y && y < otherB)
  71999. inside |= 2;
  72000. const int r = x + w;
  72001. if (r >= other.x && r < otherR)
  72002. inside |= 4;
  72003. const int b = y + h;
  72004. if (b >= other.y && b < otherB)
  72005. inside |= 8;
  72006. switch (inside)
  72007. {
  72008. case 1 + 2 + 8:
  72009. w = r - otherR;
  72010. x = otherR;
  72011. return true;
  72012. case 1 + 2 + 4:
  72013. h = b - otherB;
  72014. y = otherB;
  72015. return true;
  72016. case 2 + 4 + 8:
  72017. w = other.x - x;
  72018. return true;
  72019. case 1 + 4 + 8:
  72020. h = other.y - y;
  72021. return true;
  72022. }
  72023. return false;
  72024. }
  72025. const String Rectangle::toString() const throw()
  72026. {
  72027. String s;
  72028. s.preallocateStorage (16);
  72029. s << x << T(' ')
  72030. << y << T(' ')
  72031. << w << T(' ')
  72032. << h;
  72033. return s;
  72034. }
  72035. const Rectangle Rectangle::fromString (const String& stringVersion)
  72036. {
  72037. StringArray toks;
  72038. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  72039. return Rectangle (toks[0].trim().getIntValue(),
  72040. toks[1].trim().getIntValue(),
  72041. toks[2].trim().getIntValue(),
  72042. toks[3].trim().getIntValue());
  72043. }
  72044. END_JUCE_NAMESPACE
  72045. /********* End of inlined file: juce_Rectangle.cpp *********/
  72046. /********* Start of inlined file: juce_RectangleList.cpp *********/
  72047. BEGIN_JUCE_NAMESPACE
  72048. RectangleList::RectangleList() throw()
  72049. {
  72050. }
  72051. RectangleList::RectangleList (const Rectangle& rect) throw()
  72052. {
  72053. if (! rect.isEmpty())
  72054. rects.add (rect);
  72055. }
  72056. RectangleList::RectangleList (const RectangleList& other) throw()
  72057. : rects (other.rects)
  72058. {
  72059. }
  72060. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  72061. {
  72062. if (this != &other)
  72063. rects = other.rects;
  72064. return *this;
  72065. }
  72066. RectangleList::~RectangleList() throw()
  72067. {
  72068. }
  72069. void RectangleList::clear() throw()
  72070. {
  72071. rects.clearQuick();
  72072. }
  72073. const Rectangle RectangleList::getRectangle (const int index) const throw()
  72074. {
  72075. if (((unsigned int) index) < (unsigned int) rects.size())
  72076. return rects.getReference (index);
  72077. return Rectangle();
  72078. }
  72079. bool RectangleList::isEmpty() const throw()
  72080. {
  72081. return rects.size() == 0;
  72082. }
  72083. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  72084. : current (0),
  72085. owner (list),
  72086. index (list.rects.size())
  72087. {
  72088. }
  72089. RectangleList::Iterator::~Iterator() throw()
  72090. {
  72091. }
  72092. bool RectangleList::Iterator::next() throw()
  72093. {
  72094. if (--index >= 0)
  72095. {
  72096. current = & (owner.rects.getReference (index));
  72097. return true;
  72098. }
  72099. return false;
  72100. }
  72101. void RectangleList::add (const Rectangle& rect) throw()
  72102. {
  72103. if (! rect.isEmpty())
  72104. {
  72105. if (rects.size() == 0)
  72106. {
  72107. rects.add (rect);
  72108. }
  72109. else
  72110. {
  72111. bool anyOverlaps = false;
  72112. int i;
  72113. for (i = rects.size(); --i >= 0;)
  72114. {
  72115. Rectangle& ourRect = rects.getReference (i);
  72116. if (rect.intersects (ourRect))
  72117. {
  72118. if (rect.contains (ourRect))
  72119. rects.remove (i);
  72120. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  72121. anyOverlaps = true;
  72122. }
  72123. }
  72124. if (anyOverlaps && rects.size() > 0)
  72125. {
  72126. RectangleList r (rect);
  72127. for (i = rects.size(); --i >= 0;)
  72128. {
  72129. const Rectangle& ourRect = rects.getReference (i);
  72130. if (rect.intersects (ourRect))
  72131. {
  72132. r.subtract (ourRect);
  72133. if (r.rects.size() == 0)
  72134. return;
  72135. }
  72136. }
  72137. for (i = r.getNumRectangles(); --i >= 0;)
  72138. rects.add (r.rects.getReference (i));
  72139. }
  72140. else
  72141. {
  72142. rects.add (rect);
  72143. }
  72144. }
  72145. }
  72146. }
  72147. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  72148. {
  72149. rects.add (rect);
  72150. }
  72151. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  72152. {
  72153. if (rects.size() == 0)
  72154. {
  72155. if (w > 0 && h > 0)
  72156. rects.add (Rectangle (x, y, w, h));
  72157. }
  72158. else
  72159. {
  72160. add (Rectangle (x, y, w, h));
  72161. }
  72162. }
  72163. void RectangleList::add (const RectangleList& other) throw()
  72164. {
  72165. for (int i = 0; i < other.rects.size(); ++i)
  72166. add (other.rects.getReference (i));
  72167. }
  72168. void RectangleList::subtract (const Rectangle& rect) throw()
  72169. {
  72170. const int originalNumRects = rects.size();
  72171. if (originalNumRects > 0)
  72172. {
  72173. const int x1 = rect.x;
  72174. const int y1 = rect.y;
  72175. const int x2 = x1 + rect.w;
  72176. const int y2 = y1 + rect.h;
  72177. for (int i = getNumRectangles(); --i >= 0;)
  72178. {
  72179. Rectangle& r = rects.getReference (i);
  72180. const int rx1 = r.x;
  72181. const int ry1 = r.y;
  72182. const int rx2 = rx1 + r.w;
  72183. const int ry2 = ry1 + r.h;
  72184. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  72185. {
  72186. if (x1 > rx1 && x1 < rx2)
  72187. {
  72188. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  72189. {
  72190. r.w = x1 - rx1;
  72191. }
  72192. else
  72193. {
  72194. r.x = x1;
  72195. r.w = rx2 - x1;
  72196. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  72197. i += 2;
  72198. }
  72199. }
  72200. else if (x2 > rx1 && x2 < rx2)
  72201. {
  72202. r.x = x2;
  72203. r.w = rx2 - x2;
  72204. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  72205. {
  72206. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  72207. i += 2;
  72208. }
  72209. }
  72210. else if (y1 > ry1 && y1 < ry2)
  72211. {
  72212. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  72213. {
  72214. r.h = y1 - ry1;
  72215. }
  72216. else
  72217. {
  72218. r.y = y1;
  72219. r.h = ry2 - y1;
  72220. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  72221. i += 2;
  72222. }
  72223. }
  72224. else if (y2 > ry1 && y2 < ry2)
  72225. {
  72226. r.y = y2;
  72227. r.h = ry2 - y2;
  72228. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  72229. {
  72230. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  72231. i += 2;
  72232. }
  72233. }
  72234. else
  72235. {
  72236. rects.remove (i);
  72237. }
  72238. }
  72239. }
  72240. if (rects.size() > originalNumRects + 10)
  72241. consolidate();
  72242. }
  72243. }
  72244. void RectangleList::subtract (const RectangleList& otherList) throw()
  72245. {
  72246. for (int i = otherList.rects.size(); --i >= 0;)
  72247. subtract (otherList.rects.getReference (i));
  72248. }
  72249. bool RectangleList::clipTo (const Rectangle& rect) throw()
  72250. {
  72251. bool notEmpty = false;
  72252. if (rect.isEmpty())
  72253. {
  72254. clear();
  72255. }
  72256. else
  72257. {
  72258. for (int i = rects.size(); --i >= 0;)
  72259. {
  72260. Rectangle& r = rects.getReference (i);
  72261. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72262. rects.remove (i);
  72263. else
  72264. notEmpty = true;
  72265. }
  72266. }
  72267. return notEmpty;
  72268. }
  72269. bool RectangleList::clipTo (const RectangleList& other) throw()
  72270. {
  72271. if (rects.size() == 0)
  72272. return false;
  72273. RectangleList result;
  72274. for (int j = 0; j < rects.size(); ++j)
  72275. {
  72276. const Rectangle& rect = rects.getReference (j);
  72277. for (int i = other.rects.size(); --i >= 0;)
  72278. {
  72279. Rectangle r (other.rects.getReference (i));
  72280. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72281. result.rects.add (r);
  72282. }
  72283. }
  72284. swapWith (result);
  72285. return ! isEmpty();
  72286. }
  72287. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  72288. {
  72289. destRegion.clear();
  72290. if (! rect.isEmpty())
  72291. {
  72292. for (int i = rects.size(); --i >= 0;)
  72293. {
  72294. Rectangle r (rects.getReference (i));
  72295. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72296. destRegion.rects.add (r);
  72297. }
  72298. }
  72299. return destRegion.rects.size() > 0;
  72300. }
  72301. void RectangleList::swapWith (RectangleList& otherList) throw()
  72302. {
  72303. rects.swapWithArray (otherList.rects);
  72304. }
  72305. void RectangleList::consolidate() throw()
  72306. {
  72307. int i;
  72308. for (i = 0; i < getNumRectangles() - 1; ++i)
  72309. {
  72310. Rectangle& r = rects.getReference (i);
  72311. const int rx1 = r.x;
  72312. const int ry1 = r.y;
  72313. const int rx2 = rx1 + r.w;
  72314. const int ry2 = ry1 + r.h;
  72315. for (int j = rects.size(); --j > i;)
  72316. {
  72317. Rectangle& r2 = rects.getReference (j);
  72318. const int jrx1 = r2.x;
  72319. const int jry1 = r2.y;
  72320. const int jrx2 = jrx1 + r2.w;
  72321. const int jry2 = jry1 + r2.h;
  72322. // if the vertical edges of any blocks are touching and their horizontals don't
  72323. // line up, split them horizontally..
  72324. if (jrx1 == rx2 || jrx2 == rx1)
  72325. {
  72326. if (jry1 > ry1 && jry1 < ry2)
  72327. {
  72328. r.h = jry1 - ry1;
  72329. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  72330. i = -1;
  72331. break;
  72332. }
  72333. if (jry2 > ry1 && jry2 < ry2)
  72334. {
  72335. r.h = jry2 - ry1;
  72336. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  72337. i = -1;
  72338. break;
  72339. }
  72340. else if (ry1 > jry1 && ry1 < jry2)
  72341. {
  72342. r2.h = ry1 - jry1;
  72343. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  72344. i = -1;
  72345. break;
  72346. }
  72347. else if (ry2 > jry1 && ry2 < jry2)
  72348. {
  72349. r2.h = ry2 - jry1;
  72350. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  72351. i = -1;
  72352. break;
  72353. }
  72354. }
  72355. }
  72356. }
  72357. for (i = 0; i < rects.size() - 1; ++i)
  72358. {
  72359. Rectangle& r = rects.getReference (i);
  72360. for (int j = rects.size(); --j > i;)
  72361. {
  72362. if (r.enlargeIfAdjacent (rects.getReference (j)))
  72363. {
  72364. rects.remove (j);
  72365. i = -1;
  72366. break;
  72367. }
  72368. }
  72369. }
  72370. }
  72371. bool RectangleList::containsPoint (const int x, const int y) const throw()
  72372. {
  72373. for (int i = getNumRectangles(); --i >= 0;)
  72374. if (rects.getReference (i).contains (x, y))
  72375. return true;
  72376. return false;
  72377. }
  72378. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  72379. {
  72380. if (rects.size() > 1)
  72381. {
  72382. RectangleList r (rectangleToCheck);
  72383. for (int i = rects.size(); --i >= 0;)
  72384. {
  72385. r.subtract (rects.getReference (i));
  72386. if (r.rects.size() == 0)
  72387. return true;
  72388. }
  72389. }
  72390. else if (rects.size() > 0)
  72391. {
  72392. return rects.getReference (0).contains (rectangleToCheck);
  72393. }
  72394. return false;
  72395. }
  72396. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  72397. {
  72398. for (int i = rects.size(); --i >= 0;)
  72399. if (rects.getReference (i).intersects (rectangleToCheck))
  72400. return true;
  72401. return false;
  72402. }
  72403. bool RectangleList::intersects (const RectangleList& other) const throw()
  72404. {
  72405. for (int i = rects.size(); --i >= 0;)
  72406. if (other.intersectsRectangle (rects.getReference (i)))
  72407. return true;
  72408. return false;
  72409. }
  72410. const Rectangle RectangleList::getBounds() const throw()
  72411. {
  72412. if (rects.size() <= 1)
  72413. {
  72414. if (rects.size() == 0)
  72415. return Rectangle();
  72416. else
  72417. return rects.getReference (0);
  72418. }
  72419. else
  72420. {
  72421. const Rectangle& r = rects.getReference (0);
  72422. int minX = r.x;
  72423. int minY = r.y;
  72424. int maxX = minX + r.w;
  72425. int maxY = minY + r.h;
  72426. for (int i = rects.size(); --i > 0;)
  72427. {
  72428. const Rectangle& r2 = rects.getReference (i);
  72429. minX = jmin (minX, r2.x);
  72430. minY = jmin (minY, r2.y);
  72431. maxX = jmax (maxX, r2.getRight());
  72432. maxY = jmax (maxY, r2.getBottom());
  72433. }
  72434. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  72435. }
  72436. }
  72437. void RectangleList::offsetAll (const int dx, const int dy) throw()
  72438. {
  72439. for (int i = rects.size(); --i >= 0;)
  72440. {
  72441. Rectangle& r = rects.getReference (i);
  72442. r.x += dx;
  72443. r.y += dy;
  72444. }
  72445. }
  72446. const Path RectangleList::toPath() const throw()
  72447. {
  72448. Path p;
  72449. for (int i = rects.size(); --i >= 0;)
  72450. {
  72451. const Rectangle& r = rects.getReference (i);
  72452. p.addRectangle ((float) r.x,
  72453. (float) r.y,
  72454. (float) r.w,
  72455. (float) r.h);
  72456. }
  72457. return p;
  72458. }
  72459. END_JUCE_NAMESPACE
  72460. /********* End of inlined file: juce_RectangleList.cpp *********/
  72461. /********* Start of inlined file: juce_Image.cpp *********/
  72462. BEGIN_JUCE_NAMESPACE
  72463. static const int fullAlphaThreshold = 253;
  72464. Image::Image (const PixelFormat format_,
  72465. const int imageWidth_,
  72466. const int imageHeight_)
  72467. : format (format_),
  72468. imageWidth (imageWidth_),
  72469. imageHeight (imageHeight_),
  72470. imageData (0)
  72471. {
  72472. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72473. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72474. // actual image will be at least 1x1.
  72475. }
  72476. Image::Image (const PixelFormat format_,
  72477. const int imageWidth_,
  72478. const int imageHeight_,
  72479. const bool clearImage)
  72480. : format (format_),
  72481. imageWidth (imageWidth_),
  72482. imageHeight (imageHeight_)
  72483. {
  72484. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72485. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72486. // actual image will be at least 1x1.
  72487. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72488. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  72489. const int dataSize = lineStride * jmax (1, imageHeight_);
  72490. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  72491. : juce_malloc (dataSize));
  72492. }
  72493. Image::Image (const Image& other)
  72494. : format (other.format),
  72495. imageWidth (other.imageWidth),
  72496. imageHeight (other.imageHeight)
  72497. {
  72498. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72499. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  72500. const int dataSize = lineStride * jmax (1, imageHeight);
  72501. imageData = (uint8*) juce_malloc (dataSize);
  72502. int ls, ps;
  72503. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72504. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  72505. other.releasePixelDataReadOnly (srcData);
  72506. }
  72507. Image::~Image()
  72508. {
  72509. juce_free (imageData);
  72510. }
  72511. LowLevelGraphicsContext* Image::createLowLevelContext()
  72512. {
  72513. return new LowLevelGraphicsSoftwareRenderer (*this);
  72514. }
  72515. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  72516. {
  72517. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72518. w = w;
  72519. h = h;
  72520. ls = lineStride;
  72521. ps = pixelStride;
  72522. return imageData + x * pixelStride + y * lineStride;
  72523. }
  72524. void Image::releasePixelDataReadWrite (void*)
  72525. {
  72526. }
  72527. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  72528. {
  72529. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72530. w = w;
  72531. h = h;
  72532. ls = lineStride;
  72533. ps = pixelStride;
  72534. return imageData + x * pixelStride + y * lineStride;
  72535. }
  72536. void Image::releasePixelDataReadOnly (const void*) const
  72537. {
  72538. }
  72539. void Image::setPixelData (int x, int y, int w, int h,
  72540. const uint8* sourcePixelData, int sourceLineStride)
  72541. {
  72542. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72543. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  72544. {
  72545. int ls, ps;
  72546. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  72547. for (int i = 0; i < h; ++i)
  72548. {
  72549. memcpy (dest + ls * i,
  72550. sourcePixelData + sourceLineStride * i,
  72551. w * pixelStride);
  72552. }
  72553. releasePixelDataReadWrite (dest);
  72554. }
  72555. }
  72556. void Image::clear (int dx, int dy, int dw, int dh,
  72557. const Colour& colourToClearTo)
  72558. {
  72559. const PixelARGB col (colourToClearTo.getPixelARGB());
  72560. int ls, ps;
  72561. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  72562. uint8* dest = dstData;
  72563. while (--dh >= 0)
  72564. {
  72565. uint8* line = dest;
  72566. dest += ls;
  72567. if (isARGB())
  72568. {
  72569. for (int x = dw; --x >= 0;)
  72570. {
  72571. ((PixelARGB*) line)->set (col);
  72572. line += ps;
  72573. }
  72574. }
  72575. else if (isRGB())
  72576. {
  72577. for (int x = dw; --x >= 0;)
  72578. {
  72579. ((PixelRGB*) line)->set (col);
  72580. line += ps;
  72581. }
  72582. }
  72583. else
  72584. {
  72585. for (int x = dw; --x >= 0;)
  72586. {
  72587. *line = col.getAlpha();
  72588. line += ps;
  72589. }
  72590. }
  72591. }
  72592. releasePixelDataReadWrite (dstData);
  72593. }
  72594. Image* Image::createCopy (int newWidth, int newHeight,
  72595. const Graphics::ResamplingQuality quality) const
  72596. {
  72597. if (newWidth < 0)
  72598. newWidth = imageWidth;
  72599. if (newHeight < 0)
  72600. newHeight = imageHeight;
  72601. Image* const newImage = new Image (format, newWidth, newHeight, true);
  72602. Graphics g (*newImage);
  72603. g.setImageResamplingQuality (quality);
  72604. g.drawImage (this,
  72605. 0, 0, newWidth, newHeight,
  72606. 0, 0, imageWidth, imageHeight,
  72607. false);
  72608. return newImage;
  72609. }
  72610. const Colour Image::getPixelAt (const int x, const int y) const
  72611. {
  72612. Colour c;
  72613. if (((unsigned int) x) < (unsigned int) imageWidth
  72614. && ((unsigned int) y) < (unsigned int) imageHeight)
  72615. {
  72616. int ls, ps;
  72617. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  72618. if (isARGB())
  72619. {
  72620. PixelARGB p (*(const PixelARGB*) pixels);
  72621. p.unpremultiply();
  72622. c = Colour (p.getARGB());
  72623. }
  72624. else if (isRGB())
  72625. c = Colour (((const PixelRGB*) pixels)->getARGB());
  72626. else
  72627. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  72628. releasePixelDataReadOnly (pixels);
  72629. }
  72630. return c;
  72631. }
  72632. void Image::setPixelAt (const int x, const int y,
  72633. const Colour& colour)
  72634. {
  72635. if (((unsigned int) x) < (unsigned int) imageWidth
  72636. && ((unsigned int) y) < (unsigned int) imageHeight)
  72637. {
  72638. int ls, ps;
  72639. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72640. const PixelARGB col (colour.getPixelARGB());
  72641. if (isARGB())
  72642. ((PixelARGB*) pixels)->set (col);
  72643. else if (isRGB())
  72644. ((PixelRGB*) pixels)->set (col);
  72645. else
  72646. *pixels = col.getAlpha();
  72647. releasePixelDataReadWrite (pixels);
  72648. }
  72649. }
  72650. void Image::multiplyAlphaAt (const int x, const int y,
  72651. const float multiplier)
  72652. {
  72653. if (((unsigned int) x) < (unsigned int) imageWidth
  72654. && ((unsigned int) y) < (unsigned int) imageHeight
  72655. && hasAlphaChannel())
  72656. {
  72657. int ls, ps;
  72658. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72659. if (isARGB())
  72660. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  72661. else
  72662. *pixels = (uint8) (*pixels * multiplier);
  72663. releasePixelDataReadWrite (pixels);
  72664. }
  72665. }
  72666. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  72667. {
  72668. if (hasAlphaChannel())
  72669. {
  72670. int ls, ps;
  72671. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72672. if (isARGB())
  72673. {
  72674. for (int y = 0; y < imageHeight; ++y)
  72675. {
  72676. uint8* p = pixels + y * ls;
  72677. for (int x = 0; x < imageWidth; ++x)
  72678. {
  72679. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  72680. p += ps;
  72681. }
  72682. }
  72683. }
  72684. else
  72685. {
  72686. for (int y = 0; y < imageHeight; ++y)
  72687. {
  72688. uint8* p = pixels + y * ls;
  72689. for (int x = 0; x < imageWidth; ++x)
  72690. {
  72691. *p = (uint8) (*p * amountToMultiplyBy);
  72692. p += ps;
  72693. }
  72694. }
  72695. }
  72696. releasePixelDataReadWrite (pixels);
  72697. }
  72698. else
  72699. {
  72700. jassertfalse // can't do this without an alpha-channel!
  72701. }
  72702. }
  72703. void Image::desaturate()
  72704. {
  72705. if (isARGB() || isRGB())
  72706. {
  72707. int ls, ps;
  72708. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72709. if (isARGB())
  72710. {
  72711. for (int y = 0; y < imageHeight; ++y)
  72712. {
  72713. uint8* p = pixels + y * ls;
  72714. for (int x = 0; x < imageWidth; ++x)
  72715. {
  72716. ((PixelARGB*) p)->desaturate();
  72717. p += ps;
  72718. }
  72719. }
  72720. }
  72721. else
  72722. {
  72723. for (int y = 0; y < imageHeight; ++y)
  72724. {
  72725. uint8* p = pixels + y * ls;
  72726. for (int x = 0; x < imageWidth; ++x)
  72727. {
  72728. ((PixelRGB*) p)->desaturate();
  72729. p += ps;
  72730. }
  72731. }
  72732. }
  72733. releasePixelDataReadWrite (pixels);
  72734. }
  72735. }
  72736. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  72737. {
  72738. if (hasAlphaChannel())
  72739. {
  72740. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  72741. SparseSet <int> pixelsOnRow;
  72742. int ls, ps;
  72743. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72744. for (int y = 0; y < imageHeight; ++y)
  72745. {
  72746. pixelsOnRow.clear();
  72747. const uint8* lineData = pixels + ls * y;
  72748. if (isARGB())
  72749. {
  72750. for (int x = 0; x < imageWidth; ++x)
  72751. {
  72752. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  72753. pixelsOnRow.addRange (x, 1);
  72754. lineData += ps;
  72755. }
  72756. }
  72757. else
  72758. {
  72759. for (int x = 0; x < imageWidth; ++x)
  72760. {
  72761. if (*lineData >= threshold)
  72762. pixelsOnRow.addRange (x, 1);
  72763. lineData += ps;
  72764. }
  72765. }
  72766. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  72767. {
  72768. int x, w;
  72769. if (pixelsOnRow.getRange (i, x, w))
  72770. result.add (Rectangle (x, y, w, 1));
  72771. }
  72772. result.consolidate();
  72773. }
  72774. releasePixelDataReadOnly (pixels);
  72775. }
  72776. else
  72777. {
  72778. result.add (0, 0, imageWidth, imageHeight);
  72779. }
  72780. }
  72781. void Image::moveImageSection (int dx, int dy,
  72782. int sx, int sy,
  72783. int w, int h)
  72784. {
  72785. if (dx < 0)
  72786. {
  72787. w += dx;
  72788. sx -= dx;
  72789. dx = 0;
  72790. }
  72791. if (dy < 0)
  72792. {
  72793. h += dy;
  72794. sy -= dy;
  72795. dy = 0;
  72796. }
  72797. if (sx < 0)
  72798. {
  72799. w += sx;
  72800. dx -= sx;
  72801. sx = 0;
  72802. }
  72803. if (sy < 0)
  72804. {
  72805. h += sy;
  72806. dy -= sy;
  72807. sy = 0;
  72808. }
  72809. const int minX = jmin (dx, sx);
  72810. const int minY = jmin (dy, sy);
  72811. w = jmin (w, getWidth() - jmax (sx, dx));
  72812. h = jmin (h, getHeight() - jmax (sy, dy));
  72813. if (w > 0 && h > 0)
  72814. {
  72815. const int maxX = jmax (dx, sx) + w;
  72816. const int maxY = jmax (dy, sy) + h;
  72817. int ls, ps;
  72818. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  72819. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  72820. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  72821. const int lineSize = ps * w;
  72822. if (dy > sy)
  72823. {
  72824. while (--h >= 0)
  72825. {
  72826. const int offset = h * ls;
  72827. memmove (dst + offset, src + offset, lineSize);
  72828. }
  72829. }
  72830. else if (dst != src)
  72831. {
  72832. while (--h >= 0)
  72833. {
  72834. memmove (dst, src, lineSize);
  72835. dst += ls;
  72836. src += ls;
  72837. }
  72838. }
  72839. releasePixelDataReadWrite (pixels);
  72840. }
  72841. }
  72842. END_JUCE_NAMESPACE
  72843. /********* End of inlined file: juce_Image.cpp *********/
  72844. /********* Start of inlined file: juce_ImageCache.cpp *********/
  72845. BEGIN_JUCE_NAMESPACE
  72846. struct CachedImageInfo
  72847. {
  72848. Image* image;
  72849. int64 hashCode;
  72850. int refCount;
  72851. unsigned int releaseTime;
  72852. juce_UseDebuggingNewOperator
  72853. };
  72854. static ImageCache* instance = 0;
  72855. static int cacheTimeout = 5000;
  72856. ImageCache::ImageCache() throw()
  72857. : images (4)
  72858. {
  72859. }
  72860. ImageCache::~ImageCache()
  72861. {
  72862. const ScopedLock sl (lock);
  72863. for (int i = images.size(); --i >= 0;)
  72864. {
  72865. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  72866. delete ci->image;
  72867. delete ci;
  72868. }
  72869. images.clear();
  72870. jassert (instance == this);
  72871. instance = 0;
  72872. }
  72873. Image* ImageCache::getFromHashCode (const int64 hashCode)
  72874. {
  72875. if (instance != 0)
  72876. {
  72877. const ScopedLock sl (instance->lock);
  72878. for (int i = instance->images.size(); --i >= 0;)
  72879. {
  72880. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72881. if (ci->hashCode == hashCode)
  72882. {
  72883. atomicIncrement (ci->refCount);
  72884. return ci->image;
  72885. }
  72886. }
  72887. }
  72888. return 0;
  72889. }
  72890. void ImageCache::addImageToCache (Image* const image,
  72891. const int64 hashCode)
  72892. {
  72893. if (image != 0)
  72894. {
  72895. if (instance == 0)
  72896. instance = new ImageCache();
  72897. CachedImageInfo* const newC = new CachedImageInfo();
  72898. newC->hashCode = hashCode;
  72899. newC->image = image;
  72900. newC->refCount = 1;
  72901. newC->releaseTime = 0;
  72902. const ScopedLock sl (instance->lock);
  72903. instance->images.add (newC);
  72904. }
  72905. }
  72906. void ImageCache::release (Image* const imageToRelease)
  72907. {
  72908. if (imageToRelease != 0 && instance != 0)
  72909. {
  72910. const ScopedLock sl (instance->lock);
  72911. for (int i = instance->images.size(); --i >= 0;)
  72912. {
  72913. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72914. if (ci->image == imageToRelease)
  72915. {
  72916. if (--(ci->refCount) == 0)
  72917. ci->releaseTime = Time::getApproximateMillisecondCounter();
  72918. if (! instance->isTimerRunning())
  72919. instance->startTimer (999);
  72920. break;
  72921. }
  72922. }
  72923. }
  72924. }
  72925. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  72926. {
  72927. if (instance != 0)
  72928. {
  72929. const ScopedLock sl (instance->lock);
  72930. for (int i = instance->images.size(); --i >= 0;)
  72931. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  72932. return true;
  72933. }
  72934. return false;
  72935. }
  72936. void ImageCache::incReferenceCount (Image* const image)
  72937. {
  72938. if (instance != 0)
  72939. {
  72940. const ScopedLock sl (instance->lock);
  72941. for (int i = instance->images.size(); --i >= 0;)
  72942. {
  72943. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72944. if (ci->image == image)
  72945. {
  72946. ci->refCount++;
  72947. return;
  72948. }
  72949. }
  72950. }
  72951. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  72952. }
  72953. void ImageCache::timerCallback()
  72954. {
  72955. int numberStillNeedingReleasing = 0;
  72956. const unsigned int now = Time::getApproximateMillisecondCounter();
  72957. const ScopedLock sl (lock);
  72958. for (int i = images.size(); --i >= 0;)
  72959. {
  72960. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  72961. if (ci->refCount <= 0)
  72962. {
  72963. if (now > ci->releaseTime + cacheTimeout
  72964. || now < ci->releaseTime - 1000)
  72965. {
  72966. images.remove (i);
  72967. delete ci->image;
  72968. delete ci;
  72969. }
  72970. else
  72971. {
  72972. ++numberStillNeedingReleasing;
  72973. }
  72974. }
  72975. }
  72976. if (numberStillNeedingReleasing == 0)
  72977. stopTimer();
  72978. }
  72979. Image* ImageCache::getFromFile (const File& file)
  72980. {
  72981. const int64 hashCode = file.getFullPathName().hashCode64();
  72982. Image* image = getFromHashCode (hashCode);
  72983. if (image == 0)
  72984. {
  72985. image = ImageFileFormat::loadFrom (file);
  72986. addImageToCache (image, hashCode);
  72987. }
  72988. return image;
  72989. }
  72990. Image* ImageCache::getFromMemory (const void* imageData,
  72991. const int dataSize)
  72992. {
  72993. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  72994. Image* image = getFromHashCode (hashCode);
  72995. if (image == 0)
  72996. {
  72997. image = ImageFileFormat::loadFrom (imageData, dataSize);
  72998. addImageToCache (image, hashCode);
  72999. }
  73000. return image;
  73001. }
  73002. void ImageCache::setCacheTimeout (const int millisecs)
  73003. {
  73004. cacheTimeout = millisecs;
  73005. }
  73006. END_JUCE_NAMESPACE
  73007. /********* End of inlined file: juce_ImageCache.cpp *********/
  73008. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  73009. BEGIN_JUCE_NAMESPACE
  73010. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  73011. : size (size_)
  73012. {
  73013. values = new float* [size];
  73014. for (int i = size; --i >= 0;)
  73015. values[i] = new float [size];
  73016. clear();
  73017. }
  73018. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  73019. {
  73020. for (int i = size; --i >= 0;)
  73021. delete[] values[i];
  73022. delete[] values;
  73023. }
  73024. void ImageConvolutionKernel::setKernelValue (const int x,
  73025. const int y,
  73026. const float value) throw()
  73027. {
  73028. if (((unsigned int) x) < (unsigned int) size
  73029. && ((unsigned int) y) < (unsigned int) size)
  73030. {
  73031. values[x][y] = value;
  73032. }
  73033. else
  73034. {
  73035. jassertfalse
  73036. }
  73037. }
  73038. void ImageConvolutionKernel::clear() throw()
  73039. {
  73040. for (int y = size; --y >= 0;)
  73041. for (int x = size; --x >= 0;)
  73042. values[x][y] = 0;
  73043. }
  73044. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  73045. {
  73046. double currentTotal = 0.0;
  73047. for (int y = size; --y >= 0;)
  73048. for (int x = size; --x >= 0;)
  73049. currentTotal += values[x][y];
  73050. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  73051. }
  73052. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  73053. {
  73054. for (int y = size; --y >= 0;)
  73055. for (int x = size; --x >= 0;)
  73056. values[x][y] *= multiplier;
  73057. }
  73058. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  73059. {
  73060. const double radiusFactor = -1.0 / (radius * radius * 2);
  73061. const int centre = size >> 1;
  73062. for (int y = size; --y >= 0;)
  73063. {
  73064. for (int x = size; --x >= 0;)
  73065. {
  73066. const int cx = x - centre;
  73067. const int cy = y - centre;
  73068. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  73069. }
  73070. }
  73071. setOverallSum (1.0f);
  73072. }
  73073. void ImageConvolutionKernel::applyToImage (Image& destImage,
  73074. const Image* sourceImage,
  73075. int dx,
  73076. int dy,
  73077. int dw,
  73078. int dh) const
  73079. {
  73080. Image* imageCreated = 0;
  73081. if (sourceImage == 0)
  73082. {
  73083. sourceImage = imageCreated = destImage.createCopy();
  73084. }
  73085. else
  73086. {
  73087. jassert (sourceImage->getWidth() == destImage.getWidth()
  73088. && sourceImage->getHeight() == destImage.getHeight()
  73089. && sourceImage->getFormat() == destImage.getFormat());
  73090. if (sourceImage->getWidth() != destImage.getWidth()
  73091. || sourceImage->getHeight() != destImage.getHeight()
  73092. || sourceImage->getFormat() != destImage.getFormat())
  73093. return;
  73094. }
  73095. const int imageWidth = destImage.getWidth();
  73096. const int imageHeight = destImage.getHeight();
  73097. if (dx >= imageWidth || dy >= imageHeight)
  73098. return;
  73099. if (dx + dw > imageWidth)
  73100. dw = imageWidth - dx;
  73101. if (dy + dh > imageHeight)
  73102. dh = imageHeight - dy;
  73103. const int dx2 = dx + dw;
  73104. const int dy2 = dy + dh;
  73105. int lineStride, pixelStride;
  73106. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  73107. uint8* line = pixels;
  73108. int srcLineStride, srcPixelStride;
  73109. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  73110. if (pixelStride == 4)
  73111. {
  73112. for (int y = dy; y < dy2; ++y)
  73113. {
  73114. uint8* dest = line;
  73115. line += lineStride;
  73116. for (int x = dx; x < dx2; ++x)
  73117. {
  73118. float c1 = 0;
  73119. float c2 = 0;
  73120. float c3 = 0;
  73121. float c4 = 0;
  73122. for (int yy = 0; yy < size; ++yy)
  73123. {
  73124. const int sy = y + yy - (size >> 1);
  73125. if (sy >= imageHeight)
  73126. break;
  73127. if (sy >= 0)
  73128. {
  73129. int sx = x - (size >> 1);
  73130. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73131. for (int xx = 0; xx < size; ++xx)
  73132. {
  73133. if (sx >= imageWidth)
  73134. break;
  73135. if (sx >= 0)
  73136. {
  73137. const float kernelMult = values[xx][yy];
  73138. c1 += kernelMult * *src++;
  73139. c2 += kernelMult * *src++;
  73140. c3 += kernelMult * *src++;
  73141. c4 += kernelMult * *src++;
  73142. }
  73143. else
  73144. {
  73145. src += 4;
  73146. }
  73147. ++sx;
  73148. }
  73149. }
  73150. }
  73151. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  73152. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  73153. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  73154. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  73155. }
  73156. }
  73157. }
  73158. else if (pixelStride == 3)
  73159. {
  73160. for (int y = dy; y < dy2; ++y)
  73161. {
  73162. uint8* dest = line;
  73163. line += lineStride;
  73164. for (int x = dx; x < dx2; ++x)
  73165. {
  73166. float c1 = 0;
  73167. float c2 = 0;
  73168. float c3 = 0;
  73169. for (int yy = 0; yy < size; ++yy)
  73170. {
  73171. const int sy = y + yy - (size >> 1);
  73172. if (sy >= imageHeight)
  73173. break;
  73174. if (sy >= 0)
  73175. {
  73176. int sx = x - (size >> 1);
  73177. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73178. for (int xx = 0; xx < size; ++xx)
  73179. {
  73180. if (sx >= imageWidth)
  73181. break;
  73182. if (sx >= 0)
  73183. {
  73184. const float kernelMult = values[xx][yy];
  73185. c1 += kernelMult * *src++;
  73186. c2 += kernelMult * *src++;
  73187. c3 += kernelMult * *src++;
  73188. }
  73189. else
  73190. {
  73191. src += 3;
  73192. }
  73193. ++sx;
  73194. }
  73195. }
  73196. }
  73197. *dest++ = (uint8) roundFloatToInt (c1);
  73198. *dest++ = (uint8) roundFloatToInt (c2);
  73199. *dest++ = (uint8) roundFloatToInt (c3);
  73200. }
  73201. }
  73202. }
  73203. sourceImage->releasePixelDataReadOnly (srcPixels);
  73204. destImage.releasePixelDataReadWrite (pixels);
  73205. if (imageCreated != 0)
  73206. delete imageCreated;
  73207. }
  73208. END_JUCE_NAMESPACE
  73209. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  73210. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  73211. BEGIN_JUCE_NAMESPACE
  73212. /********* Start of inlined file: juce_GIFLoader.h *********/
  73213. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  73214. #define __JUCE_GIFLOADER_JUCEHEADER__
  73215. #ifndef DOXYGEN
  73216. static const int maxGifCode = 1 << 12;
  73217. /**
  73218. Used internally by ImageFileFormat - don't use this class directly in your
  73219. application.
  73220. @see ImageFileFormat
  73221. */
  73222. class GIFLoader
  73223. {
  73224. public:
  73225. GIFLoader (InputStream& in);
  73226. ~GIFLoader() throw();
  73227. Image* getImage() const throw() { return image; }
  73228. private:
  73229. Image* image;
  73230. InputStream& input;
  73231. uint8 buffer [300];
  73232. uint8 palette [256][4];
  73233. bool dataBlockIsZero, fresh, finished;
  73234. int currentBit, lastBit, lastByteIndex;
  73235. int codeSize, setCodeSize;
  73236. int maxCode, maxCodeSize;
  73237. int firstcode, oldcode;
  73238. int clearCode, end_code;
  73239. int table [2] [maxGifCode];
  73240. int stack [2 * maxGifCode];
  73241. int *sp;
  73242. bool getSizeFromHeader (int& width, int& height);
  73243. bool readPalette (const int numCols);
  73244. int readDataBlock (unsigned char* dest);
  73245. int processExtension (int type, int& transparent);
  73246. int readLZWByte (bool initialise, int input_code_size);
  73247. int getCode (int code_size, bool initialise);
  73248. bool readImage (int width, int height,
  73249. int interlace, int transparent);
  73250. GIFLoader (const GIFLoader&);
  73251. const GIFLoader& operator= (const GIFLoader&);
  73252. };
  73253. #endif // DOXYGEN
  73254. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  73255. /********* End of inlined file: juce_GIFLoader.h *********/
  73256. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  73257. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  73258. PNGImageFormat::PNGImageFormat() throw() {}
  73259. PNGImageFormat::~PNGImageFormat() throw() {}
  73260. const String PNGImageFormat::getFormatName()
  73261. {
  73262. return T("PNG");
  73263. }
  73264. bool PNGImageFormat::canUnderstand (InputStream& in)
  73265. {
  73266. const int bytesNeeded = 4;
  73267. char header [bytesNeeded];
  73268. return in.read (header, bytesNeeded) == bytesNeeded
  73269. && header[1] == 'P'
  73270. && header[2] == 'N'
  73271. && header[3] == 'G';
  73272. }
  73273. Image* PNGImageFormat::decodeImage (InputStream& in)
  73274. {
  73275. return juce_loadPNGImageFromStream (in);
  73276. }
  73277. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  73278. OutputStream& destStream)
  73279. {
  73280. return juce_writePNGImageToStream (sourceImage, destStream);
  73281. }
  73282. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  73283. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  73284. JPEGImageFormat::JPEGImageFormat() throw()
  73285. : quality (-1.0f)
  73286. {
  73287. }
  73288. JPEGImageFormat::~JPEGImageFormat() throw() {}
  73289. void JPEGImageFormat::setQuality (const float newQuality)
  73290. {
  73291. quality = newQuality;
  73292. }
  73293. const String JPEGImageFormat::getFormatName()
  73294. {
  73295. return T("JPEG");
  73296. }
  73297. bool JPEGImageFormat::canUnderstand (InputStream& in)
  73298. {
  73299. const int bytesNeeded = 10;
  73300. uint8 header [bytesNeeded];
  73301. if (in.read (header, bytesNeeded) == bytesNeeded)
  73302. {
  73303. return header[0] == 0xff
  73304. && header[1] == 0xd8
  73305. && header[2] == 0xff
  73306. && (header[3] == 0xe0 || header[3] == 0xe1);
  73307. }
  73308. return false;
  73309. }
  73310. Image* JPEGImageFormat::decodeImage (InputStream& in)
  73311. {
  73312. return juce_loadJPEGImageFromStream (in);
  73313. }
  73314. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  73315. OutputStream& destStream)
  73316. {
  73317. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  73318. }
  73319. class GIFImageFormat : public ImageFileFormat
  73320. {
  73321. public:
  73322. GIFImageFormat() throw() {}
  73323. ~GIFImageFormat() throw() {}
  73324. const String getFormatName()
  73325. {
  73326. return T("GIF");
  73327. }
  73328. bool canUnderstand (InputStream& in)
  73329. {
  73330. const int bytesNeeded = 4;
  73331. char header [bytesNeeded];
  73332. return (in.read (header, bytesNeeded) == bytesNeeded)
  73333. && header[0] == 'G'
  73334. && header[1] == 'I'
  73335. && header[2] == 'F';
  73336. }
  73337. Image* decodeImage (InputStream& in)
  73338. {
  73339. GIFLoader* const loader = new GIFLoader (in);
  73340. Image* const im = loader->getImage();
  73341. delete loader;
  73342. return im;
  73343. }
  73344. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  73345. {
  73346. return false;
  73347. }
  73348. };
  73349. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  73350. {
  73351. static PNGImageFormat png;
  73352. static JPEGImageFormat jpg;
  73353. static GIFImageFormat gif;
  73354. ImageFileFormat* formats[4];
  73355. int numFormats = 0;
  73356. formats [numFormats++] = &png;
  73357. formats [numFormats++] = &jpg;
  73358. formats [numFormats++] = &gif;
  73359. const int64 streamPos = input.getPosition();
  73360. for (int i = 0; i < numFormats; ++i)
  73361. {
  73362. const bool found = formats[i]->canUnderstand (input);
  73363. input.setPosition (streamPos);
  73364. if (found)
  73365. return formats[i];
  73366. }
  73367. return 0;
  73368. }
  73369. Image* ImageFileFormat::loadFrom (InputStream& input)
  73370. {
  73371. ImageFileFormat* const format = findImageFormatForStream (input);
  73372. if (format != 0)
  73373. return format->decodeImage (input);
  73374. return 0;
  73375. }
  73376. Image* ImageFileFormat::loadFrom (const File& file)
  73377. {
  73378. InputStream* const in = file.createInputStream();
  73379. if (in != 0)
  73380. {
  73381. BufferedInputStream b (in, 8192, true);
  73382. return loadFrom (b);
  73383. }
  73384. return 0;
  73385. }
  73386. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  73387. {
  73388. if (rawData != 0 && numBytes > 4)
  73389. {
  73390. MemoryInputStream stream (rawData, numBytes, false);
  73391. return loadFrom (stream);
  73392. }
  73393. return 0;
  73394. }
  73395. END_JUCE_NAMESPACE
  73396. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  73397. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  73398. BEGIN_JUCE_NAMESPACE
  73399. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  73400. {
  73401. return (b << 8) | a;
  73402. }
  73403. GIFLoader::GIFLoader (InputStream& in)
  73404. : image (0),
  73405. input (in),
  73406. dataBlockIsZero (false),
  73407. fresh (false),
  73408. finished (false)
  73409. {
  73410. currentBit = lastBit = lastByteIndex = 0;
  73411. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  73412. firstcode = oldcode = 0;
  73413. clearCode = end_code = 0;
  73414. int imageWidth, imageHeight;
  73415. int transparent = -1;
  73416. if (! getSizeFromHeader (imageWidth, imageHeight))
  73417. return;
  73418. if ((imageWidth <= 0) || (imageHeight <= 0))
  73419. return;
  73420. unsigned char buf [16];
  73421. if (in.read (buf, 3) != 3)
  73422. return;
  73423. int numColours = 2 << (buf[0] & 7);
  73424. if ((buf[0] & 0x80) != 0)
  73425. readPalette (numColours);
  73426. for (;;)
  73427. {
  73428. if (input.read (buf, 1) != 1)
  73429. break;
  73430. if (buf[0] == ';')
  73431. break;
  73432. if (buf[0] == '!')
  73433. {
  73434. if (input.read (buf, 1) != 1)
  73435. break;
  73436. if (processExtension (buf[0], transparent) < 0)
  73437. break;
  73438. continue;
  73439. }
  73440. if (buf[0] != ',')
  73441. continue;
  73442. if (input.read (buf, 9) != 9)
  73443. break;
  73444. imageWidth = makeWord (buf[4], buf[5]);
  73445. imageHeight = makeWord (buf[6], buf[7]);
  73446. numColours = 2 << (buf[8] & 7);
  73447. if ((buf[8] & 0x80) != 0)
  73448. if (! readPalette (numColours))
  73449. break;
  73450. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  73451. imageWidth, imageHeight, (transparent >= 0));
  73452. readImage (imageWidth, imageHeight,
  73453. (buf[8] & 0x40) != 0,
  73454. transparent);
  73455. break;
  73456. }
  73457. }
  73458. GIFLoader::~GIFLoader() throw()
  73459. {
  73460. }
  73461. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  73462. {
  73463. unsigned char b [8];
  73464. if (input.read (b, 6) == 6)
  73465. {
  73466. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  73467. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  73468. {
  73469. if (input.read (b, 4) == 4)
  73470. {
  73471. w = makeWord (b[0], b[1]);
  73472. h = makeWord (b[2], b[3]);
  73473. return true;
  73474. }
  73475. }
  73476. }
  73477. return false;
  73478. }
  73479. bool GIFLoader::readPalette (const int numCols)
  73480. {
  73481. unsigned char rgb[4];
  73482. for (int i = 0; i < numCols; ++i)
  73483. {
  73484. input.read (rgb, 3);
  73485. palette [i][0] = rgb[0];
  73486. palette [i][1] = rgb[1];
  73487. palette [i][2] = rgb[2];
  73488. palette [i][3] = 0xff;
  73489. }
  73490. return true;
  73491. }
  73492. int GIFLoader::readDataBlock (unsigned char* const dest)
  73493. {
  73494. unsigned char n;
  73495. if (input.read (&n, 1) == 1)
  73496. {
  73497. dataBlockIsZero = (n == 0);
  73498. if (dataBlockIsZero || (input.read (dest, n) == n))
  73499. return n;
  73500. }
  73501. return -1;
  73502. }
  73503. int GIFLoader::processExtension (const int type, int& transparent)
  73504. {
  73505. unsigned char b [300];
  73506. int n = 0;
  73507. if (type == 0xf9)
  73508. {
  73509. n = readDataBlock (b);
  73510. if (n < 0)
  73511. return 1;
  73512. if ((b[0] & 0x1) != 0)
  73513. transparent = b[3];
  73514. }
  73515. do
  73516. {
  73517. n = readDataBlock (b);
  73518. }
  73519. while (n > 0);
  73520. return n;
  73521. }
  73522. int GIFLoader::getCode (const int codeSize, const bool initialise)
  73523. {
  73524. if (initialise)
  73525. {
  73526. currentBit = 0;
  73527. lastBit = 0;
  73528. finished = false;
  73529. return 0;
  73530. }
  73531. if ((currentBit + codeSize) >= lastBit)
  73532. {
  73533. if (finished)
  73534. return -1;
  73535. buffer[0] = buffer [lastByteIndex - 2];
  73536. buffer[1] = buffer [lastByteIndex - 1];
  73537. const int n = readDataBlock (&buffer[2]);
  73538. if (n == 0)
  73539. finished = true;
  73540. lastByteIndex = 2 + n;
  73541. currentBit = (currentBit - lastBit) + 16;
  73542. lastBit = (2 + n) * 8 ;
  73543. }
  73544. int result = 0;
  73545. int i = currentBit;
  73546. for (int j = 0; j < codeSize; ++j)
  73547. {
  73548. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  73549. ++i;
  73550. }
  73551. currentBit += codeSize;
  73552. return result;
  73553. }
  73554. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  73555. {
  73556. int code, incode, i;
  73557. if (initialise)
  73558. {
  73559. setCodeSize = inputCodeSize;
  73560. codeSize = setCodeSize + 1;
  73561. clearCode = 1 << setCodeSize;
  73562. end_code = clearCode + 1;
  73563. maxCodeSize = 2 * clearCode;
  73564. maxCode = clearCode + 2;
  73565. getCode (0, true);
  73566. fresh = true;
  73567. for (i = 0; i < clearCode; ++i)
  73568. {
  73569. table[0][i] = 0;
  73570. table[1][i] = i;
  73571. }
  73572. for (; i < maxGifCode; ++i)
  73573. {
  73574. table[0][i] = 0;
  73575. table[1][i] = 0;
  73576. }
  73577. sp = stack;
  73578. return 0;
  73579. }
  73580. else if (fresh)
  73581. {
  73582. fresh = false;
  73583. do
  73584. {
  73585. firstcode = oldcode
  73586. = getCode (codeSize, false);
  73587. }
  73588. while (firstcode == clearCode);
  73589. return firstcode;
  73590. }
  73591. if (sp > stack)
  73592. return *--sp;
  73593. while ((code = getCode (codeSize, false)) >= 0)
  73594. {
  73595. if (code == clearCode)
  73596. {
  73597. for (i = 0; i < clearCode; ++i)
  73598. {
  73599. table[0][i] = 0;
  73600. table[1][i] = i;
  73601. }
  73602. for (; i < maxGifCode; ++i)
  73603. {
  73604. table[0][i] = 0;
  73605. table[1][i] = 0;
  73606. }
  73607. codeSize = setCodeSize + 1;
  73608. maxCodeSize = 2 * clearCode;
  73609. maxCode = clearCode + 2;
  73610. sp = stack;
  73611. firstcode = oldcode = getCode (codeSize, false);
  73612. return firstcode;
  73613. }
  73614. else if (code == end_code)
  73615. {
  73616. if (dataBlockIsZero)
  73617. return -2;
  73618. unsigned char buf [260];
  73619. int n;
  73620. while ((n = readDataBlock (buf)) > 0)
  73621. {}
  73622. if (n != 0)
  73623. return -2;
  73624. }
  73625. incode = code;
  73626. if (code >= maxCode)
  73627. {
  73628. *sp++ = firstcode;
  73629. code = oldcode;
  73630. }
  73631. while (code >= clearCode)
  73632. {
  73633. *sp++ = table[1][code];
  73634. if (code == table[0][code])
  73635. return -2;
  73636. code = table[0][code];
  73637. }
  73638. *sp++ = firstcode = table[1][code];
  73639. if ((code = maxCode) < maxGifCode)
  73640. {
  73641. table[0][code] = oldcode;
  73642. table[1][code] = firstcode;
  73643. ++maxCode;
  73644. if ((maxCode >= maxCodeSize)
  73645. && (maxCodeSize < maxGifCode))
  73646. {
  73647. maxCodeSize <<= 1;
  73648. ++codeSize;
  73649. }
  73650. }
  73651. oldcode = incode;
  73652. if (sp > stack)
  73653. return *--sp;
  73654. }
  73655. return code;
  73656. }
  73657. bool GIFLoader::readImage (const int width, const int height,
  73658. const int interlace, const int transparent)
  73659. {
  73660. unsigned char c;
  73661. if (input.read (&c, 1) != 1
  73662. || readLZWByte (true, c) < 0)
  73663. return false;
  73664. if (transparent >= 0)
  73665. {
  73666. palette [transparent][0] = 0;
  73667. palette [transparent][1] = 0;
  73668. palette [transparent][2] = 0;
  73669. palette [transparent][3] = 0;
  73670. }
  73671. int index;
  73672. int xpos = 0, ypos = 0, pass = 0;
  73673. int stride, pixelStride;
  73674. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  73675. uint8* p = pixels;
  73676. const bool hasAlpha = image->hasAlphaChannel();
  73677. while ((index = readLZWByte (false, c)) >= 0)
  73678. {
  73679. const uint8* const paletteEntry = palette [index];
  73680. if (hasAlpha)
  73681. {
  73682. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  73683. paletteEntry[0],
  73684. paletteEntry[1],
  73685. paletteEntry[2]);
  73686. ((PixelARGB*) p)->premultiply();
  73687. p += pixelStride;
  73688. }
  73689. else
  73690. {
  73691. ((PixelRGB*) p)->setARGB (0,
  73692. paletteEntry[0],
  73693. paletteEntry[1],
  73694. paletteEntry[2]);
  73695. p += pixelStride;
  73696. }
  73697. ++xpos;
  73698. if (xpos == width)
  73699. {
  73700. xpos = 0;
  73701. if (interlace)
  73702. {
  73703. switch (pass)
  73704. {
  73705. case 0:
  73706. case 1:
  73707. ypos += 8;
  73708. break;
  73709. case 2:
  73710. ypos += 4;
  73711. break;
  73712. case 3:
  73713. ypos += 2;
  73714. break;
  73715. }
  73716. while (ypos >= height)
  73717. {
  73718. ++pass;
  73719. switch (pass)
  73720. {
  73721. case 1:
  73722. ypos = 4;
  73723. break;
  73724. case 2:
  73725. ypos = 2;
  73726. break;
  73727. case 3:
  73728. ypos = 1;
  73729. break;
  73730. default:
  73731. return true;
  73732. }
  73733. }
  73734. }
  73735. else
  73736. {
  73737. ++ypos;
  73738. }
  73739. p = pixels + xpos * pixelStride + ypos * stride;
  73740. }
  73741. if (ypos >= height)
  73742. break;
  73743. }
  73744. image->releasePixelDataReadWrite (pixels);
  73745. return true;
  73746. }
  73747. END_JUCE_NAMESPACE
  73748. /********* End of inlined file: juce_GIFLoader.cpp *********/
  73749. #endif
  73750. //==============================================================================
  73751. // some files include lots of library code, so leave them to the end to avoid cluttering
  73752. // up the build for the clean files.
  73753. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73754. namespace zlibNamespace
  73755. {
  73756. #if JUCE_INCLUDE_ZLIB_CODE
  73757. #undef OS_CODE
  73758. #undef fdopen
  73759. /********* Start of inlined file: zlib.h *********/
  73760. #ifndef ZLIB_H
  73761. #define ZLIB_H
  73762. /********* Start of inlined file: zconf.h *********/
  73763. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73764. #ifndef ZCONF_H
  73765. #define ZCONF_H
  73766. // *** Just a few hacks here to make it compile nicely with Juce..
  73767. #define Z_PREFIX 1
  73768. #undef __MACTYPES__
  73769. #ifdef _MSC_VER
  73770. #pragma warning (disable : 4131 4127 4244 4267)
  73771. #endif
  73772. /*
  73773. * If you *really* need a unique prefix for all types and library functions,
  73774. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  73775. */
  73776. #ifdef Z_PREFIX
  73777. # define deflateInit_ z_deflateInit_
  73778. # define deflate z_deflate
  73779. # define deflateEnd z_deflateEnd
  73780. # define inflateInit_ z_inflateInit_
  73781. # define inflate z_inflate
  73782. # define inflateEnd z_inflateEnd
  73783. # define deflateInit2_ z_deflateInit2_
  73784. # define deflateSetDictionary z_deflateSetDictionary
  73785. # define deflateCopy z_deflateCopy
  73786. # define deflateReset z_deflateReset
  73787. # define deflateParams z_deflateParams
  73788. # define deflateBound z_deflateBound
  73789. # define deflatePrime z_deflatePrime
  73790. # define inflateInit2_ z_inflateInit2_
  73791. # define inflateSetDictionary z_inflateSetDictionary
  73792. # define inflateSync z_inflateSync
  73793. # define inflateSyncPoint z_inflateSyncPoint
  73794. # define inflateCopy z_inflateCopy
  73795. # define inflateReset z_inflateReset
  73796. # define inflateBack z_inflateBack
  73797. # define inflateBackEnd z_inflateBackEnd
  73798. # define compress z_compress
  73799. # define compress2 z_compress2
  73800. # define compressBound z_compressBound
  73801. # define uncompress z_uncompress
  73802. # define adler32 z_adler32
  73803. # define crc32 z_crc32
  73804. # define get_crc_table z_get_crc_table
  73805. # define zError z_zError
  73806. # define alloc_func z_alloc_func
  73807. # define free_func z_free_func
  73808. # define in_func z_in_func
  73809. # define out_func z_out_func
  73810. # define Byte z_Byte
  73811. # define uInt z_uInt
  73812. # define uLong z_uLong
  73813. # define Bytef z_Bytef
  73814. # define charf z_charf
  73815. # define intf z_intf
  73816. # define uIntf z_uIntf
  73817. # define uLongf z_uLongf
  73818. # define voidpf z_voidpf
  73819. # define voidp z_voidp
  73820. #endif
  73821. #if defined(__MSDOS__) && !defined(MSDOS)
  73822. # define MSDOS
  73823. #endif
  73824. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  73825. # define OS2
  73826. #endif
  73827. #if defined(_WINDOWS) && !defined(WINDOWS)
  73828. # define WINDOWS
  73829. #endif
  73830. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  73831. # ifndef WIN32
  73832. # define WIN32
  73833. # endif
  73834. #endif
  73835. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  73836. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  73837. # ifndef SYS16BIT
  73838. # define SYS16BIT
  73839. # endif
  73840. # endif
  73841. #endif
  73842. /*
  73843. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  73844. * than 64k bytes at a time (needed on systems with 16-bit int).
  73845. */
  73846. #ifdef SYS16BIT
  73847. # define MAXSEG_64K
  73848. #endif
  73849. #ifdef MSDOS
  73850. # define UNALIGNED_OK
  73851. #endif
  73852. #ifdef __STDC_VERSION__
  73853. # ifndef STDC
  73854. # define STDC
  73855. # endif
  73856. # if __STDC_VERSION__ >= 199901L
  73857. # ifndef STDC99
  73858. # define STDC99
  73859. # endif
  73860. # endif
  73861. #endif
  73862. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  73863. # define STDC
  73864. #endif
  73865. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  73866. # define STDC
  73867. #endif
  73868. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  73869. # define STDC
  73870. #endif
  73871. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  73872. # define STDC
  73873. #endif
  73874. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  73875. # define STDC
  73876. #endif
  73877. #ifndef STDC
  73878. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  73879. # define const /* note: need a more gentle solution here */
  73880. # endif
  73881. #endif
  73882. /* Some Mac compilers merge all .h files incorrectly: */
  73883. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  73884. # define NO_DUMMY_DECL
  73885. #endif
  73886. /* Maximum value for memLevel in deflateInit2 */
  73887. #ifndef MAX_MEM_LEVEL
  73888. # ifdef MAXSEG_64K
  73889. # define MAX_MEM_LEVEL 8
  73890. # else
  73891. # define MAX_MEM_LEVEL 9
  73892. # endif
  73893. #endif
  73894. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  73895. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  73896. * created by gzip. (Files created by minigzip can still be extracted by
  73897. * gzip.)
  73898. */
  73899. #ifndef MAX_WBITS
  73900. # define MAX_WBITS 15 /* 32K LZ77 window */
  73901. #endif
  73902. /* The memory requirements for deflate are (in bytes):
  73903. (1 << (windowBits+2)) + (1 << (memLevel+9))
  73904. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  73905. plus a few kilobytes for small objects. For example, if you want to reduce
  73906. the default memory requirements from 256K to 128K, compile with
  73907. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  73908. Of course this will generally degrade compression (there's no free lunch).
  73909. The memory requirements for inflate are (in bytes) 1 << windowBits
  73910. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  73911. for small objects.
  73912. */
  73913. /* Type declarations */
  73914. #ifndef OF /* function prototypes */
  73915. # ifdef STDC
  73916. # define OF(args) args
  73917. # else
  73918. # define OF(args) ()
  73919. # endif
  73920. #endif
  73921. /* The following definitions for FAR are needed only for MSDOS mixed
  73922. * model programming (small or medium model with some far allocations).
  73923. * This was tested only with MSC; for other MSDOS compilers you may have
  73924. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  73925. * just define FAR to be empty.
  73926. */
  73927. #ifdef SYS16BIT
  73928. # if defined(M_I86SM) || defined(M_I86MM)
  73929. /* MSC small or medium model */
  73930. # define SMALL_MEDIUM
  73931. # ifdef _MSC_VER
  73932. # define FAR _far
  73933. # else
  73934. # define FAR far
  73935. # endif
  73936. # endif
  73937. # if (defined(__SMALL__) || defined(__MEDIUM__))
  73938. /* Turbo C small or medium model */
  73939. # define SMALL_MEDIUM
  73940. # ifdef __BORLANDC__
  73941. # define FAR _far
  73942. # else
  73943. # define FAR far
  73944. # endif
  73945. # endif
  73946. #endif
  73947. #if defined(WINDOWS) || defined(WIN32)
  73948. /* If building or using zlib as a DLL, define ZLIB_DLL.
  73949. * This is not mandatory, but it offers a little performance increase.
  73950. */
  73951. # ifdef ZLIB_DLL
  73952. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  73953. # ifdef ZLIB_INTERNAL
  73954. # define ZEXTERN extern __declspec(dllexport)
  73955. # else
  73956. # define ZEXTERN extern __declspec(dllimport)
  73957. # endif
  73958. # endif
  73959. # endif /* ZLIB_DLL */
  73960. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  73961. * define ZLIB_WINAPI.
  73962. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  73963. */
  73964. # ifdef ZLIB_WINAPI
  73965. # ifdef FAR
  73966. # undef FAR
  73967. # endif
  73968. # include <windows.h>
  73969. /* No need for _export, use ZLIB.DEF instead. */
  73970. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  73971. # define ZEXPORT WINAPI
  73972. # ifdef WIN32
  73973. # define ZEXPORTVA WINAPIV
  73974. # else
  73975. # define ZEXPORTVA FAR CDECL
  73976. # endif
  73977. # endif
  73978. #endif
  73979. #if defined (__BEOS__)
  73980. # ifdef ZLIB_DLL
  73981. # ifdef ZLIB_INTERNAL
  73982. # define ZEXPORT __declspec(dllexport)
  73983. # define ZEXPORTVA __declspec(dllexport)
  73984. # else
  73985. # define ZEXPORT __declspec(dllimport)
  73986. # define ZEXPORTVA __declspec(dllimport)
  73987. # endif
  73988. # endif
  73989. #endif
  73990. #ifndef ZEXTERN
  73991. # define ZEXTERN extern
  73992. #endif
  73993. #ifndef ZEXPORT
  73994. # define ZEXPORT
  73995. #endif
  73996. #ifndef ZEXPORTVA
  73997. # define ZEXPORTVA
  73998. #endif
  73999. #ifndef FAR
  74000. # define FAR
  74001. #endif
  74002. #if !defined(__MACTYPES__)
  74003. typedef unsigned char Byte; /* 8 bits */
  74004. #endif
  74005. typedef unsigned int uInt; /* 16 bits or more */
  74006. typedef unsigned long uLong; /* 32 bits or more */
  74007. #ifdef SMALL_MEDIUM
  74008. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  74009. # define Bytef Byte FAR
  74010. #else
  74011. typedef Byte FAR Bytef;
  74012. #endif
  74013. typedef char FAR charf;
  74014. typedef int FAR intf;
  74015. typedef uInt FAR uIntf;
  74016. typedef uLong FAR uLongf;
  74017. #ifdef STDC
  74018. typedef void const *voidpc;
  74019. typedef void FAR *voidpf;
  74020. typedef void *voidp;
  74021. #else
  74022. typedef Byte const *voidpc;
  74023. typedef Byte FAR *voidpf;
  74024. typedef Byte *voidp;
  74025. #endif
  74026. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  74027. # include <sys/types.h> /* for off_t */
  74028. # include <unistd.h> /* for SEEK_* and off_t */
  74029. # ifdef VMS
  74030. # include <unixio.h> /* for off_t */
  74031. # endif
  74032. # define z_off_t off_t
  74033. #endif
  74034. #ifndef SEEK_SET
  74035. # define SEEK_SET 0 /* Seek from beginning of file. */
  74036. # define SEEK_CUR 1 /* Seek from current position. */
  74037. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  74038. #endif
  74039. #ifndef z_off_t
  74040. # define z_off_t long
  74041. #endif
  74042. #if defined(__OS400__)
  74043. # define NO_vsnprintf
  74044. #endif
  74045. #if defined(__MVS__)
  74046. # define NO_vsnprintf
  74047. # ifdef FAR
  74048. # undef FAR
  74049. # endif
  74050. #endif
  74051. /* MVS linker does not support external names larger than 8 bytes */
  74052. #if defined(__MVS__)
  74053. # pragma map(deflateInit_,"DEIN")
  74054. # pragma map(deflateInit2_,"DEIN2")
  74055. # pragma map(deflateEnd,"DEEND")
  74056. # pragma map(deflateBound,"DEBND")
  74057. # pragma map(inflateInit_,"ININ")
  74058. # pragma map(inflateInit2_,"ININ2")
  74059. # pragma map(inflateEnd,"INEND")
  74060. # pragma map(inflateSync,"INSY")
  74061. # pragma map(inflateSetDictionary,"INSEDI")
  74062. # pragma map(compressBound,"CMBND")
  74063. # pragma map(inflate_table,"INTABL")
  74064. # pragma map(inflate_fast,"INFA")
  74065. # pragma map(inflate_copyright,"INCOPY")
  74066. #endif
  74067. #endif /* ZCONF_H */
  74068. /********* End of inlined file: zconf.h *********/
  74069. #ifdef __cplusplus
  74070. extern "C" {
  74071. #endif
  74072. #define ZLIB_VERSION "1.2.3"
  74073. #define ZLIB_VERNUM 0x1230
  74074. /*
  74075. The 'zlib' compression library provides in-memory compression and
  74076. decompression functions, including integrity checks of the uncompressed
  74077. data. This version of the library supports only one compression method
  74078. (deflation) but other algorithms will be added later and will have the same
  74079. stream interface.
  74080. Compression can be done in a single step if the buffers are large
  74081. enough (for example if an input file is mmap'ed), or can be done by
  74082. repeated calls of the compression function. In the latter case, the
  74083. application must provide more input and/or consume the output
  74084. (providing more output space) before each call.
  74085. The compressed data format used by default by the in-memory functions is
  74086. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  74087. around a deflate stream, which is itself documented in RFC 1951.
  74088. The library also supports reading and writing files in gzip (.gz) format
  74089. with an interface similar to that of stdio using the functions that start
  74090. with "gz". The gzip format is different from the zlib format. gzip is a
  74091. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  74092. This library can optionally read and write gzip streams in memory as well.
  74093. The zlib format was designed to be compact and fast for use in memory
  74094. and on communications channels. The gzip format was designed for single-
  74095. file compression on file systems, has a larger header than zlib to maintain
  74096. directory information, and uses a different, slower check method than zlib.
  74097. The library does not install any signal handler. The decoder checks
  74098. the consistency of the compressed data, so the library should never
  74099. crash even in case of corrupted input.
  74100. */
  74101. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  74102. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  74103. struct internal_state;
  74104. typedef struct z_stream_s {
  74105. Bytef *next_in; /* next input byte */
  74106. uInt avail_in; /* number of bytes available at next_in */
  74107. uLong total_in; /* total nb of input bytes read so far */
  74108. Bytef *next_out; /* next output byte should be put there */
  74109. uInt avail_out; /* remaining free space at next_out */
  74110. uLong total_out; /* total nb of bytes output so far */
  74111. char *msg; /* last error message, NULL if no error */
  74112. struct internal_state FAR *state; /* not visible by applications */
  74113. alloc_func zalloc; /* used to allocate the internal state */
  74114. free_func zfree; /* used to free the internal state */
  74115. voidpf opaque; /* private data object passed to zalloc and zfree */
  74116. int data_type; /* best guess about the data type: binary or text */
  74117. uLong adler; /* adler32 value of the uncompressed data */
  74118. uLong reserved; /* reserved for future use */
  74119. } z_stream;
  74120. typedef z_stream FAR *z_streamp;
  74121. /*
  74122. gzip header information passed to and from zlib routines. See RFC 1952
  74123. for more details on the meanings of these fields.
  74124. */
  74125. typedef struct gz_header_s {
  74126. int text; /* true if compressed data believed to be text */
  74127. uLong time; /* modification time */
  74128. int xflags; /* extra flags (not used when writing a gzip file) */
  74129. int os; /* operating system */
  74130. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  74131. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  74132. uInt extra_max; /* space at extra (only when reading header) */
  74133. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  74134. uInt name_max; /* space at name (only when reading header) */
  74135. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  74136. uInt comm_max; /* space at comment (only when reading header) */
  74137. int hcrc; /* true if there was or will be a header crc */
  74138. int done; /* true when done reading gzip header (not used
  74139. when writing a gzip file) */
  74140. } gz_header;
  74141. typedef gz_header FAR *gz_headerp;
  74142. /*
  74143. The application must update next_in and avail_in when avail_in has
  74144. dropped to zero. It must update next_out and avail_out when avail_out
  74145. has dropped to zero. The application must initialize zalloc, zfree and
  74146. opaque before calling the init function. All other fields are set by the
  74147. compression library and must not be updated by the application.
  74148. The opaque value provided by the application will be passed as the first
  74149. parameter for calls of zalloc and zfree. This can be useful for custom
  74150. memory management. The compression library attaches no meaning to the
  74151. opaque value.
  74152. zalloc must return Z_NULL if there is not enough memory for the object.
  74153. If zlib is used in a multi-threaded application, zalloc and zfree must be
  74154. thread safe.
  74155. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  74156. exactly 65536 bytes, but will not be required to allocate more than this
  74157. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  74158. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  74159. have their offset normalized to zero. The default allocation function
  74160. provided by this library ensures this (see zutil.c). To reduce memory
  74161. requirements and avoid any allocation of 64K objects, at the expense of
  74162. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  74163. The fields total_in and total_out can be used for statistics or
  74164. progress reports. After compression, total_in holds the total size of
  74165. the uncompressed data and may be saved for use in the decompressor
  74166. (particularly if the decompressor wants to decompress everything in
  74167. a single step).
  74168. */
  74169. /* constants */
  74170. #define Z_NO_FLUSH 0
  74171. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  74172. #define Z_SYNC_FLUSH 2
  74173. #define Z_FULL_FLUSH 3
  74174. #define Z_FINISH 4
  74175. #define Z_BLOCK 5
  74176. /* Allowed flush values; see deflate() and inflate() below for details */
  74177. #define Z_OK 0
  74178. #define Z_STREAM_END 1
  74179. #define Z_NEED_DICT 2
  74180. #define Z_ERRNO (-1)
  74181. #define Z_STREAM_ERROR (-2)
  74182. #define Z_DATA_ERROR (-3)
  74183. #define Z_MEM_ERROR (-4)
  74184. #define Z_BUF_ERROR (-5)
  74185. #define Z_VERSION_ERROR (-6)
  74186. /* Return codes for the compression/decompression functions. Negative
  74187. * values are errors, positive values are used for special but normal events.
  74188. */
  74189. #define Z_NO_COMPRESSION 0
  74190. #define Z_BEST_SPEED 1
  74191. #define Z_BEST_COMPRESSION 9
  74192. #define Z_DEFAULT_COMPRESSION (-1)
  74193. /* compression levels */
  74194. #define Z_FILTERED 1
  74195. #define Z_HUFFMAN_ONLY 2
  74196. #define Z_RLE 3
  74197. #define Z_FIXED 4
  74198. #define Z_DEFAULT_STRATEGY 0
  74199. /* compression strategy; see deflateInit2() below for details */
  74200. #define Z_BINARY 0
  74201. #define Z_TEXT 1
  74202. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  74203. #define Z_UNKNOWN 2
  74204. /* Possible values of the data_type field (though see inflate()) */
  74205. #define Z_DEFLATED 8
  74206. /* The deflate compression method (the only one supported in this version) */
  74207. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  74208. #define zlib_version zlibVersion()
  74209. /* for compatibility with versions < 1.0.2 */
  74210. /* basic functions */
  74211. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  74212. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  74213. If the first character differs, the library code actually used is
  74214. not compatible with the zlib.h header file used by the application.
  74215. This check is automatically made by deflateInit and inflateInit.
  74216. */
  74217. /*
  74218. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  74219. Initializes the internal stream state for compression. The fields
  74220. zalloc, zfree and opaque must be initialized before by the caller.
  74221. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  74222. use default allocation functions.
  74223. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  74224. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  74225. all (the input data is simply copied a block at a time).
  74226. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  74227. compression (currently equivalent to level 6).
  74228. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  74229. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  74230. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  74231. with the version assumed by the caller (ZLIB_VERSION).
  74232. msg is set to null if there is no error message. deflateInit does not
  74233. perform any compression: this will be done by deflate().
  74234. */
  74235. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  74236. /*
  74237. deflate compresses as much data as possible, and stops when the input
  74238. buffer becomes empty or the output buffer becomes full. It may introduce some
  74239. output latency (reading input without producing any output) except when
  74240. forced to flush.
  74241. The detailed semantics are as follows. deflate performs one or both of the
  74242. following actions:
  74243. - Compress more input starting at next_in and update next_in and avail_in
  74244. accordingly. If not all input can be processed (because there is not
  74245. enough room in the output buffer), next_in and avail_in are updated and
  74246. processing will resume at this point for the next call of deflate().
  74247. - Provide more output starting at next_out and update next_out and avail_out
  74248. accordingly. This action is forced if the parameter flush is non zero.
  74249. Forcing flush frequently degrades the compression ratio, so this parameter
  74250. should be set only when necessary (in interactive applications).
  74251. Some output may be provided even if flush is not set.
  74252. Before the call of deflate(), the application should ensure that at least
  74253. one of the actions is possible, by providing more input and/or consuming
  74254. more output, and updating avail_in or avail_out accordingly; avail_out
  74255. should never be zero before the call. The application can consume the
  74256. compressed output when it wants, for example when the output buffer is full
  74257. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  74258. and with zero avail_out, it must be called again after making room in the
  74259. output buffer because there might be more output pending.
  74260. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  74261. decide how much data to accumualte before producing output, in order to
  74262. maximize compression.
  74263. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  74264. flushed to the output buffer and the output is aligned on a byte boundary, so
  74265. that the decompressor can get all input data available so far. (In particular
  74266. avail_in is zero after the call if enough output space has been provided
  74267. before the call.) Flushing may degrade compression for some compression
  74268. algorithms and so it should be used only when necessary.
  74269. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  74270. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  74271. restart from this point if previous compressed data has been damaged or if
  74272. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  74273. compression.
  74274. If deflate returns with avail_out == 0, this function must be called again
  74275. with the same value of the flush parameter and more output space (updated
  74276. avail_out), until the flush is complete (deflate returns with non-zero
  74277. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  74278. avail_out is greater than six to avoid repeated flush markers due to
  74279. avail_out == 0 on return.
  74280. If the parameter flush is set to Z_FINISH, pending input is processed,
  74281. pending output is flushed and deflate returns with Z_STREAM_END if there
  74282. was enough output space; if deflate returns with Z_OK, this function must be
  74283. called again with Z_FINISH and more output space (updated avail_out) but no
  74284. more input data, until it returns with Z_STREAM_END or an error. After
  74285. deflate has returned Z_STREAM_END, the only possible operations on the
  74286. stream are deflateReset or deflateEnd.
  74287. Z_FINISH can be used immediately after deflateInit if all the compression
  74288. is to be done in a single step. In this case, avail_out must be at least
  74289. the value returned by deflateBound (see below). If deflate does not return
  74290. Z_STREAM_END, then it must be called again as described above.
  74291. deflate() sets strm->adler to the adler32 checksum of all input read
  74292. so far (that is, total_in bytes).
  74293. deflate() may update strm->data_type if it can make a good guess about
  74294. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  74295. binary. This field is only for information purposes and does not affect
  74296. the compression algorithm in any manner.
  74297. deflate() returns Z_OK if some progress has been made (more input
  74298. processed or more output produced), Z_STREAM_END if all input has been
  74299. consumed and all output has been produced (only when flush is set to
  74300. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  74301. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  74302. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  74303. fatal, and deflate() can be called again with more input and more output
  74304. space to continue compressing.
  74305. */
  74306. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  74307. /*
  74308. All dynamically allocated data structures for this stream are freed.
  74309. This function discards any unprocessed input and does not flush any
  74310. pending output.
  74311. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  74312. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  74313. prematurely (some input or output was discarded). In the error case,
  74314. msg may be set but then points to a static string (which must not be
  74315. deallocated).
  74316. */
  74317. /*
  74318. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  74319. Initializes the internal stream state for decompression. The fields
  74320. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  74321. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  74322. value depends on the compression method), inflateInit determines the
  74323. compression method from the zlib header and allocates all data structures
  74324. accordingly; otherwise the allocation will be deferred to the first call of
  74325. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  74326. use default allocation functions.
  74327. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74328. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  74329. version assumed by the caller. msg is set to null if there is no error
  74330. message. inflateInit does not perform any decompression apart from reading
  74331. the zlib header if present: this will be done by inflate(). (So next_in and
  74332. avail_in may be modified, but next_out and avail_out are unchanged.)
  74333. */
  74334. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  74335. /*
  74336. inflate decompresses as much data as possible, and stops when the input
  74337. buffer becomes empty or the output buffer becomes full. It may introduce
  74338. some output latency (reading input without producing any output) except when
  74339. forced to flush.
  74340. The detailed semantics are as follows. inflate performs one or both of the
  74341. following actions:
  74342. - Decompress more input starting at next_in and update next_in and avail_in
  74343. accordingly. If not all input can be processed (because there is not
  74344. enough room in the output buffer), next_in is updated and processing
  74345. will resume at this point for the next call of inflate().
  74346. - Provide more output starting at next_out and update next_out and avail_out
  74347. accordingly. inflate() provides as much output as possible, until there
  74348. is no more input data or no more space in the output buffer (see below
  74349. about the flush parameter).
  74350. Before the call of inflate(), the application should ensure that at least
  74351. one of the actions is possible, by providing more input and/or consuming
  74352. more output, and updating the next_* and avail_* values accordingly.
  74353. The application can consume the uncompressed output when it wants, for
  74354. example when the output buffer is full (avail_out == 0), or after each
  74355. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  74356. must be called again after making room in the output buffer because there
  74357. might be more output pending.
  74358. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  74359. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  74360. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  74361. if and when it gets to the next deflate block boundary. When decoding the
  74362. zlib or gzip format, this will cause inflate() to return immediately after
  74363. the header and before the first block. When doing a raw inflate, inflate()
  74364. will go ahead and process the first block, and will return when it gets to
  74365. the end of that block, or when it runs out of data.
  74366. The Z_BLOCK option assists in appending to or combining deflate streams.
  74367. Also to assist in this, on return inflate() will set strm->data_type to the
  74368. number of unused bits in the last byte taken from strm->next_in, plus 64
  74369. if inflate() is currently decoding the last block in the deflate stream,
  74370. plus 128 if inflate() returned immediately after decoding an end-of-block
  74371. code or decoding the complete header up to just before the first byte of the
  74372. deflate stream. The end-of-block will not be indicated until all of the
  74373. uncompressed data from that block has been written to strm->next_out. The
  74374. number of unused bits may in general be greater than seven, except when
  74375. bit 7 of data_type is set, in which case the number of unused bits will be
  74376. less than eight.
  74377. inflate() should normally be called until it returns Z_STREAM_END or an
  74378. error. However if all decompression is to be performed in a single step
  74379. (a single call of inflate), the parameter flush should be set to
  74380. Z_FINISH. In this case all pending input is processed and all pending
  74381. output is flushed; avail_out must be large enough to hold all the
  74382. uncompressed data. (The size of the uncompressed data may have been saved
  74383. by the compressor for this purpose.) The next operation on this stream must
  74384. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  74385. is never required, but can be used to inform inflate that a faster approach
  74386. may be used for the single inflate() call.
  74387. In this implementation, inflate() always flushes as much output as
  74388. possible to the output buffer, and always uses the faster approach on the
  74389. first call. So the only effect of the flush parameter in this implementation
  74390. is on the return value of inflate(), as noted below, or when it returns early
  74391. because Z_BLOCK is used.
  74392. If a preset dictionary is needed after this call (see inflateSetDictionary
  74393. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  74394. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  74395. strm->adler to the adler32 checksum of all output produced so far (that is,
  74396. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  74397. below. At the end of the stream, inflate() checks that its computed adler32
  74398. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  74399. only if the checksum is correct.
  74400. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  74401. deflate data. The header type is detected automatically. Any information
  74402. contained in the gzip header is not retained, so applications that need that
  74403. information should instead use raw inflate, see inflateInit2() below, or
  74404. inflateBack() and perform their own processing of the gzip header and
  74405. trailer.
  74406. inflate() returns Z_OK if some progress has been made (more input processed
  74407. or more output produced), Z_STREAM_END if the end of the compressed data has
  74408. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  74409. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  74410. corrupted (input stream not conforming to the zlib format or incorrect check
  74411. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  74412. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  74413. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  74414. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  74415. inflate() can be called again with more input and more output space to
  74416. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  74417. call inflateSync() to look for a good compression block if a partial recovery
  74418. of the data is desired.
  74419. */
  74420. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  74421. /*
  74422. All dynamically allocated data structures for this stream are freed.
  74423. This function discards any unprocessed input and does not flush any
  74424. pending output.
  74425. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  74426. was inconsistent. In the error case, msg may be set but then points to a
  74427. static string (which must not be deallocated).
  74428. */
  74429. /* Advanced functions */
  74430. /*
  74431. The following functions are needed only in some special applications.
  74432. */
  74433. /*
  74434. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  74435. int level,
  74436. int method,
  74437. int windowBits,
  74438. int memLevel,
  74439. int strategy));
  74440. This is another version of deflateInit with more compression options. The
  74441. fields next_in, zalloc, zfree and opaque must be initialized before by
  74442. the caller.
  74443. The method parameter is the compression method. It must be Z_DEFLATED in
  74444. this version of the library.
  74445. The windowBits parameter is the base two logarithm of the window size
  74446. (the size of the history buffer). It should be in the range 8..15 for this
  74447. version of the library. Larger values of this parameter result in better
  74448. compression at the expense of memory usage. The default value is 15 if
  74449. deflateInit is used instead.
  74450. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  74451. determines the window size. deflate() will then generate raw deflate data
  74452. with no zlib header or trailer, and will not compute an adler32 check value.
  74453. windowBits can also be greater than 15 for optional gzip encoding. Add
  74454. 16 to windowBits to write a simple gzip header and trailer around the
  74455. compressed data instead of a zlib wrapper. The gzip header will have no
  74456. file name, no extra data, no comment, no modification time (set to zero),
  74457. no header crc, and the operating system will be set to 255 (unknown). If a
  74458. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  74459. The memLevel parameter specifies how much memory should be allocated
  74460. for the internal compression state. memLevel=1 uses minimum memory but
  74461. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  74462. for optimal speed. The default value is 8. See zconf.h for total memory
  74463. usage as a function of windowBits and memLevel.
  74464. The strategy parameter is used to tune the compression algorithm. Use the
  74465. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  74466. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  74467. string match), or Z_RLE to limit match distances to one (run-length
  74468. encoding). Filtered data consists mostly of small values with a somewhat
  74469. random distribution. In this case, the compression algorithm is tuned to
  74470. compress them better. The effect of Z_FILTERED is to force more Huffman
  74471. coding and less string matching; it is somewhat intermediate between
  74472. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  74473. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  74474. parameter only affects the compression ratio but not the correctness of the
  74475. compressed output even if it is not set appropriately. Z_FIXED prevents the
  74476. use of dynamic Huffman codes, allowing for a simpler decoder for special
  74477. applications.
  74478. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74479. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  74480. method). msg is set to null if there is no error message. deflateInit2 does
  74481. not perform any compression: this will be done by deflate().
  74482. */
  74483. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  74484. const Bytef *dictionary,
  74485. uInt dictLength));
  74486. /*
  74487. Initializes the compression dictionary from the given byte sequence
  74488. without producing any compressed output. This function must be called
  74489. immediately after deflateInit, deflateInit2 or deflateReset, before any
  74490. call of deflate. The compressor and decompressor must use exactly the same
  74491. dictionary (see inflateSetDictionary).
  74492. The dictionary should consist of strings (byte sequences) that are likely
  74493. to be encountered later in the data to be compressed, with the most commonly
  74494. used strings preferably put towards the end of the dictionary. Using a
  74495. dictionary is most useful when the data to be compressed is short and can be
  74496. predicted with good accuracy; the data can then be compressed better than
  74497. with the default empty dictionary.
  74498. Depending on the size of the compression data structures selected by
  74499. deflateInit or deflateInit2, a part of the dictionary may in effect be
  74500. discarded, for example if the dictionary is larger than the window size in
  74501. deflate or deflate2. Thus the strings most likely to be useful should be
  74502. put at the end of the dictionary, not at the front. In addition, the
  74503. current implementation of deflate will use at most the window size minus
  74504. 262 bytes of the provided dictionary.
  74505. Upon return of this function, strm->adler is set to the adler32 value
  74506. of the dictionary; the decompressor may later use this value to determine
  74507. which dictionary has been used by the compressor. (The adler32 value
  74508. applies to the whole dictionary even if only a subset of the dictionary is
  74509. actually used by the compressor.) If a raw deflate was requested, then the
  74510. adler32 value is not computed and strm->adler is not set.
  74511. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  74512. parameter is invalid (such as NULL dictionary) or the stream state is
  74513. inconsistent (for example if deflate has already been called for this stream
  74514. or if the compression method is bsort). deflateSetDictionary does not
  74515. perform any compression: this will be done by deflate().
  74516. */
  74517. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  74518. z_streamp source));
  74519. /*
  74520. Sets the destination stream as a complete copy of the source stream.
  74521. This function can be useful when several compression strategies will be
  74522. tried, for example when there are several ways of pre-processing the input
  74523. data with a filter. The streams that will be discarded should then be freed
  74524. by calling deflateEnd. Note that deflateCopy duplicates the internal
  74525. compression state which can be quite large, so this strategy is slow and
  74526. can consume lots of memory.
  74527. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74528. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74529. (such as zalloc being NULL). msg is left unchanged in both source and
  74530. destination.
  74531. */
  74532. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  74533. /*
  74534. This function is equivalent to deflateEnd followed by deflateInit,
  74535. but does not free and reallocate all the internal compression state.
  74536. The stream will keep the same compression level and any other attributes
  74537. that may have been set by deflateInit2.
  74538. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74539. stream state was inconsistent (such as zalloc or state being NULL).
  74540. */
  74541. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  74542. int level,
  74543. int strategy));
  74544. /*
  74545. Dynamically update the compression level and compression strategy. The
  74546. interpretation of level and strategy is as in deflateInit2. This can be
  74547. used to switch between compression and straight copy of the input data, or
  74548. to switch to a different kind of input data requiring a different
  74549. strategy. If the compression level is changed, the input available so far
  74550. is compressed with the old level (and may be flushed); the new level will
  74551. take effect only at the next call of deflate().
  74552. Before the call of deflateParams, the stream state must be set as for
  74553. a call of deflate(), since the currently available input may have to
  74554. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  74555. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  74556. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  74557. if strm->avail_out was zero.
  74558. */
  74559. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  74560. int good_length,
  74561. int max_lazy,
  74562. int nice_length,
  74563. int max_chain));
  74564. /*
  74565. Fine tune deflate's internal compression parameters. This should only be
  74566. used by someone who understands the algorithm used by zlib's deflate for
  74567. searching for the best matching string, and even then only by the most
  74568. fanatic optimizer trying to squeeze out the last compressed bit for their
  74569. specific input data. Read the deflate.c source code for the meaning of the
  74570. max_lazy, good_length, nice_length, and max_chain parameters.
  74571. deflateTune() can be called after deflateInit() or deflateInit2(), and
  74572. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  74573. */
  74574. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  74575. uLong sourceLen));
  74576. /*
  74577. deflateBound() returns an upper bound on the compressed size after
  74578. deflation of sourceLen bytes. It must be called after deflateInit()
  74579. or deflateInit2(). This would be used to allocate an output buffer
  74580. for deflation in a single pass, and so would be called before deflate().
  74581. */
  74582. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  74583. int bits,
  74584. int value));
  74585. /*
  74586. deflatePrime() inserts bits in the deflate output stream. The intent
  74587. is that this function is used to start off the deflate output with the
  74588. bits leftover from a previous deflate stream when appending to it. As such,
  74589. this function can only be used for raw deflate, and must be used before the
  74590. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  74591. less than or equal to 16, and that many of the least significant bits of
  74592. value will be inserted in the output.
  74593. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74594. stream state was inconsistent.
  74595. */
  74596. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  74597. gz_headerp head));
  74598. /*
  74599. deflateSetHeader() provides gzip header information for when a gzip
  74600. stream is requested by deflateInit2(). deflateSetHeader() may be called
  74601. after deflateInit2() or deflateReset() and before the first call of
  74602. deflate(). The text, time, os, extra field, name, and comment information
  74603. in the provided gz_header structure are written to the gzip header (xflag is
  74604. ignored -- the extra flags are set according to the compression level). The
  74605. caller must assure that, if not Z_NULL, name and comment are terminated with
  74606. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  74607. available there. If hcrc is true, a gzip header crc is included. Note that
  74608. the current versions of the command-line version of gzip (up through version
  74609. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  74610. gzip file" and give up.
  74611. If deflateSetHeader is not used, the default gzip header has text false,
  74612. the time set to zero, and os set to 255, with no extra, name, or comment
  74613. fields. The gzip header is returned to the default state by deflateReset().
  74614. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74615. stream state was inconsistent.
  74616. */
  74617. /*
  74618. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  74619. int windowBits));
  74620. This is another version of inflateInit with an extra parameter. The
  74621. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  74622. before by the caller.
  74623. The windowBits parameter is the base two logarithm of the maximum window
  74624. size (the size of the history buffer). It should be in the range 8..15 for
  74625. this version of the library. The default value is 15 if inflateInit is used
  74626. instead. windowBits must be greater than or equal to the windowBits value
  74627. provided to deflateInit2() while compressing, or it must be equal to 15 if
  74628. deflateInit2() was not used. If a compressed stream with a larger window
  74629. size is given as input, inflate() will return with the error code
  74630. Z_DATA_ERROR instead of trying to allocate a larger window.
  74631. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  74632. determines the window size. inflate() will then process raw deflate data,
  74633. not looking for a zlib or gzip header, not generating a check value, and not
  74634. looking for any check values for comparison at the end of the stream. This
  74635. is for use with other formats that use the deflate compressed data format
  74636. such as zip. Those formats provide their own check values. If a custom
  74637. format is developed using the raw deflate format for compressed data, it is
  74638. recommended that a check value such as an adler32 or a crc32 be applied to
  74639. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  74640. most applications, the zlib format should be used as is. Note that comments
  74641. above on the use in deflateInit2() applies to the magnitude of windowBits.
  74642. windowBits can also be greater than 15 for optional gzip decoding. Add
  74643. 32 to windowBits to enable zlib and gzip decoding with automatic header
  74644. detection, or add 16 to decode only the gzip format (the zlib format will
  74645. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  74646. a crc32 instead of an adler32.
  74647. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74648. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  74649. is set to null if there is no error message. inflateInit2 does not perform
  74650. any decompression apart from reading the zlib header if present: this will
  74651. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  74652. and avail_out are unchanged.)
  74653. */
  74654. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  74655. const Bytef *dictionary,
  74656. uInt dictLength));
  74657. /*
  74658. Initializes the decompression dictionary from the given uncompressed byte
  74659. sequence. This function must be called immediately after a call of inflate,
  74660. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  74661. can be determined from the adler32 value returned by that call of inflate.
  74662. The compressor and decompressor must use exactly the same dictionary (see
  74663. deflateSetDictionary). For raw inflate, this function can be called
  74664. immediately after inflateInit2() or inflateReset() and before any call of
  74665. inflate() to set the dictionary. The application must insure that the
  74666. dictionary that was used for compression is provided.
  74667. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  74668. parameter is invalid (such as NULL dictionary) or the stream state is
  74669. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  74670. expected one (incorrect adler32 value). inflateSetDictionary does not
  74671. perform any decompression: this will be done by subsequent calls of
  74672. inflate().
  74673. */
  74674. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  74675. /*
  74676. Skips invalid compressed data until a full flush point (see above the
  74677. description of deflate with Z_FULL_FLUSH) can be found, or until all
  74678. available input is skipped. No output is provided.
  74679. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  74680. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  74681. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  74682. case, the application may save the current current value of total_in which
  74683. indicates where valid compressed data was found. In the error case, the
  74684. application may repeatedly call inflateSync, providing more input each time,
  74685. until success or end of the input data.
  74686. */
  74687. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  74688. z_streamp source));
  74689. /*
  74690. Sets the destination stream as a complete copy of the source stream.
  74691. This function can be useful when randomly accessing a large stream. The
  74692. first pass through the stream can periodically record the inflate state,
  74693. allowing restarting inflate at those points when randomly accessing the
  74694. stream.
  74695. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74696. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74697. (such as zalloc being NULL). msg is left unchanged in both source and
  74698. destination.
  74699. */
  74700. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  74701. /*
  74702. This function is equivalent to inflateEnd followed by inflateInit,
  74703. but does not free and reallocate all the internal decompression state.
  74704. The stream will keep attributes that may have been set by inflateInit2.
  74705. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74706. stream state was inconsistent (such as zalloc or state being NULL).
  74707. */
  74708. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  74709. int bits,
  74710. int value));
  74711. /*
  74712. This function inserts bits in the inflate input stream. The intent is
  74713. that this function is used to start inflating at a bit position in the
  74714. middle of a byte. The provided bits will be used before any bytes are used
  74715. from next_in. This function should only be used with raw inflate, and
  74716. should be used before the first inflate() call after inflateInit2() or
  74717. inflateReset(). bits must be less than or equal to 16, and that many of the
  74718. least significant bits of value will be inserted in the input.
  74719. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74720. stream state was inconsistent.
  74721. */
  74722. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  74723. gz_headerp head));
  74724. /*
  74725. inflateGetHeader() requests that gzip header information be stored in the
  74726. provided gz_header structure. inflateGetHeader() may be called after
  74727. inflateInit2() or inflateReset(), and before the first call of inflate().
  74728. As inflate() processes the gzip stream, head->done is zero until the header
  74729. is completed, at which time head->done is set to one. If a zlib stream is
  74730. being decoded, then head->done is set to -1 to indicate that there will be
  74731. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  74732. force inflate() to return immediately after header processing is complete
  74733. and before any actual data is decompressed.
  74734. The text, time, xflags, and os fields are filled in with the gzip header
  74735. contents. hcrc is set to true if there is a header CRC. (The header CRC
  74736. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  74737. contains the maximum number of bytes to write to extra. Once done is true,
  74738. extra_len contains the actual extra field length, and extra contains the
  74739. extra field, or that field truncated if extra_max is less than extra_len.
  74740. If name is not Z_NULL, then up to name_max characters are written there,
  74741. terminated with a zero unless the length is greater than name_max. If
  74742. comment is not Z_NULL, then up to comm_max characters are written there,
  74743. terminated with a zero unless the length is greater than comm_max. When
  74744. any of extra, name, or comment are not Z_NULL and the respective field is
  74745. not present in the header, then that field is set to Z_NULL to signal its
  74746. absence. This allows the use of deflateSetHeader() with the returned
  74747. structure to duplicate the header. However if those fields are set to
  74748. allocated memory, then the application will need to save those pointers
  74749. elsewhere so that they can be eventually freed.
  74750. If inflateGetHeader is not used, then the header information is simply
  74751. discarded. The header is always checked for validity, including the header
  74752. CRC if present. inflateReset() will reset the process to discard the header
  74753. information. The application would need to call inflateGetHeader() again to
  74754. retrieve the header from the next gzip stream.
  74755. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74756. stream state was inconsistent.
  74757. */
  74758. /*
  74759. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  74760. unsigned char FAR *window));
  74761. Initialize the internal stream state for decompression using inflateBack()
  74762. calls. The fields zalloc, zfree and opaque in strm must be initialized
  74763. before the call. If zalloc and zfree are Z_NULL, then the default library-
  74764. derived memory allocation routines are used. windowBits is the base two
  74765. logarithm of the window size, in the range 8..15. window is a caller
  74766. supplied buffer of that size. Except for special applications where it is
  74767. assured that deflate was used with small window sizes, windowBits must be 15
  74768. and a 32K byte window must be supplied to be able to decompress general
  74769. deflate streams.
  74770. See inflateBack() for the usage of these routines.
  74771. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  74772. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  74773. be allocated, or Z_VERSION_ERROR if the version of the library does not
  74774. match the version of the header file.
  74775. */
  74776. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  74777. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  74778. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  74779. in_func in, void FAR *in_desc,
  74780. out_func out, void FAR *out_desc));
  74781. /*
  74782. inflateBack() does a raw inflate with a single call using a call-back
  74783. interface for input and output. This is more efficient than inflate() for
  74784. file i/o applications in that it avoids copying between the output and the
  74785. sliding window by simply making the window itself the output buffer. This
  74786. function trusts the application to not change the output buffer passed by
  74787. the output function, at least until inflateBack() returns.
  74788. inflateBackInit() must be called first to allocate the internal state
  74789. and to initialize the state with the user-provided window buffer.
  74790. inflateBack() may then be used multiple times to inflate a complete, raw
  74791. deflate stream with each call. inflateBackEnd() is then called to free
  74792. the allocated state.
  74793. A raw deflate stream is one with no zlib or gzip header or trailer.
  74794. This routine would normally be used in a utility that reads zip or gzip
  74795. files and writes out uncompressed files. The utility would decode the
  74796. header and process the trailer on its own, hence this routine expects
  74797. only the raw deflate stream to decompress. This is different from the
  74798. normal behavior of inflate(), which expects either a zlib or gzip header and
  74799. trailer around the deflate stream.
  74800. inflateBack() uses two subroutines supplied by the caller that are then
  74801. called by inflateBack() for input and output. inflateBack() calls those
  74802. routines until it reads a complete deflate stream and writes out all of the
  74803. uncompressed data, or until it encounters an error. The function's
  74804. parameters and return types are defined above in the in_func and out_func
  74805. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  74806. number of bytes of provided input, and a pointer to that input in buf. If
  74807. there is no input available, in() must return zero--buf is ignored in that
  74808. case--and inflateBack() will return a buffer error. inflateBack() will call
  74809. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  74810. should return zero on success, or non-zero on failure. If out() returns
  74811. non-zero, inflateBack() will return with an error. Neither in() nor out()
  74812. are permitted to change the contents of the window provided to
  74813. inflateBackInit(), which is also the buffer that out() uses to write from.
  74814. The length written by out() will be at most the window size. Any non-zero
  74815. amount of input may be provided by in().
  74816. For convenience, inflateBack() can be provided input on the first call by
  74817. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  74818. in() will be called. Therefore strm->next_in must be initialized before
  74819. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  74820. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  74821. must also be initialized, and then if strm->avail_in is not zero, input will
  74822. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  74823. The in_desc and out_desc parameters of inflateBack() is passed as the
  74824. first parameter of in() and out() respectively when they are called. These
  74825. descriptors can be optionally used to pass any information that the caller-
  74826. supplied in() and out() functions need to do their job.
  74827. On return, inflateBack() will set strm->next_in and strm->avail_in to
  74828. pass back any unused input that was provided by the last in() call. The
  74829. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  74830. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  74831. error in the deflate stream (in which case strm->msg is set to indicate the
  74832. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  74833. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  74834. distinguished using strm->next_in which will be Z_NULL only if in() returned
  74835. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  74836. out() returning non-zero. (in() will always be called before out(), so
  74837. strm->next_in is assured to be defined if out() returns non-zero.) Note
  74838. that inflateBack() cannot return Z_OK.
  74839. */
  74840. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  74841. /*
  74842. All memory allocated by inflateBackInit() is freed.
  74843. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  74844. state was inconsistent.
  74845. */
  74846. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  74847. /* Return flags indicating compile-time options.
  74848. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  74849. 1.0: size of uInt
  74850. 3.2: size of uLong
  74851. 5.4: size of voidpf (pointer)
  74852. 7.6: size of z_off_t
  74853. Compiler, assembler, and debug options:
  74854. 8: DEBUG
  74855. 9: ASMV or ASMINF -- use ASM code
  74856. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  74857. 11: 0 (reserved)
  74858. One-time table building (smaller code, but not thread-safe if true):
  74859. 12: BUILDFIXED -- build static block decoding tables when needed
  74860. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  74861. 14,15: 0 (reserved)
  74862. Library content (indicates missing functionality):
  74863. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  74864. deflate code when not needed)
  74865. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  74866. and decode gzip streams (to avoid linking crc code)
  74867. 18-19: 0 (reserved)
  74868. Operation variations (changes in library functionality):
  74869. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  74870. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  74871. 22,23: 0 (reserved)
  74872. The sprintf variant used by gzprintf (zero is best):
  74873. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  74874. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  74875. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  74876. Remainder:
  74877. 27-31: 0 (reserved)
  74878. */
  74879. /* utility functions */
  74880. /*
  74881. The following utility functions are implemented on top of the
  74882. basic stream-oriented functions. To simplify the interface, some
  74883. default options are assumed (compression level and memory usage,
  74884. standard memory allocation functions). The source code of these
  74885. utility functions can easily be modified if you need special options.
  74886. */
  74887. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  74888. const Bytef *source, uLong sourceLen));
  74889. /*
  74890. Compresses the source buffer into the destination buffer. sourceLen is
  74891. the byte length of the source buffer. Upon entry, destLen is the total
  74892. size of the destination buffer, which must be at least the value returned
  74893. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74894. compressed buffer.
  74895. This function can be used to compress a whole file at once if the
  74896. input file is mmap'ed.
  74897. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  74898. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74899. buffer.
  74900. */
  74901. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  74902. const Bytef *source, uLong sourceLen,
  74903. int level));
  74904. /*
  74905. Compresses the source buffer into the destination buffer. The level
  74906. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74907. length of the source buffer. Upon entry, destLen is the total size of the
  74908. destination buffer, which must be at least the value returned by
  74909. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74910. compressed buffer.
  74911. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74912. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74913. Z_STREAM_ERROR if the level parameter is invalid.
  74914. */
  74915. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  74916. /*
  74917. compressBound() returns an upper bound on the compressed size after
  74918. compress() or compress2() on sourceLen bytes. It would be used before
  74919. a compress() or compress2() call to allocate the destination buffer.
  74920. */
  74921. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  74922. const Bytef *source, uLong sourceLen));
  74923. /*
  74924. Decompresses the source buffer into the destination buffer. sourceLen is
  74925. the byte length of the source buffer. Upon entry, destLen is the total
  74926. size of the destination buffer, which must be large enough to hold the
  74927. entire uncompressed data. (The size of the uncompressed data must have
  74928. been saved previously by the compressor and transmitted to the decompressor
  74929. by some mechanism outside the scope of this compression library.)
  74930. Upon exit, destLen is the actual size of the compressed buffer.
  74931. This function can be used to decompress a whole file at once if the
  74932. input file is mmap'ed.
  74933. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  74934. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74935. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  74936. */
  74937. typedef voidp gzFile;
  74938. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  74939. /*
  74940. Opens a gzip (.gz) file for reading or writing. The mode parameter
  74941. is as in fopen ("rb" or "wb") but can also include a compression level
  74942. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  74943. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  74944. as in "wb1R". (See the description of deflateInit2 for more information
  74945. about the strategy parameter.)
  74946. gzopen can be used to read a file which is not in gzip format; in this
  74947. case gzread will directly read from the file without decompression.
  74948. gzopen returns NULL if the file could not be opened or if there was
  74949. insufficient memory to allocate the (de)compression state; errno
  74950. can be checked to distinguish the two cases (if errno is zero, the
  74951. zlib error is Z_MEM_ERROR). */
  74952. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  74953. /*
  74954. gzdopen() associates a gzFile with the file descriptor fd. File
  74955. descriptors are obtained from calls like open, dup, creat, pipe or
  74956. fileno (in the file has been previously opened with fopen).
  74957. The mode parameter is as in gzopen.
  74958. The next call of gzclose on the returned gzFile will also close the
  74959. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  74960. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  74961. gzdopen returns NULL if there was insufficient memory to allocate
  74962. the (de)compression state.
  74963. */
  74964. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  74965. /*
  74966. Dynamically update the compression level or strategy. See the description
  74967. of deflateInit2 for the meaning of these parameters.
  74968. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  74969. opened for writing.
  74970. */
  74971. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  74972. /*
  74973. Reads the given number of uncompressed bytes from the compressed file.
  74974. If the input file was not in gzip format, gzread copies the given number
  74975. of bytes into the buffer.
  74976. gzread returns the number of uncompressed bytes actually read (0 for
  74977. end of file, -1 for error). */
  74978. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  74979. voidpc buf, unsigned len));
  74980. /*
  74981. Writes the given number of uncompressed bytes into the compressed file.
  74982. gzwrite returns the number of uncompressed bytes actually written
  74983. (0 in case of error).
  74984. */
  74985. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  74986. /*
  74987. Converts, formats, and writes the args to the compressed file under
  74988. control of the format string, as in fprintf. gzprintf returns the number of
  74989. uncompressed bytes actually written (0 in case of error). The number of
  74990. uncompressed bytes written is limited to 4095. The caller should assure that
  74991. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  74992. return an error (0) with nothing written. In this case, there may also be a
  74993. buffer overflow with unpredictable consequences, which is possible only if
  74994. zlib was compiled with the insecure functions sprintf() or vsprintf()
  74995. because the secure snprintf() or vsnprintf() functions were not available.
  74996. */
  74997. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  74998. /*
  74999. Writes the given null-terminated string to the compressed file, excluding
  75000. the terminating null character.
  75001. gzputs returns the number of characters written, or -1 in case of error.
  75002. */
  75003. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  75004. /*
  75005. Reads bytes from the compressed file until len-1 characters are read, or
  75006. a newline character is read and transferred to buf, or an end-of-file
  75007. condition is encountered. The string is then terminated with a null
  75008. character.
  75009. gzgets returns buf, or Z_NULL in case of error.
  75010. */
  75011. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  75012. /*
  75013. Writes c, converted to an unsigned char, into the compressed file.
  75014. gzputc returns the value that was written, or -1 in case of error.
  75015. */
  75016. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  75017. /*
  75018. Reads one byte from the compressed file. gzgetc returns this byte
  75019. or -1 in case of end of file or error.
  75020. */
  75021. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  75022. /*
  75023. Push one character back onto the stream to be read again later.
  75024. Only one character of push-back is allowed. gzungetc() returns the
  75025. character pushed, or -1 on failure. gzungetc() will fail if a
  75026. character has been pushed but not read yet, or if c is -1. The pushed
  75027. character will be discarded if the stream is repositioned with gzseek()
  75028. or gzrewind().
  75029. */
  75030. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  75031. /*
  75032. Flushes all pending output into the compressed file. The parameter
  75033. flush is as in the deflate() function. The return value is the zlib
  75034. error number (see function gzerror below). gzflush returns Z_OK if
  75035. the flush parameter is Z_FINISH and all output could be flushed.
  75036. gzflush should be called only when strictly necessary because it can
  75037. degrade compression.
  75038. */
  75039. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  75040. z_off_t offset, int whence));
  75041. /*
  75042. Sets the starting position for the next gzread or gzwrite on the
  75043. given compressed file. The offset represents a number of bytes in the
  75044. uncompressed data stream. The whence parameter is defined as in lseek(2);
  75045. the value SEEK_END is not supported.
  75046. If the file is opened for reading, this function is emulated but can be
  75047. extremely slow. If the file is opened for writing, only forward seeks are
  75048. supported; gzseek then compresses a sequence of zeroes up to the new
  75049. starting position.
  75050. gzseek returns the resulting offset location as measured in bytes from
  75051. the beginning of the uncompressed stream, or -1 in case of error, in
  75052. particular if the file is opened for writing and the new starting position
  75053. would be before the current position.
  75054. */
  75055. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  75056. /*
  75057. Rewinds the given file. This function is supported only for reading.
  75058. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  75059. */
  75060. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  75061. /*
  75062. Returns the starting position for the next gzread or gzwrite on the
  75063. given compressed file. This position represents a number of bytes in the
  75064. uncompressed data stream.
  75065. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  75066. */
  75067. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  75068. /*
  75069. Returns 1 when EOF has previously been detected reading the given
  75070. input stream, otherwise zero.
  75071. */
  75072. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  75073. /*
  75074. Returns 1 if file is being read directly without decompression, otherwise
  75075. zero.
  75076. */
  75077. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  75078. /*
  75079. Flushes all pending output if necessary, closes the compressed file
  75080. and deallocates all the (de)compression state. The return value is the zlib
  75081. error number (see function gzerror below).
  75082. */
  75083. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  75084. /*
  75085. Returns the error message for the last error which occurred on the
  75086. given compressed file. errnum is set to zlib error number. If an
  75087. error occurred in the file system and not in the compression library,
  75088. errnum is set to Z_ERRNO and the application may consult errno
  75089. to get the exact error code.
  75090. */
  75091. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  75092. /*
  75093. Clears the error and end-of-file flags for file. This is analogous to the
  75094. clearerr() function in stdio. This is useful for continuing to read a gzip
  75095. file that is being written concurrently.
  75096. */
  75097. /* checksum functions */
  75098. /*
  75099. These functions are not related to compression but are exported
  75100. anyway because they might be useful in applications using the
  75101. compression library.
  75102. */
  75103. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  75104. /*
  75105. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  75106. return the updated checksum. If buf is NULL, this function returns
  75107. the required initial value for the checksum.
  75108. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  75109. much faster. Usage example:
  75110. uLong adler = adler32(0L, Z_NULL, 0);
  75111. while (read_buffer(buffer, length) != EOF) {
  75112. adler = adler32(adler, buffer, length);
  75113. }
  75114. if (adler != original_adler) error();
  75115. */
  75116. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  75117. z_off_t len2));
  75118. /*
  75119. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  75120. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  75121. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  75122. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  75123. */
  75124. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  75125. /*
  75126. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  75127. updated CRC-32. If buf is NULL, this function returns the required initial
  75128. value for the for the crc. Pre- and post-conditioning (one's complement) is
  75129. performed within this function so it shouldn't be done by the application.
  75130. Usage example:
  75131. uLong crc = crc32(0L, Z_NULL, 0);
  75132. while (read_buffer(buffer, length) != EOF) {
  75133. crc = crc32(crc, buffer, length);
  75134. }
  75135. if (crc != original_crc) error();
  75136. */
  75137. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  75138. /*
  75139. Combine two CRC-32 check values into one. For two sequences of bytes,
  75140. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  75141. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  75142. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  75143. len2.
  75144. */
  75145. /* various hacks, don't look :) */
  75146. /* deflateInit and inflateInit are macros to allow checking the zlib version
  75147. * and the compiler's view of z_stream:
  75148. */
  75149. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  75150. const char *version, int stream_size));
  75151. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  75152. const char *version, int stream_size));
  75153. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  75154. int windowBits, int memLevel,
  75155. int strategy, const char *version,
  75156. int stream_size));
  75157. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  75158. const char *version, int stream_size));
  75159. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  75160. unsigned char FAR *window,
  75161. const char *version,
  75162. int stream_size));
  75163. #define deflateInit(strm, level) \
  75164. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  75165. #define inflateInit(strm) \
  75166. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  75167. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  75168. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  75169. (strategy), ZLIB_VERSION, sizeof(z_stream))
  75170. #define inflateInit2(strm, windowBits) \
  75171. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  75172. #define inflateBackInit(strm, windowBits, window) \
  75173. inflateBackInit_((strm), (windowBits), (window), \
  75174. ZLIB_VERSION, sizeof(z_stream))
  75175. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  75176. struct internal_state {int dummy;}; /* hack for buggy compilers */
  75177. #endif
  75178. ZEXTERN const char * ZEXPORT zError OF((int));
  75179. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  75180. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  75181. #ifdef __cplusplus
  75182. }
  75183. #endif
  75184. #endif /* ZLIB_H */
  75185. /********* End of inlined file: zlib.h *********/
  75186. #undef OS_CODE
  75187. #else
  75188. #include <zlib.h>
  75189. #endif
  75190. }
  75191. BEGIN_JUCE_NAMESPACE
  75192. using namespace zlibNamespace;
  75193. // internal helper object that holds the zlib structures so they don't have to be
  75194. // included publicly.
  75195. class GZIPCompressorHelper
  75196. {
  75197. private:
  75198. z_stream* stream;
  75199. uint8* data;
  75200. int dataSize, compLevel, strategy;
  75201. bool setParams;
  75202. public:
  75203. bool finished, shouldFinish;
  75204. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  75205. : data (0),
  75206. dataSize (0),
  75207. compLevel (compressionLevel),
  75208. strategy (0),
  75209. setParams (true),
  75210. finished (false),
  75211. shouldFinish (false)
  75212. {
  75213. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  75214. if (deflateInit2 (stream,
  75215. compLevel,
  75216. Z_DEFLATED,
  75217. nowrap ? -MAX_WBITS : MAX_WBITS,
  75218. 8,
  75219. strategy) != Z_OK)
  75220. {
  75221. juce_free (stream);
  75222. stream = 0;
  75223. }
  75224. }
  75225. ~GZIPCompressorHelper()
  75226. {
  75227. if (stream != 0)
  75228. {
  75229. deflateEnd (stream);
  75230. juce_free (stream);
  75231. }
  75232. }
  75233. bool needsInput() const throw()
  75234. {
  75235. return dataSize <= 0;
  75236. }
  75237. void setInput (uint8* const newData, const int size) throw()
  75238. {
  75239. data = newData;
  75240. dataSize = size;
  75241. }
  75242. int doNextBlock (uint8* const dest, const int destSize) throw()
  75243. {
  75244. if (stream != 0)
  75245. {
  75246. stream->next_in = data;
  75247. stream->next_out = dest;
  75248. stream->avail_in = dataSize;
  75249. stream->avail_out = destSize;
  75250. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  75251. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  75252. setParams = false;
  75253. switch (result)
  75254. {
  75255. case Z_STREAM_END:
  75256. finished = true;
  75257. case Z_OK:
  75258. data += dataSize - stream->avail_in;
  75259. dataSize = stream->avail_in;
  75260. return destSize - stream->avail_out;
  75261. default:
  75262. break;
  75263. }
  75264. }
  75265. return 0;
  75266. }
  75267. };
  75268. const int gzipCompBufferSize = 32768;
  75269. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  75270. int compressionLevel,
  75271. const bool deleteDestStream_,
  75272. const bool noWrap)
  75273. : destStream (destStream_),
  75274. deleteDestStream (deleteDestStream_)
  75275. {
  75276. if (compressionLevel < 1 || compressionLevel > 9)
  75277. compressionLevel = -1;
  75278. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  75279. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  75280. }
  75281. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  75282. {
  75283. flush();
  75284. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75285. delete h;
  75286. juce_free (buffer);
  75287. if (deleteDestStream)
  75288. delete destStream;
  75289. }
  75290. void GZIPCompressorOutputStream::flush()
  75291. {
  75292. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75293. if (! h->finished)
  75294. {
  75295. h->shouldFinish = true;
  75296. while (! h->finished)
  75297. doNextBlock();
  75298. }
  75299. destStream->flush();
  75300. }
  75301. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  75302. {
  75303. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75304. if (! h->finished)
  75305. {
  75306. h->setInput ((uint8*) destBuffer, howMany);
  75307. while (! h->needsInput())
  75308. {
  75309. if (! doNextBlock())
  75310. return false;
  75311. }
  75312. }
  75313. return true;
  75314. }
  75315. bool GZIPCompressorOutputStream::doNextBlock()
  75316. {
  75317. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75318. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  75319. if (len > 0)
  75320. return destStream->write (buffer, len);
  75321. else
  75322. return true;
  75323. }
  75324. int64 GZIPCompressorOutputStream::getPosition()
  75325. {
  75326. return destStream->getPosition();
  75327. }
  75328. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  75329. {
  75330. jassertfalse // can't do it!
  75331. return false;
  75332. }
  75333. END_JUCE_NAMESPACE
  75334. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  75335. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  75336. #if JUCE_MSVC
  75337. #pragma warning (push)
  75338. #pragma warning (disable: 4309 4305)
  75339. #endif
  75340. namespace zlibNamespace
  75341. {
  75342. #if JUCE_INCLUDE_ZLIB_CODE
  75343. extern "C"
  75344. {
  75345. #undef OS_CODE
  75346. #undef fdopen
  75347. #define ZLIB_INTERNAL
  75348. #define NO_DUMMY_DECL
  75349. /********* Start of inlined file: adler32.c *********/
  75350. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75351. #define ZLIB_INTERNAL
  75352. #define BASE 65521UL /* largest prime smaller than 65536 */
  75353. #define NMAX 5552
  75354. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  75355. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  75356. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  75357. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  75358. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  75359. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  75360. /* use NO_DIVIDE if your processor does not do division in hardware */
  75361. #ifdef NO_DIVIDE
  75362. # define MOD(a) \
  75363. do { \
  75364. if (a >= (BASE << 16)) a -= (BASE << 16); \
  75365. if (a >= (BASE << 15)) a -= (BASE << 15); \
  75366. if (a >= (BASE << 14)) a -= (BASE << 14); \
  75367. if (a >= (BASE << 13)) a -= (BASE << 13); \
  75368. if (a >= (BASE << 12)) a -= (BASE << 12); \
  75369. if (a >= (BASE << 11)) a -= (BASE << 11); \
  75370. if (a >= (BASE << 10)) a -= (BASE << 10); \
  75371. if (a >= (BASE << 9)) a -= (BASE << 9); \
  75372. if (a >= (BASE << 8)) a -= (BASE << 8); \
  75373. if (a >= (BASE << 7)) a -= (BASE << 7); \
  75374. if (a >= (BASE << 6)) a -= (BASE << 6); \
  75375. if (a >= (BASE << 5)) a -= (BASE << 5); \
  75376. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75377. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75378. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75379. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75380. if (a >= BASE) a -= BASE; \
  75381. } while (0)
  75382. # define MOD4(a) \
  75383. do { \
  75384. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75385. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75386. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75387. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75388. if (a >= BASE) a -= BASE; \
  75389. } while (0)
  75390. #else
  75391. # define MOD(a) a %= BASE
  75392. # define MOD4(a) a %= BASE
  75393. #endif
  75394. /* ========================================================================= */
  75395. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  75396. {
  75397. unsigned long sum2;
  75398. unsigned n;
  75399. /* split Adler-32 into component sums */
  75400. sum2 = (adler >> 16) & 0xffff;
  75401. adler &= 0xffff;
  75402. /* in case user likes doing a byte at a time, keep it fast */
  75403. if (len == 1) {
  75404. adler += buf[0];
  75405. if (adler >= BASE)
  75406. adler -= BASE;
  75407. sum2 += adler;
  75408. if (sum2 >= BASE)
  75409. sum2 -= BASE;
  75410. return adler | (sum2 << 16);
  75411. }
  75412. /* initial Adler-32 value (deferred check for len == 1 speed) */
  75413. if (buf == Z_NULL)
  75414. return 1L;
  75415. /* in case short lengths are provided, keep it somewhat fast */
  75416. if (len < 16) {
  75417. while (len--) {
  75418. adler += *buf++;
  75419. sum2 += adler;
  75420. }
  75421. if (adler >= BASE)
  75422. adler -= BASE;
  75423. MOD4(sum2); /* only added so many BASE's */
  75424. return adler | (sum2 << 16);
  75425. }
  75426. /* do length NMAX blocks -- requires just one modulo operation */
  75427. while (len >= NMAX) {
  75428. len -= NMAX;
  75429. n = NMAX / 16; /* NMAX is divisible by 16 */
  75430. do {
  75431. DO16(buf); /* 16 sums unrolled */
  75432. buf += 16;
  75433. } while (--n);
  75434. MOD(adler);
  75435. MOD(sum2);
  75436. }
  75437. /* do remaining bytes (less than NMAX, still just one modulo) */
  75438. if (len) { /* avoid modulos if none remaining */
  75439. while (len >= 16) {
  75440. len -= 16;
  75441. DO16(buf);
  75442. buf += 16;
  75443. }
  75444. while (len--) {
  75445. adler += *buf++;
  75446. sum2 += adler;
  75447. }
  75448. MOD(adler);
  75449. MOD(sum2);
  75450. }
  75451. /* return recombined sums */
  75452. return adler | (sum2 << 16);
  75453. }
  75454. /* ========================================================================= */
  75455. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  75456. {
  75457. unsigned long sum1;
  75458. unsigned long sum2;
  75459. unsigned rem;
  75460. /* the derivation of this formula is left as an exercise for the reader */
  75461. rem = (unsigned)(len2 % BASE);
  75462. sum1 = adler1 & 0xffff;
  75463. sum2 = rem * sum1;
  75464. MOD(sum2);
  75465. sum1 += (adler2 & 0xffff) + BASE - 1;
  75466. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  75467. if (sum1 > BASE) sum1 -= BASE;
  75468. if (sum1 > BASE) sum1 -= BASE;
  75469. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  75470. if (sum2 > BASE) sum2 -= BASE;
  75471. return sum1 | (sum2 << 16);
  75472. }
  75473. /********* End of inlined file: adler32.c *********/
  75474. /********* Start of inlined file: compress.c *********/
  75475. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75476. #define ZLIB_INTERNAL
  75477. /* ===========================================================================
  75478. Compresses the source buffer into the destination buffer. The level
  75479. parameter has the same meaning as in deflateInit. sourceLen is the byte
  75480. length of the source buffer. Upon entry, destLen is the total size of the
  75481. destination buffer, which must be at least 0.1% larger than sourceLen plus
  75482. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  75483. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75484. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  75485. Z_STREAM_ERROR if the level parameter is invalid.
  75486. */
  75487. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  75488. uLong sourceLen, int level)
  75489. {
  75490. z_stream stream;
  75491. int err;
  75492. stream.next_in = (Bytef*)source;
  75493. stream.avail_in = (uInt)sourceLen;
  75494. #ifdef MAXSEG_64K
  75495. /* Check for source > 64K on 16-bit machine: */
  75496. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  75497. #endif
  75498. stream.next_out = dest;
  75499. stream.avail_out = (uInt)*destLen;
  75500. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  75501. stream.zalloc = (alloc_func)0;
  75502. stream.zfree = (free_func)0;
  75503. stream.opaque = (voidpf)0;
  75504. err = deflateInit(&stream, level);
  75505. if (err != Z_OK) return err;
  75506. err = deflate(&stream, Z_FINISH);
  75507. if (err != Z_STREAM_END) {
  75508. deflateEnd(&stream);
  75509. return err == Z_OK ? Z_BUF_ERROR : err;
  75510. }
  75511. *destLen = stream.total_out;
  75512. err = deflateEnd(&stream);
  75513. return err;
  75514. }
  75515. /* ===========================================================================
  75516. */
  75517. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  75518. {
  75519. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  75520. }
  75521. /* ===========================================================================
  75522. If the default memLevel or windowBits for deflateInit() is changed, then
  75523. this function needs to be updated.
  75524. */
  75525. uLong ZEXPORT compressBound (uLong sourceLen)
  75526. {
  75527. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  75528. }
  75529. /********* End of inlined file: compress.c *********/
  75530. #undef DO1
  75531. #undef DO8
  75532. /********* Start of inlined file: crc32.c *********/
  75533. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75534. /*
  75535. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  75536. protection on the static variables used to control the first-use generation
  75537. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  75538. first call get_crc_table() to initialize the tables before allowing more than
  75539. one thread to use crc32().
  75540. */
  75541. #ifdef MAKECRCH
  75542. # include <stdio.h>
  75543. # ifndef DYNAMIC_CRC_TABLE
  75544. # define DYNAMIC_CRC_TABLE
  75545. # endif /* !DYNAMIC_CRC_TABLE */
  75546. #endif /* MAKECRCH */
  75547. /********* Start of inlined file: zutil.h *********/
  75548. /* WARNING: this file should *not* be used by applications. It is
  75549. part of the implementation of the compression library and is
  75550. subject to change. Applications should only use zlib.h.
  75551. */
  75552. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75553. #ifndef ZUTIL_H
  75554. #define ZUTIL_H
  75555. #define ZLIB_INTERNAL
  75556. #ifdef STDC
  75557. # ifndef _WIN32_WCE
  75558. # include <stddef.h>
  75559. # endif
  75560. # include <string.h>
  75561. # include <stdlib.h>
  75562. #endif
  75563. #ifdef NO_ERRNO_H
  75564. # ifdef _WIN32_WCE
  75565. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  75566. * errno. We define it as a global variable to simplify porting.
  75567. * Its value is always 0 and should not be used. We rename it to
  75568. * avoid conflict with other libraries that use the same workaround.
  75569. */
  75570. # define errno z_errno
  75571. # endif
  75572. extern int errno;
  75573. #else
  75574. # ifndef _WIN32_WCE
  75575. # include <errno.h>
  75576. # endif
  75577. #endif
  75578. #ifndef local
  75579. # define local static
  75580. #endif
  75581. /* compile with -Dlocal if your debugger can't find static symbols */
  75582. typedef unsigned char uch;
  75583. typedef uch FAR uchf;
  75584. typedef unsigned short ush;
  75585. typedef ush FAR ushf;
  75586. typedef unsigned long ulg;
  75587. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  75588. /* (size given to avoid silly warnings with Visual C++) */
  75589. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  75590. #define ERR_RETURN(strm,err) \
  75591. return (strm->msg = (char*)ERR_MSG(err), (err))
  75592. /* To be used only when the state is known to be valid */
  75593. /* common constants */
  75594. #ifndef DEF_WBITS
  75595. # define DEF_WBITS MAX_WBITS
  75596. #endif
  75597. /* default windowBits for decompression. MAX_WBITS is for compression only */
  75598. #if MAX_MEM_LEVEL >= 8
  75599. # define DEF_MEM_LEVEL 8
  75600. #else
  75601. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  75602. #endif
  75603. /* default memLevel */
  75604. #define STORED_BLOCK 0
  75605. #define STATIC_TREES 1
  75606. #define DYN_TREES 2
  75607. /* The three kinds of block type */
  75608. #define MIN_MATCH 3
  75609. #define MAX_MATCH 258
  75610. /* The minimum and maximum match lengths */
  75611. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  75612. /* target dependencies */
  75613. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  75614. # define OS_CODE 0x00
  75615. # if defined(__TURBOC__) || defined(__BORLANDC__)
  75616. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  75617. /* Allow compilation with ANSI keywords only enabled */
  75618. void _Cdecl farfree( void *block );
  75619. void *_Cdecl farmalloc( unsigned long nbytes );
  75620. # else
  75621. # include <alloc.h>
  75622. # endif
  75623. # else /* MSC or DJGPP */
  75624. # include <malloc.h>
  75625. # endif
  75626. #endif
  75627. #ifdef AMIGA
  75628. # define OS_CODE 0x01
  75629. #endif
  75630. #if defined(VAXC) || defined(VMS)
  75631. # define OS_CODE 0x02
  75632. # define F_OPEN(name, mode) \
  75633. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  75634. #endif
  75635. #if defined(ATARI) || defined(atarist)
  75636. # define OS_CODE 0x05
  75637. #endif
  75638. #ifdef OS2
  75639. # define OS_CODE 0x06
  75640. # ifdef M_I86
  75641. #include <malloc.h>
  75642. # endif
  75643. #endif
  75644. #if defined(MACOS) || TARGET_OS_MAC
  75645. # define OS_CODE 0x07
  75646. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  75647. # include <unix.h> /* for fdopen */
  75648. # else
  75649. # ifndef fdopen
  75650. # define fdopen(fd,mode) NULL /* No fdopen() */
  75651. # endif
  75652. # endif
  75653. #endif
  75654. #ifdef TOPS20
  75655. # define OS_CODE 0x0a
  75656. #endif
  75657. #ifdef WIN32
  75658. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  75659. # define OS_CODE 0x0b
  75660. # endif
  75661. #endif
  75662. #ifdef __50SERIES /* Prime/PRIMOS */
  75663. # define OS_CODE 0x0f
  75664. #endif
  75665. #if defined(_BEOS_) || defined(RISCOS)
  75666. # define fdopen(fd,mode) NULL /* No fdopen() */
  75667. #endif
  75668. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  75669. # if defined(_WIN32_WCE)
  75670. # define fdopen(fd,mode) NULL /* No fdopen() */
  75671. # ifndef _PTRDIFF_T_DEFINED
  75672. typedef int ptrdiff_t;
  75673. # define _PTRDIFF_T_DEFINED
  75674. # endif
  75675. # else
  75676. # define fdopen(fd,type) _fdopen(fd,type)
  75677. # endif
  75678. #endif
  75679. /* common defaults */
  75680. #ifndef OS_CODE
  75681. # define OS_CODE 0x03 /* assume Unix */
  75682. #endif
  75683. #ifndef F_OPEN
  75684. # define F_OPEN(name, mode) fopen((name), (mode))
  75685. #endif
  75686. /* functions */
  75687. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  75688. # ifndef HAVE_VSNPRINTF
  75689. # define HAVE_VSNPRINTF
  75690. # endif
  75691. #endif
  75692. #if defined(__CYGWIN__)
  75693. # ifndef HAVE_VSNPRINTF
  75694. # define HAVE_VSNPRINTF
  75695. # endif
  75696. #endif
  75697. #ifndef HAVE_VSNPRINTF
  75698. # ifdef MSDOS
  75699. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  75700. but for now we just assume it doesn't. */
  75701. # define NO_vsnprintf
  75702. # endif
  75703. # ifdef __TURBOC__
  75704. # define NO_vsnprintf
  75705. # endif
  75706. # ifdef WIN32
  75707. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  75708. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  75709. # define vsnprintf _vsnprintf
  75710. # endif
  75711. # endif
  75712. # ifdef __SASC
  75713. # define NO_vsnprintf
  75714. # endif
  75715. #endif
  75716. #ifdef VMS
  75717. # define NO_vsnprintf
  75718. #endif
  75719. #if defined(pyr)
  75720. # define NO_MEMCPY
  75721. #endif
  75722. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  75723. /* Use our own functions for small and medium model with MSC <= 5.0.
  75724. * You may have to use the same strategy for Borland C (untested).
  75725. * The __SC__ check is for Symantec.
  75726. */
  75727. # define NO_MEMCPY
  75728. #endif
  75729. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  75730. # define HAVE_MEMCPY
  75731. #endif
  75732. #ifdef HAVE_MEMCPY
  75733. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  75734. # define zmemcpy _fmemcpy
  75735. # define zmemcmp _fmemcmp
  75736. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  75737. # else
  75738. # define zmemcpy memcpy
  75739. # define zmemcmp memcmp
  75740. # define zmemzero(dest, len) memset(dest, 0, len)
  75741. # endif
  75742. #else
  75743. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  75744. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  75745. extern void zmemzero OF((Bytef* dest, uInt len));
  75746. #endif
  75747. /* Diagnostic functions */
  75748. #ifdef DEBUG
  75749. # include <stdio.h>
  75750. extern int z_verbose;
  75751. extern void z_error OF((const char *m));
  75752. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  75753. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  75754. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  75755. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  75756. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  75757. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  75758. #else
  75759. # define Assert(cond,msg)
  75760. # define Trace(x)
  75761. # define Tracev(x)
  75762. # define Tracevv(x)
  75763. # define Tracec(c,x)
  75764. # define Tracecv(c,x)
  75765. #endif
  75766. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  75767. void zcfree OF((voidpf opaque, voidpf ptr));
  75768. #define ZALLOC(strm, items, size) \
  75769. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  75770. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  75771. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  75772. #endif /* ZUTIL_H */
  75773. /********* End of inlined file: zutil.h *********/
  75774. /* for STDC and FAR definitions */
  75775. #define local static
  75776. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  75777. #ifndef NOBYFOUR
  75778. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  75779. # include <limits.h>
  75780. # define BYFOUR
  75781. # if (UINT_MAX == 0xffffffffUL)
  75782. typedef unsigned int u4;
  75783. # else
  75784. # if (ULONG_MAX == 0xffffffffUL)
  75785. typedef unsigned long u4;
  75786. # else
  75787. # if (USHRT_MAX == 0xffffffffUL)
  75788. typedef unsigned short u4;
  75789. # else
  75790. # undef BYFOUR /* can't find a four-byte integer type! */
  75791. # endif
  75792. # endif
  75793. # endif
  75794. # endif /* STDC */
  75795. #endif /* !NOBYFOUR */
  75796. /* Definitions for doing the crc four data bytes at a time. */
  75797. #ifdef BYFOUR
  75798. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  75799. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  75800. local unsigned long crc32_little OF((unsigned long,
  75801. const unsigned char FAR *, unsigned));
  75802. local unsigned long crc32_big OF((unsigned long,
  75803. const unsigned char FAR *, unsigned));
  75804. # define TBLS 8
  75805. #else
  75806. # define TBLS 1
  75807. #endif /* BYFOUR */
  75808. /* Local functions for crc concatenation */
  75809. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  75810. unsigned long vec));
  75811. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  75812. #ifdef DYNAMIC_CRC_TABLE
  75813. local volatile int crc_table_empty = 1;
  75814. local unsigned long FAR crc_table[TBLS][256];
  75815. local void make_crc_table OF((void));
  75816. #ifdef MAKECRCH
  75817. local void write_table OF((FILE *, const unsigned long FAR *));
  75818. #endif /* MAKECRCH */
  75819. /*
  75820. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  75821. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
  75822. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  75823. with the lowest powers in the most significant bit. Then adding polynomials
  75824. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  75825. one. If we call the above polynomial p, and represent a byte as the
  75826. polynomial q, also with the lowest power in the most significant bit (so the
  75827. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  75828. where a mod b means the remainder after dividing a by b.
  75829. This calculation is done using the shift-register method of multiplying and
  75830. taking the remainder. The register is initialized to zero, and for each
  75831. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  75832. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  75833. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  75834. out is a one). We start with the highest power (least significant bit) of
  75835. q and repeat for all eight bits of q.
  75836. The first table is simply the CRC of all possible eight bit values. This is
  75837. all the information needed to generate CRCs on data a byte at a time for all
  75838. combinations of CRC register values and incoming bytes. The remaining tables
  75839. allow for word-at-a-time CRC calculation for both big-endian and little-
  75840. endian machines, where a word is four bytes.
  75841. */
  75842. local void make_crc_table()
  75843. {
  75844. unsigned long c;
  75845. int n, k;
  75846. unsigned long poly; /* polynomial exclusive-or pattern */
  75847. /* terms of polynomial defining this crc (except x^32): */
  75848. static volatile int first = 1; /* flag to limit concurrent making */
  75849. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  75850. /* See if another task is already doing this (not thread-safe, but better
  75851. than nothing -- significantly reduces duration of vulnerability in
  75852. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  75853. if (first) {
  75854. first = 0;
  75855. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  75856. poly = 0UL;
  75857. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  75858. poly |= 1UL << (31 - p[n]);
  75859. /* generate a crc for every 8-bit value */
  75860. for (n = 0; n < 256; n++) {
  75861. c = (unsigned long)n;
  75862. for (k = 0; k < 8; k++)
  75863. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  75864. crc_table[0][n] = c;
  75865. }
  75866. #ifdef BYFOUR
  75867. /* generate crc for each value followed by one, two, and three zeros,
  75868. and then the byte reversal of those as well as the first table */
  75869. for (n = 0; n < 256; n++) {
  75870. c = crc_table[0][n];
  75871. crc_table[4][n] = REV(c);
  75872. for (k = 1; k < 4; k++) {
  75873. c = crc_table[0][c & 0xff] ^ (c >> 8);
  75874. crc_table[k][n] = c;
  75875. crc_table[k + 4][n] = REV(c);
  75876. }
  75877. }
  75878. #endif /* BYFOUR */
  75879. crc_table_empty = 0;
  75880. }
  75881. else { /* not first */
  75882. /* wait for the other guy to finish (not efficient, but rare) */
  75883. while (crc_table_empty)
  75884. ;
  75885. }
  75886. #ifdef MAKECRCH
  75887. /* write out CRC tables to crc32.h */
  75888. {
  75889. FILE *out;
  75890. out = fopen("crc32.h", "w");
  75891. if (out == NULL) return;
  75892. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  75893. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  75894. fprintf(out, "local const unsigned long FAR ");
  75895. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  75896. write_table(out, crc_table[0]);
  75897. # ifdef BYFOUR
  75898. fprintf(out, "#ifdef BYFOUR\n");
  75899. for (k = 1; k < 8; k++) {
  75900. fprintf(out, " },\n {\n");
  75901. write_table(out, crc_table[k]);
  75902. }
  75903. fprintf(out, "#endif\n");
  75904. # endif /* BYFOUR */
  75905. fprintf(out, " }\n};\n");
  75906. fclose(out);
  75907. }
  75908. #endif /* MAKECRCH */
  75909. }
  75910. #ifdef MAKECRCH
  75911. local void write_table(out, table)
  75912. FILE *out;
  75913. const unsigned long FAR *table;
  75914. {
  75915. int n;
  75916. for (n = 0; n < 256; n++)
  75917. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  75918. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  75919. }
  75920. #endif /* MAKECRCH */
  75921. #else /* !DYNAMIC_CRC_TABLE */
  75922. /* ========================================================================
  75923. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  75924. */
  75925. /********* Start of inlined file: crc32.h *********/
  75926. local const unsigned long FAR crc_table[TBLS][256] =
  75927. {
  75928. {
  75929. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  75930. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  75931. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  75932. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  75933. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  75934. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  75935. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  75936. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  75937. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  75938. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  75939. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  75940. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  75941. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  75942. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  75943. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  75944. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  75945. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  75946. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  75947. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  75948. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  75949. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  75950. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  75951. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  75952. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  75953. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  75954. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  75955. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  75956. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  75957. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  75958. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  75959. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  75960. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  75961. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  75962. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  75963. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  75964. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  75965. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  75966. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  75967. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  75968. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  75969. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  75970. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  75971. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  75972. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  75973. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  75974. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  75975. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  75976. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  75977. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  75978. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  75979. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  75980. 0x2d02ef8dUL
  75981. #ifdef BYFOUR
  75982. },
  75983. {
  75984. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  75985. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  75986. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  75987. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  75988. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  75989. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  75990. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  75991. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  75992. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  75993. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  75994. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  75995. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  75996. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  75997. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  75998. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  75999. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  76000. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  76001. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  76002. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  76003. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  76004. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  76005. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  76006. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  76007. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  76008. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  76009. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  76010. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  76011. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  76012. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  76013. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  76014. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  76015. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  76016. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  76017. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  76018. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  76019. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  76020. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  76021. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  76022. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  76023. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  76024. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  76025. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  76026. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  76027. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  76028. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  76029. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  76030. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  76031. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  76032. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  76033. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  76034. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  76035. 0x9324fd72UL
  76036. },
  76037. {
  76038. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  76039. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  76040. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  76041. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  76042. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  76043. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  76044. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  76045. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  76046. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  76047. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  76048. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  76049. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  76050. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  76051. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  76052. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  76053. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  76054. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  76055. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  76056. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  76057. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  76058. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  76059. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  76060. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  76061. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  76062. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  76063. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  76064. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  76065. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  76066. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  76067. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  76068. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  76069. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  76070. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  76071. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  76072. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  76073. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  76074. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  76075. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  76076. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  76077. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  76078. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  76079. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  76080. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  76081. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  76082. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  76083. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  76084. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  76085. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  76086. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  76087. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  76088. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  76089. 0xbe9834edUL
  76090. },
  76091. {
  76092. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  76093. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  76094. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  76095. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  76096. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  76097. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  76098. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  76099. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  76100. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  76101. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  76102. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  76103. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  76104. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  76105. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  76106. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  76107. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  76108. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  76109. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  76110. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  76111. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  76112. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  76113. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  76114. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  76115. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  76116. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  76117. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  76118. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  76119. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  76120. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  76121. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  76122. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  76123. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  76124. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  76125. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  76126. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  76127. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  76128. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  76129. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  76130. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  76131. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  76132. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  76133. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  76134. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  76135. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  76136. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  76137. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  76138. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  76139. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  76140. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  76141. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  76142. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  76143. 0xde0506f1UL
  76144. },
  76145. {
  76146. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  76147. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  76148. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  76149. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  76150. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  76151. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  76152. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  76153. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  76154. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  76155. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  76156. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  76157. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  76158. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  76159. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  76160. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  76161. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  76162. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  76163. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  76164. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  76165. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  76166. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  76167. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  76168. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  76169. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  76170. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  76171. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  76172. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  76173. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  76174. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  76175. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  76176. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  76177. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  76178. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  76179. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  76180. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  76181. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  76182. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  76183. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  76184. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  76185. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  76186. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  76187. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  76188. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  76189. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  76190. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  76191. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  76192. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  76193. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  76194. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  76195. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  76196. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  76197. 0x8def022dUL
  76198. },
  76199. {
  76200. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  76201. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  76202. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  76203. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  76204. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  76205. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  76206. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  76207. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  76208. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  76209. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  76210. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  76211. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  76212. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  76213. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  76214. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  76215. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  76216. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  76217. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  76218. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  76219. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  76220. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  76221. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  76222. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  76223. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  76224. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  76225. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  76226. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  76227. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  76228. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  76229. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  76230. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  76231. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  76232. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  76233. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  76234. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  76235. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  76236. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  76237. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  76238. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  76239. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  76240. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  76241. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  76242. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  76243. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  76244. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  76245. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  76246. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  76247. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  76248. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  76249. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  76250. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  76251. 0x72fd2493UL
  76252. },
  76253. {
  76254. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  76255. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  76256. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  76257. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  76258. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  76259. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  76260. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  76261. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  76262. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  76263. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  76264. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  76265. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  76266. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  76267. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  76268. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  76269. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  76270. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  76271. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  76272. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  76273. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  76274. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  76275. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  76276. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  76277. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  76278. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  76279. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  76280. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  76281. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  76282. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  76283. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  76284. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  76285. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  76286. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  76287. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  76288. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  76289. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  76290. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  76291. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  76292. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  76293. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  76294. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  76295. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  76296. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  76297. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  76298. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  76299. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  76300. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  76301. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  76302. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  76303. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  76304. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  76305. 0xed3498beUL
  76306. },
  76307. {
  76308. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  76309. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  76310. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  76311. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  76312. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  76313. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  76314. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  76315. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  76316. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  76317. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  76318. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  76319. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  76320. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  76321. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  76322. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  76323. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  76324. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  76325. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  76326. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  76327. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  76328. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  76329. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  76330. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  76331. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  76332. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  76333. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  76334. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  76335. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  76336. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  76337. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  76338. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  76339. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  76340. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  76341. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  76342. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  76343. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  76344. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  76345. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  76346. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  76347. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  76348. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  76349. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  76350. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  76351. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  76352. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  76353. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  76354. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  76355. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  76356. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  76357. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  76358. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  76359. 0xf10605deUL
  76360. #endif
  76361. }
  76362. };
  76363. /********* End of inlined file: crc32.h *********/
  76364. #endif /* DYNAMIC_CRC_TABLE */
  76365. /* =========================================================================
  76366. * This function can be used by asm versions of crc32()
  76367. */
  76368. const unsigned long FAR * ZEXPORT get_crc_table()
  76369. {
  76370. #ifdef DYNAMIC_CRC_TABLE
  76371. if (crc_table_empty)
  76372. make_crc_table();
  76373. #endif /* DYNAMIC_CRC_TABLE */
  76374. return (const unsigned long FAR *)crc_table;
  76375. }
  76376. /* ========================================================================= */
  76377. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  76378. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  76379. /* ========================================================================= */
  76380. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76381. {
  76382. if (buf == Z_NULL) return 0UL;
  76383. #ifdef DYNAMIC_CRC_TABLE
  76384. if (crc_table_empty)
  76385. make_crc_table();
  76386. #endif /* DYNAMIC_CRC_TABLE */
  76387. #ifdef BYFOUR
  76388. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  76389. u4 endian;
  76390. endian = 1;
  76391. if (*((unsigned char *)(&endian)))
  76392. return crc32_little(crc, buf, len);
  76393. else
  76394. return crc32_big(crc, buf, len);
  76395. }
  76396. #endif /* BYFOUR */
  76397. crc = crc ^ 0xffffffffUL;
  76398. while (len >= 8) {
  76399. DO8;
  76400. len -= 8;
  76401. }
  76402. if (len) do {
  76403. DO1;
  76404. } while (--len);
  76405. return crc ^ 0xffffffffUL;
  76406. }
  76407. #ifdef BYFOUR
  76408. /* ========================================================================= */
  76409. #define DOLIT4 c ^= *buf4++; \
  76410. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  76411. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  76412. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  76413. /* ========================================================================= */
  76414. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76415. {
  76416. register u4 c;
  76417. register const u4 FAR *buf4;
  76418. c = (u4)crc;
  76419. c = ~c;
  76420. while (len && ((ptrdiff_t)buf & 3)) {
  76421. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76422. len--;
  76423. }
  76424. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76425. while (len >= 32) {
  76426. DOLIT32;
  76427. len -= 32;
  76428. }
  76429. while (len >= 4) {
  76430. DOLIT4;
  76431. len -= 4;
  76432. }
  76433. buf = (const unsigned char FAR *)buf4;
  76434. if (len) do {
  76435. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76436. } while (--len);
  76437. c = ~c;
  76438. return (unsigned long)c;
  76439. }
  76440. /* ========================================================================= */
  76441. #define DOBIG4 c ^= *++buf4; \
  76442. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  76443. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  76444. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  76445. /* ========================================================================= */
  76446. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76447. {
  76448. register u4 c;
  76449. register const u4 FAR *buf4;
  76450. c = REV((u4)crc);
  76451. c = ~c;
  76452. while (len && ((ptrdiff_t)buf & 3)) {
  76453. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76454. len--;
  76455. }
  76456. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76457. buf4--;
  76458. while (len >= 32) {
  76459. DOBIG32;
  76460. len -= 32;
  76461. }
  76462. while (len >= 4) {
  76463. DOBIG4;
  76464. len -= 4;
  76465. }
  76466. buf4++;
  76467. buf = (const unsigned char FAR *)buf4;
  76468. if (len) do {
  76469. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76470. } while (--len);
  76471. c = ~c;
  76472. return (unsigned long)(REV(c));
  76473. }
  76474. #endif /* BYFOUR */
  76475. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  76476. /* ========================================================================= */
  76477. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  76478. {
  76479. unsigned long sum;
  76480. sum = 0;
  76481. while (vec) {
  76482. if (vec & 1)
  76483. sum ^= *mat;
  76484. vec >>= 1;
  76485. mat++;
  76486. }
  76487. return sum;
  76488. }
  76489. /* ========================================================================= */
  76490. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  76491. {
  76492. int n;
  76493. for (n = 0; n < GF2_DIM; n++)
  76494. square[n] = gf2_matrix_times(mat, mat[n]);
  76495. }
  76496. /* ========================================================================= */
  76497. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  76498. {
  76499. int n;
  76500. unsigned long row;
  76501. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  76502. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  76503. /* degenerate case */
  76504. if (len2 == 0)
  76505. return crc1;
  76506. /* put operator for one zero bit in odd */
  76507. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  76508. row = 1;
  76509. for (n = 1; n < GF2_DIM; n++) {
  76510. odd[n] = row;
  76511. row <<= 1;
  76512. }
  76513. /* put operator for two zero bits in even */
  76514. gf2_matrix_square(even, odd);
  76515. /* put operator for four zero bits in odd */
  76516. gf2_matrix_square(odd, even);
  76517. /* apply len2 zeros to crc1 (first square will put the operator for one
  76518. zero byte, eight zero bits, in even) */
  76519. do {
  76520. /* apply zeros operator for this bit of len2 */
  76521. gf2_matrix_square(even, odd);
  76522. if (len2 & 1)
  76523. crc1 = gf2_matrix_times(even, crc1);
  76524. len2 >>= 1;
  76525. /* if no more bits set, then done */
  76526. if (len2 == 0)
  76527. break;
  76528. /* another iteration of the loop with odd and even swapped */
  76529. gf2_matrix_square(odd, even);
  76530. if (len2 & 1)
  76531. crc1 = gf2_matrix_times(odd, crc1);
  76532. len2 >>= 1;
  76533. /* if no more bits set, then done */
  76534. } while (len2 != 0);
  76535. /* return combined crc */
  76536. crc1 ^= crc2;
  76537. return crc1;
  76538. }
  76539. /********* End of inlined file: crc32.c *********/
  76540. /********* Start of inlined file: deflate.c *********/
  76541. /*
  76542. * ALGORITHM
  76543. *
  76544. * The "deflation" process depends on being able to identify portions
  76545. * of the input text which are identical to earlier input (within a
  76546. * sliding window trailing behind the input currently being processed).
  76547. *
  76548. * The most straightforward technique turns out to be the fastest for
  76549. * most input files: try all possible matches and select the longest.
  76550. * The key feature of this algorithm is that insertions into the string
  76551. * dictionary are very simple and thus fast, and deletions are avoided
  76552. * completely. Insertions are performed at each input character, whereas
  76553. * string matches are performed only when the previous match ends. So it
  76554. * is preferable to spend more time in matches to allow very fast string
  76555. * insertions and avoid deletions. The matching algorithm for small
  76556. * strings is inspired from that of Rabin & Karp. A brute force approach
  76557. * is used to find longer strings when a small match has been found.
  76558. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  76559. * (by Leonid Broukhis).
  76560. * A previous version of this file used a more sophisticated algorithm
  76561. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  76562. * time, but has a larger average cost, uses more memory and is patented.
  76563. * However the F&G algorithm may be faster for some highly redundant
  76564. * files if the parameter max_chain_length (described below) is too large.
  76565. *
  76566. * ACKNOWLEDGEMENTS
  76567. *
  76568. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  76569. * I found it in 'freeze' written by Leonid Broukhis.
  76570. * Thanks to many people for bug reports and testing.
  76571. *
  76572. * REFERENCES
  76573. *
  76574. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  76575. * Available in http://www.ietf.org/rfc/rfc1951.txt
  76576. *
  76577. * A description of the Rabin and Karp algorithm is given in the book
  76578. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  76579. *
  76580. * Fiala,E.R., and Greene,D.H.
  76581. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  76582. *
  76583. */
  76584. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76585. /********* Start of inlined file: deflate.h *********/
  76586. /* WARNING: this file should *not* be used by applications. It is
  76587. part of the implementation of the compression library and is
  76588. subject to change. Applications should only use zlib.h.
  76589. */
  76590. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76591. #ifndef DEFLATE_H
  76592. #define DEFLATE_H
  76593. /* define NO_GZIP when compiling if you want to disable gzip header and
  76594. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  76595. the crc code when it is not needed. For shared libraries, gzip encoding
  76596. should be left enabled. */
  76597. #ifndef NO_GZIP
  76598. # define GZIP
  76599. #endif
  76600. #define NO_DUMMY_DECL
  76601. /* ===========================================================================
  76602. * Internal compression state.
  76603. */
  76604. #define LENGTH_CODES 29
  76605. /* number of length codes, not counting the special END_BLOCK code */
  76606. #define LITERALS 256
  76607. /* number of literal bytes 0..255 */
  76608. #define L_CODES (LITERALS+1+LENGTH_CODES)
  76609. /* number of Literal or Length codes, including the END_BLOCK code */
  76610. #define D_CODES 30
  76611. /* number of distance codes */
  76612. #define BL_CODES 19
  76613. /* number of codes used to transfer the bit lengths */
  76614. #define HEAP_SIZE (2*L_CODES+1)
  76615. /* maximum heap size */
  76616. #define MAX_BITS 15
  76617. /* All codes must not exceed MAX_BITS bits */
  76618. #define INIT_STATE 42
  76619. #define EXTRA_STATE 69
  76620. #define NAME_STATE 73
  76621. #define COMMENT_STATE 91
  76622. #define HCRC_STATE 103
  76623. #define BUSY_STATE 113
  76624. #define FINISH_STATE 666
  76625. /* Stream status */
  76626. /* Data structure describing a single value and its code string. */
  76627. typedef struct ct_data_s {
  76628. union {
  76629. ush freq; /* frequency count */
  76630. ush code; /* bit string */
  76631. } fc;
  76632. union {
  76633. ush dad; /* father node in Huffman tree */
  76634. ush len; /* length of bit string */
  76635. } dl;
  76636. } FAR ct_data;
  76637. #define Freq fc.freq
  76638. #define Code fc.code
  76639. #define Dad dl.dad
  76640. #define Len dl.len
  76641. typedef struct static_tree_desc_s static_tree_desc;
  76642. typedef struct tree_desc_s {
  76643. ct_data *dyn_tree; /* the dynamic tree */
  76644. int max_code; /* largest code with non zero frequency */
  76645. static_tree_desc *stat_desc; /* the corresponding static tree */
  76646. } FAR tree_desc;
  76647. typedef ush Pos;
  76648. typedef Pos FAR Posf;
  76649. typedef unsigned IPos;
  76650. /* A Pos is an index in the character window. We use short instead of int to
  76651. * save space in the various tables. IPos is used only for parameter passing.
  76652. */
  76653. typedef struct internal_state {
  76654. z_streamp strm; /* pointer back to this zlib stream */
  76655. int status; /* as the name implies */
  76656. Bytef *pending_buf; /* output still pending */
  76657. ulg pending_buf_size; /* size of pending_buf */
  76658. Bytef *pending_out; /* next pending byte to output to the stream */
  76659. uInt pending; /* nb of bytes in the pending buffer */
  76660. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76661. gz_headerp gzhead; /* gzip header information to write */
  76662. uInt gzindex; /* where in extra, name, or comment */
  76663. Byte method; /* STORED (for zip only) or DEFLATED */
  76664. int last_flush; /* value of flush param for previous deflate call */
  76665. /* used by deflate.c: */
  76666. uInt w_size; /* LZ77 window size (32K by default) */
  76667. uInt w_bits; /* log2(w_size) (8..16) */
  76668. uInt w_mask; /* w_size - 1 */
  76669. Bytef *window;
  76670. /* Sliding window. Input bytes are read into the second half of the window,
  76671. * and move to the first half later to keep a dictionary of at least wSize
  76672. * bytes. With this organization, matches are limited to a distance of
  76673. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  76674. * performed with a length multiple of the block size. Also, it limits
  76675. * the window size to 64K, which is quite useful on MSDOS.
  76676. * To do: use the user input buffer as sliding window.
  76677. */
  76678. ulg window_size;
  76679. /* Actual size of window: 2*wSize, except when the user input buffer
  76680. * is directly used as sliding window.
  76681. */
  76682. Posf *prev;
  76683. /* Link to older string with same hash index. To limit the size of this
  76684. * array to 64K, this link is maintained only for the last 32K strings.
  76685. * An index in this array is thus a window index modulo 32K.
  76686. */
  76687. Posf *head; /* Heads of the hash chains or NIL. */
  76688. uInt ins_h; /* hash index of string to be inserted */
  76689. uInt hash_size; /* number of elements in hash table */
  76690. uInt hash_bits; /* log2(hash_size) */
  76691. uInt hash_mask; /* hash_size-1 */
  76692. uInt hash_shift;
  76693. /* Number of bits by which ins_h must be shifted at each input
  76694. * step. It must be such that after MIN_MATCH steps, the oldest
  76695. * byte no longer takes part in the hash key, that is:
  76696. * hash_shift * MIN_MATCH >= hash_bits
  76697. */
  76698. long block_start;
  76699. /* Window position at the beginning of the current output block. Gets
  76700. * negative when the window is moved backwards.
  76701. */
  76702. uInt match_length; /* length of best match */
  76703. IPos prev_match; /* previous match */
  76704. int match_available; /* set if previous match exists */
  76705. uInt strstart; /* start of string to insert */
  76706. uInt match_start; /* start of matching string */
  76707. uInt lookahead; /* number of valid bytes ahead in window */
  76708. uInt prev_length;
  76709. /* Length of the best match at previous step. Matches not greater than this
  76710. * are discarded. This is used in the lazy match evaluation.
  76711. */
  76712. uInt max_chain_length;
  76713. /* To speed up deflation, hash chains are never searched beyond this
  76714. * length. A higher limit improves compression ratio but degrades the
  76715. * speed.
  76716. */
  76717. uInt max_lazy_match;
  76718. /* Attempt to find a better match only when the current match is strictly
  76719. * smaller than this value. This mechanism is used only for compression
  76720. * levels >= 4.
  76721. */
  76722. # define max_insert_length max_lazy_match
  76723. /* Insert new strings in the hash table only if the match length is not
  76724. * greater than this length. This saves time but degrades compression.
  76725. * max_insert_length is used only for compression levels <= 3.
  76726. */
  76727. int level; /* compression level (1..9) */
  76728. int strategy; /* favor or force Huffman coding*/
  76729. uInt good_match;
  76730. /* Use a faster search when the previous match is longer than this */
  76731. int nice_match; /* Stop searching when current match exceeds this */
  76732. /* used by trees.c: */
  76733. /* Didn't use ct_data typedef below to supress compiler warning */
  76734. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  76735. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  76736. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  76737. struct tree_desc_s l_desc; /* desc. for literal tree */
  76738. struct tree_desc_s d_desc; /* desc. for distance tree */
  76739. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  76740. ush bl_count[MAX_BITS+1];
  76741. /* number of codes at each bit length for an optimal tree */
  76742. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  76743. int heap_len; /* number of elements in the heap */
  76744. int heap_max; /* element of largest frequency */
  76745. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  76746. * The same heap array is used to build all trees.
  76747. */
  76748. uch depth[2*L_CODES+1];
  76749. /* Depth of each subtree used as tie breaker for trees of equal frequency
  76750. */
  76751. uchf *l_buf; /* buffer for literals or lengths */
  76752. uInt lit_bufsize;
  76753. /* Size of match buffer for literals/lengths. There are 4 reasons for
  76754. * limiting lit_bufsize to 64K:
  76755. * - frequencies can be kept in 16 bit counters
  76756. * - if compression is not successful for the first block, all input
  76757. * data is still in the window so we can still emit a stored block even
  76758. * when input comes from standard input. (This can also be done for
  76759. * all blocks if lit_bufsize is not greater than 32K.)
  76760. * - if compression is not successful for a file smaller than 64K, we can
  76761. * even emit a stored file instead of a stored block (saving 5 bytes).
  76762. * This is applicable only for zip (not gzip or zlib).
  76763. * - creating new Huffman trees less frequently may not provide fast
  76764. * adaptation to changes in the input data statistics. (Take for
  76765. * example a binary file with poorly compressible code followed by
  76766. * a highly compressible string table.) Smaller buffer sizes give
  76767. * fast adaptation but have of course the overhead of transmitting
  76768. * trees more frequently.
  76769. * - I can't count above 4
  76770. */
  76771. uInt last_lit; /* running index in l_buf */
  76772. ushf *d_buf;
  76773. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  76774. * the same number of elements. To use different lengths, an extra flag
  76775. * array would be necessary.
  76776. */
  76777. ulg opt_len; /* bit length of current block with optimal trees */
  76778. ulg static_len; /* bit length of current block with static trees */
  76779. uInt matches; /* number of string matches in current block */
  76780. int last_eob_len; /* bit length of EOB code for last block */
  76781. #ifdef DEBUG
  76782. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  76783. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  76784. #endif
  76785. ush bi_buf;
  76786. /* Output buffer. bits are inserted starting at the bottom (least
  76787. * significant bits).
  76788. */
  76789. int bi_valid;
  76790. /* Number of valid bits in bi_buf. All bits above the last valid bit
  76791. * are always zero.
  76792. */
  76793. } FAR deflate_state;
  76794. /* Output a byte on the stream.
  76795. * IN assertion: there is enough room in pending_buf.
  76796. */
  76797. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  76798. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76799. /* Minimum amount of lookahead, except at the end of the input file.
  76800. * See deflate.c for comments about the MIN_MATCH+1.
  76801. */
  76802. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  76803. /* In order to simplify the code, particularly on 16 bit machines, match
  76804. * distances are limited to MAX_DIST instead of WSIZE.
  76805. */
  76806. /* in trees.c */
  76807. void _tr_init OF((deflate_state *s));
  76808. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  76809. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76810. int eof));
  76811. void _tr_align OF((deflate_state *s));
  76812. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76813. int eof));
  76814. #define d_code(dist) \
  76815. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  76816. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  76817. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  76818. * used.
  76819. */
  76820. #ifndef DEBUG
  76821. /* Inline versions of _tr_tally for speed: */
  76822. #if defined(GEN_TREES_H) || !defined(STDC)
  76823. extern uch _length_code[];
  76824. extern uch _dist_code[];
  76825. #else
  76826. extern const uch _length_code[];
  76827. extern const uch _dist_code[];
  76828. #endif
  76829. # define _tr_tally_lit(s, c, flush) \
  76830. { uch cc = (c); \
  76831. s->d_buf[s->last_lit] = 0; \
  76832. s->l_buf[s->last_lit++] = cc; \
  76833. s->dyn_ltree[cc].Freq++; \
  76834. flush = (s->last_lit == s->lit_bufsize-1); \
  76835. }
  76836. # define _tr_tally_dist(s, distance, length, flush) \
  76837. { uch len = (length); \
  76838. ush dist = (distance); \
  76839. s->d_buf[s->last_lit] = dist; \
  76840. s->l_buf[s->last_lit++] = len; \
  76841. dist--; \
  76842. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  76843. s->dyn_dtree[d_code(dist)].Freq++; \
  76844. flush = (s->last_lit == s->lit_bufsize-1); \
  76845. }
  76846. #else
  76847. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  76848. # define _tr_tally_dist(s, distance, length, flush) \
  76849. flush = _tr_tally(s, distance, length)
  76850. #endif
  76851. #endif /* DEFLATE_H */
  76852. /********* End of inlined file: deflate.h *********/
  76853. const char deflate_copyright[] =
  76854. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  76855. /*
  76856. If you use the zlib library in a product, an acknowledgment is welcome
  76857. in the documentation of your product. If for some reason you cannot
  76858. include such an acknowledgment, I would appreciate that you keep this
  76859. copyright string in the executable of your product.
  76860. */
  76861. /* ===========================================================================
  76862. * Function prototypes.
  76863. */
  76864. typedef enum {
  76865. need_more, /* block not completed, need more input or more output */
  76866. block_done, /* block flush performed */
  76867. finish_started, /* finish started, need only more output at next deflate */
  76868. finish_done /* finish done, accept no more input or output */
  76869. } block_state;
  76870. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  76871. /* Compression function. Returns the block state after the call. */
  76872. local void fill_window OF((deflate_state *s));
  76873. local block_state deflate_stored OF((deflate_state *s, int flush));
  76874. local block_state deflate_fast OF((deflate_state *s, int flush));
  76875. #ifndef FASTEST
  76876. local block_state deflate_slow OF((deflate_state *s, int flush));
  76877. #endif
  76878. local void lm_init OF((deflate_state *s));
  76879. local void putShortMSB OF((deflate_state *s, uInt b));
  76880. local void flush_pending OF((z_streamp strm));
  76881. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  76882. #ifndef FASTEST
  76883. #ifdef ASMV
  76884. void match_init OF((void)); /* asm code initialization */
  76885. uInt longest_match OF((deflate_state *s, IPos cur_match));
  76886. #else
  76887. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  76888. #endif
  76889. #endif
  76890. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  76891. #ifdef DEBUG
  76892. local void check_match OF((deflate_state *s, IPos start, IPos match,
  76893. int length));
  76894. #endif
  76895. /* ===========================================================================
  76896. * Local data
  76897. */
  76898. #define NIL 0
  76899. /* Tail of hash chains */
  76900. #ifndef TOO_FAR
  76901. # define TOO_FAR 4096
  76902. #endif
  76903. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  76904. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76905. /* Minimum amount of lookahead, except at the end of the input file.
  76906. * See deflate.c for comments about the MIN_MATCH+1.
  76907. */
  76908. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  76909. * the desired pack level (0..9). The values given below have been tuned to
  76910. * exclude worst case performance for pathological files. Better values may be
  76911. * found for specific files.
  76912. */
  76913. typedef struct config_s {
  76914. ush good_length; /* reduce lazy search above this match length */
  76915. ush max_lazy; /* do not perform lazy search above this match length */
  76916. ush nice_length; /* quit search above this match length */
  76917. ush max_chain;
  76918. compress_func func;
  76919. } config;
  76920. #ifdef FASTEST
  76921. local const config configuration_table[2] = {
  76922. /* good lazy nice chain */
  76923. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76924. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  76925. #else
  76926. local const config configuration_table[10] = {
  76927. /* good lazy nice chain */
  76928. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76929. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  76930. /* 2 */ {4, 5, 16, 8, deflate_fast},
  76931. /* 3 */ {4, 6, 32, 32, deflate_fast},
  76932. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  76933. /* 5 */ {8, 16, 32, 32, deflate_slow},
  76934. /* 6 */ {8, 16, 128, 128, deflate_slow},
  76935. /* 7 */ {8, 32, 128, 256, deflate_slow},
  76936. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  76937. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  76938. #endif
  76939. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  76940. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  76941. * meaning.
  76942. */
  76943. #define EQUAL 0
  76944. /* result of memcmp for equal strings */
  76945. #ifndef NO_DUMMY_DECL
  76946. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  76947. #endif
  76948. /* ===========================================================================
  76949. * Update a hash value with the given input byte
  76950. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  76951. * input characters, so that a running hash key can be computed from the
  76952. * previous key instead of complete recalculation each time.
  76953. */
  76954. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  76955. /* ===========================================================================
  76956. * Insert string str in the dictionary and set match_head to the previous head
  76957. * of the hash chain (the most recent string with same hash key). Return
  76958. * the previous length of the hash chain.
  76959. * If this file is compiled with -DFASTEST, the compression level is forced
  76960. * to 1, and no hash chains are maintained.
  76961. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  76962. * input characters and the first MIN_MATCH bytes of str are valid
  76963. * (except for the last MIN_MATCH-1 bytes of the input file).
  76964. */
  76965. #ifdef FASTEST
  76966. #define INSERT_STRING(s, str, match_head) \
  76967. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76968. match_head = s->head[s->ins_h], \
  76969. s->head[s->ins_h] = (Pos)(str))
  76970. #else
  76971. #define INSERT_STRING(s, str, match_head) \
  76972. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76973. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  76974. s->head[s->ins_h] = (Pos)(str))
  76975. #endif
  76976. /* ===========================================================================
  76977. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  76978. * prev[] will be initialized on the fly.
  76979. */
  76980. #define CLEAR_HASH(s) \
  76981. s->head[s->hash_size-1] = NIL; \
  76982. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  76983. /* ========================================================================= */
  76984. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  76985. {
  76986. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  76987. Z_DEFAULT_STRATEGY, version, stream_size);
  76988. /* To do: ignore strm->next_in if we use it as window */
  76989. }
  76990. /* ========================================================================= */
  76991. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  76992. {
  76993. deflate_state *s;
  76994. int wrap = 1;
  76995. static const char my_version[] = ZLIB_VERSION;
  76996. ushf *overlay;
  76997. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  76998. * output size for (length,distance) codes is <= 24 bits.
  76999. */
  77000. if (version == Z_NULL || version[0] != my_version[0] ||
  77001. stream_size != sizeof(z_stream)) {
  77002. return Z_VERSION_ERROR;
  77003. }
  77004. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77005. strm->msg = Z_NULL;
  77006. if (strm->zalloc == (alloc_func)0) {
  77007. strm->zalloc = zcalloc;
  77008. strm->opaque = (voidpf)0;
  77009. }
  77010. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77011. #ifdef FASTEST
  77012. if (level != 0) level = 1;
  77013. #else
  77014. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77015. #endif
  77016. if (windowBits < 0) { /* suppress zlib wrapper */
  77017. wrap = 0;
  77018. windowBits = -windowBits;
  77019. }
  77020. #ifdef GZIP
  77021. else if (windowBits > 15) {
  77022. wrap = 2; /* write gzip wrapper instead */
  77023. windowBits -= 16;
  77024. }
  77025. #endif
  77026. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  77027. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  77028. strategy < 0 || strategy > Z_FIXED) {
  77029. return Z_STREAM_ERROR;
  77030. }
  77031. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  77032. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  77033. if (s == Z_NULL) return Z_MEM_ERROR;
  77034. strm->state = (struct internal_state FAR *)s;
  77035. s->strm = strm;
  77036. s->wrap = wrap;
  77037. s->gzhead = Z_NULL;
  77038. s->w_bits = windowBits;
  77039. s->w_size = 1 << s->w_bits;
  77040. s->w_mask = s->w_size - 1;
  77041. s->hash_bits = memLevel + 7;
  77042. s->hash_size = 1 << s->hash_bits;
  77043. s->hash_mask = s->hash_size - 1;
  77044. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  77045. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  77046. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  77047. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  77048. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  77049. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  77050. s->pending_buf = (uchf *) overlay;
  77051. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  77052. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  77053. s->pending_buf == Z_NULL) {
  77054. s->status = FINISH_STATE;
  77055. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  77056. deflateEnd (strm);
  77057. return Z_MEM_ERROR;
  77058. }
  77059. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  77060. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  77061. s->level = level;
  77062. s->strategy = strategy;
  77063. s->method = (Byte)method;
  77064. return deflateReset(strm);
  77065. }
  77066. /* ========================================================================= */
  77067. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  77068. {
  77069. deflate_state *s;
  77070. uInt length = dictLength;
  77071. uInt n;
  77072. IPos hash_head = 0;
  77073. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  77074. strm->state->wrap == 2 ||
  77075. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  77076. return Z_STREAM_ERROR;
  77077. s = strm->state;
  77078. if (s->wrap)
  77079. strm->adler = adler32(strm->adler, dictionary, dictLength);
  77080. if (length < MIN_MATCH) return Z_OK;
  77081. if (length > MAX_DIST(s)) {
  77082. length = MAX_DIST(s);
  77083. dictionary += dictLength - length; /* use the tail of the dictionary */
  77084. }
  77085. zmemcpy(s->window, dictionary, length);
  77086. s->strstart = length;
  77087. s->block_start = (long)length;
  77088. /* Insert all strings in the hash table (except for the last two bytes).
  77089. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  77090. * call of fill_window.
  77091. */
  77092. s->ins_h = s->window[0];
  77093. UPDATE_HASH(s, s->ins_h, s->window[1]);
  77094. for (n = 0; n <= length - MIN_MATCH; n++) {
  77095. INSERT_STRING(s, n, hash_head);
  77096. }
  77097. if (hash_head) hash_head = 0; /* to make compiler happy */
  77098. return Z_OK;
  77099. }
  77100. /* ========================================================================= */
  77101. int ZEXPORT deflateReset (z_streamp strm)
  77102. {
  77103. deflate_state *s;
  77104. if (strm == Z_NULL || strm->state == Z_NULL ||
  77105. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  77106. return Z_STREAM_ERROR;
  77107. }
  77108. strm->total_in = strm->total_out = 0;
  77109. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  77110. strm->data_type = Z_UNKNOWN;
  77111. s = (deflate_state *)strm->state;
  77112. s->pending = 0;
  77113. s->pending_out = s->pending_buf;
  77114. if (s->wrap < 0) {
  77115. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  77116. }
  77117. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  77118. strm->adler =
  77119. #ifdef GZIP
  77120. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  77121. #endif
  77122. adler32(0L, Z_NULL, 0);
  77123. s->last_flush = Z_NO_FLUSH;
  77124. _tr_init(s);
  77125. lm_init(s);
  77126. return Z_OK;
  77127. }
  77128. /* ========================================================================= */
  77129. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  77130. {
  77131. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77132. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  77133. strm->state->gzhead = head;
  77134. return Z_OK;
  77135. }
  77136. /* ========================================================================= */
  77137. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  77138. {
  77139. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77140. strm->state->bi_valid = bits;
  77141. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  77142. return Z_OK;
  77143. }
  77144. /* ========================================================================= */
  77145. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  77146. {
  77147. deflate_state *s;
  77148. compress_func func;
  77149. int err = Z_OK;
  77150. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77151. s = strm->state;
  77152. #ifdef FASTEST
  77153. if (level != 0) level = 1;
  77154. #else
  77155. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77156. #endif
  77157. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  77158. return Z_STREAM_ERROR;
  77159. }
  77160. func = configuration_table[s->level].func;
  77161. if (func != configuration_table[level].func && strm->total_in != 0) {
  77162. /* Flush the last buffer: */
  77163. err = deflate(strm, Z_PARTIAL_FLUSH);
  77164. }
  77165. if (s->level != level) {
  77166. s->level = level;
  77167. s->max_lazy_match = configuration_table[level].max_lazy;
  77168. s->good_match = configuration_table[level].good_length;
  77169. s->nice_match = configuration_table[level].nice_length;
  77170. s->max_chain_length = configuration_table[level].max_chain;
  77171. }
  77172. s->strategy = strategy;
  77173. return err;
  77174. }
  77175. /* ========================================================================= */
  77176. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  77177. {
  77178. deflate_state *s;
  77179. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77180. s = strm->state;
  77181. s->good_match = good_length;
  77182. s->max_lazy_match = max_lazy;
  77183. s->nice_match = nice_length;
  77184. s->max_chain_length = max_chain;
  77185. return Z_OK;
  77186. }
  77187. /* =========================================================================
  77188. * For the default windowBits of 15 and memLevel of 8, this function returns
  77189. * a close to exact, as well as small, upper bound on the compressed size.
  77190. * They are coded as constants here for a reason--if the #define's are
  77191. * changed, then this function needs to be changed as well. The return
  77192. * value for 15 and 8 only works for those exact settings.
  77193. *
  77194. * For any setting other than those defaults for windowBits and memLevel,
  77195. * the value returned is a conservative worst case for the maximum expansion
  77196. * resulting from using fixed blocks instead of stored blocks, which deflate
  77197. * can emit on compressed data for some combinations of the parameters.
  77198. *
  77199. * This function could be more sophisticated to provide closer upper bounds
  77200. * for every combination of windowBits and memLevel, as well as wrap.
  77201. * But even the conservative upper bound of about 14% expansion does not
  77202. * seem onerous for output buffer allocation.
  77203. */
  77204. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  77205. {
  77206. deflate_state *s;
  77207. uLong destLen;
  77208. /* conservative upper bound */
  77209. destLen = sourceLen +
  77210. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  77211. /* if can't get parameters, return conservative bound */
  77212. if (strm == Z_NULL || strm->state == Z_NULL)
  77213. return destLen;
  77214. /* if not default parameters, return conservative bound */
  77215. s = strm->state;
  77216. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  77217. return destLen;
  77218. /* default settings: return tight bound for that case */
  77219. return compressBound(sourceLen);
  77220. }
  77221. /* =========================================================================
  77222. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  77223. * IN assertion: the stream state is correct and there is enough room in
  77224. * pending_buf.
  77225. */
  77226. local void putShortMSB (deflate_state *s, uInt b)
  77227. {
  77228. put_byte(s, (Byte)(b >> 8));
  77229. put_byte(s, (Byte)(b & 0xff));
  77230. }
  77231. /* =========================================================================
  77232. * Flush as much pending output as possible. All deflate() output goes
  77233. * through this function so some applications may wish to modify it
  77234. * to avoid allocating a large strm->next_out buffer and copying into it.
  77235. * (See also read_buf()).
  77236. */
  77237. local void flush_pending (z_streamp strm)
  77238. {
  77239. unsigned len = strm->state->pending;
  77240. if (len > strm->avail_out) len = strm->avail_out;
  77241. if (len == 0) return;
  77242. zmemcpy(strm->next_out, strm->state->pending_out, len);
  77243. strm->next_out += len;
  77244. strm->state->pending_out += len;
  77245. strm->total_out += len;
  77246. strm->avail_out -= len;
  77247. strm->state->pending -= len;
  77248. if (strm->state->pending == 0) {
  77249. strm->state->pending_out = strm->state->pending_buf;
  77250. }
  77251. }
  77252. /* ========================================================================= */
  77253. int ZEXPORT deflate (z_streamp strm, int flush)
  77254. {
  77255. int old_flush; /* value of flush param for previous deflate call */
  77256. deflate_state *s;
  77257. if (strm == Z_NULL || strm->state == Z_NULL ||
  77258. flush > Z_FINISH || flush < 0) {
  77259. return Z_STREAM_ERROR;
  77260. }
  77261. s = strm->state;
  77262. if (strm->next_out == Z_NULL ||
  77263. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  77264. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  77265. ERR_RETURN(strm, Z_STREAM_ERROR);
  77266. }
  77267. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  77268. s->strm = strm; /* just in case */
  77269. old_flush = s->last_flush;
  77270. s->last_flush = flush;
  77271. /* Write the header */
  77272. if (s->status == INIT_STATE) {
  77273. #ifdef GZIP
  77274. if (s->wrap == 2) {
  77275. strm->adler = crc32(0L, Z_NULL, 0);
  77276. put_byte(s, 31);
  77277. put_byte(s, 139);
  77278. put_byte(s, 8);
  77279. if (s->gzhead == NULL) {
  77280. put_byte(s, 0);
  77281. put_byte(s, 0);
  77282. put_byte(s, 0);
  77283. put_byte(s, 0);
  77284. put_byte(s, 0);
  77285. put_byte(s, s->level == 9 ? 2 :
  77286. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77287. 4 : 0));
  77288. put_byte(s, OS_CODE);
  77289. s->status = BUSY_STATE;
  77290. }
  77291. else {
  77292. put_byte(s, (s->gzhead->text ? 1 : 0) +
  77293. (s->gzhead->hcrc ? 2 : 0) +
  77294. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  77295. (s->gzhead->name == Z_NULL ? 0 : 8) +
  77296. (s->gzhead->comment == Z_NULL ? 0 : 16)
  77297. );
  77298. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  77299. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  77300. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  77301. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  77302. put_byte(s, s->level == 9 ? 2 :
  77303. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77304. 4 : 0));
  77305. put_byte(s, s->gzhead->os & 0xff);
  77306. if (s->gzhead->extra != NULL) {
  77307. put_byte(s, s->gzhead->extra_len & 0xff);
  77308. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  77309. }
  77310. if (s->gzhead->hcrc)
  77311. strm->adler = crc32(strm->adler, s->pending_buf,
  77312. s->pending);
  77313. s->gzindex = 0;
  77314. s->status = EXTRA_STATE;
  77315. }
  77316. }
  77317. else
  77318. #endif
  77319. {
  77320. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  77321. uInt level_flags;
  77322. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  77323. level_flags = 0;
  77324. else if (s->level < 6)
  77325. level_flags = 1;
  77326. else if (s->level == 6)
  77327. level_flags = 2;
  77328. else
  77329. level_flags = 3;
  77330. header |= (level_flags << 6);
  77331. if (s->strstart != 0) header |= PRESET_DICT;
  77332. header += 31 - (header % 31);
  77333. s->status = BUSY_STATE;
  77334. putShortMSB(s, header);
  77335. /* Save the adler32 of the preset dictionary: */
  77336. if (s->strstart != 0) {
  77337. putShortMSB(s, (uInt)(strm->adler >> 16));
  77338. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77339. }
  77340. strm->adler = adler32(0L, Z_NULL, 0);
  77341. }
  77342. }
  77343. #ifdef GZIP
  77344. if (s->status == EXTRA_STATE) {
  77345. if (s->gzhead->extra != NULL) {
  77346. uInt beg = s->pending; /* start of bytes to update crc */
  77347. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  77348. if (s->pending == s->pending_buf_size) {
  77349. if (s->gzhead->hcrc && s->pending > beg)
  77350. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77351. s->pending - beg);
  77352. flush_pending(strm);
  77353. beg = s->pending;
  77354. if (s->pending == s->pending_buf_size)
  77355. break;
  77356. }
  77357. put_byte(s, s->gzhead->extra[s->gzindex]);
  77358. s->gzindex++;
  77359. }
  77360. if (s->gzhead->hcrc && s->pending > beg)
  77361. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77362. s->pending - beg);
  77363. if (s->gzindex == s->gzhead->extra_len) {
  77364. s->gzindex = 0;
  77365. s->status = NAME_STATE;
  77366. }
  77367. }
  77368. else
  77369. s->status = NAME_STATE;
  77370. }
  77371. if (s->status == NAME_STATE) {
  77372. if (s->gzhead->name != NULL) {
  77373. uInt beg = s->pending; /* start of bytes to update crc */
  77374. int val;
  77375. do {
  77376. if (s->pending == s->pending_buf_size) {
  77377. if (s->gzhead->hcrc && s->pending > beg)
  77378. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77379. s->pending - beg);
  77380. flush_pending(strm);
  77381. beg = s->pending;
  77382. if (s->pending == s->pending_buf_size) {
  77383. val = 1;
  77384. break;
  77385. }
  77386. }
  77387. val = s->gzhead->name[s->gzindex++];
  77388. put_byte(s, val);
  77389. } while (val != 0);
  77390. if (s->gzhead->hcrc && s->pending > beg)
  77391. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77392. s->pending - beg);
  77393. if (val == 0) {
  77394. s->gzindex = 0;
  77395. s->status = COMMENT_STATE;
  77396. }
  77397. }
  77398. else
  77399. s->status = COMMENT_STATE;
  77400. }
  77401. if (s->status == COMMENT_STATE) {
  77402. if (s->gzhead->comment != NULL) {
  77403. uInt beg = s->pending; /* start of bytes to update crc */
  77404. int val;
  77405. do {
  77406. if (s->pending == s->pending_buf_size) {
  77407. if (s->gzhead->hcrc && s->pending > beg)
  77408. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77409. s->pending - beg);
  77410. flush_pending(strm);
  77411. beg = s->pending;
  77412. if (s->pending == s->pending_buf_size) {
  77413. val = 1;
  77414. break;
  77415. }
  77416. }
  77417. val = s->gzhead->comment[s->gzindex++];
  77418. put_byte(s, val);
  77419. } while (val != 0);
  77420. if (s->gzhead->hcrc && s->pending > beg)
  77421. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77422. s->pending - beg);
  77423. if (val == 0)
  77424. s->status = HCRC_STATE;
  77425. }
  77426. else
  77427. s->status = HCRC_STATE;
  77428. }
  77429. if (s->status == HCRC_STATE) {
  77430. if (s->gzhead->hcrc) {
  77431. if (s->pending + 2 > s->pending_buf_size)
  77432. flush_pending(strm);
  77433. if (s->pending + 2 <= s->pending_buf_size) {
  77434. put_byte(s, (Byte)(strm->adler & 0xff));
  77435. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77436. strm->adler = crc32(0L, Z_NULL, 0);
  77437. s->status = BUSY_STATE;
  77438. }
  77439. }
  77440. else
  77441. s->status = BUSY_STATE;
  77442. }
  77443. #endif
  77444. /* Flush as much pending output as possible */
  77445. if (s->pending != 0) {
  77446. flush_pending(strm);
  77447. if (strm->avail_out == 0) {
  77448. /* Since avail_out is 0, deflate will be called again with
  77449. * more output space, but possibly with both pending and
  77450. * avail_in equal to zero. There won't be anything to do,
  77451. * but this is not an error situation so make sure we
  77452. * return OK instead of BUF_ERROR at next call of deflate:
  77453. */
  77454. s->last_flush = -1;
  77455. return Z_OK;
  77456. }
  77457. /* Make sure there is something to do and avoid duplicate consecutive
  77458. * flushes. For repeated and useless calls with Z_FINISH, we keep
  77459. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  77460. */
  77461. } else if (strm->avail_in == 0 && flush <= old_flush &&
  77462. flush != Z_FINISH) {
  77463. ERR_RETURN(strm, Z_BUF_ERROR);
  77464. }
  77465. /* User must not provide more input after the first FINISH: */
  77466. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  77467. ERR_RETURN(strm, Z_BUF_ERROR);
  77468. }
  77469. /* Start a new block or continue the current one.
  77470. */
  77471. if (strm->avail_in != 0 || s->lookahead != 0 ||
  77472. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  77473. block_state bstate;
  77474. bstate = (*(configuration_table[s->level].func))(s, flush);
  77475. if (bstate == finish_started || bstate == finish_done) {
  77476. s->status = FINISH_STATE;
  77477. }
  77478. if (bstate == need_more || bstate == finish_started) {
  77479. if (strm->avail_out == 0) {
  77480. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  77481. }
  77482. return Z_OK;
  77483. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  77484. * of deflate should use the same flush parameter to make sure
  77485. * that the flush is complete. So we don't have to output an
  77486. * empty block here, this will be done at next call. This also
  77487. * ensures that for a very small output buffer, we emit at most
  77488. * one empty block.
  77489. */
  77490. }
  77491. if (bstate == block_done) {
  77492. if (flush == Z_PARTIAL_FLUSH) {
  77493. _tr_align(s);
  77494. } else { /* FULL_FLUSH or SYNC_FLUSH */
  77495. _tr_stored_block(s, (char*)0, 0L, 0);
  77496. /* For a full flush, this empty block will be recognized
  77497. * as a special marker by inflate_sync().
  77498. */
  77499. if (flush == Z_FULL_FLUSH) {
  77500. CLEAR_HASH(s); /* forget history */
  77501. }
  77502. }
  77503. flush_pending(strm);
  77504. if (strm->avail_out == 0) {
  77505. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  77506. return Z_OK;
  77507. }
  77508. }
  77509. }
  77510. Assert(strm->avail_out > 0, "bug2");
  77511. if (flush != Z_FINISH) return Z_OK;
  77512. if (s->wrap <= 0) return Z_STREAM_END;
  77513. /* Write the trailer */
  77514. #ifdef GZIP
  77515. if (s->wrap == 2) {
  77516. put_byte(s, (Byte)(strm->adler & 0xff));
  77517. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77518. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  77519. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  77520. put_byte(s, (Byte)(strm->total_in & 0xff));
  77521. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  77522. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  77523. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  77524. }
  77525. else
  77526. #endif
  77527. {
  77528. putShortMSB(s, (uInt)(strm->adler >> 16));
  77529. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77530. }
  77531. flush_pending(strm);
  77532. /* If avail_out is zero, the application will call deflate again
  77533. * to flush the rest.
  77534. */
  77535. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  77536. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  77537. }
  77538. /* ========================================================================= */
  77539. int ZEXPORT deflateEnd (z_streamp strm)
  77540. {
  77541. int status;
  77542. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77543. status = strm->state->status;
  77544. if (status != INIT_STATE &&
  77545. status != EXTRA_STATE &&
  77546. status != NAME_STATE &&
  77547. status != COMMENT_STATE &&
  77548. status != HCRC_STATE &&
  77549. status != BUSY_STATE &&
  77550. status != FINISH_STATE) {
  77551. return Z_STREAM_ERROR;
  77552. }
  77553. /* Deallocate in reverse order of allocations: */
  77554. TRY_FREE(strm, strm->state->pending_buf);
  77555. TRY_FREE(strm, strm->state->head);
  77556. TRY_FREE(strm, strm->state->prev);
  77557. TRY_FREE(strm, strm->state->window);
  77558. ZFREE(strm, strm->state);
  77559. strm->state = Z_NULL;
  77560. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  77561. }
  77562. /* =========================================================================
  77563. * Copy the source state to the destination state.
  77564. * To simplify the source, this is not supported for 16-bit MSDOS (which
  77565. * doesn't have enough memory anyway to duplicate compression states).
  77566. */
  77567. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  77568. {
  77569. #ifdef MAXSEG_64K
  77570. return Z_STREAM_ERROR;
  77571. #else
  77572. deflate_state *ds;
  77573. deflate_state *ss;
  77574. ushf *overlay;
  77575. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  77576. return Z_STREAM_ERROR;
  77577. }
  77578. ss = source->state;
  77579. zmemcpy(dest, source, sizeof(z_stream));
  77580. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  77581. if (ds == Z_NULL) return Z_MEM_ERROR;
  77582. dest->state = (struct internal_state FAR *) ds;
  77583. zmemcpy(ds, ss, sizeof(deflate_state));
  77584. ds->strm = dest;
  77585. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  77586. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  77587. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  77588. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  77589. ds->pending_buf = (uchf *) overlay;
  77590. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  77591. ds->pending_buf == Z_NULL) {
  77592. deflateEnd (dest);
  77593. return Z_MEM_ERROR;
  77594. }
  77595. /* following zmemcpy do not work for 16-bit MSDOS */
  77596. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  77597. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  77598. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  77599. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  77600. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  77601. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  77602. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  77603. ds->l_desc.dyn_tree = ds->dyn_ltree;
  77604. ds->d_desc.dyn_tree = ds->dyn_dtree;
  77605. ds->bl_desc.dyn_tree = ds->bl_tree;
  77606. return Z_OK;
  77607. #endif /* MAXSEG_64K */
  77608. }
  77609. /* ===========================================================================
  77610. * Read a new buffer from the current input stream, update the adler32
  77611. * and total number of bytes read. All deflate() input goes through
  77612. * this function so some applications may wish to modify it to avoid
  77613. * allocating a large strm->next_in buffer and copying from it.
  77614. * (See also flush_pending()).
  77615. */
  77616. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  77617. {
  77618. unsigned len = strm->avail_in;
  77619. if (len > size) len = size;
  77620. if (len == 0) return 0;
  77621. strm->avail_in -= len;
  77622. if (strm->state->wrap == 1) {
  77623. strm->adler = adler32(strm->adler, strm->next_in, len);
  77624. }
  77625. #ifdef GZIP
  77626. else if (strm->state->wrap == 2) {
  77627. strm->adler = crc32(strm->adler, strm->next_in, len);
  77628. }
  77629. #endif
  77630. zmemcpy(buf, strm->next_in, len);
  77631. strm->next_in += len;
  77632. strm->total_in += len;
  77633. return (int)len;
  77634. }
  77635. /* ===========================================================================
  77636. * Initialize the "longest match" routines for a new zlib stream
  77637. */
  77638. local void lm_init (deflate_state *s)
  77639. {
  77640. s->window_size = (ulg)2L*s->w_size;
  77641. CLEAR_HASH(s);
  77642. /* Set the default configuration parameters:
  77643. */
  77644. s->max_lazy_match = configuration_table[s->level].max_lazy;
  77645. s->good_match = configuration_table[s->level].good_length;
  77646. s->nice_match = configuration_table[s->level].nice_length;
  77647. s->max_chain_length = configuration_table[s->level].max_chain;
  77648. s->strstart = 0;
  77649. s->block_start = 0L;
  77650. s->lookahead = 0;
  77651. s->match_length = s->prev_length = MIN_MATCH-1;
  77652. s->match_available = 0;
  77653. s->ins_h = 0;
  77654. #ifndef FASTEST
  77655. #ifdef ASMV
  77656. match_init(); /* initialize the asm code */
  77657. #endif
  77658. #endif
  77659. }
  77660. #ifndef FASTEST
  77661. /* ===========================================================================
  77662. * Set match_start to the longest match starting at the given string and
  77663. * return its length. Matches shorter or equal to prev_length are discarded,
  77664. * in which case the result is equal to prev_length and match_start is
  77665. * garbage.
  77666. * IN assertions: cur_match is the head of the hash chain for the current
  77667. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  77668. * OUT assertion: the match length is not greater than s->lookahead.
  77669. */
  77670. #ifndef ASMV
  77671. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  77672. * match.S. The code will be functionally equivalent.
  77673. */
  77674. local uInt longest_match(deflate_state *s, IPos cur_match)
  77675. {
  77676. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  77677. register Bytef *scan = s->window + s->strstart; /* current string */
  77678. register Bytef *match; /* matched string */
  77679. register int len; /* length of current match */
  77680. int best_len = s->prev_length; /* best match length so far */
  77681. int nice_match = s->nice_match; /* stop if match long enough */
  77682. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  77683. s->strstart - (IPos)MAX_DIST(s) : NIL;
  77684. /* Stop when cur_match becomes <= limit. To simplify the code,
  77685. * we prevent matches with the string of window index 0.
  77686. */
  77687. Posf *prev = s->prev;
  77688. uInt wmask = s->w_mask;
  77689. #ifdef UNALIGNED_OK
  77690. /* Compare two bytes at a time. Note: this is not always beneficial.
  77691. * Try with and without -DUNALIGNED_OK to check.
  77692. */
  77693. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  77694. register ush scan_start = *(ushf*)scan;
  77695. register ush scan_end = *(ushf*)(scan+best_len-1);
  77696. #else
  77697. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77698. register Byte scan_end1 = scan[best_len-1];
  77699. register Byte scan_end = scan[best_len];
  77700. #endif
  77701. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77702. * It is easy to get rid of this optimization if necessary.
  77703. */
  77704. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77705. /* Do not waste too much time if we already have a good match: */
  77706. if (s->prev_length >= s->good_match) {
  77707. chain_length >>= 2;
  77708. }
  77709. /* Do not look for matches beyond the end of the input. This is necessary
  77710. * to make deflate deterministic.
  77711. */
  77712. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  77713. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77714. do {
  77715. Assert(cur_match < s->strstart, "no future");
  77716. match = s->window + cur_match;
  77717. /* Skip to next match if the match length cannot increase
  77718. * or if the match length is less than 2. Note that the checks below
  77719. * for insufficient lookahead only occur occasionally for performance
  77720. * reasons. Therefore uninitialized memory will be accessed, and
  77721. * conditional jumps will be made that depend on those values.
  77722. * However the length of the match is limited to the lookahead, so
  77723. * the output of deflate is not affected by the uninitialized values.
  77724. */
  77725. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  77726. /* This code assumes sizeof(unsigned short) == 2. Do not use
  77727. * UNALIGNED_OK if your compiler uses a different size.
  77728. */
  77729. if (*(ushf*)(match+best_len-1) != scan_end ||
  77730. *(ushf*)match != scan_start) continue;
  77731. /* It is not necessary to compare scan[2] and match[2] since they are
  77732. * always equal when the other bytes match, given that the hash keys
  77733. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  77734. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  77735. * lookahead only every 4th comparison; the 128th check will be made
  77736. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  77737. * necessary to put more guard bytes at the end of the window, or
  77738. * to check more often for insufficient lookahead.
  77739. */
  77740. Assert(scan[2] == match[2], "scan[2]?");
  77741. scan++, match++;
  77742. do {
  77743. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77744. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77745. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77746. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77747. scan < strend);
  77748. /* The funny "do {}" generates better code on most compilers */
  77749. /* Here, scan <= window+strstart+257 */
  77750. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77751. if (*scan == *match) scan++;
  77752. len = (MAX_MATCH - 1) - (int)(strend-scan);
  77753. scan = strend - (MAX_MATCH-1);
  77754. #else /* UNALIGNED_OK */
  77755. if (match[best_len] != scan_end ||
  77756. match[best_len-1] != scan_end1 ||
  77757. *match != *scan ||
  77758. *++match != scan[1]) continue;
  77759. /* The check at best_len-1 can be removed because it will be made
  77760. * again later. (This heuristic is not always a win.)
  77761. * It is not necessary to compare scan[2] and match[2] since they
  77762. * are always equal when the other bytes match, given that
  77763. * the hash keys are equal and that HASH_BITS >= 8.
  77764. */
  77765. scan += 2, match++;
  77766. Assert(*scan == *match, "match[2]?");
  77767. /* We check for insufficient lookahead only every 8th comparison;
  77768. * the 256th check will be made at strstart+258.
  77769. */
  77770. do {
  77771. } while (*++scan == *++match && *++scan == *++match &&
  77772. *++scan == *++match && *++scan == *++match &&
  77773. *++scan == *++match && *++scan == *++match &&
  77774. *++scan == *++match && *++scan == *++match &&
  77775. scan < strend);
  77776. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77777. len = MAX_MATCH - (int)(strend - scan);
  77778. scan = strend - MAX_MATCH;
  77779. #endif /* UNALIGNED_OK */
  77780. if (len > best_len) {
  77781. s->match_start = cur_match;
  77782. best_len = len;
  77783. if (len >= nice_match) break;
  77784. #ifdef UNALIGNED_OK
  77785. scan_end = *(ushf*)(scan+best_len-1);
  77786. #else
  77787. scan_end1 = scan[best_len-1];
  77788. scan_end = scan[best_len];
  77789. #endif
  77790. }
  77791. } while ((cur_match = prev[cur_match & wmask]) > limit
  77792. && --chain_length != 0);
  77793. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  77794. return s->lookahead;
  77795. }
  77796. #endif /* ASMV */
  77797. #endif /* FASTEST */
  77798. /* ---------------------------------------------------------------------------
  77799. * Optimized version for level == 1 or strategy == Z_RLE only
  77800. */
  77801. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  77802. {
  77803. register Bytef *scan = s->window + s->strstart; /* current string */
  77804. register Bytef *match; /* matched string */
  77805. register int len; /* length of current match */
  77806. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77807. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77808. * It is easy to get rid of this optimization if necessary.
  77809. */
  77810. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77811. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77812. Assert(cur_match < s->strstart, "no future");
  77813. match = s->window + cur_match;
  77814. /* Return failure if the match length is less than 2:
  77815. */
  77816. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  77817. /* The check at best_len-1 can be removed because it will be made
  77818. * again later. (This heuristic is not always a win.)
  77819. * It is not necessary to compare scan[2] and match[2] since they
  77820. * are always equal when the other bytes match, given that
  77821. * the hash keys are equal and that HASH_BITS >= 8.
  77822. */
  77823. scan += 2, match += 2;
  77824. Assert(*scan == *match, "match[2]?");
  77825. /* We check for insufficient lookahead only every 8th comparison;
  77826. * the 256th check will be made at strstart+258.
  77827. */
  77828. do {
  77829. } while (*++scan == *++match && *++scan == *++match &&
  77830. *++scan == *++match && *++scan == *++match &&
  77831. *++scan == *++match && *++scan == *++match &&
  77832. *++scan == *++match && *++scan == *++match &&
  77833. scan < strend);
  77834. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77835. len = MAX_MATCH - (int)(strend - scan);
  77836. if (len < MIN_MATCH) return MIN_MATCH - 1;
  77837. s->match_start = cur_match;
  77838. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  77839. }
  77840. #ifdef DEBUG
  77841. /* ===========================================================================
  77842. * Check that the match at match_start is indeed a match.
  77843. */
  77844. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  77845. {
  77846. /* check that the match is indeed a match */
  77847. if (zmemcmp(s->window + match,
  77848. s->window + start, length) != EQUAL) {
  77849. fprintf(stderr, " start %u, match %u, length %d\n",
  77850. start, match, length);
  77851. do {
  77852. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  77853. } while (--length != 0);
  77854. z_error("invalid match");
  77855. }
  77856. if (z_verbose > 1) {
  77857. fprintf(stderr,"\\[%d,%d]", start-match, length);
  77858. do { putc(s->window[start++], stderr); } while (--length != 0);
  77859. }
  77860. }
  77861. #else
  77862. # define check_match(s, start, match, length)
  77863. #endif /* DEBUG */
  77864. /* ===========================================================================
  77865. * Fill the window when the lookahead becomes insufficient.
  77866. * Updates strstart and lookahead.
  77867. *
  77868. * IN assertion: lookahead < MIN_LOOKAHEAD
  77869. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  77870. * At least one byte has been read, or avail_in == 0; reads are
  77871. * performed for at least two bytes (required for the zip translate_eol
  77872. * option -- not supported here).
  77873. */
  77874. local void fill_window (deflate_state *s)
  77875. {
  77876. register unsigned n, m;
  77877. register Posf *p;
  77878. unsigned more; /* Amount of free space at the end of the window. */
  77879. uInt wsize = s->w_size;
  77880. do {
  77881. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  77882. /* Deal with !@#$% 64K limit: */
  77883. if (sizeof(int) <= 2) {
  77884. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  77885. more = wsize;
  77886. } else if (more == (unsigned)(-1)) {
  77887. /* Very unlikely, but possible on 16 bit machine if
  77888. * strstart == 0 && lookahead == 1 (input done a byte at time)
  77889. */
  77890. more--;
  77891. }
  77892. }
  77893. /* If the window is almost full and there is insufficient lookahead,
  77894. * move the upper half to the lower one to make room in the upper half.
  77895. */
  77896. if (s->strstart >= wsize+MAX_DIST(s)) {
  77897. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  77898. s->match_start -= wsize;
  77899. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  77900. s->block_start -= (long) wsize;
  77901. /* Slide the hash table (could be avoided with 32 bit values
  77902. at the expense of memory usage). We slide even when level == 0
  77903. to keep the hash table consistent if we switch back to level > 0
  77904. later. (Using level 0 permanently is not an optimal usage of
  77905. zlib, so we don't care about this pathological case.)
  77906. */
  77907. /* %%% avoid this when Z_RLE */
  77908. n = s->hash_size;
  77909. p = &s->head[n];
  77910. do {
  77911. m = *--p;
  77912. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77913. } while (--n);
  77914. n = wsize;
  77915. #ifndef FASTEST
  77916. p = &s->prev[n];
  77917. do {
  77918. m = *--p;
  77919. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77920. /* If n is not on any hash chain, prev[n] is garbage but
  77921. * its value will never be used.
  77922. */
  77923. } while (--n);
  77924. #endif
  77925. more += wsize;
  77926. }
  77927. if (s->strm->avail_in == 0) return;
  77928. /* If there was no sliding:
  77929. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  77930. * more == window_size - lookahead - strstart
  77931. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  77932. * => more >= window_size - 2*WSIZE + 2
  77933. * In the BIG_MEM or MMAP case (not yet supported),
  77934. * window_size == input_size + MIN_LOOKAHEAD &&
  77935. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  77936. * Otherwise, window_size == 2*WSIZE so more >= 2.
  77937. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  77938. */
  77939. Assert(more >= 2, "more < 2");
  77940. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  77941. s->lookahead += n;
  77942. /* Initialize the hash value now that we have some input: */
  77943. if (s->lookahead >= MIN_MATCH) {
  77944. s->ins_h = s->window[s->strstart];
  77945. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77946. #if MIN_MATCH != 3
  77947. Call UPDATE_HASH() MIN_MATCH-3 more times
  77948. #endif
  77949. }
  77950. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  77951. * but this is not important since only literal bytes will be emitted.
  77952. */
  77953. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  77954. }
  77955. /* ===========================================================================
  77956. * Flush the current block, with given end-of-file flag.
  77957. * IN assertion: strstart is set to the end of the current match.
  77958. */
  77959. #define FLUSH_BLOCK_ONLY(s, eof) { \
  77960. _tr_flush_block(s, (s->block_start >= 0L ? \
  77961. (charf *)&s->window[(unsigned)s->block_start] : \
  77962. (charf *)Z_NULL), \
  77963. (ulg)((long)s->strstart - s->block_start), \
  77964. (eof)); \
  77965. s->block_start = s->strstart; \
  77966. flush_pending(s->strm); \
  77967. Tracev((stderr,"[FLUSH]")); \
  77968. }
  77969. /* Same but force premature exit if necessary. */
  77970. #define FLUSH_BLOCK(s, eof) { \
  77971. FLUSH_BLOCK_ONLY(s, eof); \
  77972. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  77973. }
  77974. /* ===========================================================================
  77975. * Copy without compression as much as possible from the input stream, return
  77976. * the current block state.
  77977. * This function does not insert new strings in the dictionary since
  77978. * uncompressible data is probably not useful. This function is used
  77979. * only for the level=0 compression option.
  77980. * NOTE: this function should be optimized to avoid extra copying from
  77981. * window to pending_buf.
  77982. */
  77983. local block_state deflate_stored(deflate_state *s, int flush)
  77984. {
  77985. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  77986. * to pending_buf_size, and each stored block has a 5 byte header:
  77987. */
  77988. ulg max_block_size = 0xffff;
  77989. ulg max_start;
  77990. if (max_block_size > s->pending_buf_size - 5) {
  77991. max_block_size = s->pending_buf_size - 5;
  77992. }
  77993. /* Copy as much as possible from input to output: */
  77994. for (;;) {
  77995. /* Fill the window as much as possible: */
  77996. if (s->lookahead <= 1) {
  77997. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  77998. s->block_start >= (long)s->w_size, "slide too late");
  77999. fill_window(s);
  78000. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  78001. if (s->lookahead == 0) break; /* flush the current block */
  78002. }
  78003. Assert(s->block_start >= 0L, "block gone");
  78004. s->strstart += s->lookahead;
  78005. s->lookahead = 0;
  78006. /* Emit a stored block if pending_buf will be full: */
  78007. max_start = s->block_start + max_block_size;
  78008. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  78009. /* strstart == 0 is possible when wraparound on 16-bit machine */
  78010. s->lookahead = (uInt)(s->strstart - max_start);
  78011. s->strstart = (uInt)max_start;
  78012. FLUSH_BLOCK(s, 0);
  78013. }
  78014. /* Flush if we may have to slide, otherwise block_start may become
  78015. * negative and the data will be gone:
  78016. */
  78017. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  78018. FLUSH_BLOCK(s, 0);
  78019. }
  78020. }
  78021. FLUSH_BLOCK(s, flush == Z_FINISH);
  78022. return flush == Z_FINISH ? finish_done : block_done;
  78023. }
  78024. /* ===========================================================================
  78025. * Compress as much as possible from the input stream, return the current
  78026. * block state.
  78027. * This function does not perform lazy evaluation of matches and inserts
  78028. * new strings in the dictionary only for unmatched strings or for short
  78029. * matches. It is used only for the fast compression options.
  78030. */
  78031. local block_state deflate_fast(deflate_state *s, int flush)
  78032. {
  78033. IPos hash_head = NIL; /* head of the hash chain */
  78034. int bflush; /* set if current block must be flushed */
  78035. for (;;) {
  78036. /* Make sure that we always have enough lookahead, except
  78037. * at the end of the input file. We need MAX_MATCH bytes
  78038. * for the next match, plus MIN_MATCH bytes to insert the
  78039. * string following the next match.
  78040. */
  78041. if (s->lookahead < MIN_LOOKAHEAD) {
  78042. fill_window(s);
  78043. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78044. return need_more;
  78045. }
  78046. if (s->lookahead == 0) break; /* flush the current block */
  78047. }
  78048. /* Insert the string window[strstart .. strstart+2] in the
  78049. * dictionary, and set hash_head to the head of the hash chain:
  78050. */
  78051. if (s->lookahead >= MIN_MATCH) {
  78052. INSERT_STRING(s, s->strstart, hash_head);
  78053. }
  78054. /* Find the longest match, discarding those <= prev_length.
  78055. * At this point we have always match_length < MIN_MATCH
  78056. */
  78057. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  78058. /* To simplify the code, we prevent matches with the string
  78059. * of window index 0 (in particular we have to avoid a match
  78060. * of the string with itself at the start of the input file).
  78061. */
  78062. #ifdef FASTEST
  78063. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  78064. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  78065. s->match_length = longest_match_fast (s, hash_head);
  78066. }
  78067. #else
  78068. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78069. s->match_length = longest_match (s, hash_head);
  78070. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78071. s->match_length = longest_match_fast (s, hash_head);
  78072. }
  78073. #endif
  78074. /* longest_match() or longest_match_fast() sets match_start */
  78075. }
  78076. if (s->match_length >= MIN_MATCH) {
  78077. check_match(s, s->strstart, s->match_start, s->match_length);
  78078. _tr_tally_dist(s, s->strstart - s->match_start,
  78079. s->match_length - MIN_MATCH, bflush);
  78080. s->lookahead -= s->match_length;
  78081. /* Insert new strings in the hash table only if the match length
  78082. * is not too large. This saves time but degrades compression.
  78083. */
  78084. #ifndef FASTEST
  78085. if (s->match_length <= s->max_insert_length &&
  78086. s->lookahead >= MIN_MATCH) {
  78087. s->match_length--; /* string at strstart already in table */
  78088. do {
  78089. s->strstart++;
  78090. INSERT_STRING(s, s->strstart, hash_head);
  78091. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  78092. * always MIN_MATCH bytes ahead.
  78093. */
  78094. } while (--s->match_length != 0);
  78095. s->strstart++;
  78096. } else
  78097. #endif
  78098. {
  78099. s->strstart += s->match_length;
  78100. s->match_length = 0;
  78101. s->ins_h = s->window[s->strstart];
  78102. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  78103. #if MIN_MATCH != 3
  78104. Call UPDATE_HASH() MIN_MATCH-3 more times
  78105. #endif
  78106. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  78107. * matter since it will be recomputed at next deflate call.
  78108. */
  78109. }
  78110. } else {
  78111. /* No match, output a literal byte */
  78112. Tracevv((stderr,"%c", s->window[s->strstart]));
  78113. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78114. s->lookahead--;
  78115. s->strstart++;
  78116. }
  78117. if (bflush) FLUSH_BLOCK(s, 0);
  78118. }
  78119. FLUSH_BLOCK(s, flush == Z_FINISH);
  78120. return flush == Z_FINISH ? finish_done : block_done;
  78121. }
  78122. #ifndef FASTEST
  78123. /* ===========================================================================
  78124. * Same as above, but achieves better compression. We use a lazy
  78125. * evaluation for matches: a match is finally adopted only if there is
  78126. * no better match at the next window position.
  78127. */
  78128. local block_state deflate_slow(deflate_state *s, int flush)
  78129. {
  78130. IPos hash_head = NIL; /* head of hash chain */
  78131. int bflush; /* set if current block must be flushed */
  78132. /* Process the input block. */
  78133. for (;;) {
  78134. /* Make sure that we always have enough lookahead, except
  78135. * at the end of the input file. We need MAX_MATCH bytes
  78136. * for the next match, plus MIN_MATCH bytes to insert the
  78137. * string following the next match.
  78138. */
  78139. if (s->lookahead < MIN_LOOKAHEAD) {
  78140. fill_window(s);
  78141. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78142. return need_more;
  78143. }
  78144. if (s->lookahead == 0) break; /* flush the current block */
  78145. }
  78146. /* Insert the string window[strstart .. strstart+2] in the
  78147. * dictionary, and set hash_head to the head of the hash chain:
  78148. */
  78149. if (s->lookahead >= MIN_MATCH) {
  78150. INSERT_STRING(s, s->strstart, hash_head);
  78151. }
  78152. /* Find the longest match, discarding those <= prev_length.
  78153. */
  78154. s->prev_length = s->match_length, s->prev_match = s->match_start;
  78155. s->match_length = MIN_MATCH-1;
  78156. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  78157. s->strstart - hash_head <= MAX_DIST(s)) {
  78158. /* To simplify the code, we prevent matches with the string
  78159. * of window index 0 (in particular we have to avoid a match
  78160. * of the string with itself at the start of the input file).
  78161. */
  78162. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78163. s->match_length = longest_match (s, hash_head);
  78164. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78165. s->match_length = longest_match_fast (s, hash_head);
  78166. }
  78167. /* longest_match() or longest_match_fast() sets match_start */
  78168. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  78169. #if TOO_FAR <= 32767
  78170. || (s->match_length == MIN_MATCH &&
  78171. s->strstart - s->match_start > TOO_FAR)
  78172. #endif
  78173. )) {
  78174. /* If prev_match is also MIN_MATCH, match_start is garbage
  78175. * but we will ignore the current match anyway.
  78176. */
  78177. s->match_length = MIN_MATCH-1;
  78178. }
  78179. }
  78180. /* If there was a match at the previous step and the current
  78181. * match is not better, output the previous match:
  78182. */
  78183. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  78184. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  78185. /* Do not insert strings in hash table beyond this. */
  78186. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  78187. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  78188. s->prev_length - MIN_MATCH, bflush);
  78189. /* Insert in hash table all strings up to the end of the match.
  78190. * strstart-1 and strstart are already inserted. If there is not
  78191. * enough lookahead, the last two strings are not inserted in
  78192. * the hash table.
  78193. */
  78194. s->lookahead -= s->prev_length-1;
  78195. s->prev_length -= 2;
  78196. do {
  78197. if (++s->strstart <= max_insert) {
  78198. INSERT_STRING(s, s->strstart, hash_head);
  78199. }
  78200. } while (--s->prev_length != 0);
  78201. s->match_available = 0;
  78202. s->match_length = MIN_MATCH-1;
  78203. s->strstart++;
  78204. if (bflush) FLUSH_BLOCK(s, 0);
  78205. } else if (s->match_available) {
  78206. /* If there was no match at the previous position, output a
  78207. * single literal. If there was a match but the current match
  78208. * is longer, truncate the previous match to a single literal.
  78209. */
  78210. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78211. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78212. if (bflush) {
  78213. FLUSH_BLOCK_ONLY(s, 0);
  78214. }
  78215. s->strstart++;
  78216. s->lookahead--;
  78217. if (s->strm->avail_out == 0) return need_more;
  78218. } else {
  78219. /* There is no previous match to compare with, wait for
  78220. * the next step to decide.
  78221. */
  78222. s->match_available = 1;
  78223. s->strstart++;
  78224. s->lookahead--;
  78225. }
  78226. }
  78227. Assert (flush != Z_NO_FLUSH, "no flush?");
  78228. if (s->match_available) {
  78229. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78230. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78231. s->match_available = 0;
  78232. }
  78233. FLUSH_BLOCK(s, flush == Z_FINISH);
  78234. return flush == Z_FINISH ? finish_done : block_done;
  78235. }
  78236. #endif /* FASTEST */
  78237. #if 0
  78238. /* ===========================================================================
  78239. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  78240. * one. Do not maintain a hash table. (It will be regenerated if this run of
  78241. * deflate switches away from Z_RLE.)
  78242. */
  78243. local block_state deflate_rle(s, flush)
  78244. deflate_state *s;
  78245. int flush;
  78246. {
  78247. int bflush; /* set if current block must be flushed */
  78248. uInt run; /* length of run */
  78249. uInt max; /* maximum length of run */
  78250. uInt prev; /* byte at distance one to match */
  78251. Bytef *scan; /* scan for end of run */
  78252. for (;;) {
  78253. /* Make sure that we always have enough lookahead, except
  78254. * at the end of the input file. We need MAX_MATCH bytes
  78255. * for the longest encodable run.
  78256. */
  78257. if (s->lookahead < MAX_MATCH) {
  78258. fill_window(s);
  78259. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  78260. return need_more;
  78261. }
  78262. if (s->lookahead == 0) break; /* flush the current block */
  78263. }
  78264. /* See how many times the previous byte repeats */
  78265. run = 0;
  78266. if (s->strstart > 0) { /* if there is a previous byte, that is */
  78267. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  78268. scan = s->window + s->strstart - 1;
  78269. prev = *scan++;
  78270. do {
  78271. if (*scan++ != prev)
  78272. break;
  78273. } while (++run < max);
  78274. }
  78275. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  78276. if (run >= MIN_MATCH) {
  78277. check_match(s, s->strstart, s->strstart - 1, run);
  78278. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  78279. s->lookahead -= run;
  78280. s->strstart += run;
  78281. } else {
  78282. /* No match, output a literal byte */
  78283. Tracevv((stderr,"%c", s->window[s->strstart]));
  78284. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78285. s->lookahead--;
  78286. s->strstart++;
  78287. }
  78288. if (bflush) FLUSH_BLOCK(s, 0);
  78289. }
  78290. FLUSH_BLOCK(s, flush == Z_FINISH);
  78291. return flush == Z_FINISH ? finish_done : block_done;
  78292. }
  78293. #endif
  78294. /********* End of inlined file: deflate.c *********/
  78295. /********* Start of inlined file: inffast.c *********/
  78296. /********* Start of inlined file: inftrees.h *********/
  78297. /* WARNING: this file should *not* be used by applications. It is
  78298. part of the implementation of the compression library and is
  78299. subject to change. Applications should only use zlib.h.
  78300. */
  78301. #ifndef _INFTREES_H_
  78302. #define _INFTREES_H_
  78303. /* Structure for decoding tables. Each entry provides either the
  78304. information needed to do the operation requested by the code that
  78305. indexed that table entry, or it provides a pointer to another
  78306. table that indexes more bits of the code. op indicates whether
  78307. the entry is a pointer to another table, a literal, a length or
  78308. distance, an end-of-block, or an invalid code. For a table
  78309. pointer, the low four bits of op is the number of index bits of
  78310. that table. For a length or distance, the low four bits of op
  78311. is the number of extra bits to get after the code. bits is
  78312. the number of bits in this code or part of the code to drop off
  78313. of the bit buffer. val is the actual byte to output in the case
  78314. of a literal, the base length or distance, or the offset from
  78315. the current table to the next table. Each entry is four bytes. */
  78316. typedef struct {
  78317. unsigned char op; /* operation, extra bits, table bits */
  78318. unsigned char bits; /* bits in this part of the code */
  78319. unsigned short val; /* offset in table or code value */
  78320. } code;
  78321. /* op values as set by inflate_table():
  78322. 00000000 - literal
  78323. 0000tttt - table link, tttt != 0 is the number of table index bits
  78324. 0001eeee - length or distance, eeee is the number of extra bits
  78325. 01100000 - end of block
  78326. 01000000 - invalid code
  78327. */
  78328. /* Maximum size of dynamic tree. The maximum found in a long but non-
  78329. exhaustive search was 1444 code structures (852 for length/literals
  78330. and 592 for distances, the latter actually the result of an
  78331. exhaustive search). The true maximum is not known, but the value
  78332. below is more than safe. */
  78333. #define ENOUGH 2048
  78334. #define MAXD 592
  78335. /* Type of code to build for inftable() */
  78336. typedef enum {
  78337. CODES,
  78338. LENS,
  78339. DISTS
  78340. } codetype;
  78341. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  78342. unsigned codes, code FAR * FAR *table,
  78343. unsigned FAR *bits, unsigned short FAR *work));
  78344. #endif
  78345. /********* End of inlined file: inftrees.h *********/
  78346. /********* Start of inlined file: inflate.h *********/
  78347. /* WARNING: this file should *not* be used by applications. It is
  78348. part of the implementation of the compression library and is
  78349. subject to change. Applications should only use zlib.h.
  78350. */
  78351. #ifndef _INFLATE_H_
  78352. #define _INFLATE_H_
  78353. /* define NO_GZIP when compiling if you want to disable gzip header and
  78354. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  78355. the crc code when it is not needed. For shared libraries, gzip decoding
  78356. should be left enabled. */
  78357. #ifndef NO_GZIP
  78358. # define GUNZIP
  78359. #endif
  78360. /* Possible inflate modes between inflate() calls */
  78361. typedef enum {
  78362. HEAD, /* i: waiting for magic header */
  78363. FLAGS, /* i: waiting for method and flags (gzip) */
  78364. TIME, /* i: waiting for modification time (gzip) */
  78365. OS, /* i: waiting for extra flags and operating system (gzip) */
  78366. EXLEN, /* i: waiting for extra length (gzip) */
  78367. EXTRA, /* i: waiting for extra bytes (gzip) */
  78368. NAME, /* i: waiting for end of file name (gzip) */
  78369. COMMENT, /* i: waiting for end of comment (gzip) */
  78370. HCRC, /* i: waiting for header crc (gzip) */
  78371. DICTID, /* i: waiting for dictionary check value */
  78372. DICT, /* waiting for inflateSetDictionary() call */
  78373. TYPE, /* i: waiting for type bits, including last-flag bit */
  78374. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  78375. STORED, /* i: waiting for stored size (length and complement) */
  78376. COPY, /* i/o: waiting for input or output to copy stored block */
  78377. TABLE, /* i: waiting for dynamic block table lengths */
  78378. LENLENS, /* i: waiting for code length code lengths */
  78379. CODELENS, /* i: waiting for length/lit and distance code lengths */
  78380. LEN, /* i: waiting for length/lit code */
  78381. LENEXT, /* i: waiting for length extra bits */
  78382. DIST, /* i: waiting for distance code */
  78383. DISTEXT, /* i: waiting for distance extra bits */
  78384. MATCH, /* o: waiting for output space to copy string */
  78385. LIT, /* o: waiting for output space to write literal */
  78386. CHECK, /* i: waiting for 32-bit check value */
  78387. LENGTH, /* i: waiting for 32-bit length (gzip) */
  78388. DONE, /* finished check, done -- remain here until reset */
  78389. BAD, /* got a data error -- remain here until reset */
  78390. MEM, /* got an inflate() memory error -- remain here until reset */
  78391. SYNC /* looking for synchronization bytes to restart inflate() */
  78392. } inflate_mode;
  78393. /*
  78394. State transitions between above modes -
  78395. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  78396. Process header:
  78397. HEAD -> (gzip) or (zlib)
  78398. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  78399. NAME -> COMMENT -> HCRC -> TYPE
  78400. (zlib) -> DICTID or TYPE
  78401. DICTID -> DICT -> TYPE
  78402. Read deflate blocks:
  78403. TYPE -> STORED or TABLE or LEN or CHECK
  78404. STORED -> COPY -> TYPE
  78405. TABLE -> LENLENS -> CODELENS -> LEN
  78406. Read deflate codes:
  78407. LEN -> LENEXT or LIT or TYPE
  78408. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  78409. LIT -> LEN
  78410. Process trailer:
  78411. CHECK -> LENGTH -> DONE
  78412. */
  78413. /* state maintained between inflate() calls. Approximately 7K bytes. */
  78414. struct inflate_state {
  78415. inflate_mode mode; /* current inflate mode */
  78416. int last; /* true if processing last block */
  78417. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  78418. int havedict; /* true if dictionary provided */
  78419. int flags; /* gzip header method and flags (0 if zlib) */
  78420. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  78421. unsigned long check; /* protected copy of check value */
  78422. unsigned long total; /* protected copy of output count */
  78423. gz_headerp head; /* where to save gzip header information */
  78424. /* sliding window */
  78425. unsigned wbits; /* log base 2 of requested window size */
  78426. unsigned wsize; /* window size or zero if not using window */
  78427. unsigned whave; /* valid bytes in the window */
  78428. unsigned write; /* window write index */
  78429. unsigned char FAR *window; /* allocated sliding window, if needed */
  78430. /* bit accumulator */
  78431. unsigned long hold; /* input bit accumulator */
  78432. unsigned bits; /* number of bits in "in" */
  78433. /* for string and stored block copying */
  78434. unsigned length; /* literal or length of data to copy */
  78435. unsigned offset; /* distance back to copy string from */
  78436. /* for table and code decoding */
  78437. unsigned extra; /* extra bits needed */
  78438. /* fixed and dynamic code tables */
  78439. code const FAR *lencode; /* starting table for length/literal codes */
  78440. code const FAR *distcode; /* starting table for distance codes */
  78441. unsigned lenbits; /* index bits for lencode */
  78442. unsigned distbits; /* index bits for distcode */
  78443. /* dynamic table building */
  78444. unsigned ncode; /* number of code length code lengths */
  78445. unsigned nlen; /* number of length code lengths */
  78446. unsigned ndist; /* number of distance code lengths */
  78447. unsigned have; /* number of code lengths in lens[] */
  78448. code FAR *next; /* next available space in codes[] */
  78449. unsigned short lens[320]; /* temporary storage for code lengths */
  78450. unsigned short work[288]; /* work area for code table building */
  78451. code codes[ENOUGH]; /* space for code tables */
  78452. };
  78453. #endif
  78454. /********* End of inlined file: inflate.h *********/
  78455. /********* Start of inlined file: inffast.h *********/
  78456. /* WARNING: this file should *not* be used by applications. It is
  78457. part of the implementation of the compression library and is
  78458. subject to change. Applications should only use zlib.h.
  78459. */
  78460. void inflate_fast OF((z_streamp strm, unsigned start));
  78461. /********* End of inlined file: inffast.h *********/
  78462. #ifndef ASMINF
  78463. /* Allow machine dependent optimization for post-increment or pre-increment.
  78464. Based on testing to date,
  78465. Pre-increment preferred for:
  78466. - PowerPC G3 (Adler)
  78467. - MIPS R5000 (Randers-Pehrson)
  78468. Post-increment preferred for:
  78469. - none
  78470. No measurable difference:
  78471. - Pentium III (Anderson)
  78472. - M68060 (Nikl)
  78473. */
  78474. #ifdef POSTINC
  78475. # define OFF 0
  78476. # define PUP(a) *(a)++
  78477. #else
  78478. # define OFF 1
  78479. # define PUP(a) *++(a)
  78480. #endif
  78481. /*
  78482. Decode literal, length, and distance codes and write out the resulting
  78483. literal and match bytes until either not enough input or output is
  78484. available, an end-of-block is encountered, or a data error is encountered.
  78485. When large enough input and output buffers are supplied to inflate(), for
  78486. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  78487. inflate execution time is spent in this routine.
  78488. Entry assumptions:
  78489. state->mode == LEN
  78490. strm->avail_in >= 6
  78491. strm->avail_out >= 258
  78492. start >= strm->avail_out
  78493. state->bits < 8
  78494. On return, state->mode is one of:
  78495. LEN -- ran out of enough output space or enough available input
  78496. TYPE -- reached end of block code, inflate() to interpret next block
  78497. BAD -- error in block data
  78498. Notes:
  78499. - The maximum input bits used by a length/distance pair is 15 bits for the
  78500. length code, 5 bits for the length extra, 15 bits for the distance code,
  78501. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  78502. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  78503. checking for available input while decoding.
  78504. - The maximum bytes that a single length/distance pair can output is 258
  78505. bytes, which is the maximum length that can be coded. inflate_fast()
  78506. requires strm->avail_out >= 258 for each loop to avoid checking for
  78507. output space.
  78508. */
  78509. void inflate_fast (z_streamp strm, unsigned start)
  78510. {
  78511. struct inflate_state FAR *state;
  78512. unsigned char FAR *in; /* local strm->next_in */
  78513. unsigned char FAR *last; /* while in < last, enough input available */
  78514. unsigned char FAR *out; /* local strm->next_out */
  78515. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  78516. unsigned char FAR *end; /* while out < end, enough space available */
  78517. #ifdef INFLATE_STRICT
  78518. unsigned dmax; /* maximum distance from zlib header */
  78519. #endif
  78520. unsigned wsize; /* window size or zero if not using window */
  78521. unsigned whave; /* valid bytes in the window */
  78522. unsigned write; /* window write index */
  78523. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  78524. unsigned long hold; /* local strm->hold */
  78525. unsigned bits; /* local strm->bits */
  78526. code const FAR *lcode; /* local strm->lencode */
  78527. code const FAR *dcode; /* local strm->distcode */
  78528. unsigned lmask; /* mask for first level of length codes */
  78529. unsigned dmask; /* mask for first level of distance codes */
  78530. code thisx; /* retrieved table entry */
  78531. unsigned op; /* code bits, operation, extra bits, or */
  78532. /* window position, window bytes to copy */
  78533. unsigned len; /* match length, unused bytes */
  78534. unsigned dist; /* match distance */
  78535. unsigned char FAR *from; /* where to copy match from */
  78536. /* copy state to local variables */
  78537. state = (struct inflate_state FAR *)strm->state;
  78538. in = strm->next_in - OFF;
  78539. last = in + (strm->avail_in - 5);
  78540. out = strm->next_out - OFF;
  78541. beg = out - (start - strm->avail_out);
  78542. end = out + (strm->avail_out - 257);
  78543. #ifdef INFLATE_STRICT
  78544. dmax = state->dmax;
  78545. #endif
  78546. wsize = state->wsize;
  78547. whave = state->whave;
  78548. write = state->write;
  78549. window = state->window;
  78550. hold = state->hold;
  78551. bits = state->bits;
  78552. lcode = state->lencode;
  78553. dcode = state->distcode;
  78554. lmask = (1U << state->lenbits) - 1;
  78555. dmask = (1U << state->distbits) - 1;
  78556. /* decode literals and length/distances until end-of-block or not enough
  78557. input data or output space */
  78558. do {
  78559. if (bits < 15) {
  78560. hold += (unsigned long)(PUP(in)) << bits;
  78561. bits += 8;
  78562. hold += (unsigned long)(PUP(in)) << bits;
  78563. bits += 8;
  78564. }
  78565. thisx = lcode[hold & lmask];
  78566. dolen:
  78567. op = (unsigned)(thisx.bits);
  78568. hold >>= op;
  78569. bits -= op;
  78570. op = (unsigned)(thisx.op);
  78571. if (op == 0) { /* literal */
  78572. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78573. "inflate: literal '%c'\n" :
  78574. "inflate: literal 0x%02x\n", thisx.val));
  78575. PUP(out) = (unsigned char)(thisx.val);
  78576. }
  78577. else if (op & 16) { /* length base */
  78578. len = (unsigned)(thisx.val);
  78579. op &= 15; /* number of extra bits */
  78580. if (op) {
  78581. if (bits < op) {
  78582. hold += (unsigned long)(PUP(in)) << bits;
  78583. bits += 8;
  78584. }
  78585. len += (unsigned)hold & ((1U << op) - 1);
  78586. hold >>= op;
  78587. bits -= op;
  78588. }
  78589. Tracevv((stderr, "inflate: length %u\n", len));
  78590. if (bits < 15) {
  78591. hold += (unsigned long)(PUP(in)) << bits;
  78592. bits += 8;
  78593. hold += (unsigned long)(PUP(in)) << bits;
  78594. bits += 8;
  78595. }
  78596. thisx = dcode[hold & dmask];
  78597. dodist:
  78598. op = (unsigned)(thisx.bits);
  78599. hold >>= op;
  78600. bits -= op;
  78601. op = (unsigned)(thisx.op);
  78602. if (op & 16) { /* distance base */
  78603. dist = (unsigned)(thisx.val);
  78604. op &= 15; /* number of extra bits */
  78605. if (bits < op) {
  78606. hold += (unsigned long)(PUP(in)) << bits;
  78607. bits += 8;
  78608. if (bits < op) {
  78609. hold += (unsigned long)(PUP(in)) << bits;
  78610. bits += 8;
  78611. }
  78612. }
  78613. dist += (unsigned)hold & ((1U << op) - 1);
  78614. #ifdef INFLATE_STRICT
  78615. if (dist > dmax) {
  78616. strm->msg = (char *)"invalid distance too far back";
  78617. state->mode = BAD;
  78618. break;
  78619. }
  78620. #endif
  78621. hold >>= op;
  78622. bits -= op;
  78623. Tracevv((stderr, "inflate: distance %u\n", dist));
  78624. op = (unsigned)(out - beg); /* max distance in output */
  78625. if (dist > op) { /* see if copy from window */
  78626. op = dist - op; /* distance back in window */
  78627. if (op > whave) {
  78628. strm->msg = (char *)"invalid distance too far back";
  78629. state->mode = BAD;
  78630. break;
  78631. }
  78632. from = window - OFF;
  78633. if (write == 0) { /* very common case */
  78634. from += wsize - op;
  78635. if (op < len) { /* some from window */
  78636. len -= op;
  78637. do {
  78638. PUP(out) = PUP(from);
  78639. } while (--op);
  78640. from = out - dist; /* rest from output */
  78641. }
  78642. }
  78643. else if (write < op) { /* wrap around window */
  78644. from += wsize + write - op;
  78645. op -= write;
  78646. if (op < len) { /* some from end of window */
  78647. len -= op;
  78648. do {
  78649. PUP(out) = PUP(from);
  78650. } while (--op);
  78651. from = window - OFF;
  78652. if (write < len) { /* some from start of window */
  78653. op = write;
  78654. len -= op;
  78655. do {
  78656. PUP(out) = PUP(from);
  78657. } while (--op);
  78658. from = out - dist; /* rest from output */
  78659. }
  78660. }
  78661. }
  78662. else { /* contiguous in window */
  78663. from += write - op;
  78664. if (op < len) { /* some from window */
  78665. len -= op;
  78666. do {
  78667. PUP(out) = PUP(from);
  78668. } while (--op);
  78669. from = out - dist; /* rest from output */
  78670. }
  78671. }
  78672. while (len > 2) {
  78673. PUP(out) = PUP(from);
  78674. PUP(out) = PUP(from);
  78675. PUP(out) = PUP(from);
  78676. len -= 3;
  78677. }
  78678. if (len) {
  78679. PUP(out) = PUP(from);
  78680. if (len > 1)
  78681. PUP(out) = PUP(from);
  78682. }
  78683. }
  78684. else {
  78685. from = out - dist; /* copy direct from output */
  78686. do { /* minimum length is three */
  78687. PUP(out) = PUP(from);
  78688. PUP(out) = PUP(from);
  78689. PUP(out) = PUP(from);
  78690. len -= 3;
  78691. } while (len > 2);
  78692. if (len) {
  78693. PUP(out) = PUP(from);
  78694. if (len > 1)
  78695. PUP(out) = PUP(from);
  78696. }
  78697. }
  78698. }
  78699. else if ((op & 64) == 0) { /* 2nd level distance code */
  78700. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  78701. goto dodist;
  78702. }
  78703. else {
  78704. strm->msg = (char *)"invalid distance code";
  78705. state->mode = BAD;
  78706. break;
  78707. }
  78708. }
  78709. else if ((op & 64) == 0) { /* 2nd level length code */
  78710. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  78711. goto dolen;
  78712. }
  78713. else if (op & 32) { /* end-of-block */
  78714. Tracevv((stderr, "inflate: end of block\n"));
  78715. state->mode = TYPE;
  78716. break;
  78717. }
  78718. else {
  78719. strm->msg = (char *)"invalid literal/length code";
  78720. state->mode = BAD;
  78721. break;
  78722. }
  78723. } while (in < last && out < end);
  78724. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  78725. len = bits >> 3;
  78726. in -= len;
  78727. bits -= len << 3;
  78728. hold &= (1U << bits) - 1;
  78729. /* update state and return */
  78730. strm->next_in = in + OFF;
  78731. strm->next_out = out + OFF;
  78732. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  78733. strm->avail_out = (unsigned)(out < end ?
  78734. 257 + (end - out) : 257 - (out - end));
  78735. state->hold = hold;
  78736. state->bits = bits;
  78737. return;
  78738. }
  78739. /*
  78740. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  78741. - Using bit fields for code structure
  78742. - Different op definition to avoid & for extra bits (do & for table bits)
  78743. - Three separate decoding do-loops for direct, window, and write == 0
  78744. - Special case for distance > 1 copies to do overlapped load and store copy
  78745. - Explicit branch predictions (based on measured branch probabilities)
  78746. - Deferring match copy and interspersed it with decoding subsequent codes
  78747. - Swapping literal/length else
  78748. - Swapping window/direct else
  78749. - Larger unrolled copy loops (three is about right)
  78750. - Moving len -= 3 statement into middle of loop
  78751. */
  78752. #endif /* !ASMINF */
  78753. /********* End of inlined file: inffast.c *********/
  78754. #undef PULLBYTE
  78755. #undef LOAD
  78756. #undef RESTORE
  78757. #undef INITBITS
  78758. #undef NEEDBITS
  78759. #undef DROPBITS
  78760. #undef BYTEBITS
  78761. /********* Start of inlined file: inflate.c *********/
  78762. /*
  78763. * Change history:
  78764. *
  78765. * 1.2.beta0 24 Nov 2002
  78766. * - First version -- complete rewrite of inflate to simplify code, avoid
  78767. * creation of window when not needed, minimize use of window when it is
  78768. * needed, make inffast.c even faster, implement gzip decoding, and to
  78769. * improve code readability and style over the previous zlib inflate code
  78770. *
  78771. * 1.2.beta1 25 Nov 2002
  78772. * - Use pointers for available input and output checking in inffast.c
  78773. * - Remove input and output counters in inffast.c
  78774. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  78775. * - Remove unnecessary second byte pull from length extra in inffast.c
  78776. * - Unroll direct copy to three copies per loop in inffast.c
  78777. *
  78778. * 1.2.beta2 4 Dec 2002
  78779. * - Change external routine names to reduce potential conflicts
  78780. * - Correct filename to inffixed.h for fixed tables in inflate.c
  78781. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  78782. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  78783. * to avoid negation problem on Alphas (64 bit) in inflate.c
  78784. *
  78785. * 1.2.beta3 22 Dec 2002
  78786. * - Add comments on state->bits assertion in inffast.c
  78787. * - Add comments on op field in inftrees.h
  78788. * - Fix bug in reuse of allocated window after inflateReset()
  78789. * - Remove bit fields--back to byte structure for speed
  78790. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  78791. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  78792. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  78793. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  78794. * - Use local copies of stream next and avail values, as well as local bit
  78795. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  78796. *
  78797. * 1.2.beta4 1 Jan 2003
  78798. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  78799. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  78800. * - Add comments in inffast.c to introduce the inflate_fast() routine
  78801. * - Rearrange window copies in inflate_fast() for speed and simplification
  78802. * - Unroll last copy for window match in inflate_fast()
  78803. * - Use local copies of window variables in inflate_fast() for speed
  78804. * - Pull out common write == 0 case for speed in inflate_fast()
  78805. * - Make op and len in inflate_fast() unsigned for consistency
  78806. * - Add FAR to lcode and dcode declarations in inflate_fast()
  78807. * - Simplified bad distance check in inflate_fast()
  78808. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  78809. * source file infback.c to provide a call-back interface to inflate for
  78810. * programs like gzip and unzip -- uses window as output buffer to avoid
  78811. * window copying
  78812. *
  78813. * 1.2.beta5 1 Jan 2003
  78814. * - Improved inflateBack() interface to allow the caller to provide initial
  78815. * input in strm.
  78816. * - Fixed stored blocks bug in inflateBack()
  78817. *
  78818. * 1.2.beta6 4 Jan 2003
  78819. * - Added comments in inffast.c on effectiveness of POSTINC
  78820. * - Typecasting all around to reduce compiler warnings
  78821. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  78822. * make compilers happy
  78823. * - Changed type of window in inflateBackInit() to unsigned char *
  78824. *
  78825. * 1.2.beta7 27 Jan 2003
  78826. * - Changed many types to unsigned or unsigned short to avoid warnings
  78827. * - Added inflateCopy() function
  78828. *
  78829. * 1.2.0 9 Mar 2003
  78830. * - Changed inflateBack() interface to provide separate opaque descriptors
  78831. * for the in() and out() functions
  78832. * - Changed inflateBack() argument and in_func typedef to swap the length
  78833. * and buffer address return values for the input function
  78834. * - Check next_in and next_out for Z_NULL on entry to inflate()
  78835. *
  78836. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  78837. */
  78838. /********* Start of inlined file: inffast.h *********/
  78839. /* WARNING: this file should *not* be used by applications. It is
  78840. part of the implementation of the compression library and is
  78841. subject to change. Applications should only use zlib.h.
  78842. */
  78843. void inflate_fast OF((z_streamp strm, unsigned start));
  78844. /********* End of inlined file: inffast.h *********/
  78845. #ifdef MAKEFIXED
  78846. # ifndef BUILDFIXED
  78847. # define BUILDFIXED
  78848. # endif
  78849. #endif
  78850. /* function prototypes */
  78851. local void fixedtables OF((struct inflate_state FAR *state));
  78852. local int updatewindow OF((z_streamp strm, unsigned out));
  78853. #ifdef BUILDFIXED
  78854. void makefixed OF((void));
  78855. #endif
  78856. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  78857. unsigned len));
  78858. int ZEXPORT inflateReset (z_streamp strm)
  78859. {
  78860. struct inflate_state FAR *state;
  78861. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78862. state = (struct inflate_state FAR *)strm->state;
  78863. strm->total_in = strm->total_out = state->total = 0;
  78864. strm->msg = Z_NULL;
  78865. strm->adler = 1; /* to support ill-conceived Java test suite */
  78866. state->mode = HEAD;
  78867. state->last = 0;
  78868. state->havedict = 0;
  78869. state->dmax = 32768U;
  78870. state->head = Z_NULL;
  78871. state->wsize = 0;
  78872. state->whave = 0;
  78873. state->write = 0;
  78874. state->hold = 0;
  78875. state->bits = 0;
  78876. state->lencode = state->distcode = state->next = state->codes;
  78877. Tracev((stderr, "inflate: reset\n"));
  78878. return Z_OK;
  78879. }
  78880. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  78881. {
  78882. struct inflate_state FAR *state;
  78883. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78884. state = (struct inflate_state FAR *)strm->state;
  78885. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  78886. value &= (1L << bits) - 1;
  78887. state->hold += value << state->bits;
  78888. state->bits += bits;
  78889. return Z_OK;
  78890. }
  78891. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  78892. {
  78893. struct inflate_state FAR *state;
  78894. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  78895. stream_size != (int)(sizeof(z_stream)))
  78896. return Z_VERSION_ERROR;
  78897. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78898. strm->msg = Z_NULL; /* in case we return an error */
  78899. if (strm->zalloc == (alloc_func)0) {
  78900. strm->zalloc = zcalloc;
  78901. strm->opaque = (voidpf)0;
  78902. }
  78903. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78904. state = (struct inflate_state FAR *)
  78905. ZALLOC(strm, 1, sizeof(struct inflate_state));
  78906. if (state == Z_NULL) return Z_MEM_ERROR;
  78907. Tracev((stderr, "inflate: allocated\n"));
  78908. strm->state = (struct internal_state FAR *)state;
  78909. if (windowBits < 0) {
  78910. state->wrap = 0;
  78911. windowBits = -windowBits;
  78912. }
  78913. else {
  78914. state->wrap = (windowBits >> 4) + 1;
  78915. #ifdef GUNZIP
  78916. if (windowBits < 48) windowBits &= 15;
  78917. #endif
  78918. }
  78919. if (windowBits < 8 || windowBits > 15) {
  78920. ZFREE(strm, state);
  78921. strm->state = Z_NULL;
  78922. return Z_STREAM_ERROR;
  78923. }
  78924. state->wbits = (unsigned)windowBits;
  78925. state->window = Z_NULL;
  78926. return inflateReset(strm);
  78927. }
  78928. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  78929. {
  78930. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  78931. }
  78932. /*
  78933. Return state with length and distance decoding tables and index sizes set to
  78934. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  78935. If BUILDFIXED is defined, then instead this routine builds the tables the
  78936. first time it's called, and returns those tables the first time and
  78937. thereafter. This reduces the size of the code by about 2K bytes, in
  78938. exchange for a little execution time. However, BUILDFIXED should not be
  78939. used for threaded applications, since the rewriting of the tables and virgin
  78940. may not be thread-safe.
  78941. */
  78942. local void fixedtables (struct inflate_state FAR *state)
  78943. {
  78944. #ifdef BUILDFIXED
  78945. static int virgin = 1;
  78946. static code *lenfix, *distfix;
  78947. static code fixed[544];
  78948. /* build fixed huffman tables if first call (may not be thread safe) */
  78949. if (virgin) {
  78950. unsigned sym, bits;
  78951. static code *next;
  78952. /* literal/length table */
  78953. sym = 0;
  78954. while (sym < 144) state->lens[sym++] = 8;
  78955. while (sym < 256) state->lens[sym++] = 9;
  78956. while (sym < 280) state->lens[sym++] = 7;
  78957. while (sym < 288) state->lens[sym++] = 8;
  78958. next = fixed;
  78959. lenfix = next;
  78960. bits = 9;
  78961. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  78962. /* distance table */
  78963. sym = 0;
  78964. while (sym < 32) state->lens[sym++] = 5;
  78965. distfix = next;
  78966. bits = 5;
  78967. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  78968. /* do this just once */
  78969. virgin = 0;
  78970. }
  78971. #else /* !BUILDFIXED */
  78972. /********* Start of inlined file: inffixed.h *********/
  78973. /* inffixed.h -- table for decoding fixed codes
  78974. * Generated automatically by makefixed().
  78975. */
  78976. /* WARNING: this file should *not* be used by applications. It
  78977. is part of the implementation of the compression library and
  78978. is subject to change. Applications should only use zlib.h.
  78979. */
  78980. static const code lenfix[512] = {
  78981. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  78982. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  78983. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  78984. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  78985. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  78986. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  78987. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  78988. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  78989. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  78990. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  78991. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  78992. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  78993. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  78994. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  78995. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  78996. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  78997. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  78998. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  78999. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  79000. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  79001. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  79002. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  79003. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  79004. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  79005. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  79006. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  79007. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  79008. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  79009. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  79010. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  79011. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  79012. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  79013. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  79014. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  79015. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  79016. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  79017. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  79018. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  79019. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  79020. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  79021. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  79022. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  79023. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  79024. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  79025. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  79026. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  79027. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  79028. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  79029. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  79030. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  79031. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  79032. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  79033. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  79034. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  79035. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  79036. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  79037. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  79038. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  79039. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  79040. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  79041. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  79042. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  79043. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  79044. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  79045. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  79046. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  79047. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  79048. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  79049. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  79050. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  79051. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  79052. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  79053. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  79054. {0,9,255}
  79055. };
  79056. static const code distfix[32] = {
  79057. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  79058. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  79059. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  79060. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  79061. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  79062. {22,5,193},{64,5,0}
  79063. };
  79064. /********* End of inlined file: inffixed.h *********/
  79065. #endif /* BUILDFIXED */
  79066. state->lencode = lenfix;
  79067. state->lenbits = 9;
  79068. state->distcode = distfix;
  79069. state->distbits = 5;
  79070. }
  79071. #ifdef MAKEFIXED
  79072. #include <stdio.h>
  79073. /*
  79074. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  79075. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  79076. those tables to stdout, which would be piped to inffixed.h. A small program
  79077. can simply call makefixed to do this:
  79078. void makefixed(void);
  79079. int main(void)
  79080. {
  79081. makefixed();
  79082. return 0;
  79083. }
  79084. Then that can be linked with zlib built with MAKEFIXED defined and run:
  79085. a.out > inffixed.h
  79086. */
  79087. void makefixed()
  79088. {
  79089. unsigned low, size;
  79090. struct inflate_state state;
  79091. fixedtables(&state);
  79092. puts(" /* inffixed.h -- table for decoding fixed codes");
  79093. puts(" * Generated automatically by makefixed().");
  79094. puts(" */");
  79095. puts("");
  79096. puts(" /* WARNING: this file should *not* be used by applications.");
  79097. puts(" It is part of the implementation of this library and is");
  79098. puts(" subject to change. Applications should only use zlib.h.");
  79099. puts(" */");
  79100. puts("");
  79101. size = 1U << 9;
  79102. printf(" static const code lenfix[%u] = {", size);
  79103. low = 0;
  79104. for (;;) {
  79105. if ((low % 7) == 0) printf("\n ");
  79106. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  79107. state.lencode[low].val);
  79108. if (++low == size) break;
  79109. putchar(',');
  79110. }
  79111. puts("\n };");
  79112. size = 1U << 5;
  79113. printf("\n static const code distfix[%u] = {", size);
  79114. low = 0;
  79115. for (;;) {
  79116. if ((low % 6) == 0) printf("\n ");
  79117. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  79118. state.distcode[low].val);
  79119. if (++low == size) break;
  79120. putchar(',');
  79121. }
  79122. puts("\n };");
  79123. }
  79124. #endif /* MAKEFIXED */
  79125. /*
  79126. Update the window with the last wsize (normally 32K) bytes written before
  79127. returning. If window does not exist yet, create it. This is only called
  79128. when a window is already in use, or when output has been written during this
  79129. inflate call, but the end of the deflate stream has not been reached yet.
  79130. It is also called to create a window for dictionary data when a dictionary
  79131. is loaded.
  79132. Providing output buffers larger than 32K to inflate() should provide a speed
  79133. advantage, since only the last 32K of output is copied to the sliding window
  79134. upon return from inflate(), and since all distances after the first 32K of
  79135. output will fall in the output data, making match copies simpler and faster.
  79136. The advantage may be dependent on the size of the processor's data caches.
  79137. */
  79138. local int updatewindow (z_streamp strm, unsigned out)
  79139. {
  79140. struct inflate_state FAR *state;
  79141. unsigned copy, dist;
  79142. state = (struct inflate_state FAR *)strm->state;
  79143. /* if it hasn't been done already, allocate space for the window */
  79144. if (state->window == Z_NULL) {
  79145. state->window = (unsigned char FAR *)
  79146. ZALLOC(strm, 1U << state->wbits,
  79147. sizeof(unsigned char));
  79148. if (state->window == Z_NULL) return 1;
  79149. }
  79150. /* if window not in use yet, initialize */
  79151. if (state->wsize == 0) {
  79152. state->wsize = 1U << state->wbits;
  79153. state->write = 0;
  79154. state->whave = 0;
  79155. }
  79156. /* copy state->wsize or less output bytes into the circular window */
  79157. copy = out - strm->avail_out;
  79158. if (copy >= state->wsize) {
  79159. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  79160. state->write = 0;
  79161. state->whave = state->wsize;
  79162. }
  79163. else {
  79164. dist = state->wsize - state->write;
  79165. if (dist > copy) dist = copy;
  79166. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  79167. copy -= dist;
  79168. if (copy) {
  79169. zmemcpy(state->window, strm->next_out - copy, copy);
  79170. state->write = copy;
  79171. state->whave = state->wsize;
  79172. }
  79173. else {
  79174. state->write += dist;
  79175. if (state->write == state->wsize) state->write = 0;
  79176. if (state->whave < state->wsize) state->whave += dist;
  79177. }
  79178. }
  79179. return 0;
  79180. }
  79181. /* Macros for inflate(): */
  79182. /* check function to use adler32() for zlib or crc32() for gzip */
  79183. #ifdef GUNZIP
  79184. # define UPDATE(check, buf, len) \
  79185. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  79186. #else
  79187. # define UPDATE(check, buf, len) adler32(check, buf, len)
  79188. #endif
  79189. /* check macros for header crc */
  79190. #ifdef GUNZIP
  79191. # define CRC2(check, word) \
  79192. do { \
  79193. hbuf[0] = (unsigned char)(word); \
  79194. hbuf[1] = (unsigned char)((word) >> 8); \
  79195. check = crc32(check, hbuf, 2); \
  79196. } while (0)
  79197. # define CRC4(check, word) \
  79198. do { \
  79199. hbuf[0] = (unsigned char)(word); \
  79200. hbuf[1] = (unsigned char)((word) >> 8); \
  79201. hbuf[2] = (unsigned char)((word) >> 16); \
  79202. hbuf[3] = (unsigned char)((word) >> 24); \
  79203. check = crc32(check, hbuf, 4); \
  79204. } while (0)
  79205. #endif
  79206. /* Load registers with state in inflate() for speed */
  79207. #define LOAD() \
  79208. do { \
  79209. put = strm->next_out; \
  79210. left = strm->avail_out; \
  79211. next = strm->next_in; \
  79212. have = strm->avail_in; \
  79213. hold = state->hold; \
  79214. bits = state->bits; \
  79215. } while (0)
  79216. /* Restore state from registers in inflate() */
  79217. #define RESTORE() \
  79218. do { \
  79219. strm->next_out = put; \
  79220. strm->avail_out = left; \
  79221. strm->next_in = next; \
  79222. strm->avail_in = have; \
  79223. state->hold = hold; \
  79224. state->bits = bits; \
  79225. } while (0)
  79226. /* Clear the input bit accumulator */
  79227. #define INITBITS() \
  79228. do { \
  79229. hold = 0; \
  79230. bits = 0; \
  79231. } while (0)
  79232. /* Get a byte of input into the bit accumulator, or return from inflate()
  79233. if there is no input available. */
  79234. #define PULLBYTE() \
  79235. do { \
  79236. if (have == 0) goto inf_leave; \
  79237. have--; \
  79238. hold += (unsigned long)(*next++) << bits; \
  79239. bits += 8; \
  79240. } while (0)
  79241. /* Assure that there are at least n bits in the bit accumulator. If there is
  79242. not enough available input to do that, then return from inflate(). */
  79243. #define NEEDBITS(n) \
  79244. do { \
  79245. while (bits < (unsigned)(n)) \
  79246. PULLBYTE(); \
  79247. } while (0)
  79248. /* Return the low n bits of the bit accumulator (n < 16) */
  79249. #define BITS(n) \
  79250. ((unsigned)hold & ((1U << (n)) - 1))
  79251. /* Remove n bits from the bit accumulator */
  79252. #define DROPBITS(n) \
  79253. do { \
  79254. hold >>= (n); \
  79255. bits -= (unsigned)(n); \
  79256. } while (0)
  79257. /* Remove zero to seven bits as needed to go to a byte boundary */
  79258. #define BYTEBITS() \
  79259. do { \
  79260. hold >>= bits & 7; \
  79261. bits -= bits & 7; \
  79262. } while (0)
  79263. /* Reverse the bytes in a 32-bit value */
  79264. #define REVERSE(q) \
  79265. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  79266. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  79267. /*
  79268. inflate() uses a state machine to process as much input data and generate as
  79269. much output data as possible before returning. The state machine is
  79270. structured roughly as follows:
  79271. for (;;) switch (state) {
  79272. ...
  79273. case STATEn:
  79274. if (not enough input data or output space to make progress)
  79275. return;
  79276. ... make progress ...
  79277. state = STATEm;
  79278. break;
  79279. ...
  79280. }
  79281. so when inflate() is called again, the same case is attempted again, and
  79282. if the appropriate resources are provided, the machine proceeds to the
  79283. next state. The NEEDBITS() macro is usually the way the state evaluates
  79284. whether it can proceed or should return. NEEDBITS() does the return if
  79285. the requested bits are not available. The typical use of the BITS macros
  79286. is:
  79287. NEEDBITS(n);
  79288. ... do something with BITS(n) ...
  79289. DROPBITS(n);
  79290. where NEEDBITS(n) either returns from inflate() if there isn't enough
  79291. input left to load n bits into the accumulator, or it continues. BITS(n)
  79292. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  79293. the low n bits off the accumulator. INITBITS() clears the accumulator
  79294. and sets the number of available bits to zero. BYTEBITS() discards just
  79295. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  79296. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  79297. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  79298. if there is no input available. The decoding of variable length codes uses
  79299. PULLBYTE() directly in order to pull just enough bytes to decode the next
  79300. code, and no more.
  79301. Some states loop until they get enough input, making sure that enough
  79302. state information is maintained to continue the loop where it left off
  79303. if NEEDBITS() returns in the loop. For example, want, need, and keep
  79304. would all have to actually be part of the saved state in case NEEDBITS()
  79305. returns:
  79306. case STATEw:
  79307. while (want < need) {
  79308. NEEDBITS(n);
  79309. keep[want++] = BITS(n);
  79310. DROPBITS(n);
  79311. }
  79312. state = STATEx;
  79313. case STATEx:
  79314. As shown above, if the next state is also the next case, then the break
  79315. is omitted.
  79316. A state may also return if there is not enough output space available to
  79317. complete that state. Those states are copying stored data, writing a
  79318. literal byte, and copying a matching string.
  79319. When returning, a "goto inf_leave" is used to update the total counters,
  79320. update the check value, and determine whether any progress has been made
  79321. during that inflate() call in order to return the proper return code.
  79322. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  79323. When there is a window, goto inf_leave will update the window with the last
  79324. output written. If a goto inf_leave occurs in the middle of decompression
  79325. and there is no window currently, goto inf_leave will create one and copy
  79326. output to the window for the next call of inflate().
  79327. In this implementation, the flush parameter of inflate() only affects the
  79328. return code (per zlib.h). inflate() always writes as much as possible to
  79329. strm->next_out, given the space available and the provided input--the effect
  79330. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  79331. the allocation of and copying into a sliding window until necessary, which
  79332. provides the effect documented in zlib.h for Z_FINISH when the entire input
  79333. stream available. So the only thing the flush parameter actually does is:
  79334. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  79335. will return Z_BUF_ERROR if it has not reached the end of the stream.
  79336. */
  79337. int ZEXPORT inflate (z_streamp strm, int flush)
  79338. {
  79339. struct inflate_state FAR *state;
  79340. unsigned char FAR *next; /* next input */
  79341. unsigned char FAR *put; /* next output */
  79342. unsigned have, left; /* available input and output */
  79343. unsigned long hold; /* bit buffer */
  79344. unsigned bits; /* bits in bit buffer */
  79345. unsigned in, out; /* save starting available input and output */
  79346. unsigned copy; /* number of stored or match bytes to copy */
  79347. unsigned char FAR *from; /* where to copy match bytes from */
  79348. code thisx; /* current decoding table entry */
  79349. code last; /* parent table entry */
  79350. unsigned len; /* length to copy for repeats, bits to drop */
  79351. int ret; /* return code */
  79352. #ifdef GUNZIP
  79353. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  79354. #endif
  79355. static const unsigned short order[19] = /* permutation of code lengths */
  79356. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  79357. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  79358. (strm->next_in == Z_NULL && strm->avail_in != 0))
  79359. return Z_STREAM_ERROR;
  79360. state = (struct inflate_state FAR *)strm->state;
  79361. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  79362. LOAD();
  79363. in = have;
  79364. out = left;
  79365. ret = Z_OK;
  79366. for (;;)
  79367. switch (state->mode) {
  79368. case HEAD:
  79369. if (state->wrap == 0) {
  79370. state->mode = TYPEDO;
  79371. break;
  79372. }
  79373. NEEDBITS(16);
  79374. #ifdef GUNZIP
  79375. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  79376. state->check = crc32(0L, Z_NULL, 0);
  79377. CRC2(state->check, hold);
  79378. INITBITS();
  79379. state->mode = FLAGS;
  79380. break;
  79381. }
  79382. state->flags = 0; /* expect zlib header */
  79383. if (state->head != Z_NULL)
  79384. state->head->done = -1;
  79385. if (!(state->wrap & 1) || /* check if zlib header allowed */
  79386. #else
  79387. if (
  79388. #endif
  79389. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  79390. strm->msg = (char *)"incorrect header check";
  79391. state->mode = BAD;
  79392. break;
  79393. }
  79394. if (BITS(4) != Z_DEFLATED) {
  79395. strm->msg = (char *)"unknown compression method";
  79396. state->mode = BAD;
  79397. break;
  79398. }
  79399. DROPBITS(4);
  79400. len = BITS(4) + 8;
  79401. if (len > state->wbits) {
  79402. strm->msg = (char *)"invalid window size";
  79403. state->mode = BAD;
  79404. break;
  79405. }
  79406. state->dmax = 1U << len;
  79407. Tracev((stderr, "inflate: zlib header ok\n"));
  79408. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79409. state->mode = hold & 0x200 ? DICTID : TYPE;
  79410. INITBITS();
  79411. break;
  79412. #ifdef GUNZIP
  79413. case FLAGS:
  79414. NEEDBITS(16);
  79415. state->flags = (int)(hold);
  79416. if ((state->flags & 0xff) != Z_DEFLATED) {
  79417. strm->msg = (char *)"unknown compression method";
  79418. state->mode = BAD;
  79419. break;
  79420. }
  79421. if (state->flags & 0xe000) {
  79422. strm->msg = (char *)"unknown header flags set";
  79423. state->mode = BAD;
  79424. break;
  79425. }
  79426. if (state->head != Z_NULL)
  79427. state->head->text = (int)((hold >> 8) & 1);
  79428. if (state->flags & 0x0200) CRC2(state->check, hold);
  79429. INITBITS();
  79430. state->mode = TIME;
  79431. case TIME:
  79432. NEEDBITS(32);
  79433. if (state->head != Z_NULL)
  79434. state->head->time = hold;
  79435. if (state->flags & 0x0200) CRC4(state->check, hold);
  79436. INITBITS();
  79437. state->mode = OS;
  79438. case OS:
  79439. NEEDBITS(16);
  79440. if (state->head != Z_NULL) {
  79441. state->head->xflags = (int)(hold & 0xff);
  79442. state->head->os = (int)(hold >> 8);
  79443. }
  79444. if (state->flags & 0x0200) CRC2(state->check, hold);
  79445. INITBITS();
  79446. state->mode = EXLEN;
  79447. case EXLEN:
  79448. if (state->flags & 0x0400) {
  79449. NEEDBITS(16);
  79450. state->length = (unsigned)(hold);
  79451. if (state->head != Z_NULL)
  79452. state->head->extra_len = (unsigned)hold;
  79453. if (state->flags & 0x0200) CRC2(state->check, hold);
  79454. INITBITS();
  79455. }
  79456. else if (state->head != Z_NULL)
  79457. state->head->extra = Z_NULL;
  79458. state->mode = EXTRA;
  79459. case EXTRA:
  79460. if (state->flags & 0x0400) {
  79461. copy = state->length;
  79462. if (copy > have) copy = have;
  79463. if (copy) {
  79464. if (state->head != Z_NULL &&
  79465. state->head->extra != Z_NULL) {
  79466. len = state->head->extra_len - state->length;
  79467. zmemcpy(state->head->extra + len, next,
  79468. len + copy > state->head->extra_max ?
  79469. state->head->extra_max - len : copy);
  79470. }
  79471. if (state->flags & 0x0200)
  79472. state->check = crc32(state->check, next, copy);
  79473. have -= copy;
  79474. next += copy;
  79475. state->length -= copy;
  79476. }
  79477. if (state->length) goto inf_leave;
  79478. }
  79479. state->length = 0;
  79480. state->mode = NAME;
  79481. case NAME:
  79482. if (state->flags & 0x0800) {
  79483. if (have == 0) goto inf_leave;
  79484. copy = 0;
  79485. do {
  79486. len = (unsigned)(next[copy++]);
  79487. if (state->head != Z_NULL &&
  79488. state->head->name != Z_NULL &&
  79489. state->length < state->head->name_max)
  79490. state->head->name[state->length++] = len;
  79491. } while (len && copy < have);
  79492. if (state->flags & 0x0200)
  79493. state->check = crc32(state->check, next, copy);
  79494. have -= copy;
  79495. next += copy;
  79496. if (len) goto inf_leave;
  79497. }
  79498. else if (state->head != Z_NULL)
  79499. state->head->name = Z_NULL;
  79500. state->length = 0;
  79501. state->mode = COMMENT;
  79502. case COMMENT:
  79503. if (state->flags & 0x1000) {
  79504. if (have == 0) goto inf_leave;
  79505. copy = 0;
  79506. do {
  79507. len = (unsigned)(next[copy++]);
  79508. if (state->head != Z_NULL &&
  79509. state->head->comment != Z_NULL &&
  79510. state->length < state->head->comm_max)
  79511. state->head->comment[state->length++] = len;
  79512. } while (len && copy < have);
  79513. if (state->flags & 0x0200)
  79514. state->check = crc32(state->check, next, copy);
  79515. have -= copy;
  79516. next += copy;
  79517. if (len) goto inf_leave;
  79518. }
  79519. else if (state->head != Z_NULL)
  79520. state->head->comment = Z_NULL;
  79521. state->mode = HCRC;
  79522. case HCRC:
  79523. if (state->flags & 0x0200) {
  79524. NEEDBITS(16);
  79525. if (hold != (state->check & 0xffff)) {
  79526. strm->msg = (char *)"header crc mismatch";
  79527. state->mode = BAD;
  79528. break;
  79529. }
  79530. INITBITS();
  79531. }
  79532. if (state->head != Z_NULL) {
  79533. state->head->hcrc = (int)((state->flags >> 9) & 1);
  79534. state->head->done = 1;
  79535. }
  79536. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  79537. state->mode = TYPE;
  79538. break;
  79539. #endif
  79540. case DICTID:
  79541. NEEDBITS(32);
  79542. strm->adler = state->check = REVERSE(hold);
  79543. INITBITS();
  79544. state->mode = DICT;
  79545. case DICT:
  79546. if (state->havedict == 0) {
  79547. RESTORE();
  79548. return Z_NEED_DICT;
  79549. }
  79550. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79551. state->mode = TYPE;
  79552. case TYPE:
  79553. if (flush == Z_BLOCK) goto inf_leave;
  79554. case TYPEDO:
  79555. if (state->last) {
  79556. BYTEBITS();
  79557. state->mode = CHECK;
  79558. break;
  79559. }
  79560. NEEDBITS(3);
  79561. state->last = BITS(1);
  79562. DROPBITS(1);
  79563. switch (BITS(2)) {
  79564. case 0: /* stored block */
  79565. Tracev((stderr, "inflate: stored block%s\n",
  79566. state->last ? " (last)" : ""));
  79567. state->mode = STORED;
  79568. break;
  79569. case 1: /* fixed block */
  79570. fixedtables(state);
  79571. Tracev((stderr, "inflate: fixed codes block%s\n",
  79572. state->last ? " (last)" : ""));
  79573. state->mode = LEN; /* decode codes */
  79574. break;
  79575. case 2: /* dynamic block */
  79576. Tracev((stderr, "inflate: dynamic codes block%s\n",
  79577. state->last ? " (last)" : ""));
  79578. state->mode = TABLE;
  79579. break;
  79580. case 3:
  79581. strm->msg = (char *)"invalid block type";
  79582. state->mode = BAD;
  79583. }
  79584. DROPBITS(2);
  79585. break;
  79586. case STORED:
  79587. BYTEBITS(); /* go to byte boundary */
  79588. NEEDBITS(32);
  79589. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  79590. strm->msg = (char *)"invalid stored block lengths";
  79591. state->mode = BAD;
  79592. break;
  79593. }
  79594. state->length = (unsigned)hold & 0xffff;
  79595. Tracev((stderr, "inflate: stored length %u\n",
  79596. state->length));
  79597. INITBITS();
  79598. state->mode = COPY;
  79599. case COPY:
  79600. copy = state->length;
  79601. if (copy) {
  79602. if (copy > have) copy = have;
  79603. if (copy > left) copy = left;
  79604. if (copy == 0) goto inf_leave;
  79605. zmemcpy(put, next, copy);
  79606. have -= copy;
  79607. next += copy;
  79608. left -= copy;
  79609. put += copy;
  79610. state->length -= copy;
  79611. break;
  79612. }
  79613. Tracev((stderr, "inflate: stored end\n"));
  79614. state->mode = TYPE;
  79615. break;
  79616. case TABLE:
  79617. NEEDBITS(14);
  79618. state->nlen = BITS(5) + 257;
  79619. DROPBITS(5);
  79620. state->ndist = BITS(5) + 1;
  79621. DROPBITS(5);
  79622. state->ncode = BITS(4) + 4;
  79623. DROPBITS(4);
  79624. #ifndef PKZIP_BUG_WORKAROUND
  79625. if (state->nlen > 286 || state->ndist > 30) {
  79626. strm->msg = (char *)"too many length or distance symbols";
  79627. state->mode = BAD;
  79628. break;
  79629. }
  79630. #endif
  79631. Tracev((stderr, "inflate: table sizes ok\n"));
  79632. state->have = 0;
  79633. state->mode = LENLENS;
  79634. case LENLENS:
  79635. while (state->have < state->ncode) {
  79636. NEEDBITS(3);
  79637. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  79638. DROPBITS(3);
  79639. }
  79640. while (state->have < 19)
  79641. state->lens[order[state->have++]] = 0;
  79642. state->next = state->codes;
  79643. state->lencode = (code const FAR *)(state->next);
  79644. state->lenbits = 7;
  79645. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  79646. &(state->lenbits), state->work);
  79647. if (ret) {
  79648. strm->msg = (char *)"invalid code lengths set";
  79649. state->mode = BAD;
  79650. break;
  79651. }
  79652. Tracev((stderr, "inflate: code lengths ok\n"));
  79653. state->have = 0;
  79654. state->mode = CODELENS;
  79655. case CODELENS:
  79656. while (state->have < state->nlen + state->ndist) {
  79657. for (;;) {
  79658. thisx = state->lencode[BITS(state->lenbits)];
  79659. if ((unsigned)(thisx.bits) <= bits) break;
  79660. PULLBYTE();
  79661. }
  79662. if (thisx.val < 16) {
  79663. NEEDBITS(thisx.bits);
  79664. DROPBITS(thisx.bits);
  79665. state->lens[state->have++] = thisx.val;
  79666. }
  79667. else {
  79668. if (thisx.val == 16) {
  79669. NEEDBITS(thisx.bits + 2);
  79670. DROPBITS(thisx.bits);
  79671. if (state->have == 0) {
  79672. strm->msg = (char *)"invalid bit length repeat";
  79673. state->mode = BAD;
  79674. break;
  79675. }
  79676. len = state->lens[state->have - 1];
  79677. copy = 3 + BITS(2);
  79678. DROPBITS(2);
  79679. }
  79680. else if (thisx.val == 17) {
  79681. NEEDBITS(thisx.bits + 3);
  79682. DROPBITS(thisx.bits);
  79683. len = 0;
  79684. copy = 3 + BITS(3);
  79685. DROPBITS(3);
  79686. }
  79687. else {
  79688. NEEDBITS(thisx.bits + 7);
  79689. DROPBITS(thisx.bits);
  79690. len = 0;
  79691. copy = 11 + BITS(7);
  79692. DROPBITS(7);
  79693. }
  79694. if (state->have + copy > state->nlen + state->ndist) {
  79695. strm->msg = (char *)"invalid bit length repeat";
  79696. state->mode = BAD;
  79697. break;
  79698. }
  79699. while (copy--)
  79700. state->lens[state->have++] = (unsigned short)len;
  79701. }
  79702. }
  79703. /* handle error breaks in while */
  79704. if (state->mode == BAD) break;
  79705. /* build code tables */
  79706. state->next = state->codes;
  79707. state->lencode = (code const FAR *)(state->next);
  79708. state->lenbits = 9;
  79709. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  79710. &(state->lenbits), state->work);
  79711. if (ret) {
  79712. strm->msg = (char *)"invalid literal/lengths set";
  79713. state->mode = BAD;
  79714. break;
  79715. }
  79716. state->distcode = (code const FAR *)(state->next);
  79717. state->distbits = 6;
  79718. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  79719. &(state->next), &(state->distbits), state->work);
  79720. if (ret) {
  79721. strm->msg = (char *)"invalid distances set";
  79722. state->mode = BAD;
  79723. break;
  79724. }
  79725. Tracev((stderr, "inflate: codes ok\n"));
  79726. state->mode = LEN;
  79727. case LEN:
  79728. if (have >= 6 && left >= 258) {
  79729. RESTORE();
  79730. inflate_fast(strm, out);
  79731. LOAD();
  79732. break;
  79733. }
  79734. for (;;) {
  79735. thisx = state->lencode[BITS(state->lenbits)];
  79736. if ((unsigned)(thisx.bits) <= bits) break;
  79737. PULLBYTE();
  79738. }
  79739. if (thisx.op && (thisx.op & 0xf0) == 0) {
  79740. last = thisx;
  79741. for (;;) {
  79742. thisx = state->lencode[last.val +
  79743. (BITS(last.bits + last.op) >> last.bits)];
  79744. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79745. PULLBYTE();
  79746. }
  79747. DROPBITS(last.bits);
  79748. }
  79749. DROPBITS(thisx.bits);
  79750. state->length = (unsigned)thisx.val;
  79751. if ((int)(thisx.op) == 0) {
  79752. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79753. "inflate: literal '%c'\n" :
  79754. "inflate: literal 0x%02x\n", thisx.val));
  79755. state->mode = LIT;
  79756. break;
  79757. }
  79758. if (thisx.op & 32) {
  79759. Tracevv((stderr, "inflate: end of block\n"));
  79760. state->mode = TYPE;
  79761. break;
  79762. }
  79763. if (thisx.op & 64) {
  79764. strm->msg = (char *)"invalid literal/length code";
  79765. state->mode = BAD;
  79766. break;
  79767. }
  79768. state->extra = (unsigned)(thisx.op) & 15;
  79769. state->mode = LENEXT;
  79770. case LENEXT:
  79771. if (state->extra) {
  79772. NEEDBITS(state->extra);
  79773. state->length += BITS(state->extra);
  79774. DROPBITS(state->extra);
  79775. }
  79776. Tracevv((stderr, "inflate: length %u\n", state->length));
  79777. state->mode = DIST;
  79778. case DIST:
  79779. for (;;) {
  79780. thisx = state->distcode[BITS(state->distbits)];
  79781. if ((unsigned)(thisx.bits) <= bits) break;
  79782. PULLBYTE();
  79783. }
  79784. if ((thisx.op & 0xf0) == 0) {
  79785. last = thisx;
  79786. for (;;) {
  79787. thisx = state->distcode[last.val +
  79788. (BITS(last.bits + last.op) >> last.bits)];
  79789. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79790. PULLBYTE();
  79791. }
  79792. DROPBITS(last.bits);
  79793. }
  79794. DROPBITS(thisx.bits);
  79795. if (thisx.op & 64) {
  79796. strm->msg = (char *)"invalid distance code";
  79797. state->mode = BAD;
  79798. break;
  79799. }
  79800. state->offset = (unsigned)thisx.val;
  79801. state->extra = (unsigned)(thisx.op) & 15;
  79802. state->mode = DISTEXT;
  79803. case DISTEXT:
  79804. if (state->extra) {
  79805. NEEDBITS(state->extra);
  79806. state->offset += BITS(state->extra);
  79807. DROPBITS(state->extra);
  79808. }
  79809. #ifdef INFLATE_STRICT
  79810. if (state->offset > state->dmax) {
  79811. strm->msg = (char *)"invalid distance too far back";
  79812. state->mode = BAD;
  79813. break;
  79814. }
  79815. #endif
  79816. if (state->offset > state->whave + out - left) {
  79817. strm->msg = (char *)"invalid distance too far back";
  79818. state->mode = BAD;
  79819. break;
  79820. }
  79821. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  79822. state->mode = MATCH;
  79823. case MATCH:
  79824. if (left == 0) goto inf_leave;
  79825. copy = out - left;
  79826. if (state->offset > copy) { /* copy from window */
  79827. copy = state->offset - copy;
  79828. if (copy > state->write) {
  79829. copy -= state->write;
  79830. from = state->window + (state->wsize - copy);
  79831. }
  79832. else
  79833. from = state->window + (state->write - copy);
  79834. if (copy > state->length) copy = state->length;
  79835. }
  79836. else { /* copy from output */
  79837. from = put - state->offset;
  79838. copy = state->length;
  79839. }
  79840. if (copy > left) copy = left;
  79841. left -= copy;
  79842. state->length -= copy;
  79843. do {
  79844. *put++ = *from++;
  79845. } while (--copy);
  79846. if (state->length == 0) state->mode = LEN;
  79847. break;
  79848. case LIT:
  79849. if (left == 0) goto inf_leave;
  79850. *put++ = (unsigned char)(state->length);
  79851. left--;
  79852. state->mode = LEN;
  79853. break;
  79854. case CHECK:
  79855. if (state->wrap) {
  79856. NEEDBITS(32);
  79857. out -= left;
  79858. strm->total_out += out;
  79859. state->total += out;
  79860. if (out)
  79861. strm->adler = state->check =
  79862. UPDATE(state->check, put - out, out);
  79863. out = left;
  79864. if ((
  79865. #ifdef GUNZIP
  79866. state->flags ? hold :
  79867. #endif
  79868. REVERSE(hold)) != state->check) {
  79869. strm->msg = (char *)"incorrect data check";
  79870. state->mode = BAD;
  79871. break;
  79872. }
  79873. INITBITS();
  79874. Tracev((stderr, "inflate: check matches trailer\n"));
  79875. }
  79876. #ifdef GUNZIP
  79877. state->mode = LENGTH;
  79878. case LENGTH:
  79879. if (state->wrap && state->flags) {
  79880. NEEDBITS(32);
  79881. if (hold != (state->total & 0xffffffffUL)) {
  79882. strm->msg = (char *)"incorrect length check";
  79883. state->mode = BAD;
  79884. break;
  79885. }
  79886. INITBITS();
  79887. Tracev((stderr, "inflate: length matches trailer\n"));
  79888. }
  79889. #endif
  79890. state->mode = DONE;
  79891. case DONE:
  79892. ret = Z_STREAM_END;
  79893. goto inf_leave;
  79894. case BAD:
  79895. ret = Z_DATA_ERROR;
  79896. goto inf_leave;
  79897. case MEM:
  79898. return Z_MEM_ERROR;
  79899. case SYNC:
  79900. default:
  79901. return Z_STREAM_ERROR;
  79902. }
  79903. /*
  79904. Return from inflate(), updating the total counts and the check value.
  79905. If there was no progress during the inflate() call, return a buffer
  79906. error. Call updatewindow() to create and/or update the window state.
  79907. Note: a memory error from inflate() is non-recoverable.
  79908. */
  79909. inf_leave:
  79910. RESTORE();
  79911. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  79912. if (updatewindow(strm, out)) {
  79913. state->mode = MEM;
  79914. return Z_MEM_ERROR;
  79915. }
  79916. in -= strm->avail_in;
  79917. out -= strm->avail_out;
  79918. strm->total_in += in;
  79919. strm->total_out += out;
  79920. state->total += out;
  79921. if (state->wrap && out)
  79922. strm->adler = state->check =
  79923. UPDATE(state->check, strm->next_out - out, out);
  79924. strm->data_type = state->bits + (state->last ? 64 : 0) +
  79925. (state->mode == TYPE ? 128 : 0);
  79926. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  79927. ret = Z_BUF_ERROR;
  79928. return ret;
  79929. }
  79930. int ZEXPORT inflateEnd (z_streamp strm)
  79931. {
  79932. struct inflate_state FAR *state;
  79933. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  79934. return Z_STREAM_ERROR;
  79935. state = (struct inflate_state FAR *)strm->state;
  79936. if (state->window != Z_NULL) ZFREE(strm, state->window);
  79937. ZFREE(strm, strm->state);
  79938. strm->state = Z_NULL;
  79939. Tracev((stderr, "inflate: end\n"));
  79940. return Z_OK;
  79941. }
  79942. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  79943. {
  79944. struct inflate_state FAR *state;
  79945. unsigned long id_;
  79946. /* check state */
  79947. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79948. state = (struct inflate_state FAR *)strm->state;
  79949. if (state->wrap != 0 && state->mode != DICT)
  79950. return Z_STREAM_ERROR;
  79951. /* check for correct dictionary id */
  79952. if (state->mode == DICT) {
  79953. id_ = adler32(0L, Z_NULL, 0);
  79954. id_ = adler32(id_, dictionary, dictLength);
  79955. if (id_ != state->check)
  79956. return Z_DATA_ERROR;
  79957. }
  79958. /* copy dictionary to window */
  79959. if (updatewindow(strm, strm->avail_out)) {
  79960. state->mode = MEM;
  79961. return Z_MEM_ERROR;
  79962. }
  79963. if (dictLength > state->wsize) {
  79964. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  79965. state->wsize);
  79966. state->whave = state->wsize;
  79967. }
  79968. else {
  79969. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  79970. dictLength);
  79971. state->whave = dictLength;
  79972. }
  79973. state->havedict = 1;
  79974. Tracev((stderr, "inflate: dictionary set\n"));
  79975. return Z_OK;
  79976. }
  79977. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  79978. {
  79979. struct inflate_state FAR *state;
  79980. /* check state */
  79981. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79982. state = (struct inflate_state FAR *)strm->state;
  79983. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  79984. /* save header structure */
  79985. state->head = head;
  79986. head->done = 0;
  79987. return Z_OK;
  79988. }
  79989. /*
  79990. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  79991. or when out of input. When called, *have is the number of pattern bytes
  79992. found in order so far, in 0..3. On return *have is updated to the new
  79993. state. If on return *have equals four, then the pattern was found and the
  79994. return value is how many bytes were read including the last byte of the
  79995. pattern. If *have is less than four, then the pattern has not been found
  79996. yet and the return value is len. In the latter case, syncsearch() can be
  79997. called again with more data and the *have state. *have is initialized to
  79998. zero for the first call.
  79999. */
  80000. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  80001. {
  80002. unsigned got;
  80003. unsigned next;
  80004. got = *have;
  80005. next = 0;
  80006. while (next < len && got < 4) {
  80007. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  80008. got++;
  80009. else if (buf[next])
  80010. got = 0;
  80011. else
  80012. got = 4 - got;
  80013. next++;
  80014. }
  80015. *have = got;
  80016. return next;
  80017. }
  80018. int ZEXPORT inflateSync (z_streamp strm)
  80019. {
  80020. unsigned len; /* number of bytes to look at or looked at */
  80021. unsigned long in, out; /* temporary to save total_in and total_out */
  80022. unsigned char buf[4]; /* to restore bit buffer to byte string */
  80023. struct inflate_state FAR *state;
  80024. /* check parameters */
  80025. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80026. state = (struct inflate_state FAR *)strm->state;
  80027. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  80028. /* if first time, start search in bit buffer */
  80029. if (state->mode != SYNC) {
  80030. state->mode = SYNC;
  80031. state->hold <<= state->bits & 7;
  80032. state->bits -= state->bits & 7;
  80033. len = 0;
  80034. while (state->bits >= 8) {
  80035. buf[len++] = (unsigned char)(state->hold);
  80036. state->hold >>= 8;
  80037. state->bits -= 8;
  80038. }
  80039. state->have = 0;
  80040. syncsearch(&(state->have), buf, len);
  80041. }
  80042. /* search available input */
  80043. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  80044. strm->avail_in -= len;
  80045. strm->next_in += len;
  80046. strm->total_in += len;
  80047. /* return no joy or set up to restart inflate() on a new block */
  80048. if (state->have != 4) return Z_DATA_ERROR;
  80049. in = strm->total_in; out = strm->total_out;
  80050. inflateReset(strm);
  80051. strm->total_in = in; strm->total_out = out;
  80052. state->mode = TYPE;
  80053. return Z_OK;
  80054. }
  80055. /*
  80056. Returns true if inflate is currently at the end of a block generated by
  80057. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  80058. implementation to provide an additional safety check. PPP uses
  80059. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  80060. block. When decompressing, PPP checks that at the end of input packet,
  80061. inflate is waiting for these length bytes.
  80062. */
  80063. int ZEXPORT inflateSyncPoint (z_streamp strm)
  80064. {
  80065. struct inflate_state FAR *state;
  80066. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80067. state = (struct inflate_state FAR *)strm->state;
  80068. return state->mode == STORED && state->bits == 0;
  80069. }
  80070. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  80071. {
  80072. struct inflate_state FAR *state;
  80073. struct inflate_state FAR *copy;
  80074. unsigned char FAR *window;
  80075. unsigned wsize;
  80076. /* check input */
  80077. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  80078. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  80079. return Z_STREAM_ERROR;
  80080. state = (struct inflate_state FAR *)source->state;
  80081. /* allocate space */
  80082. copy = (struct inflate_state FAR *)
  80083. ZALLOC(source, 1, sizeof(struct inflate_state));
  80084. if (copy == Z_NULL) return Z_MEM_ERROR;
  80085. window = Z_NULL;
  80086. if (state->window != Z_NULL) {
  80087. window = (unsigned char FAR *)
  80088. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  80089. if (window == Z_NULL) {
  80090. ZFREE(source, copy);
  80091. return Z_MEM_ERROR;
  80092. }
  80093. }
  80094. /* copy state */
  80095. zmemcpy(dest, source, sizeof(z_stream));
  80096. zmemcpy(copy, state, sizeof(struct inflate_state));
  80097. if (state->lencode >= state->codes &&
  80098. state->lencode <= state->codes + ENOUGH - 1) {
  80099. copy->lencode = copy->codes + (state->lencode - state->codes);
  80100. copy->distcode = copy->codes + (state->distcode - state->codes);
  80101. }
  80102. copy->next = copy->codes + (state->next - state->codes);
  80103. if (window != Z_NULL) {
  80104. wsize = 1U << state->wbits;
  80105. zmemcpy(window, state->window, wsize);
  80106. }
  80107. copy->window = window;
  80108. dest->state = (struct internal_state FAR *)copy;
  80109. return Z_OK;
  80110. }
  80111. /********* End of inlined file: inflate.c *********/
  80112. /********* Start of inlined file: inftrees.c *********/
  80113. #define MAXBITS 15
  80114. const char inflate_copyright[] =
  80115. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  80116. /*
  80117. If you use the zlib library in a product, an acknowledgment is welcome
  80118. in the documentation of your product. If for some reason you cannot
  80119. include such an acknowledgment, I would appreciate that you keep this
  80120. copyright string in the executable of your product.
  80121. */
  80122. /*
  80123. Build a set of tables to decode the provided canonical Huffman code.
  80124. The code lengths are lens[0..codes-1]. The result starts at *table,
  80125. whose indices are 0..2^bits-1. work is a writable array of at least
  80126. lens shorts, which is used as a work area. type is the type of code
  80127. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  80128. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  80129. on return points to the next available entry's address. bits is the
  80130. requested root table index bits, and on return it is the actual root
  80131. table index bits. It will differ if the request is greater than the
  80132. longest code or if it is less than the shortest code.
  80133. */
  80134. int inflate_table (codetype type,
  80135. unsigned short FAR *lens,
  80136. unsigned codes,
  80137. code FAR * FAR *table,
  80138. unsigned FAR *bits,
  80139. unsigned short FAR *work)
  80140. {
  80141. unsigned len; /* a code's length in bits */
  80142. unsigned sym; /* index of code symbols */
  80143. unsigned min, max; /* minimum and maximum code lengths */
  80144. unsigned root; /* number of index bits for root table */
  80145. unsigned curr; /* number of index bits for current table */
  80146. unsigned drop; /* code bits to drop for sub-table */
  80147. int left; /* number of prefix codes available */
  80148. unsigned used; /* code entries in table used */
  80149. unsigned huff; /* Huffman code */
  80150. unsigned incr; /* for incrementing code, index */
  80151. unsigned fill; /* index for replicating entries */
  80152. unsigned low; /* low bits for current root entry */
  80153. unsigned mask; /* mask for low root bits */
  80154. code thisx; /* table entry for duplication */
  80155. code FAR *next; /* next available space in table */
  80156. const unsigned short FAR *base; /* base value table to use */
  80157. const unsigned short FAR *extra; /* extra bits table to use */
  80158. int end; /* use base and extra for symbol > end */
  80159. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  80160. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  80161. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  80162. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  80163. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  80164. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  80165. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  80166. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  80167. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  80168. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  80169. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  80170. 8193, 12289, 16385, 24577, 0, 0};
  80171. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  80172. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  80173. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  80174. 28, 28, 29, 29, 64, 64};
  80175. /*
  80176. Process a set of code lengths to create a canonical Huffman code. The
  80177. code lengths are lens[0..codes-1]. Each length corresponds to the
  80178. symbols 0..codes-1. The Huffman code is generated by first sorting the
  80179. symbols by length from short to long, and retaining the symbol order
  80180. for codes with equal lengths. Then the code starts with all zero bits
  80181. for the first code of the shortest length, and the codes are integer
  80182. increments for the same length, and zeros are appended as the length
  80183. increases. For the deflate format, these bits are stored backwards
  80184. from their more natural integer increment ordering, and so when the
  80185. decoding tables are built in the large loop below, the integer codes
  80186. are incremented backwards.
  80187. This routine assumes, but does not check, that all of the entries in
  80188. lens[] are in the range 0..MAXBITS. The caller must assure this.
  80189. 1..MAXBITS is interpreted as that code length. zero means that that
  80190. symbol does not occur in this code.
  80191. The codes are sorted by computing a count of codes for each length,
  80192. creating from that a table of starting indices for each length in the
  80193. sorted table, and then entering the symbols in order in the sorted
  80194. table. The sorted table is work[], with that space being provided by
  80195. the caller.
  80196. The length counts are used for other purposes as well, i.e. finding
  80197. the minimum and maximum length codes, determining if there are any
  80198. codes at all, checking for a valid set of lengths, and looking ahead
  80199. at length counts to determine sub-table sizes when building the
  80200. decoding tables.
  80201. */
  80202. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  80203. for (len = 0; len <= MAXBITS; len++)
  80204. count[len] = 0;
  80205. for (sym = 0; sym < codes; sym++)
  80206. count[lens[sym]]++;
  80207. /* bound code lengths, force root to be within code lengths */
  80208. root = *bits;
  80209. for (max = MAXBITS; max >= 1; max--)
  80210. if (count[max] != 0) break;
  80211. if (root > max) root = max;
  80212. if (max == 0) { /* no symbols to code at all */
  80213. thisx.op = (unsigned char)64; /* invalid code marker */
  80214. thisx.bits = (unsigned char)1;
  80215. thisx.val = (unsigned short)0;
  80216. *(*table)++ = thisx; /* make a table to force an error */
  80217. *(*table)++ = thisx;
  80218. *bits = 1;
  80219. return 0; /* no symbols, but wait for decoding to report error */
  80220. }
  80221. for (min = 1; min <= MAXBITS; min++)
  80222. if (count[min] != 0) break;
  80223. if (root < min) root = min;
  80224. /* check for an over-subscribed or incomplete set of lengths */
  80225. left = 1;
  80226. for (len = 1; len <= MAXBITS; len++) {
  80227. left <<= 1;
  80228. left -= count[len];
  80229. if (left < 0) return -1; /* over-subscribed */
  80230. }
  80231. if (left > 0 && (type == CODES || max != 1))
  80232. return -1; /* incomplete set */
  80233. /* generate offsets into symbol table for each length for sorting */
  80234. offs[1] = 0;
  80235. for (len = 1; len < MAXBITS; len++)
  80236. offs[len + 1] = offs[len] + count[len];
  80237. /* sort symbols by length, by symbol order within each length */
  80238. for (sym = 0; sym < codes; sym++)
  80239. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  80240. /*
  80241. Create and fill in decoding tables. In this loop, the table being
  80242. filled is at next and has curr index bits. The code being used is huff
  80243. with length len. That code is converted to an index by dropping drop
  80244. bits off of the bottom. For codes where len is less than drop + curr,
  80245. those top drop + curr - len bits are incremented through all values to
  80246. fill the table with replicated entries.
  80247. root is the number of index bits for the root table. When len exceeds
  80248. root, sub-tables are created pointed to by the root entry with an index
  80249. of the low root bits of huff. This is saved in low to check for when a
  80250. new sub-table should be started. drop is zero when the root table is
  80251. being filled, and drop is root when sub-tables are being filled.
  80252. When a new sub-table is needed, it is necessary to look ahead in the
  80253. code lengths to determine what size sub-table is needed. The length
  80254. counts are used for this, and so count[] is decremented as codes are
  80255. entered in the tables.
  80256. used keeps track of how many table entries have been allocated from the
  80257. provided *table space. It is checked when a LENS table is being made
  80258. against the space in *table, ENOUGH, minus the maximum space needed by
  80259. the worst case distance code, MAXD. This should never happen, but the
  80260. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  80261. This assumes that when type == LENS, bits == 9.
  80262. sym increments through all symbols, and the loop terminates when
  80263. all codes of length max, i.e. all codes, have been processed. This
  80264. routine permits incomplete codes, so another loop after this one fills
  80265. in the rest of the decoding tables with invalid code markers.
  80266. */
  80267. /* set up for code type */
  80268. switch (type) {
  80269. case CODES:
  80270. base = extra = work; /* dummy value--not used */
  80271. end = 19;
  80272. break;
  80273. case LENS:
  80274. base = lbase;
  80275. base -= 257;
  80276. extra = lext;
  80277. extra -= 257;
  80278. end = 256;
  80279. break;
  80280. default: /* DISTS */
  80281. base = dbase;
  80282. extra = dext;
  80283. end = -1;
  80284. }
  80285. /* initialize state for loop */
  80286. huff = 0; /* starting code */
  80287. sym = 0; /* starting code symbol */
  80288. len = min; /* starting code length */
  80289. next = *table; /* current table to fill in */
  80290. curr = root; /* current table index bits */
  80291. drop = 0; /* current bits to drop from code for index */
  80292. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  80293. used = 1U << root; /* use root table entries */
  80294. mask = used - 1; /* mask for comparing low */
  80295. /* check available table space */
  80296. if (type == LENS && used >= ENOUGH - MAXD)
  80297. return 1;
  80298. /* process all codes and make table entries */
  80299. for (;;) {
  80300. /* create table entry */
  80301. thisx.bits = (unsigned char)(len - drop);
  80302. if ((int)(work[sym]) < end) {
  80303. thisx.op = (unsigned char)0;
  80304. thisx.val = work[sym];
  80305. }
  80306. else if ((int)(work[sym]) > end) {
  80307. thisx.op = (unsigned char)(extra[work[sym]]);
  80308. thisx.val = base[work[sym]];
  80309. }
  80310. else {
  80311. thisx.op = (unsigned char)(32 + 64); /* end of block */
  80312. thisx.val = 0;
  80313. }
  80314. /* replicate for those indices with low len bits equal to huff */
  80315. incr = 1U << (len - drop);
  80316. fill = 1U << curr;
  80317. min = fill; /* save offset to next table */
  80318. do {
  80319. fill -= incr;
  80320. next[(huff >> drop) + fill] = thisx;
  80321. } while (fill != 0);
  80322. /* backwards increment the len-bit code huff */
  80323. incr = 1U << (len - 1);
  80324. while (huff & incr)
  80325. incr >>= 1;
  80326. if (incr != 0) {
  80327. huff &= incr - 1;
  80328. huff += incr;
  80329. }
  80330. else
  80331. huff = 0;
  80332. /* go to next symbol, update count, len */
  80333. sym++;
  80334. if (--(count[len]) == 0) {
  80335. if (len == max) break;
  80336. len = lens[work[sym]];
  80337. }
  80338. /* create new sub-table if needed */
  80339. if (len > root && (huff & mask) != low) {
  80340. /* if first time, transition to sub-tables */
  80341. if (drop == 0)
  80342. drop = root;
  80343. /* increment past last table */
  80344. next += min; /* here min is 1 << curr */
  80345. /* determine length of next table */
  80346. curr = len - drop;
  80347. left = (int)(1 << curr);
  80348. while (curr + drop < max) {
  80349. left -= count[curr + drop];
  80350. if (left <= 0) break;
  80351. curr++;
  80352. left <<= 1;
  80353. }
  80354. /* check for enough space */
  80355. used += 1U << curr;
  80356. if (type == LENS && used >= ENOUGH - MAXD)
  80357. return 1;
  80358. /* point entry in root table to sub-table */
  80359. low = huff & mask;
  80360. (*table)[low].op = (unsigned char)curr;
  80361. (*table)[low].bits = (unsigned char)root;
  80362. (*table)[low].val = (unsigned short)(next - *table);
  80363. }
  80364. }
  80365. /*
  80366. Fill in rest of table for incomplete codes. This loop is similar to the
  80367. loop above in incrementing huff for table indices. It is assumed that
  80368. len is equal to curr + drop, so there is no loop needed to increment
  80369. through high index bits. When the current sub-table is filled, the loop
  80370. drops back to the root table to fill in any remaining entries there.
  80371. */
  80372. thisx.op = (unsigned char)64; /* invalid code marker */
  80373. thisx.bits = (unsigned char)(len - drop);
  80374. thisx.val = (unsigned short)0;
  80375. while (huff != 0) {
  80376. /* when done with sub-table, drop back to root table */
  80377. if (drop != 0 && (huff & mask) != low) {
  80378. drop = 0;
  80379. len = root;
  80380. next = *table;
  80381. thisx.bits = (unsigned char)len;
  80382. }
  80383. /* put invalid code marker in table */
  80384. next[huff >> drop] = thisx;
  80385. /* backwards increment the len-bit code huff */
  80386. incr = 1U << (len - 1);
  80387. while (huff & incr)
  80388. incr >>= 1;
  80389. if (incr != 0) {
  80390. huff &= incr - 1;
  80391. huff += incr;
  80392. }
  80393. else
  80394. huff = 0;
  80395. }
  80396. /* set return parameters */
  80397. *table += used;
  80398. *bits = root;
  80399. return 0;
  80400. }
  80401. /********* End of inlined file: inftrees.c *********/
  80402. /********* Start of inlined file: trees.c *********/
  80403. /*
  80404. * ALGORITHM
  80405. *
  80406. * The "deflation" process uses several Huffman trees. The more
  80407. * common source values are represented by shorter bit sequences.
  80408. *
  80409. * Each code tree is stored in a compressed form which is itself
  80410. * a Huffman encoding of the lengths of all the code strings (in
  80411. * ascending order by source values). The actual code strings are
  80412. * reconstructed from the lengths in the inflate process, as described
  80413. * in the deflate specification.
  80414. *
  80415. * REFERENCES
  80416. *
  80417. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  80418. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  80419. *
  80420. * Storer, James A.
  80421. * Data Compression: Methods and Theory, pp. 49-50.
  80422. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  80423. *
  80424. * Sedgewick, R.
  80425. * Algorithms, p290.
  80426. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  80427. */
  80428. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80429. /* #define GEN_TREES_H */
  80430. #ifdef DEBUG
  80431. # include <ctype.h>
  80432. #endif
  80433. /* ===========================================================================
  80434. * Constants
  80435. */
  80436. #define MAX_BL_BITS 7
  80437. /* Bit length codes must not exceed MAX_BL_BITS bits */
  80438. #define END_BLOCK 256
  80439. /* end of block literal code */
  80440. #define REP_3_6 16
  80441. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  80442. #define REPZ_3_10 17
  80443. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  80444. #define REPZ_11_138 18
  80445. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  80446. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  80447. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  80448. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  80449. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  80450. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  80451. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  80452. local const uch bl_order[BL_CODES]
  80453. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  80454. /* The lengths of the bit length codes are sent in order of decreasing
  80455. * probability, to avoid transmitting the lengths for unused bit length codes.
  80456. */
  80457. #define Buf_size (8 * 2*sizeof(char))
  80458. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  80459. * more than 16 bits on some systems.)
  80460. */
  80461. /* ===========================================================================
  80462. * Local data. These are initialized only once.
  80463. */
  80464. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  80465. #if defined(GEN_TREES_H) || !defined(STDC)
  80466. /* non ANSI compilers may not accept trees.h */
  80467. local ct_data static_ltree[L_CODES+2];
  80468. /* The static literal tree. Since the bit lengths are imposed, there is no
  80469. * need for the L_CODES extra codes used during heap construction. However
  80470. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  80471. * below).
  80472. */
  80473. local ct_data static_dtree[D_CODES];
  80474. /* The static distance tree. (Actually a trivial tree since all codes use
  80475. * 5 bits.)
  80476. */
  80477. uch _dist_code[DIST_CODE_LEN];
  80478. /* Distance codes. The first 256 values correspond to the distances
  80479. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  80480. * the 15 bit distances.
  80481. */
  80482. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  80483. /* length code for each normalized match length (0 == MIN_MATCH) */
  80484. local int base_length[LENGTH_CODES];
  80485. /* First normalized length for each code (0 = MIN_MATCH) */
  80486. local int base_dist[D_CODES];
  80487. /* First normalized distance for each code (0 = distance of 1) */
  80488. #else
  80489. /********* Start of inlined file: trees.h *********/
  80490. local const ct_data static_ltree[L_CODES+2] = {
  80491. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  80492. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  80493. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  80494. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  80495. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  80496. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  80497. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  80498. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  80499. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  80500. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  80501. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  80502. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  80503. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  80504. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  80505. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  80506. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  80507. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  80508. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  80509. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  80510. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  80511. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  80512. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  80513. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  80514. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  80515. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  80516. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  80517. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  80518. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  80519. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  80520. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  80521. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  80522. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  80523. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  80524. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  80525. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  80526. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  80527. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  80528. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  80529. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  80530. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  80531. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  80532. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  80533. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  80534. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  80535. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  80536. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  80537. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  80538. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  80539. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  80540. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  80541. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  80542. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  80543. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  80544. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  80545. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  80546. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  80547. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  80548. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  80549. };
  80550. local const ct_data static_dtree[D_CODES] = {
  80551. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  80552. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  80553. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  80554. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  80555. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  80556. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  80557. };
  80558. const uch _dist_code[DIST_CODE_LEN] = {
  80559. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  80560. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  80561. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  80562. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  80563. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  80564. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  80565. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80566. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80567. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80568. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  80569. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80570. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80571. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  80572. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  80573. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80574. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80575. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80576. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  80577. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80578. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80579. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80580. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80581. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80582. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80583. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80584. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  80585. };
  80586. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  80587. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  80588. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  80589. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  80590. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  80591. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  80592. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  80593. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80594. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80595. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80596. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  80597. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80598. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80599. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  80600. };
  80601. local const int base_length[LENGTH_CODES] = {
  80602. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  80603. 64, 80, 96, 112, 128, 160, 192, 224, 0
  80604. };
  80605. local const int base_dist[D_CODES] = {
  80606. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  80607. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  80608. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  80609. };
  80610. /********* End of inlined file: trees.h *********/
  80611. #endif /* GEN_TREES_H */
  80612. struct static_tree_desc_s {
  80613. const ct_data *static_tree; /* static tree or NULL */
  80614. const intf *extra_bits; /* extra bits for each code or NULL */
  80615. int extra_base; /* base index for extra_bits */
  80616. int elems; /* max number of elements in the tree */
  80617. int max_length; /* max bit length for the codes */
  80618. };
  80619. local static_tree_desc static_l_desc =
  80620. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  80621. local static_tree_desc static_d_desc =
  80622. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  80623. local static_tree_desc static_bl_desc =
  80624. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  80625. /* ===========================================================================
  80626. * Local (static) routines in this file.
  80627. */
  80628. local void tr_static_init OF((void));
  80629. local void init_block OF((deflate_state *s));
  80630. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  80631. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  80632. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  80633. local void build_tree OF((deflate_state *s, tree_desc *desc));
  80634. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80635. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80636. local int build_bl_tree OF((deflate_state *s));
  80637. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  80638. int blcodes));
  80639. local void compress_block OF((deflate_state *s, ct_data *ltree,
  80640. ct_data *dtree));
  80641. local void set_data_type OF((deflate_state *s));
  80642. local unsigned bi_reverse OF((unsigned value, int length));
  80643. local void bi_windup OF((deflate_state *s));
  80644. local void bi_flush OF((deflate_state *s));
  80645. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  80646. int header));
  80647. #ifdef GEN_TREES_H
  80648. local void gen_trees_header OF((void));
  80649. #endif
  80650. #ifndef DEBUG
  80651. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  80652. /* Send a code of the given tree. c and tree must not have side effects */
  80653. #else /* DEBUG */
  80654. # define send_code(s, c, tree) \
  80655. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  80656. send_bits(s, tree[c].Code, tree[c].Len); }
  80657. #endif
  80658. /* ===========================================================================
  80659. * Output a short LSB first on the stream.
  80660. * IN assertion: there is enough room in pendingBuf.
  80661. */
  80662. #define put_short(s, w) { \
  80663. put_byte(s, (uch)((w) & 0xff)); \
  80664. put_byte(s, (uch)((ush)(w) >> 8)); \
  80665. }
  80666. /* ===========================================================================
  80667. * Send a value on a given number of bits.
  80668. * IN assertion: length <= 16 and value fits in length bits.
  80669. */
  80670. #ifdef DEBUG
  80671. local void send_bits OF((deflate_state *s, int value, int length));
  80672. local void send_bits (deflate_state *s, int value, int length)
  80673. {
  80674. Tracevv((stderr," l %2d v %4x ", length, value));
  80675. Assert(length > 0 && length <= 15, "invalid length");
  80676. s->bits_sent += (ulg)length;
  80677. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  80678. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  80679. * unused bits in value.
  80680. */
  80681. if (s->bi_valid > (int)Buf_size - length) {
  80682. s->bi_buf |= (value << s->bi_valid);
  80683. put_short(s, s->bi_buf);
  80684. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  80685. s->bi_valid += length - Buf_size;
  80686. } else {
  80687. s->bi_buf |= value << s->bi_valid;
  80688. s->bi_valid += length;
  80689. }
  80690. }
  80691. #else /* !DEBUG */
  80692. #define send_bits(s, value, length) \
  80693. { int len = length;\
  80694. if (s->bi_valid > (int)Buf_size - len) {\
  80695. int val = value;\
  80696. s->bi_buf |= (val << s->bi_valid);\
  80697. put_short(s, s->bi_buf);\
  80698. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  80699. s->bi_valid += len - Buf_size;\
  80700. } else {\
  80701. s->bi_buf |= (value) << s->bi_valid;\
  80702. s->bi_valid += len;\
  80703. }\
  80704. }
  80705. #endif /* DEBUG */
  80706. /* the arguments must not have side effects */
  80707. /* ===========================================================================
  80708. * Initialize the various 'constant' tables.
  80709. */
  80710. local void tr_static_init()
  80711. {
  80712. #if defined(GEN_TREES_H) || !defined(STDC)
  80713. static int static_init_done = 0;
  80714. int n; /* iterates over tree elements */
  80715. int bits; /* bit counter */
  80716. int length; /* length value */
  80717. int code; /* code value */
  80718. int dist; /* distance index */
  80719. ush bl_count[MAX_BITS+1];
  80720. /* number of codes at each bit length for an optimal tree */
  80721. if (static_init_done) return;
  80722. /* For some embedded targets, global variables are not initialized: */
  80723. static_l_desc.static_tree = static_ltree;
  80724. static_l_desc.extra_bits = extra_lbits;
  80725. static_d_desc.static_tree = static_dtree;
  80726. static_d_desc.extra_bits = extra_dbits;
  80727. static_bl_desc.extra_bits = extra_blbits;
  80728. /* Initialize the mapping length (0..255) -> length code (0..28) */
  80729. length = 0;
  80730. for (code = 0; code < LENGTH_CODES-1; code++) {
  80731. base_length[code] = length;
  80732. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  80733. _length_code[length++] = (uch)code;
  80734. }
  80735. }
  80736. Assert (length == 256, "tr_static_init: length != 256");
  80737. /* Note that the length 255 (match length 258) can be represented
  80738. * in two different ways: code 284 + 5 bits or code 285, so we
  80739. * overwrite length_code[255] to use the best encoding:
  80740. */
  80741. _length_code[length-1] = (uch)code;
  80742. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  80743. dist = 0;
  80744. for (code = 0 ; code < 16; code++) {
  80745. base_dist[code] = dist;
  80746. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  80747. _dist_code[dist++] = (uch)code;
  80748. }
  80749. }
  80750. Assert (dist == 256, "tr_static_init: dist != 256");
  80751. dist >>= 7; /* from now on, all distances are divided by 128 */
  80752. for ( ; code < D_CODES; code++) {
  80753. base_dist[code] = dist << 7;
  80754. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  80755. _dist_code[256 + dist++] = (uch)code;
  80756. }
  80757. }
  80758. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  80759. /* Construct the codes of the static literal tree */
  80760. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  80761. n = 0;
  80762. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  80763. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  80764. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  80765. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  80766. /* Codes 286 and 287 do not exist, but we must include them in the
  80767. * tree construction to get a canonical Huffman tree (longest code
  80768. * all ones)
  80769. */
  80770. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  80771. /* The static distance tree is trivial: */
  80772. for (n = 0; n < D_CODES; n++) {
  80773. static_dtree[n].Len = 5;
  80774. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  80775. }
  80776. static_init_done = 1;
  80777. # ifdef GEN_TREES_H
  80778. gen_trees_header();
  80779. # endif
  80780. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  80781. }
  80782. /* ===========================================================================
  80783. * Genererate the file trees.h describing the static trees.
  80784. */
  80785. #ifdef GEN_TREES_H
  80786. # ifndef DEBUG
  80787. # include <stdio.h>
  80788. # endif
  80789. # define SEPARATOR(i, last, width) \
  80790. ((i) == (last)? "\n};\n\n" : \
  80791. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  80792. void gen_trees_header()
  80793. {
  80794. FILE *header = fopen("trees.h", "w");
  80795. int i;
  80796. Assert (header != NULL, "Can't open trees.h");
  80797. fprintf(header,
  80798. "/* header created automatically with -DGEN_TREES_H */\n\n");
  80799. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  80800. for (i = 0; i < L_CODES+2; i++) {
  80801. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  80802. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  80803. }
  80804. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  80805. for (i = 0; i < D_CODES; i++) {
  80806. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  80807. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  80808. }
  80809. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  80810. for (i = 0; i < DIST_CODE_LEN; i++) {
  80811. fprintf(header, "%2u%s", _dist_code[i],
  80812. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  80813. }
  80814. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  80815. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  80816. fprintf(header, "%2u%s", _length_code[i],
  80817. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  80818. }
  80819. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  80820. for (i = 0; i < LENGTH_CODES; i++) {
  80821. fprintf(header, "%1u%s", base_length[i],
  80822. SEPARATOR(i, LENGTH_CODES-1, 20));
  80823. }
  80824. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  80825. for (i = 0; i < D_CODES; i++) {
  80826. fprintf(header, "%5u%s", base_dist[i],
  80827. SEPARATOR(i, D_CODES-1, 10));
  80828. }
  80829. fclose(header);
  80830. }
  80831. #endif /* GEN_TREES_H */
  80832. /* ===========================================================================
  80833. * Initialize the tree data structures for a new zlib stream.
  80834. */
  80835. void _tr_init(deflate_state *s)
  80836. {
  80837. tr_static_init();
  80838. s->l_desc.dyn_tree = s->dyn_ltree;
  80839. s->l_desc.stat_desc = &static_l_desc;
  80840. s->d_desc.dyn_tree = s->dyn_dtree;
  80841. s->d_desc.stat_desc = &static_d_desc;
  80842. s->bl_desc.dyn_tree = s->bl_tree;
  80843. s->bl_desc.stat_desc = &static_bl_desc;
  80844. s->bi_buf = 0;
  80845. s->bi_valid = 0;
  80846. s->last_eob_len = 8; /* enough lookahead for inflate */
  80847. #ifdef DEBUG
  80848. s->compressed_len = 0L;
  80849. s->bits_sent = 0L;
  80850. #endif
  80851. /* Initialize the first block of the first file: */
  80852. init_block(s);
  80853. }
  80854. /* ===========================================================================
  80855. * Initialize a new block.
  80856. */
  80857. local void init_block (deflate_state *s)
  80858. {
  80859. int n; /* iterates over tree elements */
  80860. /* Initialize the trees. */
  80861. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  80862. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  80863. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  80864. s->dyn_ltree[END_BLOCK].Freq = 1;
  80865. s->opt_len = s->static_len = 0L;
  80866. s->last_lit = s->matches = 0;
  80867. }
  80868. #define SMALLEST 1
  80869. /* Index within the heap array of least frequent node in the Huffman tree */
  80870. /* ===========================================================================
  80871. * Remove the smallest element from the heap and recreate the heap with
  80872. * one less element. Updates heap and heap_len.
  80873. */
  80874. #define pqremove(s, tree, top) \
  80875. {\
  80876. top = s->heap[SMALLEST]; \
  80877. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  80878. pqdownheap(s, tree, SMALLEST); \
  80879. }
  80880. /* ===========================================================================
  80881. * Compares to subtrees, using the tree depth as tie breaker when
  80882. * the subtrees have equal frequency. This minimizes the worst case length.
  80883. */
  80884. #define smaller(tree, n, m, depth) \
  80885. (tree[n].Freq < tree[m].Freq || \
  80886. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  80887. /* ===========================================================================
  80888. * Restore the heap property by moving down the tree starting at node k,
  80889. * exchanging a node with the smallest of its two sons if necessary, stopping
  80890. * when the heap property is re-established (each father smaller than its
  80891. * two sons).
  80892. */
  80893. local void pqdownheap (deflate_state *s,
  80894. ct_data *tree, /* the tree to restore */
  80895. int k) /* node to move down */
  80896. {
  80897. int v = s->heap[k];
  80898. int j = k << 1; /* left son of k */
  80899. while (j <= s->heap_len) {
  80900. /* Set j to the smallest of the two sons: */
  80901. if (j < s->heap_len &&
  80902. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  80903. j++;
  80904. }
  80905. /* Exit if v is smaller than both sons */
  80906. if (smaller(tree, v, s->heap[j], s->depth)) break;
  80907. /* Exchange v with the smallest son */
  80908. s->heap[k] = s->heap[j]; k = j;
  80909. /* And continue down the tree, setting j to the left son of k */
  80910. j <<= 1;
  80911. }
  80912. s->heap[k] = v;
  80913. }
  80914. /* ===========================================================================
  80915. * Compute the optimal bit lengths for a tree and update the total bit length
  80916. * for the current block.
  80917. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  80918. * above are the tree nodes sorted by increasing frequency.
  80919. * OUT assertions: the field len is set to the optimal bit length, the
  80920. * array bl_count contains the frequencies for each bit length.
  80921. * The length opt_len is updated; static_len is also updated if stree is
  80922. * not null.
  80923. */
  80924. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  80925. {
  80926. ct_data *tree = desc->dyn_tree;
  80927. int max_code = desc->max_code;
  80928. const ct_data *stree = desc->stat_desc->static_tree;
  80929. const intf *extra = desc->stat_desc->extra_bits;
  80930. int base = desc->stat_desc->extra_base;
  80931. int max_length = desc->stat_desc->max_length;
  80932. int h; /* heap index */
  80933. int n, m; /* iterate over the tree elements */
  80934. int bits; /* bit length */
  80935. int xbits; /* extra bits */
  80936. ush f; /* frequency */
  80937. int overflow = 0; /* number of elements with bit length too large */
  80938. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  80939. /* In a first pass, compute the optimal bit lengths (which may
  80940. * overflow in the case of the bit length tree).
  80941. */
  80942. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  80943. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  80944. n = s->heap[h];
  80945. bits = tree[tree[n].Dad].Len + 1;
  80946. if (bits > max_length) bits = max_length, overflow++;
  80947. tree[n].Len = (ush)bits;
  80948. /* We overwrite tree[n].Dad which is no longer needed */
  80949. if (n > max_code) continue; /* not a leaf node */
  80950. s->bl_count[bits]++;
  80951. xbits = 0;
  80952. if (n >= base) xbits = extra[n-base];
  80953. f = tree[n].Freq;
  80954. s->opt_len += (ulg)f * (bits + xbits);
  80955. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  80956. }
  80957. if (overflow == 0) return;
  80958. Trace((stderr,"\nbit length overflow\n"));
  80959. /* This happens for example on obj2 and pic of the Calgary corpus */
  80960. /* Find the first bit length which could increase: */
  80961. do {
  80962. bits = max_length-1;
  80963. while (s->bl_count[bits] == 0) bits--;
  80964. s->bl_count[bits]--; /* move one leaf down the tree */
  80965. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  80966. s->bl_count[max_length]--;
  80967. /* The brother of the overflow item also moves one step up,
  80968. * but this does not affect bl_count[max_length]
  80969. */
  80970. overflow -= 2;
  80971. } while (overflow > 0);
  80972. /* Now recompute all bit lengths, scanning in increasing frequency.
  80973. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  80974. * lengths instead of fixing only the wrong ones. This idea is taken
  80975. * from 'ar' written by Haruhiko Okumura.)
  80976. */
  80977. for (bits = max_length; bits != 0; bits--) {
  80978. n = s->bl_count[bits];
  80979. while (n != 0) {
  80980. m = s->heap[--h];
  80981. if (m > max_code) continue;
  80982. if ((unsigned) tree[m].Len != (unsigned) bits) {
  80983. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  80984. s->opt_len += ((long)bits - (long)tree[m].Len)
  80985. *(long)tree[m].Freq;
  80986. tree[m].Len = (ush)bits;
  80987. }
  80988. n--;
  80989. }
  80990. }
  80991. }
  80992. /* ===========================================================================
  80993. * Generate the codes for a given tree and bit counts (which need not be
  80994. * optimal).
  80995. * IN assertion: the array bl_count contains the bit length statistics for
  80996. * the given tree and the field len is set for all tree elements.
  80997. * OUT assertion: the field code is set for all tree elements of non
  80998. * zero code length.
  80999. */
  81000. local void gen_codes (ct_data *tree, /* the tree to decorate */
  81001. int max_code, /* largest code with non zero frequency */
  81002. ushf *bl_count) /* number of codes at each bit length */
  81003. {
  81004. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  81005. ush code = 0; /* running code value */
  81006. int bits; /* bit index */
  81007. int n; /* code index */
  81008. /* The distribution counts are first used to generate the code values
  81009. * without bit reversal.
  81010. */
  81011. for (bits = 1; bits <= MAX_BITS; bits++) {
  81012. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  81013. }
  81014. /* Check that the bit counts in bl_count are consistent. The last code
  81015. * must be all ones.
  81016. */
  81017. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  81018. "inconsistent bit counts");
  81019. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  81020. for (n = 0; n <= max_code; n++) {
  81021. int len = tree[n].Len;
  81022. if (len == 0) continue;
  81023. /* Now reverse the bits */
  81024. tree[n].Code = bi_reverse(next_code[len]++, len);
  81025. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  81026. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  81027. }
  81028. }
  81029. /* ===========================================================================
  81030. * Construct one Huffman tree and assigns the code bit strings and lengths.
  81031. * Update the total bit length for the current block.
  81032. * IN assertion: the field freq is set for all tree elements.
  81033. * OUT assertions: the fields len and code are set to the optimal bit length
  81034. * and corresponding code. The length opt_len is updated; static_len is
  81035. * also updated if stree is not null. The field max_code is set.
  81036. */
  81037. local void build_tree (deflate_state *s,
  81038. tree_desc *desc) /* the tree descriptor */
  81039. {
  81040. ct_data *tree = desc->dyn_tree;
  81041. const ct_data *stree = desc->stat_desc->static_tree;
  81042. int elems = desc->stat_desc->elems;
  81043. int n, m; /* iterate over heap elements */
  81044. int max_code = -1; /* largest code with non zero frequency */
  81045. int node; /* new node being created */
  81046. /* Construct the initial heap, with least frequent element in
  81047. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  81048. * heap[0] is not used.
  81049. */
  81050. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  81051. for (n = 0; n < elems; n++) {
  81052. if (tree[n].Freq != 0) {
  81053. s->heap[++(s->heap_len)] = max_code = n;
  81054. s->depth[n] = 0;
  81055. } else {
  81056. tree[n].Len = 0;
  81057. }
  81058. }
  81059. /* The pkzip format requires that at least one distance code exists,
  81060. * and that at least one bit should be sent even if there is only one
  81061. * possible code. So to avoid special checks later on we force at least
  81062. * two codes of non zero frequency.
  81063. */
  81064. while (s->heap_len < 2) {
  81065. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  81066. tree[node].Freq = 1;
  81067. s->depth[node] = 0;
  81068. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  81069. /* node is 0 or 1 so it does not have extra bits */
  81070. }
  81071. desc->max_code = max_code;
  81072. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  81073. * establish sub-heaps of increasing lengths:
  81074. */
  81075. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  81076. /* Construct the Huffman tree by repeatedly combining the least two
  81077. * frequent nodes.
  81078. */
  81079. node = elems; /* next internal node of the tree */
  81080. do {
  81081. pqremove(s, tree, n); /* n = node of least frequency */
  81082. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  81083. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  81084. s->heap[--(s->heap_max)] = m;
  81085. /* Create a new node father of n and m */
  81086. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  81087. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  81088. s->depth[n] : s->depth[m]) + 1);
  81089. tree[n].Dad = tree[m].Dad = (ush)node;
  81090. #ifdef DUMP_BL_TREE
  81091. if (tree == s->bl_tree) {
  81092. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  81093. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  81094. }
  81095. #endif
  81096. /* and insert the new node in the heap */
  81097. s->heap[SMALLEST] = node++;
  81098. pqdownheap(s, tree, SMALLEST);
  81099. } while (s->heap_len >= 2);
  81100. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  81101. /* At this point, the fields freq and dad are set. We can now
  81102. * generate the bit lengths.
  81103. */
  81104. gen_bitlen(s, (tree_desc *)desc);
  81105. /* The field len is now set, we can generate the bit codes */
  81106. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  81107. }
  81108. /* ===========================================================================
  81109. * Scan a literal or distance tree to determine the frequencies of the codes
  81110. * in the bit length tree.
  81111. */
  81112. local void scan_tree (deflate_state *s,
  81113. ct_data *tree, /* the tree to be scanned */
  81114. int max_code) /* and its largest code of non zero frequency */
  81115. {
  81116. int n; /* iterates over all tree elements */
  81117. int prevlen = -1; /* last emitted length */
  81118. int curlen; /* length of current code */
  81119. int nextlen = tree[0].Len; /* length of next code */
  81120. int count = 0; /* repeat count of the current code */
  81121. int max_count = 7; /* max repeat count */
  81122. int min_count = 4; /* min repeat count */
  81123. if (nextlen == 0) max_count = 138, min_count = 3;
  81124. tree[max_code+1].Len = (ush)0xffff; /* guard */
  81125. for (n = 0; n <= max_code; n++) {
  81126. curlen = nextlen; nextlen = tree[n+1].Len;
  81127. if (++count < max_count && curlen == nextlen) {
  81128. continue;
  81129. } else if (count < min_count) {
  81130. s->bl_tree[curlen].Freq += count;
  81131. } else if (curlen != 0) {
  81132. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  81133. s->bl_tree[REP_3_6].Freq++;
  81134. } else if (count <= 10) {
  81135. s->bl_tree[REPZ_3_10].Freq++;
  81136. } else {
  81137. s->bl_tree[REPZ_11_138].Freq++;
  81138. }
  81139. count = 0; prevlen = curlen;
  81140. if (nextlen == 0) {
  81141. max_count = 138, min_count = 3;
  81142. } else if (curlen == nextlen) {
  81143. max_count = 6, min_count = 3;
  81144. } else {
  81145. max_count = 7, min_count = 4;
  81146. }
  81147. }
  81148. }
  81149. /* ===========================================================================
  81150. * Send a literal or distance tree in compressed form, using the codes in
  81151. * bl_tree.
  81152. */
  81153. local void send_tree (deflate_state *s,
  81154. ct_data *tree, /* the tree to be scanned */
  81155. int max_code) /* and its largest code of non zero frequency */
  81156. {
  81157. int n; /* iterates over all tree elements */
  81158. int prevlen = -1; /* last emitted length */
  81159. int curlen; /* length of current code */
  81160. int nextlen = tree[0].Len; /* length of next code */
  81161. int count = 0; /* repeat count of the current code */
  81162. int max_count = 7; /* max repeat count */
  81163. int min_count = 4; /* min repeat count */
  81164. /* tree[max_code+1].Len = -1; */ /* guard already set */
  81165. if (nextlen == 0) max_count = 138, min_count = 3;
  81166. for (n = 0; n <= max_code; n++) {
  81167. curlen = nextlen; nextlen = tree[n+1].Len;
  81168. if (++count < max_count && curlen == nextlen) {
  81169. continue;
  81170. } else if (count < min_count) {
  81171. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  81172. } else if (curlen != 0) {
  81173. if (curlen != prevlen) {
  81174. send_code(s, curlen, s->bl_tree); count--;
  81175. }
  81176. Assert(count >= 3 && count <= 6, " 3_6?");
  81177. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  81178. } else if (count <= 10) {
  81179. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  81180. } else {
  81181. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  81182. }
  81183. count = 0; prevlen = curlen;
  81184. if (nextlen == 0) {
  81185. max_count = 138, min_count = 3;
  81186. } else if (curlen == nextlen) {
  81187. max_count = 6, min_count = 3;
  81188. } else {
  81189. max_count = 7, min_count = 4;
  81190. }
  81191. }
  81192. }
  81193. /* ===========================================================================
  81194. * Construct the Huffman tree for the bit lengths and return the index in
  81195. * bl_order of the last bit length code to send.
  81196. */
  81197. local int build_bl_tree (deflate_state *s)
  81198. {
  81199. int max_blindex; /* index of last bit length code of non zero freq */
  81200. /* Determine the bit length frequencies for literal and distance trees */
  81201. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  81202. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  81203. /* Build the bit length tree: */
  81204. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  81205. /* opt_len now includes the length of the tree representations, except
  81206. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  81207. */
  81208. /* Determine the number of bit length codes to send. The pkzip format
  81209. * requires that at least 4 bit length codes be sent. (appnote.txt says
  81210. * 3 but the actual value used is 4.)
  81211. */
  81212. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  81213. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  81214. }
  81215. /* Update opt_len to include the bit length tree and counts */
  81216. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  81217. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  81218. s->opt_len, s->static_len));
  81219. return max_blindex;
  81220. }
  81221. /* ===========================================================================
  81222. * Send the header for a block using dynamic Huffman trees: the counts, the
  81223. * lengths of the bit length codes, the literal tree and the distance tree.
  81224. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  81225. */
  81226. local void send_all_trees (deflate_state *s,
  81227. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  81228. {
  81229. int rank; /* index in bl_order */
  81230. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  81231. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  81232. "too many codes");
  81233. Tracev((stderr, "\nbl counts: "));
  81234. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  81235. send_bits(s, dcodes-1, 5);
  81236. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  81237. for (rank = 0; rank < blcodes; rank++) {
  81238. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  81239. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  81240. }
  81241. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  81242. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  81243. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  81244. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  81245. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  81246. }
  81247. /* ===========================================================================
  81248. * Send a stored block
  81249. */
  81250. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  81251. {
  81252. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  81253. #ifdef DEBUG
  81254. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  81255. s->compressed_len += (stored_len + 4) << 3;
  81256. #endif
  81257. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  81258. }
  81259. /* ===========================================================================
  81260. * Send one empty static block to give enough lookahead for inflate.
  81261. * This takes 10 bits, of which 7 may remain in the bit buffer.
  81262. * The current inflate code requires 9 bits of lookahead. If the
  81263. * last two codes for the previous block (real code plus EOB) were coded
  81264. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  81265. * the last real code. In this case we send two empty static blocks instead
  81266. * of one. (There are no problems if the previous block is stored or fixed.)
  81267. * To simplify the code, we assume the worst case of last real code encoded
  81268. * on one bit only.
  81269. */
  81270. void _tr_align (deflate_state *s)
  81271. {
  81272. send_bits(s, STATIC_TREES<<1, 3);
  81273. send_code(s, END_BLOCK, static_ltree);
  81274. #ifdef DEBUG
  81275. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  81276. #endif
  81277. bi_flush(s);
  81278. /* Of the 10 bits for the empty block, we have already sent
  81279. * (10 - bi_valid) bits. The lookahead for the last real code (before
  81280. * the EOB of the previous block) was thus at least one plus the length
  81281. * of the EOB plus what we have just sent of the empty static block.
  81282. */
  81283. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  81284. send_bits(s, STATIC_TREES<<1, 3);
  81285. send_code(s, END_BLOCK, static_ltree);
  81286. #ifdef DEBUG
  81287. s->compressed_len += 10L;
  81288. #endif
  81289. bi_flush(s);
  81290. }
  81291. s->last_eob_len = 7;
  81292. }
  81293. /* ===========================================================================
  81294. * Determine the best encoding for the current block: dynamic trees, static
  81295. * trees or store, and output the encoded block to the zip file.
  81296. */
  81297. void _tr_flush_block (deflate_state *s,
  81298. charf *buf, /* input block, or NULL if too old */
  81299. ulg stored_len, /* length of input block */
  81300. int eof) /* true if this is the last block for a file */
  81301. {
  81302. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  81303. int max_blindex = 0; /* index of last bit length code of non zero freq */
  81304. /* Build the Huffman trees unless a stored block is forced */
  81305. if (s->level > 0) {
  81306. /* Check if the file is binary or text */
  81307. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  81308. set_data_type(s);
  81309. /* Construct the literal and distance trees */
  81310. build_tree(s, (tree_desc *)(&(s->l_desc)));
  81311. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  81312. s->static_len));
  81313. build_tree(s, (tree_desc *)(&(s->d_desc)));
  81314. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  81315. s->static_len));
  81316. /* At this point, opt_len and static_len are the total bit lengths of
  81317. * the compressed block data, excluding the tree representations.
  81318. */
  81319. /* Build the bit length tree for the above two trees, and get the index
  81320. * in bl_order of the last bit length code to send.
  81321. */
  81322. max_blindex = build_bl_tree(s);
  81323. /* Determine the best encoding. Compute the block lengths in bytes. */
  81324. opt_lenb = (s->opt_len+3+7)>>3;
  81325. static_lenb = (s->static_len+3+7)>>3;
  81326. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  81327. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  81328. s->last_lit));
  81329. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  81330. } else {
  81331. Assert(buf != (char*)0, "lost buf");
  81332. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  81333. }
  81334. #ifdef FORCE_STORED
  81335. if (buf != (char*)0) { /* force stored block */
  81336. #else
  81337. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  81338. /* 4: two words for the lengths */
  81339. #endif
  81340. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  81341. * Otherwise we can't have processed more than WSIZE input bytes since
  81342. * the last block flush, because compression would have been
  81343. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  81344. * transform a block into a stored block.
  81345. */
  81346. _tr_stored_block(s, buf, stored_len, eof);
  81347. #ifdef FORCE_STATIC
  81348. } else if (static_lenb >= 0) { /* force static trees */
  81349. #else
  81350. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  81351. #endif
  81352. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  81353. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  81354. #ifdef DEBUG
  81355. s->compressed_len += 3 + s->static_len;
  81356. #endif
  81357. } else {
  81358. send_bits(s, (DYN_TREES<<1)+eof, 3);
  81359. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  81360. max_blindex+1);
  81361. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  81362. #ifdef DEBUG
  81363. s->compressed_len += 3 + s->opt_len;
  81364. #endif
  81365. }
  81366. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  81367. /* The above check is made mod 2^32, for files larger than 512 MB
  81368. * and uLong implemented on 32 bits.
  81369. */
  81370. init_block(s);
  81371. if (eof) {
  81372. bi_windup(s);
  81373. #ifdef DEBUG
  81374. s->compressed_len += 7; /* align on byte boundary */
  81375. #endif
  81376. }
  81377. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  81378. s->compressed_len-7*eof));
  81379. }
  81380. /* ===========================================================================
  81381. * Save the match info and tally the frequency counts. Return true if
  81382. * the current block must be flushed.
  81383. */
  81384. int _tr_tally (deflate_state *s,
  81385. unsigned dist, /* distance of matched string */
  81386. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  81387. {
  81388. s->d_buf[s->last_lit] = (ush)dist;
  81389. s->l_buf[s->last_lit++] = (uch)lc;
  81390. if (dist == 0) {
  81391. /* lc is the unmatched char */
  81392. s->dyn_ltree[lc].Freq++;
  81393. } else {
  81394. s->matches++;
  81395. /* Here, lc is the match length - MIN_MATCH */
  81396. dist--; /* dist = match distance - 1 */
  81397. Assert((ush)dist < (ush)MAX_DIST(s) &&
  81398. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  81399. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  81400. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  81401. s->dyn_dtree[d_code(dist)].Freq++;
  81402. }
  81403. #ifdef TRUNCATE_BLOCK
  81404. /* Try to guess if it is profitable to stop the current block here */
  81405. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  81406. /* Compute an upper bound for the compressed length */
  81407. ulg out_length = (ulg)s->last_lit*8L;
  81408. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  81409. int dcode;
  81410. for (dcode = 0; dcode < D_CODES; dcode++) {
  81411. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  81412. (5L+extra_dbits[dcode]);
  81413. }
  81414. out_length >>= 3;
  81415. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  81416. s->last_lit, in_length, out_length,
  81417. 100L - out_length*100L/in_length));
  81418. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  81419. }
  81420. #endif
  81421. return (s->last_lit == s->lit_bufsize-1);
  81422. /* We avoid equality with lit_bufsize because of wraparound at 64K
  81423. * on 16 bit machines and because stored blocks are restricted to
  81424. * 64K-1 bytes.
  81425. */
  81426. }
  81427. /* ===========================================================================
  81428. * Send the block data compressed using the given Huffman trees
  81429. */
  81430. local void compress_block (deflate_state *s,
  81431. ct_data *ltree, /* literal tree */
  81432. ct_data *dtree) /* distance tree */
  81433. {
  81434. unsigned dist; /* distance of matched string */
  81435. int lc; /* match length or unmatched char (if dist == 0) */
  81436. unsigned lx = 0; /* running index in l_buf */
  81437. unsigned code; /* the code to send */
  81438. int extra; /* number of extra bits to send */
  81439. if (s->last_lit != 0) do {
  81440. dist = s->d_buf[lx];
  81441. lc = s->l_buf[lx++];
  81442. if (dist == 0) {
  81443. send_code(s, lc, ltree); /* send a literal byte */
  81444. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  81445. } else {
  81446. /* Here, lc is the match length - MIN_MATCH */
  81447. code = _length_code[lc];
  81448. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  81449. extra = extra_lbits[code];
  81450. if (extra != 0) {
  81451. lc -= base_length[code];
  81452. send_bits(s, lc, extra); /* send the extra length bits */
  81453. }
  81454. dist--; /* dist is now the match distance - 1 */
  81455. code = d_code(dist);
  81456. Assert (code < D_CODES, "bad d_code");
  81457. send_code(s, code, dtree); /* send the distance code */
  81458. extra = extra_dbits[code];
  81459. if (extra != 0) {
  81460. dist -= base_dist[code];
  81461. send_bits(s, dist, extra); /* send the extra distance bits */
  81462. }
  81463. } /* literal or match pair ? */
  81464. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  81465. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  81466. "pendingBuf overflow");
  81467. } while (lx < s->last_lit);
  81468. send_code(s, END_BLOCK, ltree);
  81469. s->last_eob_len = ltree[END_BLOCK].Len;
  81470. }
  81471. /* ===========================================================================
  81472. * Set the data type to BINARY or TEXT, using a crude approximation:
  81473. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  81474. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  81475. * IN assertion: the fields Freq of dyn_ltree are set.
  81476. */
  81477. local void set_data_type (deflate_state *s)
  81478. {
  81479. int n;
  81480. for (n = 0; n < 9; n++)
  81481. if (s->dyn_ltree[n].Freq != 0)
  81482. break;
  81483. if (n == 9)
  81484. for (n = 14; n < 32; n++)
  81485. if (s->dyn_ltree[n].Freq != 0)
  81486. break;
  81487. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  81488. }
  81489. /* ===========================================================================
  81490. * Reverse the first len bits of a code, using straightforward code (a faster
  81491. * method would use a table)
  81492. * IN assertion: 1 <= len <= 15
  81493. */
  81494. local unsigned bi_reverse (unsigned code, int len)
  81495. {
  81496. register unsigned res = 0;
  81497. do {
  81498. res |= code & 1;
  81499. code >>= 1, res <<= 1;
  81500. } while (--len > 0);
  81501. return res >> 1;
  81502. }
  81503. /* ===========================================================================
  81504. * Flush the bit buffer, keeping at most 7 bits in it.
  81505. */
  81506. local void bi_flush (deflate_state *s)
  81507. {
  81508. if (s->bi_valid == 16) {
  81509. put_short(s, s->bi_buf);
  81510. s->bi_buf = 0;
  81511. s->bi_valid = 0;
  81512. } else if (s->bi_valid >= 8) {
  81513. put_byte(s, (Byte)s->bi_buf);
  81514. s->bi_buf >>= 8;
  81515. s->bi_valid -= 8;
  81516. }
  81517. }
  81518. /* ===========================================================================
  81519. * Flush the bit buffer and align the output on a byte boundary
  81520. */
  81521. local void bi_windup (deflate_state *s)
  81522. {
  81523. if (s->bi_valid > 8) {
  81524. put_short(s, s->bi_buf);
  81525. } else if (s->bi_valid > 0) {
  81526. put_byte(s, (Byte)s->bi_buf);
  81527. }
  81528. s->bi_buf = 0;
  81529. s->bi_valid = 0;
  81530. #ifdef DEBUG
  81531. s->bits_sent = (s->bits_sent+7) & ~7;
  81532. #endif
  81533. }
  81534. /* ===========================================================================
  81535. * Copy a stored block, storing first the length and its
  81536. * one's complement if requested.
  81537. */
  81538. local void copy_block(deflate_state *s,
  81539. charf *buf, /* the input data */
  81540. unsigned len, /* its length */
  81541. int header) /* true if block header must be written */
  81542. {
  81543. bi_windup(s); /* align on byte boundary */
  81544. s->last_eob_len = 8; /* enough lookahead for inflate */
  81545. if (header) {
  81546. put_short(s, (ush)len);
  81547. put_short(s, (ush)~len);
  81548. #ifdef DEBUG
  81549. s->bits_sent += 2*16;
  81550. #endif
  81551. }
  81552. #ifdef DEBUG
  81553. s->bits_sent += (ulg)len<<3;
  81554. #endif
  81555. while (len--) {
  81556. put_byte(s, *buf++);
  81557. }
  81558. }
  81559. /********* End of inlined file: trees.c *********/
  81560. /********* Start of inlined file: zutil.c *********/
  81561. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81562. #ifndef NO_DUMMY_DECL
  81563. struct internal_state {int dummy;}; /* for buggy compilers */
  81564. #endif
  81565. const char * const z_errmsg[10] = {
  81566. "need dictionary", /* Z_NEED_DICT 2 */
  81567. "stream end", /* Z_STREAM_END 1 */
  81568. "", /* Z_OK 0 */
  81569. "file error", /* Z_ERRNO (-1) */
  81570. "stream error", /* Z_STREAM_ERROR (-2) */
  81571. "data error", /* Z_DATA_ERROR (-3) */
  81572. "insufficient memory", /* Z_MEM_ERROR (-4) */
  81573. "buffer error", /* Z_BUF_ERROR (-5) */
  81574. "incompatible version",/* Z_VERSION_ERROR (-6) */
  81575. ""};
  81576. /*const char * ZEXPORT zlibVersion()
  81577. {
  81578. return ZLIB_VERSION;
  81579. }
  81580. uLong ZEXPORT zlibCompileFlags()
  81581. {
  81582. uLong flags;
  81583. flags = 0;
  81584. switch (sizeof(uInt)) {
  81585. case 2: break;
  81586. case 4: flags += 1; break;
  81587. case 8: flags += 2; break;
  81588. default: flags += 3;
  81589. }
  81590. switch (sizeof(uLong)) {
  81591. case 2: break;
  81592. case 4: flags += 1 << 2; break;
  81593. case 8: flags += 2 << 2; break;
  81594. default: flags += 3 << 2;
  81595. }
  81596. switch (sizeof(voidpf)) {
  81597. case 2: break;
  81598. case 4: flags += 1 << 4; break;
  81599. case 8: flags += 2 << 4; break;
  81600. default: flags += 3 << 4;
  81601. }
  81602. switch (sizeof(z_off_t)) {
  81603. case 2: break;
  81604. case 4: flags += 1 << 6; break;
  81605. case 8: flags += 2 << 6; break;
  81606. default: flags += 3 << 6;
  81607. }
  81608. #ifdef DEBUG
  81609. flags += 1 << 8;
  81610. #endif
  81611. #if defined(ASMV) || defined(ASMINF)
  81612. flags += 1 << 9;
  81613. #endif
  81614. #ifdef ZLIB_WINAPI
  81615. flags += 1 << 10;
  81616. #endif
  81617. #ifdef BUILDFIXED
  81618. flags += 1 << 12;
  81619. #endif
  81620. #ifdef DYNAMIC_CRC_TABLE
  81621. flags += 1 << 13;
  81622. #endif
  81623. #ifdef NO_GZCOMPRESS
  81624. flags += 1L << 16;
  81625. #endif
  81626. #ifdef NO_GZIP
  81627. flags += 1L << 17;
  81628. #endif
  81629. #ifdef PKZIP_BUG_WORKAROUND
  81630. flags += 1L << 20;
  81631. #endif
  81632. #ifdef FASTEST
  81633. flags += 1L << 21;
  81634. #endif
  81635. #ifdef STDC
  81636. # ifdef NO_vsnprintf
  81637. flags += 1L << 25;
  81638. # ifdef HAS_vsprintf_void
  81639. flags += 1L << 26;
  81640. # endif
  81641. # else
  81642. # ifdef HAS_vsnprintf_void
  81643. flags += 1L << 26;
  81644. # endif
  81645. # endif
  81646. #else
  81647. flags += 1L << 24;
  81648. # ifdef NO_snprintf
  81649. flags += 1L << 25;
  81650. # ifdef HAS_sprintf_void
  81651. flags += 1L << 26;
  81652. # endif
  81653. # else
  81654. # ifdef HAS_snprintf_void
  81655. flags += 1L << 26;
  81656. # endif
  81657. # endif
  81658. #endif
  81659. return flags;
  81660. }*/
  81661. #ifdef DEBUG
  81662. # ifndef verbose
  81663. # define verbose 0
  81664. # endif
  81665. int z_verbose = verbose;
  81666. void z_error (const char *m)
  81667. {
  81668. fprintf(stderr, "%s\n", m);
  81669. exit(1);
  81670. }
  81671. #endif
  81672. /* exported to allow conversion of error code to string for compress() and
  81673. * uncompress()
  81674. */
  81675. const char * ZEXPORT zError(int err)
  81676. {
  81677. return ERR_MSG(err);
  81678. }
  81679. #if defined(_WIN32_WCE)
  81680. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  81681. * errno. We define it as a global variable to simplify porting.
  81682. * Its value is always 0 and should not be used.
  81683. */
  81684. int errno = 0;
  81685. #endif
  81686. #ifndef HAVE_MEMCPY
  81687. void zmemcpy(dest, source, len)
  81688. Bytef* dest;
  81689. const Bytef* source;
  81690. uInt len;
  81691. {
  81692. if (len == 0) return;
  81693. do {
  81694. *dest++ = *source++; /* ??? to be unrolled */
  81695. } while (--len != 0);
  81696. }
  81697. int zmemcmp(s1, s2, len)
  81698. const Bytef* s1;
  81699. const Bytef* s2;
  81700. uInt len;
  81701. {
  81702. uInt j;
  81703. for (j = 0; j < len; j++) {
  81704. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  81705. }
  81706. return 0;
  81707. }
  81708. void zmemzero(dest, len)
  81709. Bytef* dest;
  81710. uInt len;
  81711. {
  81712. if (len == 0) return;
  81713. do {
  81714. *dest++ = 0; /* ??? to be unrolled */
  81715. } while (--len != 0);
  81716. }
  81717. #endif
  81718. #ifdef SYS16BIT
  81719. #ifdef __TURBOC__
  81720. /* Turbo C in 16-bit mode */
  81721. # define MY_ZCALLOC
  81722. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  81723. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  81724. * must fix the pointer. Warning: the pointer must be put back to its
  81725. * original form in order to free it, use zcfree().
  81726. */
  81727. #define MAX_PTR 10
  81728. /* 10*64K = 640K */
  81729. local int next_ptr = 0;
  81730. typedef struct ptr_table_s {
  81731. voidpf org_ptr;
  81732. voidpf new_ptr;
  81733. } ptr_table;
  81734. local ptr_table table[MAX_PTR];
  81735. /* This table is used to remember the original form of pointers
  81736. * to large buffers (64K). Such pointers are normalized with a zero offset.
  81737. * Since MSDOS is not a preemptive multitasking OS, this table is not
  81738. * protected from concurrent access. This hack doesn't work anyway on
  81739. * a protected system like OS/2. Use Microsoft C instead.
  81740. */
  81741. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81742. {
  81743. voidpf buf = opaque; /* just to make some compilers happy */
  81744. ulg bsize = (ulg)items*size;
  81745. /* If we allocate less than 65520 bytes, we assume that farmalloc
  81746. * will return a usable pointer which doesn't have to be normalized.
  81747. */
  81748. if (bsize < 65520L) {
  81749. buf = farmalloc(bsize);
  81750. if (*(ush*)&buf != 0) return buf;
  81751. } else {
  81752. buf = farmalloc(bsize + 16L);
  81753. }
  81754. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  81755. table[next_ptr].org_ptr = buf;
  81756. /* Normalize the pointer to seg:0 */
  81757. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  81758. *(ush*)&buf = 0;
  81759. table[next_ptr++].new_ptr = buf;
  81760. return buf;
  81761. }
  81762. void zcfree (voidpf opaque, voidpf ptr)
  81763. {
  81764. int n;
  81765. if (*(ush*)&ptr != 0) { /* object < 64K */
  81766. farfree(ptr);
  81767. return;
  81768. }
  81769. /* Find the original pointer */
  81770. for (n = 0; n < next_ptr; n++) {
  81771. if (ptr != table[n].new_ptr) continue;
  81772. farfree(table[n].org_ptr);
  81773. while (++n < next_ptr) {
  81774. table[n-1] = table[n];
  81775. }
  81776. next_ptr--;
  81777. return;
  81778. }
  81779. ptr = opaque; /* just to make some compilers happy */
  81780. Assert(0, "zcfree: ptr not found");
  81781. }
  81782. #endif /* __TURBOC__ */
  81783. #ifdef M_I86
  81784. /* Microsoft C in 16-bit mode */
  81785. # define MY_ZCALLOC
  81786. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  81787. # define _halloc halloc
  81788. # define _hfree hfree
  81789. #endif
  81790. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81791. {
  81792. if (opaque) opaque = 0; /* to make compiler happy */
  81793. return _halloc((long)items, size);
  81794. }
  81795. void zcfree (voidpf opaque, voidpf ptr)
  81796. {
  81797. if (opaque) opaque = 0; /* to make compiler happy */
  81798. _hfree(ptr);
  81799. }
  81800. #endif /* M_I86 */
  81801. #endif /* SYS16BIT */
  81802. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  81803. #ifndef STDC
  81804. extern voidp malloc OF((uInt size));
  81805. extern voidp calloc OF((uInt items, uInt size));
  81806. extern void free OF((voidpf ptr));
  81807. #endif
  81808. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81809. {
  81810. if (opaque) items += size - size; /* make compiler happy */
  81811. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  81812. (voidpf)calloc(items, size);
  81813. }
  81814. void zcfree (voidpf opaque, voidpf ptr)
  81815. {
  81816. free(ptr);
  81817. if (opaque) return; /* make compiler happy */
  81818. }
  81819. #endif /* MY_ZCALLOC */
  81820. /********* End of inlined file: zutil.c *********/
  81821. #undef Byte
  81822. }
  81823. #else
  81824. #include <zlib.h>
  81825. #endif
  81826. }
  81827. #if JUCE_MSVC
  81828. #pragma warning (pop)
  81829. #endif
  81830. BEGIN_JUCE_NAMESPACE
  81831. using namespace zlibNamespace;
  81832. // internal helper object that holds the zlib structures so they don't have to be
  81833. // included publicly.
  81834. class GZIPDecompressHelper
  81835. {
  81836. private:
  81837. z_stream* stream;
  81838. uint8* data;
  81839. int dataSize;
  81840. public:
  81841. bool finished, needsDictionary, error;
  81842. GZIPDecompressHelper (const bool noWrap) throw()
  81843. : data (0),
  81844. dataSize (0),
  81845. finished (false),
  81846. needsDictionary (false),
  81847. error (false)
  81848. {
  81849. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  81850. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  81851. : MAX_WBITS) != Z_OK)
  81852. {
  81853. juce_free (stream);
  81854. stream = 0;
  81855. error = true;
  81856. finished = true;
  81857. }
  81858. }
  81859. ~GZIPDecompressHelper() throw()
  81860. {
  81861. if (stream != 0)
  81862. {
  81863. inflateEnd (stream);
  81864. juce_free (stream);
  81865. }
  81866. }
  81867. bool needsInput() const throw() { return dataSize <= 0; }
  81868. void setInput (uint8* const data_, const int size) throw()
  81869. {
  81870. data = data_;
  81871. dataSize = size;
  81872. }
  81873. int doNextBlock (uint8* const dest, const int destSize) throw()
  81874. {
  81875. if (stream != 0 && data != 0 && ! finished)
  81876. {
  81877. stream->next_in = data;
  81878. stream->next_out = dest;
  81879. stream->avail_in = dataSize;
  81880. stream->avail_out = destSize;
  81881. switch (inflate (stream, Z_PARTIAL_FLUSH))
  81882. {
  81883. case Z_STREAM_END:
  81884. finished = true;
  81885. // deliberate fall-through
  81886. case Z_OK:
  81887. data += dataSize - stream->avail_in;
  81888. dataSize = stream->avail_in;
  81889. return destSize - stream->avail_out;
  81890. case Z_NEED_DICT:
  81891. needsDictionary = true;
  81892. data += dataSize - stream->avail_in;
  81893. dataSize = stream->avail_in;
  81894. break;
  81895. case Z_DATA_ERROR:
  81896. case Z_MEM_ERROR:
  81897. error = true;
  81898. default:
  81899. break;
  81900. }
  81901. }
  81902. return 0;
  81903. }
  81904. };
  81905. const int gzipDecompBufferSize = 32768;
  81906. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  81907. const bool deleteSourceWhenDestroyed_,
  81908. const bool noWrap_,
  81909. const int64 uncompressedStreamLength_)
  81910. : sourceStream (sourceStream_),
  81911. uncompressedStreamLength (uncompressedStreamLength_),
  81912. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  81913. noWrap (noWrap_),
  81914. isEof (false),
  81915. activeBufferSize (0),
  81916. originalSourcePos (sourceStream_->getPosition()),
  81917. currentPos (0)
  81918. {
  81919. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  81920. helper = new GZIPDecompressHelper (noWrap_);
  81921. }
  81922. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  81923. {
  81924. juce_free (buffer);
  81925. if (deleteSourceWhenDestroyed)
  81926. delete sourceStream;
  81927. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81928. delete h;
  81929. }
  81930. int64 GZIPDecompressorInputStream::getTotalLength()
  81931. {
  81932. return uncompressedStreamLength;
  81933. }
  81934. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  81935. {
  81936. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81937. if ((howMany > 0) && ! isEof)
  81938. {
  81939. jassert (destBuffer != 0);
  81940. if (destBuffer != 0)
  81941. {
  81942. int numRead = 0;
  81943. uint8* d = (uint8*) destBuffer;
  81944. while (! h->error)
  81945. {
  81946. const int n = h->doNextBlock (d, howMany);
  81947. currentPos += n;
  81948. if (n == 0)
  81949. {
  81950. if (h->finished || h->needsDictionary)
  81951. {
  81952. isEof = true;
  81953. return numRead;
  81954. }
  81955. if (h->needsInput())
  81956. {
  81957. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  81958. if (activeBufferSize > 0)
  81959. {
  81960. h->setInput ((uint8*) buffer, activeBufferSize);
  81961. }
  81962. else
  81963. {
  81964. isEof = true;
  81965. return numRead;
  81966. }
  81967. }
  81968. }
  81969. else
  81970. {
  81971. numRead += n;
  81972. howMany -= n;
  81973. d += n;
  81974. if (howMany <= 0)
  81975. return numRead;
  81976. }
  81977. }
  81978. }
  81979. }
  81980. return 0;
  81981. }
  81982. bool GZIPDecompressorInputStream::isExhausted()
  81983. {
  81984. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81985. return h->error || isEof;
  81986. }
  81987. int64 GZIPDecompressorInputStream::getPosition()
  81988. {
  81989. return currentPos;
  81990. }
  81991. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  81992. {
  81993. if (newPos != currentPos)
  81994. {
  81995. if (newPos > currentPos)
  81996. {
  81997. skipNextBytes (newPos - currentPos);
  81998. }
  81999. else
  82000. {
  82001. // reset the stream and start again..
  82002. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  82003. delete h;
  82004. isEof = false;
  82005. activeBufferSize = 0;
  82006. currentPos = 0;
  82007. helper = new GZIPDecompressHelper (noWrap);
  82008. sourceStream->setPosition (originalSourcePos);
  82009. skipNextBytes (newPos);
  82010. }
  82011. }
  82012. return true;
  82013. }
  82014. END_JUCE_NAMESPACE
  82015. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  82016. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  82017. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  82018. #if JUCE_USE_FLAC
  82019. #if JUCE_WINDOWS
  82020. #include <windows.h>
  82021. #endif
  82022. #ifdef _MSC_VER
  82023. #pragma warning (disable : 4505)
  82024. #pragma warning (push)
  82025. #endif
  82026. namespace FlacNamespace
  82027. {
  82028. #if JUCE_INCLUDE_FLAC_CODE
  82029. #define FLAC__NO_DLL 1
  82030. #if ! defined (SIZE_MAX)
  82031. #define SIZE_MAX 0xffffffff
  82032. #endif
  82033. #define __STDC_LIMIT_MACROS 1
  82034. /********* Start of inlined file: all.h *********/
  82035. #ifndef FLAC__ALL_H
  82036. #define FLAC__ALL_H
  82037. /********* Start of inlined file: export.h *********/
  82038. #ifndef FLAC__EXPORT_H
  82039. #define FLAC__EXPORT_H
  82040. /** \file include/FLAC/export.h
  82041. *
  82042. * \brief
  82043. * This module contains #defines and symbols for exporting function
  82044. * calls, and providing version information and compiled-in features.
  82045. *
  82046. * See the \link flac_export export \endlink module.
  82047. */
  82048. /** \defgroup flac_export FLAC/export.h: export symbols
  82049. * \ingroup flac
  82050. *
  82051. * \brief
  82052. * This module contains #defines and symbols for exporting function
  82053. * calls, and providing version information and compiled-in features.
  82054. *
  82055. * If you are compiling with MSVC and will link to the static library
  82056. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  82057. * make sure the symbols are exported properly.
  82058. *
  82059. * \{
  82060. */
  82061. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  82062. #define FLAC_API
  82063. #else
  82064. #ifdef FLAC_API_EXPORTS
  82065. #define FLAC_API _declspec(dllexport)
  82066. #else
  82067. #define FLAC_API _declspec(dllimport)
  82068. #endif
  82069. #endif
  82070. /** These #defines will mirror the libtool-based library version number, see
  82071. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  82072. */
  82073. #define FLAC_API_VERSION_CURRENT 10
  82074. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  82075. #define FLAC_API_VERSION_AGE 2 /**< see above */
  82076. #ifdef __cplusplus
  82077. extern "C" {
  82078. #endif
  82079. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  82080. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  82081. #ifdef __cplusplus
  82082. }
  82083. #endif
  82084. /* \} */
  82085. #endif
  82086. /********* End of inlined file: export.h *********/
  82087. /********* Start of inlined file: assert.h *********/
  82088. #ifndef FLAC__ASSERT_H
  82089. #define FLAC__ASSERT_H
  82090. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  82091. #ifdef DEBUG
  82092. #include <assert.h>
  82093. #define FLAC__ASSERT(x) assert(x)
  82094. #define FLAC__ASSERT_DECLARATION(x) x
  82095. #else
  82096. #define FLAC__ASSERT(x)
  82097. #define FLAC__ASSERT_DECLARATION(x)
  82098. #endif
  82099. #endif
  82100. /********* End of inlined file: assert.h *********/
  82101. /********* Start of inlined file: callback.h *********/
  82102. #ifndef FLAC__CALLBACK_H
  82103. #define FLAC__CALLBACK_H
  82104. /********* Start of inlined file: ordinals.h *********/
  82105. #ifndef FLAC__ORDINALS_H
  82106. #define FLAC__ORDINALS_H
  82107. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  82108. #include <inttypes.h>
  82109. #endif
  82110. typedef signed char FLAC__int8;
  82111. typedef unsigned char FLAC__uint8;
  82112. #if defined(_MSC_VER) || defined(__BORLANDC__)
  82113. typedef __int16 FLAC__int16;
  82114. typedef __int32 FLAC__int32;
  82115. typedef __int64 FLAC__int64;
  82116. typedef unsigned __int16 FLAC__uint16;
  82117. typedef unsigned __int32 FLAC__uint32;
  82118. typedef unsigned __int64 FLAC__uint64;
  82119. #elif defined(__EMX__)
  82120. typedef short FLAC__int16;
  82121. typedef long FLAC__int32;
  82122. typedef long long FLAC__int64;
  82123. typedef unsigned short FLAC__uint16;
  82124. typedef unsigned long FLAC__uint32;
  82125. typedef unsigned long long FLAC__uint64;
  82126. #else
  82127. typedef int16_t FLAC__int16;
  82128. typedef int32_t FLAC__int32;
  82129. typedef int64_t FLAC__int64;
  82130. typedef uint16_t FLAC__uint16;
  82131. typedef uint32_t FLAC__uint32;
  82132. typedef uint64_t FLAC__uint64;
  82133. #endif
  82134. typedef int FLAC__bool;
  82135. typedef FLAC__uint8 FLAC__byte;
  82136. #ifdef true
  82137. #undef true
  82138. #endif
  82139. #ifdef false
  82140. #undef false
  82141. #endif
  82142. #ifndef __cplusplus
  82143. #define true 1
  82144. #define false 0
  82145. #endif
  82146. #endif
  82147. /********* End of inlined file: ordinals.h *********/
  82148. #include <stdlib.h> /* for size_t */
  82149. /** \file include/FLAC/callback.h
  82150. *
  82151. * \brief
  82152. * This module defines the structures for describing I/O callbacks
  82153. * to the other FLAC interfaces.
  82154. *
  82155. * See the detailed documentation for callbacks in the
  82156. * \link flac_callbacks callbacks \endlink module.
  82157. */
  82158. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  82159. * \ingroup flac
  82160. *
  82161. * \brief
  82162. * This module defines the structures for describing I/O callbacks
  82163. * to the other FLAC interfaces.
  82164. *
  82165. * The purpose of the I/O callback functions is to create a common way
  82166. * for the metadata interfaces to handle I/O.
  82167. *
  82168. * Originally the metadata interfaces required filenames as the way of
  82169. * specifying FLAC files to operate on. This is problematic in some
  82170. * environments so there is an additional option to specify a set of
  82171. * callbacks for doing I/O on the FLAC file, instead of the filename.
  82172. *
  82173. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  82174. * opaque structure for a data source.
  82175. *
  82176. * The callback function prototypes are similar (but not identical) to the
  82177. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  82178. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  82179. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  82180. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  82181. * is required. \warning You generally CANNOT directly use fseek or ftell
  82182. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  82183. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  82184. * large files. You will have to find an equivalent function (e.g. ftello),
  82185. * or write a wrapper. The same is true for feof() since this is usually
  82186. * implemented as a macro, not as a function whose address can be taken.
  82187. *
  82188. * \{
  82189. */
  82190. #ifdef __cplusplus
  82191. extern "C" {
  82192. #endif
  82193. /** This is the opaque handle type used by the callbacks. Typically
  82194. * this is a \c FILE* or address of a file descriptor.
  82195. */
  82196. typedef void* FLAC__IOHandle;
  82197. /** Signature for the read callback.
  82198. * The signature and semantics match POSIX fread() implementations
  82199. * and can generally be used interchangeably.
  82200. *
  82201. * \param ptr The address of the read buffer.
  82202. * \param size The size of the records to be read.
  82203. * \param nmemb The number of records to be read.
  82204. * \param handle The handle to the data source.
  82205. * \retval size_t
  82206. * The number of records read.
  82207. */
  82208. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82209. /** Signature for the write callback.
  82210. * The signature and semantics match POSIX fwrite() implementations
  82211. * and can generally be used interchangeably.
  82212. *
  82213. * \param ptr The address of the write buffer.
  82214. * \param size The size of the records to be written.
  82215. * \param nmemb The number of records to be written.
  82216. * \param handle The handle to the data source.
  82217. * \retval size_t
  82218. * The number of records written.
  82219. */
  82220. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82221. /** Signature for the seek callback.
  82222. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  82223. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  82224. * and 32-bits wide.
  82225. *
  82226. * \param handle The handle to the data source.
  82227. * \param offset The new position, relative to \a whence
  82228. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  82229. * \retval int
  82230. * \c 0 on success, \c -1 on error.
  82231. */
  82232. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  82233. /** Signature for the tell callback.
  82234. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  82235. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  82236. * and 32-bits wide.
  82237. *
  82238. * \param handle The handle to the data source.
  82239. * \retval FLAC__int64
  82240. * The current position on success, \c -1 on error.
  82241. */
  82242. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  82243. /** Signature for the EOF callback.
  82244. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  82245. * on many systems, feof() is a macro, so in this case a wrapper function
  82246. * must be provided instead.
  82247. *
  82248. * \param handle The handle to the data source.
  82249. * \retval int
  82250. * \c 0 if not at end of file, nonzero if at end of file.
  82251. */
  82252. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  82253. /** Signature for the close callback.
  82254. * The signature and semantics match POSIX fclose() implementations
  82255. * and can generally be used interchangeably.
  82256. *
  82257. * \param handle The handle to the data source.
  82258. * \retval int
  82259. * \c 0 on success, \c EOF on error.
  82260. */
  82261. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  82262. /** A structure for holding a set of callbacks.
  82263. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  82264. * describe which of the callbacks are required. The ones that are not
  82265. * required may be set to NULL.
  82266. *
  82267. * If the seek requirement for an interface is optional, you can signify that
  82268. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  82269. */
  82270. typedef struct {
  82271. FLAC__IOCallback_Read read;
  82272. FLAC__IOCallback_Write write;
  82273. FLAC__IOCallback_Seek seek;
  82274. FLAC__IOCallback_Tell tell;
  82275. FLAC__IOCallback_Eof eof;
  82276. FLAC__IOCallback_Close close;
  82277. } FLAC__IOCallbacks;
  82278. /* \} */
  82279. #ifdef __cplusplus
  82280. }
  82281. #endif
  82282. #endif
  82283. /********* End of inlined file: callback.h *********/
  82284. /********* Start of inlined file: format.h *********/
  82285. #ifndef FLAC__FORMAT_H
  82286. #define FLAC__FORMAT_H
  82287. #ifdef __cplusplus
  82288. extern "C" {
  82289. #endif
  82290. /** \file include/FLAC/format.h
  82291. *
  82292. * \brief
  82293. * This module contains structure definitions for the representation
  82294. * of FLAC format components in memory. These are the basic
  82295. * structures used by the rest of the interfaces.
  82296. *
  82297. * See the detailed documentation in the
  82298. * \link flac_format format \endlink module.
  82299. */
  82300. /** \defgroup flac_format FLAC/format.h: format components
  82301. * \ingroup flac
  82302. *
  82303. * \brief
  82304. * This module contains structure definitions for the representation
  82305. * of FLAC format components in memory. These are the basic
  82306. * structures used by the rest of the interfaces.
  82307. *
  82308. * First, you should be familiar with the
  82309. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  82310. * follow directly from the specification. As a user of libFLAC, the
  82311. * interesting parts really are the structures that describe the frame
  82312. * header and metadata blocks.
  82313. *
  82314. * The format structures here are very primitive, designed to store
  82315. * information in an efficient way. Reading information from the
  82316. * structures is easy but creating or modifying them directly is
  82317. * more complex. For the most part, as a user of a library, editing
  82318. * is not necessary; however, for metadata blocks it is, so there are
  82319. * convenience functions provided in the \link flac_metadata metadata
  82320. * module \endlink to simplify the manipulation of metadata blocks.
  82321. *
  82322. * \note
  82323. * It's not the best convention, but symbols ending in _LEN are in bits
  82324. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  82325. * global variables because they are usually used when declaring byte
  82326. * arrays and some compilers require compile-time knowledge of array
  82327. * sizes when declared on the stack.
  82328. *
  82329. * \{
  82330. */
  82331. /*
  82332. Most of the values described in this file are defined by the FLAC
  82333. format specification. There is nothing to tune here.
  82334. */
  82335. /** The largest legal metadata type code. */
  82336. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  82337. /** The minimum block size, in samples, permitted by the format. */
  82338. #define FLAC__MIN_BLOCK_SIZE (16u)
  82339. /** The maximum block size, in samples, permitted by the format. */
  82340. #define FLAC__MAX_BLOCK_SIZE (65535u)
  82341. /** The maximum block size, in samples, permitted by the FLAC subset for
  82342. * sample rates up to 48kHz. */
  82343. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  82344. /** The maximum number of channels permitted by the format. */
  82345. #define FLAC__MAX_CHANNELS (8u)
  82346. /** The minimum sample resolution permitted by the format. */
  82347. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  82348. /** The maximum sample resolution permitted by the format. */
  82349. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  82350. /** The maximum sample resolution permitted by libFLAC.
  82351. *
  82352. * \warning
  82353. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  82354. * the reference encoder/decoder is currently limited to 24 bits because
  82355. * of prevalent 32-bit math, so make sure and use this value when
  82356. * appropriate.
  82357. */
  82358. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  82359. /** The maximum sample rate permitted by the format. The value is
  82360. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  82361. * as to why.
  82362. */
  82363. #define FLAC__MAX_SAMPLE_RATE (655350u)
  82364. /** The maximum LPC order permitted by the format. */
  82365. #define FLAC__MAX_LPC_ORDER (32u)
  82366. /** The maximum LPC order permitted by the FLAC subset for sample rates
  82367. * up to 48kHz. */
  82368. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  82369. /** The minimum quantized linear predictor coefficient precision
  82370. * permitted by the format.
  82371. */
  82372. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  82373. /** The maximum quantized linear predictor coefficient precision
  82374. * permitted by the format.
  82375. */
  82376. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  82377. /** The maximum order of the fixed predictors permitted by the format. */
  82378. #define FLAC__MAX_FIXED_ORDER (4u)
  82379. /** The maximum Rice partition order permitted by the format. */
  82380. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  82381. /** The maximum Rice partition order permitted by the FLAC Subset. */
  82382. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  82383. /** The version string of the release, stamped onto the libraries and binaries.
  82384. *
  82385. * \note
  82386. * This does not correspond to the shared library version number, which
  82387. * is used to determine binary compatibility.
  82388. */
  82389. extern FLAC_API const char *FLAC__VERSION_STRING;
  82390. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  82391. * This is a NUL-terminated ASCII string; when inserted into the
  82392. * VORBIS_COMMENT the trailing null is stripped.
  82393. */
  82394. extern FLAC_API const char *FLAC__VENDOR_STRING;
  82395. /** The byte string representation of the beginning of a FLAC stream. */
  82396. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  82397. /** The 32-bit integer big-endian representation of the beginning of
  82398. * a FLAC stream.
  82399. */
  82400. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  82401. /** The length of the FLAC signature in bits. */
  82402. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  82403. /** The length of the FLAC signature in bytes. */
  82404. #define FLAC__STREAM_SYNC_LENGTH (4u)
  82405. /*****************************************************************************
  82406. *
  82407. * Subframe structures
  82408. *
  82409. *****************************************************************************/
  82410. /*****************************************************************************/
  82411. /** An enumeration of the available entropy coding methods. */
  82412. typedef enum {
  82413. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  82414. /**< Residual is coded by partitioning into contexts, each with it's own
  82415. * 4-bit Rice parameter. */
  82416. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  82417. /**< Residual is coded by partitioning into contexts, each with it's own
  82418. * 5-bit Rice parameter. */
  82419. } FLAC__EntropyCodingMethodType;
  82420. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  82421. *
  82422. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  82423. * give the string equivalent. The contents should not be modified.
  82424. */
  82425. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  82426. /** Contents of a Rice partitioned residual
  82427. */
  82428. typedef struct {
  82429. unsigned *parameters;
  82430. /**< The Rice parameters for each context. */
  82431. unsigned *raw_bits;
  82432. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  82433. * partitions and zero for unescaped partitions.
  82434. */
  82435. unsigned capacity_by_order;
  82436. /**< The capacity of the \a parameters and \a raw_bits arrays
  82437. * specified as an order, i.e. the number of array elements
  82438. * allocated is 2 ^ \a capacity_by_order.
  82439. */
  82440. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  82441. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  82442. */
  82443. typedef struct {
  82444. unsigned order;
  82445. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  82446. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  82447. /**< The context's Rice parameters and/or raw bits. */
  82448. } FLAC__EntropyCodingMethod_PartitionedRice;
  82449. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  82450. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  82451. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  82452. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  82453. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  82454. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  82455. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  82456. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  82457. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  82458. */
  82459. typedef struct {
  82460. FLAC__EntropyCodingMethodType type;
  82461. union {
  82462. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  82463. } data;
  82464. } FLAC__EntropyCodingMethod;
  82465. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  82466. /*****************************************************************************/
  82467. /** An enumeration of the available subframe types. */
  82468. typedef enum {
  82469. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  82470. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  82471. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  82472. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  82473. } FLAC__SubframeType;
  82474. /** Maps a FLAC__SubframeType to a C string.
  82475. *
  82476. * Using a FLAC__SubframeType as the index to this array will
  82477. * give the string equivalent. The contents should not be modified.
  82478. */
  82479. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  82480. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  82481. */
  82482. typedef struct {
  82483. FLAC__int32 value; /**< The constant signal value. */
  82484. } FLAC__Subframe_Constant;
  82485. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  82486. */
  82487. typedef struct {
  82488. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  82489. } FLAC__Subframe_Verbatim;
  82490. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  82491. */
  82492. typedef struct {
  82493. FLAC__EntropyCodingMethod entropy_coding_method;
  82494. /**< The residual coding method. */
  82495. unsigned order;
  82496. /**< The polynomial order. */
  82497. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  82498. /**< Warmup samples to prime the predictor, length == order. */
  82499. const FLAC__int32 *residual;
  82500. /**< The residual signal, length == (blocksize minus order) samples. */
  82501. } FLAC__Subframe_Fixed;
  82502. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  82503. */
  82504. typedef struct {
  82505. FLAC__EntropyCodingMethod entropy_coding_method;
  82506. /**< The residual coding method. */
  82507. unsigned order;
  82508. /**< The FIR order. */
  82509. unsigned qlp_coeff_precision;
  82510. /**< Quantized FIR filter coefficient precision in bits. */
  82511. int quantization_level;
  82512. /**< The qlp coeff shift needed. */
  82513. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  82514. /**< FIR filter coefficients. */
  82515. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  82516. /**< Warmup samples to prime the predictor, length == order. */
  82517. const FLAC__int32 *residual;
  82518. /**< The residual signal, length == (blocksize minus order) samples. */
  82519. } FLAC__Subframe_LPC;
  82520. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  82521. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  82522. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  82523. */
  82524. typedef struct {
  82525. FLAC__SubframeType type;
  82526. union {
  82527. FLAC__Subframe_Constant constant;
  82528. FLAC__Subframe_Fixed fixed;
  82529. FLAC__Subframe_LPC lpc;
  82530. FLAC__Subframe_Verbatim verbatim;
  82531. } data;
  82532. unsigned wasted_bits;
  82533. } FLAC__Subframe;
  82534. /** == 1 (bit)
  82535. *
  82536. * This used to be a zero-padding bit (hence the name
  82537. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  82538. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  82539. * to mean something else.
  82540. */
  82541. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  82542. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  82543. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  82544. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  82545. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  82546. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  82547. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  82548. /*****************************************************************************/
  82549. /*****************************************************************************
  82550. *
  82551. * Frame structures
  82552. *
  82553. *****************************************************************************/
  82554. /** An enumeration of the available channel assignments. */
  82555. typedef enum {
  82556. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  82557. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  82558. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  82559. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  82560. } FLAC__ChannelAssignment;
  82561. /** Maps a FLAC__ChannelAssignment to a C string.
  82562. *
  82563. * Using a FLAC__ChannelAssignment as the index to this array will
  82564. * give the string equivalent. The contents should not be modified.
  82565. */
  82566. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  82567. /** An enumeration of the possible frame numbering methods. */
  82568. typedef enum {
  82569. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  82570. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  82571. } FLAC__FrameNumberType;
  82572. /** Maps a FLAC__FrameNumberType to a C string.
  82573. *
  82574. * Using a FLAC__FrameNumberType as the index to this array will
  82575. * give the string equivalent. The contents should not be modified.
  82576. */
  82577. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  82578. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  82579. */
  82580. typedef struct {
  82581. unsigned blocksize;
  82582. /**< The number of samples per subframe. */
  82583. unsigned sample_rate;
  82584. /**< The sample rate in Hz. */
  82585. unsigned channels;
  82586. /**< The number of channels (== number of subframes). */
  82587. FLAC__ChannelAssignment channel_assignment;
  82588. /**< The channel assignment for the frame. */
  82589. unsigned bits_per_sample;
  82590. /**< The sample resolution. */
  82591. FLAC__FrameNumberType number_type;
  82592. /**< The numbering scheme used for the frame. As a convenience, the
  82593. * decoder will always convert a frame number to a sample number because
  82594. * the rules are complex. */
  82595. union {
  82596. FLAC__uint32 frame_number;
  82597. FLAC__uint64 sample_number;
  82598. } number;
  82599. /**< The frame number or sample number of first sample in frame;
  82600. * use the \a number_type value to determine which to use. */
  82601. FLAC__uint8 crc;
  82602. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  82603. * of the raw frame header bytes, meaning everything before the CRC byte
  82604. * including the sync code.
  82605. */
  82606. } FLAC__FrameHeader;
  82607. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  82608. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  82609. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  82610. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  82611. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  82612. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  82613. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  82614. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  82615. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  82616. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  82617. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  82618. */
  82619. typedef struct {
  82620. FLAC__uint16 crc;
  82621. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  82622. * 0) of the bytes before the crc, back to and including the frame header
  82623. * sync code.
  82624. */
  82625. } FLAC__FrameFooter;
  82626. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  82627. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  82628. */
  82629. typedef struct {
  82630. FLAC__FrameHeader header;
  82631. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  82632. FLAC__FrameFooter footer;
  82633. } FLAC__Frame;
  82634. /*****************************************************************************/
  82635. /*****************************************************************************
  82636. *
  82637. * Meta-data structures
  82638. *
  82639. *****************************************************************************/
  82640. /** An enumeration of the available metadata block types. */
  82641. typedef enum {
  82642. FLAC__METADATA_TYPE_STREAMINFO = 0,
  82643. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  82644. FLAC__METADATA_TYPE_PADDING = 1,
  82645. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  82646. FLAC__METADATA_TYPE_APPLICATION = 2,
  82647. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  82648. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  82649. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  82650. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  82651. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  82652. FLAC__METADATA_TYPE_CUESHEET = 5,
  82653. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  82654. FLAC__METADATA_TYPE_PICTURE = 6,
  82655. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  82656. FLAC__METADATA_TYPE_UNDEFINED = 7
  82657. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  82658. } FLAC__MetadataType;
  82659. /** Maps a FLAC__MetadataType to a C string.
  82660. *
  82661. * Using a FLAC__MetadataType as the index to this array will
  82662. * give the string equivalent. The contents should not be modified.
  82663. */
  82664. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  82665. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  82666. */
  82667. typedef struct {
  82668. unsigned min_blocksize, max_blocksize;
  82669. unsigned min_framesize, max_framesize;
  82670. unsigned sample_rate;
  82671. unsigned channels;
  82672. unsigned bits_per_sample;
  82673. FLAC__uint64 total_samples;
  82674. FLAC__byte md5sum[16];
  82675. } FLAC__StreamMetadata_StreamInfo;
  82676. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82677. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82678. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82679. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82680. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  82681. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  82682. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  82683. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  82684. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  82685. /** The total stream length of the STREAMINFO block in bytes. */
  82686. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  82687. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  82688. */
  82689. typedef struct {
  82690. int dummy;
  82691. /**< Conceptually this is an empty struct since we don't store the
  82692. * padding bytes. Empty structs are not allowed by some C compilers,
  82693. * hence the dummy.
  82694. */
  82695. } FLAC__StreamMetadata_Padding;
  82696. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  82697. */
  82698. typedef struct {
  82699. FLAC__byte id[4];
  82700. FLAC__byte *data;
  82701. } FLAC__StreamMetadata_Application;
  82702. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  82703. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  82704. */
  82705. typedef struct {
  82706. FLAC__uint64 sample_number;
  82707. /**< The sample number of the target frame. */
  82708. FLAC__uint64 stream_offset;
  82709. /**< The offset, in bytes, of the target frame with respect to
  82710. * beginning of the first frame. */
  82711. unsigned frame_samples;
  82712. /**< The number of samples in the target frame. */
  82713. } FLAC__StreamMetadata_SeekPoint;
  82714. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  82715. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  82716. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  82717. /** The total stream length of a seek point in bytes. */
  82718. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  82719. /** The value used in the \a sample_number field of
  82720. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  82721. * point (== 0xffffffffffffffff).
  82722. */
  82723. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  82724. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  82725. *
  82726. * \note From the format specification:
  82727. * - The seek points must be sorted by ascending sample number.
  82728. * - Each seek point's sample number must be the first sample of the
  82729. * target frame.
  82730. * - Each seek point's sample number must be unique within the table.
  82731. * - Existence of a SEEKTABLE block implies a correct setting of
  82732. * total_samples in the stream_info block.
  82733. * - Behavior is undefined when more than one SEEKTABLE block is
  82734. * present in a stream.
  82735. */
  82736. typedef struct {
  82737. unsigned num_points;
  82738. FLAC__StreamMetadata_SeekPoint *points;
  82739. } FLAC__StreamMetadata_SeekTable;
  82740. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82741. *
  82742. * For convenience, the APIs maintain a trailing NUL character at the end of
  82743. * \a entry which is not counted toward \a length, i.e.
  82744. * \code strlen(entry) == length \endcode
  82745. */
  82746. typedef struct {
  82747. FLAC__uint32 length;
  82748. FLAC__byte *entry;
  82749. } FLAC__StreamMetadata_VorbisComment_Entry;
  82750. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  82751. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82752. */
  82753. typedef struct {
  82754. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  82755. FLAC__uint32 num_comments;
  82756. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  82757. } FLAC__StreamMetadata_VorbisComment;
  82758. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  82759. /** FLAC CUESHEET track index structure. (See the
  82760. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  82761. * the full description of each field.)
  82762. */
  82763. typedef struct {
  82764. FLAC__uint64 offset;
  82765. /**< Offset in samples, relative to the track offset, of the index
  82766. * point.
  82767. */
  82768. FLAC__byte number;
  82769. /**< The index point number. */
  82770. } FLAC__StreamMetadata_CueSheet_Index;
  82771. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  82772. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  82773. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  82774. /** FLAC CUESHEET track structure. (See the
  82775. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  82776. * the full description of each field.)
  82777. */
  82778. typedef struct {
  82779. FLAC__uint64 offset;
  82780. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  82781. FLAC__byte number;
  82782. /**< The track number. */
  82783. char isrc[13];
  82784. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  82785. unsigned type:1;
  82786. /**< The track type: 0 for audio, 1 for non-audio. */
  82787. unsigned pre_emphasis:1;
  82788. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  82789. FLAC__byte num_indices;
  82790. /**< The number of track index points. */
  82791. FLAC__StreamMetadata_CueSheet_Index *indices;
  82792. /**< NULL if num_indices == 0, else pointer to array of index points. */
  82793. } FLAC__StreamMetadata_CueSheet_Track;
  82794. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  82795. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  82796. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  82797. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  82798. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  82799. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  82800. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  82801. /** FLAC CUESHEET structure. (See the
  82802. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  82803. * for the full description of each field.)
  82804. */
  82805. typedef struct {
  82806. char media_catalog_number[129];
  82807. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  82808. * general, the media catalog number may be 0 to 128 bytes long; any
  82809. * unused characters should be right-padded with NUL characters.
  82810. */
  82811. FLAC__uint64 lead_in;
  82812. /**< The number of lead-in samples. */
  82813. FLAC__bool is_cd;
  82814. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  82815. unsigned num_tracks;
  82816. /**< The number of tracks. */
  82817. FLAC__StreamMetadata_CueSheet_Track *tracks;
  82818. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  82819. } FLAC__StreamMetadata_CueSheet;
  82820. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  82821. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  82822. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  82823. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  82824. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  82825. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  82826. typedef enum {
  82827. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  82828. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  82829. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  82830. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  82831. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  82832. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  82833. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  82834. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  82835. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  82836. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  82837. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  82838. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  82839. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  82840. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  82841. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  82842. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  82843. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  82844. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  82845. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  82846. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  82847. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  82848. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  82849. } FLAC__StreamMetadata_Picture_Type;
  82850. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  82851. *
  82852. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  82853. * will give the string equivalent. The contents should not be
  82854. * modified.
  82855. */
  82856. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  82857. /** FLAC PICTURE structure. (See the
  82858. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  82859. * for the full description of each field.)
  82860. */
  82861. typedef struct {
  82862. FLAC__StreamMetadata_Picture_Type type;
  82863. /**< The kind of picture stored. */
  82864. char *mime_type;
  82865. /**< Picture data's MIME type, in ASCII printable characters
  82866. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  82867. * use picture data of MIME type \c image/jpeg or \c image/png. A
  82868. * MIME type of '-->' is also allowed, in which case the picture
  82869. * data should be a complete URL. In file storage, the MIME type is
  82870. * stored as a 32-bit length followed by the ASCII string with no NUL
  82871. * terminator, but is converted to a plain C string in this structure
  82872. * for convenience.
  82873. */
  82874. FLAC__byte *description;
  82875. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  82876. * the description is stored as a 32-bit length followed by the UTF-8
  82877. * string with no NUL terminator, but is converted to a plain C string
  82878. * in this structure for convenience.
  82879. */
  82880. FLAC__uint32 width;
  82881. /**< Picture's width in pixels. */
  82882. FLAC__uint32 height;
  82883. /**< Picture's height in pixels. */
  82884. FLAC__uint32 depth;
  82885. /**< Picture's color depth in bits-per-pixel. */
  82886. FLAC__uint32 colors;
  82887. /**< For indexed palettes (like GIF), picture's number of colors (the
  82888. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  82889. */
  82890. FLAC__uint32 data_length;
  82891. /**< Length of binary picture data in bytes. */
  82892. FLAC__byte *data;
  82893. /**< Binary picture data. */
  82894. } FLAC__StreamMetadata_Picture;
  82895. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  82896. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  82897. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  82898. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  82899. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  82900. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  82901. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  82902. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  82903. /** Structure that is used when a metadata block of unknown type is loaded.
  82904. * The contents are opaque. The structure is used only internally to
  82905. * correctly handle unknown metadata.
  82906. */
  82907. typedef struct {
  82908. FLAC__byte *data;
  82909. } FLAC__StreamMetadata_Unknown;
  82910. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  82911. */
  82912. typedef struct {
  82913. FLAC__MetadataType type;
  82914. /**< The type of the metadata block; used determine which member of the
  82915. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  82916. * then \a data.unknown must be used. */
  82917. FLAC__bool is_last;
  82918. /**< \c true if this metadata block is the last, else \a false */
  82919. unsigned length;
  82920. /**< Length, in bytes, of the block data as it appears in the stream. */
  82921. union {
  82922. FLAC__StreamMetadata_StreamInfo stream_info;
  82923. FLAC__StreamMetadata_Padding padding;
  82924. FLAC__StreamMetadata_Application application;
  82925. FLAC__StreamMetadata_SeekTable seek_table;
  82926. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  82927. FLAC__StreamMetadata_CueSheet cue_sheet;
  82928. FLAC__StreamMetadata_Picture picture;
  82929. FLAC__StreamMetadata_Unknown unknown;
  82930. } data;
  82931. /**< Polymorphic block data; use the \a type value to determine which
  82932. * to use. */
  82933. } FLAC__StreamMetadata;
  82934. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  82935. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  82936. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  82937. /** The total stream length of a metadata block header in bytes. */
  82938. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  82939. /*****************************************************************************/
  82940. /*****************************************************************************
  82941. *
  82942. * Utility functions
  82943. *
  82944. *****************************************************************************/
  82945. /** Tests that a sample rate is valid for FLAC.
  82946. *
  82947. * \param sample_rate The sample rate to test for compliance.
  82948. * \retval FLAC__bool
  82949. * \c true if the given sample rate conforms to the specification, else
  82950. * \c false.
  82951. */
  82952. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  82953. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  82954. * for valid sample rates are slightly more complex since the rate has to
  82955. * be expressible completely in the frame header.
  82956. *
  82957. * \param sample_rate The sample rate to test for compliance.
  82958. * \retval FLAC__bool
  82959. * \c true if the given sample rate conforms to the specification for the
  82960. * subset, else \c false.
  82961. */
  82962. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  82963. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  82964. * comment specification.
  82965. *
  82966. * Vorbis comment names must be composed only of characters from
  82967. * [0x20-0x3C,0x3E-0x7D].
  82968. *
  82969. * \param name A NUL-terminated string to be checked.
  82970. * \assert
  82971. * \code name != NULL \endcode
  82972. * \retval FLAC__bool
  82973. * \c false if entry name is illegal, else \c true.
  82974. */
  82975. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  82976. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  82977. * comment specification.
  82978. *
  82979. * Vorbis comment values must be valid UTF-8 sequences.
  82980. *
  82981. * \param value A string to be checked.
  82982. * \param length A the length of \a value in bytes. May be
  82983. * \c (unsigned)(-1) to indicate that \a value is a plain
  82984. * UTF-8 NUL-terminated string.
  82985. * \assert
  82986. * \code value != NULL \endcode
  82987. * \retval FLAC__bool
  82988. * \c false if entry name is illegal, else \c true.
  82989. */
  82990. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  82991. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  82992. * comment specification.
  82993. *
  82994. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  82995. * 'value' must be legal according to
  82996. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  82997. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  82998. *
  82999. * \param entry An entry to be checked.
  83000. * \param length The length of \a entry in bytes.
  83001. * \assert
  83002. * \code value != NULL \endcode
  83003. * \retval FLAC__bool
  83004. * \c false if entry name is illegal, else \c true.
  83005. */
  83006. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  83007. /** Check a seek table to see if it conforms to the FLAC specification.
  83008. * See the format specification for limits on the contents of the
  83009. * seek table.
  83010. *
  83011. * \param seek_table A pointer to a seek table to be checked.
  83012. * \assert
  83013. * \code seek_table != NULL \endcode
  83014. * \retval FLAC__bool
  83015. * \c false if seek table is illegal, else \c true.
  83016. */
  83017. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  83018. /** Sort a seek table's seek points according to the format specification.
  83019. * This includes a "unique-ification" step to remove duplicates, i.e.
  83020. * seek points with identical \a sample_number values. Duplicate seek
  83021. * points are converted into placeholder points and sorted to the end of
  83022. * the table.
  83023. *
  83024. * \param seek_table A pointer to a seek table to be sorted.
  83025. * \assert
  83026. * \code seek_table != NULL \endcode
  83027. * \retval unsigned
  83028. * The number of duplicate seek points converted into placeholders.
  83029. */
  83030. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  83031. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83032. * See the format specification for limits on the contents of the
  83033. * cue sheet.
  83034. *
  83035. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  83036. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83037. * stringent requirements for a CD-DA (audio) disc.
  83038. * \param violation Address of a pointer to a string. If there is a
  83039. * violation, a pointer to a string explanation of the
  83040. * violation will be returned here. \a violation may be
  83041. * \c NULL if you don't need the returned string. Do not
  83042. * free the returned string; it will always point to static
  83043. * data.
  83044. * \assert
  83045. * \code cue_sheet != NULL \endcode
  83046. * \retval FLAC__bool
  83047. * \c false if cue sheet is illegal, else \c true.
  83048. */
  83049. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  83050. /** Check picture data to see if it conforms to the FLAC specification.
  83051. * See the format specification for limits on the contents of the
  83052. * PICTURE block.
  83053. *
  83054. * \param picture A pointer to existing picture data to be checked.
  83055. * \param violation Address of a pointer to a string. If there is a
  83056. * violation, a pointer to a string explanation of the
  83057. * violation will be returned here. \a violation may be
  83058. * \c NULL if you don't need the returned string. Do not
  83059. * free the returned string; it will always point to static
  83060. * data.
  83061. * \assert
  83062. * \code picture != NULL \endcode
  83063. * \retval FLAC__bool
  83064. * \c false if picture data is illegal, else \c true.
  83065. */
  83066. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  83067. /* \} */
  83068. #ifdef __cplusplus
  83069. }
  83070. #endif
  83071. #endif
  83072. /********* End of inlined file: format.h *********/
  83073. /********* Start of inlined file: metadata.h *********/
  83074. #ifndef FLAC__METADATA_H
  83075. #define FLAC__METADATA_H
  83076. #include <sys/types.h> /* for off_t */
  83077. /* --------------------------------------------------------------------
  83078. (For an example of how all these routines are used, see the source
  83079. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  83080. metaflac in src/metaflac/)
  83081. ------------------------------------------------------------------*/
  83082. /** \file include/FLAC/metadata.h
  83083. *
  83084. * \brief
  83085. * This module provides functions for creating and manipulating FLAC
  83086. * metadata blocks in memory, and three progressively more powerful
  83087. * interfaces for traversing and editing metadata in FLAC files.
  83088. *
  83089. * See the detailed documentation for each interface in the
  83090. * \link flac_metadata metadata \endlink module.
  83091. */
  83092. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  83093. * \ingroup flac
  83094. *
  83095. * \brief
  83096. * This module provides functions for creating and manipulating FLAC
  83097. * metadata blocks in memory, and three progressively more powerful
  83098. * interfaces for traversing and editing metadata in native FLAC files.
  83099. * Note that currently only the Chain interface (level 2) supports Ogg
  83100. * FLAC files, and it is read-only i.e. no writing back changed
  83101. * metadata to file.
  83102. *
  83103. * There are three metadata interfaces of increasing complexity:
  83104. *
  83105. * Level 0:
  83106. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  83107. * PICTURE blocks.
  83108. *
  83109. * Level 1:
  83110. * Read-write access to all metadata blocks. This level is write-
  83111. * efficient in most cases (more on this below), and uses less memory
  83112. * than level 2.
  83113. *
  83114. * Level 2:
  83115. * Read-write access to all metadata blocks. This level is write-
  83116. * efficient in all cases, but uses more memory since all metadata for
  83117. * the whole file is read into memory and manipulated before writing
  83118. * out again.
  83119. *
  83120. * What do we mean by efficient? Since FLAC metadata appears at the
  83121. * beginning of the file, when writing metadata back to a FLAC file
  83122. * it is possible to grow or shrink the metadata such that the entire
  83123. * file must be rewritten. However, if the size remains the same during
  83124. * changes or PADDING blocks are utilized, only the metadata needs to be
  83125. * overwritten, which is much faster.
  83126. *
  83127. * Efficient means the whole file is rewritten at most one time, and only
  83128. * when necessary. Level 1 is not efficient only in the case that you
  83129. * cause more than one metadata block to grow or shrink beyond what can
  83130. * be accomodated by padding. In this case you should probably use level
  83131. * 2, which allows you to edit all the metadata for a file in memory and
  83132. * write it out all at once.
  83133. *
  83134. * All levels know how to skip over and not disturb an ID3v2 tag at the
  83135. * front of the file.
  83136. *
  83137. * All levels access files via their filenames. In addition, level 2
  83138. * has additional alternative read and write functions that take an I/O
  83139. * handle and callbacks, for situations where access by filename is not
  83140. * possible.
  83141. *
  83142. * In addition to the three interfaces, this module defines functions for
  83143. * creating and manipulating various metadata objects in memory. As we see
  83144. * from the Format module, FLAC metadata blocks in memory are very primitive
  83145. * structures for storing information in an efficient way. Reading
  83146. * information from the structures is easy but creating or modifying them
  83147. * directly is more complex. The metadata object routines here facilitate
  83148. * this by taking care of the consistency and memory management drudgery.
  83149. *
  83150. * Unless you will be using the level 1 or 2 interfaces to modify existing
  83151. * metadata however, you will not probably not need these.
  83152. *
  83153. * From a dependency standpoint, none of the encoders or decoders require
  83154. * the metadata module. This is so that embedded users can strip out the
  83155. * metadata module from libFLAC to reduce the size and complexity.
  83156. */
  83157. #ifdef __cplusplus
  83158. extern "C" {
  83159. #endif
  83160. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  83161. * \ingroup flac_metadata
  83162. *
  83163. * \brief
  83164. * The level 0 interface consists of individual routines to read the
  83165. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  83166. * only a filename.
  83167. *
  83168. * They try to skip any ID3v2 tag at the head of the file.
  83169. *
  83170. * \{
  83171. */
  83172. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  83173. * will try to skip any ID3v2 tag at the head of the file.
  83174. *
  83175. * \param filename The path to the FLAC file to read.
  83176. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  83177. * FLAC__StreamMetadata is a simple structure with no
  83178. * memory allocation involved, you pass the address of
  83179. * an existing structure. It need not be initialized.
  83180. * \assert
  83181. * \code filename != NULL \endcode
  83182. * \code streaminfo != NULL \endcode
  83183. * \retval FLAC__bool
  83184. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  83185. * \c false if there was a memory allocation error, a file decoder error,
  83186. * or the file contained no STREAMINFO block. (A memory allocation error
  83187. * is possible because this function must set up a file decoder.)
  83188. */
  83189. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  83190. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  83191. * function will try to skip any ID3v2 tag at the head of the file.
  83192. *
  83193. * \param filename The path to the FLAC file to read.
  83194. * \param tags The address where the returned pointer will be
  83195. * stored. The \a tags object must be deleted by
  83196. * the caller using FLAC__metadata_object_delete().
  83197. * \assert
  83198. * \code filename != NULL \endcode
  83199. * \code tags != NULL \endcode
  83200. * \retval FLAC__bool
  83201. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  83202. * and \a *tags will be set to the address of the metadata structure.
  83203. * Returns \c false if there was a memory allocation error, a file
  83204. * decoder error, or the file contained no VORBIS_COMMENT block, and
  83205. * \a *tags will be set to \c NULL.
  83206. */
  83207. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  83208. /** Read the CUESHEET metadata block of the given FLAC file. This
  83209. * function will try to skip any ID3v2 tag at the head of the file.
  83210. *
  83211. * \param filename The path to the FLAC file to read.
  83212. * \param cuesheet The address where the returned pointer will be
  83213. * stored. The \a cuesheet object must be deleted by
  83214. * the caller using FLAC__metadata_object_delete().
  83215. * \assert
  83216. * \code filename != NULL \endcode
  83217. * \code cuesheet != NULL \endcode
  83218. * \retval FLAC__bool
  83219. * \c true if a valid CUESHEET block was read from \a filename,
  83220. * and \a *cuesheet will be set to the address of the metadata
  83221. * structure. Returns \c false if there was a memory allocation
  83222. * error, a file decoder error, or the file contained no CUESHEET
  83223. * block, and \a *cuesheet will be set to \c NULL.
  83224. */
  83225. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  83226. /** Read a PICTURE metadata block of the given FLAC file. This
  83227. * function will try to skip any ID3v2 tag at the head of the file.
  83228. * Since there can be more than one PICTURE block in a file, this
  83229. * function takes a number of parameters that act as constraints to
  83230. * the search. The PICTURE block with the largest area matching all
  83231. * the constraints will be returned, or \a *picture will be set to
  83232. * \c NULL if there was no such block.
  83233. *
  83234. * \param filename The path to the FLAC file to read.
  83235. * \param picture The address where the returned pointer will be
  83236. * stored. The \a picture object must be deleted by
  83237. * the caller using FLAC__metadata_object_delete().
  83238. * \param type The desired picture type. Use \c -1 to mean
  83239. * "any type".
  83240. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  83241. * string will be matched exactly. Use \c NULL to
  83242. * mean "any MIME type".
  83243. * \param description The desired description. The string will be
  83244. * matched exactly. Use \c NULL to mean "any
  83245. * description".
  83246. * \param max_width The maximum width in pixels desired. Use
  83247. * \c (unsigned)(-1) to mean "any width".
  83248. * \param max_height The maximum height in pixels desired. Use
  83249. * \c (unsigned)(-1) to mean "any height".
  83250. * \param max_depth The maximum color depth in bits-per-pixel desired.
  83251. * Use \c (unsigned)(-1) to mean "any depth".
  83252. * \param max_colors The maximum number of colors desired. Use
  83253. * \c (unsigned)(-1) to mean "any number of colors".
  83254. * \assert
  83255. * \code filename != NULL \endcode
  83256. * \code picture != NULL \endcode
  83257. * \retval FLAC__bool
  83258. * \c true if a valid PICTURE block was read from \a filename,
  83259. * and \a *picture will be set to the address of the metadata
  83260. * structure. Returns \c false if there was a memory allocation
  83261. * error, a file decoder error, or the file contained no PICTURE
  83262. * block, and \a *picture will be set to \c NULL.
  83263. */
  83264. FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors);
  83265. /* \} */
  83266. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  83267. * \ingroup flac_metadata
  83268. *
  83269. * \brief
  83270. * The level 1 interface provides read-write access to FLAC file metadata and
  83271. * operates directly on the FLAC file.
  83272. *
  83273. * The general usage of this interface is:
  83274. *
  83275. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  83276. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  83277. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  83278. * see if the file is writable, or only read access is allowed.
  83279. * - Use FLAC__metadata_simple_iterator_next() and
  83280. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  83281. * This is does not read the actual blocks themselves.
  83282. * FLAC__metadata_simple_iterator_next() is relatively fast.
  83283. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  83284. * forward from the front of the file.
  83285. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  83286. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  83287. * the current iterator position. The returned object is yours to modify
  83288. * and free.
  83289. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  83290. * back. You must have write permission to the original file. Make sure to
  83291. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  83292. * below.
  83293. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  83294. * Use the object creation functions from
  83295. * \link flac_metadata_object here \endlink to generate new objects.
  83296. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  83297. * currently referred to by the iterator, or replace it with padding.
  83298. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  83299. * finished.
  83300. *
  83301. * \note
  83302. * The FLAC file remains open the whole time between
  83303. * FLAC__metadata_simple_iterator_init() and
  83304. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  83305. * the file during this time.
  83306. *
  83307. * \note
  83308. * Do not modify the \a is_last, \a length, or \a type fields of returned
  83309. * FLAC__StreamMetadata objects. These are managed automatically.
  83310. *
  83311. * \note
  83312. * If any of the modification functions
  83313. * (FLAC__metadata_simple_iterator_set_block(),
  83314. * FLAC__metadata_simple_iterator_delete_block(),
  83315. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  83316. * you should delete the iterator as it may no longer be valid.
  83317. *
  83318. * \{
  83319. */
  83320. struct FLAC__Metadata_SimpleIterator;
  83321. /** The opaque structure definition for the level 1 iterator type.
  83322. * See the
  83323. * \link flac_metadata_level1 metadata level 1 module \endlink
  83324. * for a detailed description.
  83325. */
  83326. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  83327. /** Status type for FLAC__Metadata_SimpleIterator.
  83328. *
  83329. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  83330. */
  83331. typedef enum {
  83332. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  83333. /**< The iterator is in the normal OK state */
  83334. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  83335. /**< The data passed into a function violated the function's usage criteria */
  83336. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  83337. /**< The iterator could not open the target file */
  83338. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  83339. /**< The iterator could not find the FLAC signature at the start of the file */
  83340. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  83341. /**< The iterator tried to write to a file that was not writable */
  83342. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  83343. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  83344. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  83345. /**< The iterator encountered an error while reading the FLAC file */
  83346. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  83347. /**< The iterator encountered an error while seeking in the FLAC file */
  83348. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  83349. /**< The iterator encountered an error while writing the FLAC file */
  83350. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  83351. /**< The iterator encountered an error renaming the FLAC file */
  83352. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  83353. /**< The iterator encountered an error removing the temporary file */
  83354. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  83355. /**< Memory allocation failed */
  83356. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  83357. /**< The caller violated an assertion or an unexpected error occurred */
  83358. } FLAC__Metadata_SimpleIteratorStatus;
  83359. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  83360. *
  83361. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  83362. * will give the string equivalent. The contents should not be modified.
  83363. */
  83364. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  83365. /** Create a new iterator instance.
  83366. *
  83367. * \retval FLAC__Metadata_SimpleIterator*
  83368. * \c NULL if there was an error allocating memory, else the new instance.
  83369. */
  83370. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  83371. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83372. *
  83373. * \param iterator A pointer to an existing iterator.
  83374. * \assert
  83375. * \code iterator != NULL \endcode
  83376. */
  83377. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  83378. /** Get the current status of the iterator. Call this after a function
  83379. * returns \c false to get the reason for the error. Also resets the status
  83380. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  83381. *
  83382. * \param iterator A pointer to an existing iterator.
  83383. * \assert
  83384. * \code iterator != NULL \endcode
  83385. * \retval FLAC__Metadata_SimpleIteratorStatus
  83386. * The current status of the iterator.
  83387. */
  83388. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  83389. /** Initialize the iterator to point to the first metadata block in the
  83390. * given FLAC file.
  83391. *
  83392. * \param iterator A pointer to an existing iterator.
  83393. * \param filename The path to the FLAC file.
  83394. * \param read_only If \c true, the FLAC file will be opened
  83395. * in read-only mode; if \c false, the FLAC
  83396. * file will be opened for edit even if no
  83397. * edits are performed.
  83398. * \param preserve_file_stats If \c true, the owner and modification
  83399. * time will be preserved even if the FLAC
  83400. * file is written to.
  83401. * \assert
  83402. * \code iterator != NULL \endcode
  83403. * \code filename != NULL \endcode
  83404. * \retval FLAC__bool
  83405. * \c false if a memory allocation error occurs, the file can't be
  83406. * opened, or another error occurs, else \c true.
  83407. */
  83408. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats);
  83409. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  83410. * FLAC__metadata_simple_iterator_set_block() and
  83411. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  83412. *
  83413. * \param iterator A pointer to an existing iterator.
  83414. * \assert
  83415. * \code iterator != NULL \endcode
  83416. * \retval FLAC__bool
  83417. * See above.
  83418. */
  83419. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  83420. /** Moves the iterator forward one metadata block, returning \c false if
  83421. * already at the end.
  83422. *
  83423. * \param iterator A pointer to an existing initialized iterator.
  83424. * \assert
  83425. * \code iterator != NULL \endcode
  83426. * \a iterator has been successfully initialized with
  83427. * FLAC__metadata_simple_iterator_init()
  83428. * \retval FLAC__bool
  83429. * \c false if already at the last metadata block of the chain, else
  83430. * \c true.
  83431. */
  83432. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  83433. /** Moves the iterator backward one metadata block, returning \c false if
  83434. * already at the beginning.
  83435. *
  83436. * \param iterator A pointer to an existing initialized iterator.
  83437. * \assert
  83438. * \code iterator != NULL \endcode
  83439. * \a iterator has been successfully initialized with
  83440. * FLAC__metadata_simple_iterator_init()
  83441. * \retval FLAC__bool
  83442. * \c false if already at the first metadata block of the chain, else
  83443. * \c true.
  83444. */
  83445. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  83446. /** Returns a flag telling if the current metadata block is the last.
  83447. *
  83448. * \param iterator A pointer to an existing initialized iterator.
  83449. * \assert
  83450. * \code iterator != NULL \endcode
  83451. * \a iterator has been successfully initialized with
  83452. * FLAC__metadata_simple_iterator_init()
  83453. * \retval FLAC__bool
  83454. * \c true if the current metadata block is the last in the file,
  83455. * else \c false.
  83456. */
  83457. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  83458. /** Get the offset of the metadata block at the current position. This
  83459. * avoids reading the actual block data which can save time for large
  83460. * blocks.
  83461. *
  83462. * \param iterator A pointer to an existing initialized iterator.
  83463. * \assert
  83464. * \code iterator != NULL \endcode
  83465. * \a iterator has been successfully initialized with
  83466. * FLAC__metadata_simple_iterator_init()
  83467. * \retval off_t
  83468. * The offset of the metadata block at the current iterator position.
  83469. * This is the byte offset relative to the beginning of the file of
  83470. * the current metadata block's header.
  83471. */
  83472. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  83473. /** Get the type of the metadata block at the current position. This
  83474. * avoids reading the actual block data which can save time for large
  83475. * blocks.
  83476. *
  83477. * \param iterator A pointer to an existing initialized iterator.
  83478. * \assert
  83479. * \code iterator != NULL \endcode
  83480. * \a iterator has been successfully initialized with
  83481. * FLAC__metadata_simple_iterator_init()
  83482. * \retval FLAC__MetadataType
  83483. * The type of the metadata block at the current iterator position.
  83484. */
  83485. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  83486. /** Get the length of the metadata block at the current position. This
  83487. * avoids reading the actual block data which can save time for large
  83488. * blocks.
  83489. *
  83490. * \param iterator A pointer to an existing initialized iterator.
  83491. * \assert
  83492. * \code iterator != NULL \endcode
  83493. * \a iterator has been successfully initialized with
  83494. * FLAC__metadata_simple_iterator_init()
  83495. * \retval unsigned
  83496. * The length of the metadata block at the current iterator position.
  83497. * The is same length as that in the
  83498. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  83499. * i.e. the length of the metadata body that follows the header.
  83500. */
  83501. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  83502. /** Get the application ID of the \c APPLICATION block at the current
  83503. * position. This avoids reading the actual block data which can save
  83504. * time for large blocks.
  83505. *
  83506. * \param iterator A pointer to an existing initialized iterator.
  83507. * \param id A pointer to a buffer of at least \c 4 bytes where
  83508. * the ID will be stored.
  83509. * \assert
  83510. * \code iterator != NULL \endcode
  83511. * \code id != NULL \endcode
  83512. * \a iterator has been successfully initialized with
  83513. * FLAC__metadata_simple_iterator_init()
  83514. * \retval FLAC__bool
  83515. * \c true if the ID was successfully read, else \c false, in which
  83516. * case you should check FLAC__metadata_simple_iterator_status() to
  83517. * find out why. If the status is
  83518. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  83519. * current metadata block is not an \c APPLICATION block. Otherwise
  83520. * if the status is
  83521. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  83522. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  83523. * occurred and the iterator can no longer be used.
  83524. */
  83525. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  83526. /** Get the metadata block at the current position. You can modify the
  83527. * block but must use FLAC__metadata_simple_iterator_set_block() to
  83528. * write it back to the FLAC file.
  83529. *
  83530. * You must call FLAC__metadata_object_delete() on the returned object
  83531. * when you are finished with it.
  83532. *
  83533. * \param iterator A pointer to an existing initialized iterator.
  83534. * \assert
  83535. * \code iterator != NULL \endcode
  83536. * \a iterator has been successfully initialized with
  83537. * FLAC__metadata_simple_iterator_init()
  83538. * \retval FLAC__StreamMetadata*
  83539. * The current metadata block, or \c NULL if there was a memory
  83540. * allocation error.
  83541. */
  83542. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  83543. /** Write a block back to the FLAC file. This function tries to be
  83544. * as efficient as possible; how the block is actually written is
  83545. * shown by the following:
  83546. *
  83547. * Existing block is a STREAMINFO block and the new block is a
  83548. * STREAMINFO block: the new block is written in place. Make sure
  83549. * you know what you're doing when changing the values of a
  83550. * STREAMINFO block.
  83551. *
  83552. * Existing block is a STREAMINFO block and the new block is a
  83553. * not a STREAMINFO block: this is an error since the first block
  83554. * must be a STREAMINFO block. Returns \c false without altering the
  83555. * file.
  83556. *
  83557. * Existing block is not a STREAMINFO block and the new block is a
  83558. * STREAMINFO block: this is an error since there may be only one
  83559. * STREAMINFO block. Returns \c false without altering the file.
  83560. *
  83561. * Existing block and new block are the same length: the existing
  83562. * block will be replaced by the new block, written in place.
  83563. *
  83564. * Existing block is longer than new block: if use_padding is \c true,
  83565. * the existing block will be overwritten in place with the new
  83566. * block followed by a PADDING block, if possible, to make the total
  83567. * size the same as the existing block. Remember that a padding
  83568. * block requires at least four bytes so if the difference in size
  83569. * between the new block and existing block is less than that, the
  83570. * entire file will have to be rewritten, using the new block's
  83571. * exact size. If use_padding is \c false, the entire file will be
  83572. * rewritten, replacing the existing block by the new block.
  83573. *
  83574. * Existing block is shorter than new block: if use_padding is \c true,
  83575. * the function will try and expand the new block into the following
  83576. * PADDING block, if it exists and doing so won't shrink the PADDING
  83577. * block to less than 4 bytes. If there is no following PADDING
  83578. * block, or it will shrink to less than 4 bytes, or use_padding is
  83579. * \c false, the entire file is rewritten, replacing the existing block
  83580. * with the new block. Note that in this case any following PADDING
  83581. * block is preserved as is.
  83582. *
  83583. * After writing the block, the iterator will remain in the same
  83584. * place, i.e. pointing to the new block.
  83585. *
  83586. * \param iterator A pointer to an existing initialized iterator.
  83587. * \param block The block to set.
  83588. * \param use_padding See above.
  83589. * \assert
  83590. * \code iterator != NULL \endcode
  83591. * \a iterator has been successfully initialized with
  83592. * FLAC__metadata_simple_iterator_init()
  83593. * \code block != NULL \endcode
  83594. * \retval FLAC__bool
  83595. * \c true if successful, else \c false.
  83596. */
  83597. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83598. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  83599. * except that instead of writing over an existing block, it appends
  83600. * a block after the existing block. \a use_padding is again used to
  83601. * tell the function to try an expand into following padding in an
  83602. * attempt to avoid rewriting the entire file.
  83603. *
  83604. * This function will fail and return \c false if given a STREAMINFO
  83605. * block.
  83606. *
  83607. * After writing the block, the iterator will be pointing to the
  83608. * new block.
  83609. *
  83610. * \param iterator A pointer to an existing initialized iterator.
  83611. * \param block The block to set.
  83612. * \param use_padding See above.
  83613. * \assert
  83614. * \code iterator != NULL \endcode
  83615. * \a iterator has been successfully initialized with
  83616. * FLAC__metadata_simple_iterator_init()
  83617. * \code block != NULL \endcode
  83618. * \retval FLAC__bool
  83619. * \c true if successful, else \c false.
  83620. */
  83621. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83622. /** Deletes the block at the current position. This will cause the
  83623. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  83624. * in which case the block will be replaced by an equal-sized PADDING
  83625. * block. The iterator will be left pointing to the block before the
  83626. * one just deleted.
  83627. *
  83628. * You may not delete the STREAMINFO block.
  83629. *
  83630. * \param iterator A pointer to an existing initialized iterator.
  83631. * \param use_padding See above.
  83632. * \assert
  83633. * \code iterator != NULL \endcode
  83634. * \a iterator has been successfully initialized with
  83635. * FLAC__metadata_simple_iterator_init()
  83636. * \retval FLAC__bool
  83637. * \c true if successful, else \c false.
  83638. */
  83639. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  83640. /* \} */
  83641. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  83642. * \ingroup flac_metadata
  83643. *
  83644. * \brief
  83645. * The level 2 interface provides read-write access to FLAC file metadata;
  83646. * all metadata is read into memory, operated on in memory, and then written
  83647. * to file, which is more efficient than level 1 when editing multiple blocks.
  83648. *
  83649. * Currently Ogg FLAC is supported for read only, via
  83650. * FLAC__metadata_chain_read_ogg() but a subsequent
  83651. * FLAC__metadata_chain_write() will fail.
  83652. *
  83653. * The general usage of this interface is:
  83654. *
  83655. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  83656. * linked list of FLAC metadata blocks.
  83657. * - Read all metadata into the the chain from a FLAC file using
  83658. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  83659. * check the status.
  83660. * - Optionally, consolidate the padding using
  83661. * FLAC__metadata_chain_merge_padding() or
  83662. * FLAC__metadata_chain_sort_padding().
  83663. * - Create a new iterator using FLAC__metadata_iterator_new()
  83664. * - Initialize the iterator to point to the first element in the chain
  83665. * using FLAC__metadata_iterator_init()
  83666. * - Traverse the chain using FLAC__metadata_iterator_next and
  83667. * FLAC__metadata_iterator_prev().
  83668. * - Get a block for reading or modification using
  83669. * FLAC__metadata_iterator_get_block(). The pointer to the object
  83670. * inside the chain is returned, so the block is yours to modify.
  83671. * Changes will be reflected in the FLAC file when you write the
  83672. * chain. You can also add and delete blocks (see functions below).
  83673. * - When done, write out the chain using FLAC__metadata_chain_write().
  83674. * Make sure to read the whole comment to the function below.
  83675. * - Delete the chain using FLAC__metadata_chain_delete().
  83676. *
  83677. * \note
  83678. * Even though the FLAC file is not open while the chain is being
  83679. * manipulated, you must not alter the file externally during
  83680. * this time. The chain assumes the FLAC file will not change
  83681. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  83682. * and FLAC__metadata_chain_write().
  83683. *
  83684. * \note
  83685. * Do not modify the is_last, length, or type fields of returned
  83686. * FLAC__StreamMetadata objects. These are managed automatically.
  83687. *
  83688. * \note
  83689. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  83690. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  83691. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  83692. * become owned by the chain and they will be deleted when the chain is
  83693. * deleted.
  83694. *
  83695. * \{
  83696. */
  83697. struct FLAC__Metadata_Chain;
  83698. /** The opaque structure definition for the level 2 chain type.
  83699. */
  83700. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  83701. struct FLAC__Metadata_Iterator;
  83702. /** The opaque structure definition for the level 2 iterator type.
  83703. */
  83704. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  83705. typedef enum {
  83706. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  83707. /**< The chain is in the normal OK state */
  83708. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  83709. /**< The data passed into a function violated the function's usage criteria */
  83710. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  83711. /**< The chain could not open the target file */
  83712. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  83713. /**< The chain could not find the FLAC signature at the start of the file */
  83714. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  83715. /**< The chain tried to write to a file that was not writable */
  83716. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  83717. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  83718. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  83719. /**< The chain encountered an error while reading the FLAC file */
  83720. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  83721. /**< The chain encountered an error while seeking in the FLAC file */
  83722. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  83723. /**< The chain encountered an error while writing the FLAC file */
  83724. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  83725. /**< The chain encountered an error renaming the FLAC file */
  83726. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  83727. /**< The chain encountered an error removing the temporary file */
  83728. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  83729. /**< Memory allocation failed */
  83730. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  83731. /**< The caller violated an assertion or an unexpected error occurred */
  83732. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  83733. /**< One or more of the required callbacks was NULL */
  83734. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  83735. /**< FLAC__metadata_chain_write() was called on a chain read by
  83736. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83737. * or
  83738. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  83739. * was called on a chain read by
  83740. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83741. * Matching read/write methods must always be used. */
  83742. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  83743. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  83744. * chain write requires a tempfile; use
  83745. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  83746. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  83747. * called when the chain write does not require a tempfile; use
  83748. * FLAC__metadata_chain_write_with_callbacks() instead.
  83749. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  83750. * before writing via callbacks. */
  83751. } FLAC__Metadata_ChainStatus;
  83752. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  83753. *
  83754. * Using a FLAC__Metadata_ChainStatus as the index to this array
  83755. * will give the string equivalent. The contents should not be modified.
  83756. */
  83757. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  83758. /*********** FLAC__Metadata_Chain ***********/
  83759. /** Create a new chain instance.
  83760. *
  83761. * \retval FLAC__Metadata_Chain*
  83762. * \c NULL if there was an error allocating memory, else the new instance.
  83763. */
  83764. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  83765. /** Free a chain instance. Deletes the object pointed to by \a chain.
  83766. *
  83767. * \param chain A pointer to an existing chain.
  83768. * \assert
  83769. * \code chain != NULL \endcode
  83770. */
  83771. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  83772. /** Get the current status of the chain. Call this after a function
  83773. * returns \c false to get the reason for the error. Also resets the
  83774. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  83775. *
  83776. * \param chain A pointer to an existing chain.
  83777. * \assert
  83778. * \code chain != NULL \endcode
  83779. * \retval FLAC__Metadata_ChainStatus
  83780. * The current status of the chain.
  83781. */
  83782. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  83783. /** Read all metadata from a FLAC file into the chain.
  83784. *
  83785. * \param chain A pointer to an existing chain.
  83786. * \param filename The path to the FLAC file to read.
  83787. * \assert
  83788. * \code chain != NULL \endcode
  83789. * \code filename != NULL \endcode
  83790. * \retval FLAC__bool
  83791. * \c true if a valid list of metadata blocks was read from
  83792. * \a filename, else \c false. On failure, check the status with
  83793. * FLAC__metadata_chain_status().
  83794. */
  83795. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  83796. /** Read all metadata from an Ogg FLAC file into the chain.
  83797. *
  83798. * \note Ogg FLAC metadata data writing is not supported yet and
  83799. * FLAC__metadata_chain_write() will fail.
  83800. *
  83801. * \param chain A pointer to an existing chain.
  83802. * \param filename The path to the Ogg FLAC file to read.
  83803. * \assert
  83804. * \code chain != NULL \endcode
  83805. * \code filename != NULL \endcode
  83806. * \retval FLAC__bool
  83807. * \c true if a valid list of metadata blocks was read from
  83808. * \a filename, else \c false. On failure, check the status with
  83809. * FLAC__metadata_chain_status().
  83810. */
  83811. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  83812. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  83813. *
  83814. * The \a handle need only be open for reading, but must be seekable.
  83815. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83816. * for Windows).
  83817. *
  83818. * \param chain A pointer to an existing chain.
  83819. * \param handle The I/O handle of the FLAC stream to read. The
  83820. * handle will NOT be closed after the metadata is read;
  83821. * that is the duty of the caller.
  83822. * \param callbacks
  83823. * A set of callbacks to use for I/O. The mandatory
  83824. * callbacks are \a read, \a seek, and \a tell.
  83825. * \assert
  83826. * \code chain != NULL \endcode
  83827. * \retval FLAC__bool
  83828. * \c true if a valid list of metadata blocks was read from
  83829. * \a handle, else \c false. On failure, check the status with
  83830. * FLAC__metadata_chain_status().
  83831. */
  83832. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83833. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  83834. *
  83835. * The \a handle need only be open for reading, but must be seekable.
  83836. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83837. * for Windows).
  83838. *
  83839. * \note Ogg FLAC metadata data writing is not supported yet and
  83840. * FLAC__metadata_chain_write() will fail.
  83841. *
  83842. * \param chain A pointer to an existing chain.
  83843. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  83844. * handle will NOT be closed after the metadata is read;
  83845. * that is the duty of the caller.
  83846. * \param callbacks
  83847. * A set of callbacks to use for I/O. The mandatory
  83848. * callbacks are \a read, \a seek, and \a tell.
  83849. * \assert
  83850. * \code chain != NULL \endcode
  83851. * \retval FLAC__bool
  83852. * \c true if a valid list of metadata blocks was read from
  83853. * \a handle, else \c false. On failure, check the status with
  83854. * FLAC__metadata_chain_status().
  83855. */
  83856. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83857. /** Checks if writing the given chain would require the use of a
  83858. * temporary file, or if it could be written in place.
  83859. *
  83860. * Under certain conditions, padding can be utilized so that writing
  83861. * edited metadata back to the FLAC file does not require rewriting the
  83862. * entire file. If rewriting is required, then a temporary workfile is
  83863. * required. When writing metadata using callbacks, you must check
  83864. * this function to know whether to call
  83865. * FLAC__metadata_chain_write_with_callbacks() or
  83866. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  83867. * writing with FLAC__metadata_chain_write(), the temporary file is
  83868. * handled internally.
  83869. *
  83870. * \param chain A pointer to an existing chain.
  83871. * \param use_padding
  83872. * Whether or not padding will be allowed to be used
  83873. * during the write. The value of \a use_padding given
  83874. * here must match the value later passed to
  83875. * FLAC__metadata_chain_write_with_callbacks() or
  83876. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  83877. * \assert
  83878. * \code chain != NULL \endcode
  83879. * \retval FLAC__bool
  83880. * \c true if writing the current chain would require a tempfile, or
  83881. * \c false if metadata can be written in place.
  83882. */
  83883. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  83884. /** Write all metadata out to the FLAC file. This function tries to be as
  83885. * efficient as possible; how the metadata is actually written is shown by
  83886. * the following:
  83887. *
  83888. * If the current chain is the same size as the existing metadata, the new
  83889. * data is written in place.
  83890. *
  83891. * If the current chain is longer than the existing metadata, and
  83892. * \a use_padding is \c true, and the last block is a PADDING block of
  83893. * sufficient length, the function will truncate the final padding block
  83894. * so that the overall size of the metadata is the same as the existing
  83895. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  83896. * the above conditions are met, the entire FLAC file must be rewritten.
  83897. * If you want to use padding this way it is a good idea to call
  83898. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  83899. * amount of padding to work with, unless you need to preserve ordering
  83900. * of the PADDING blocks for some reason.
  83901. *
  83902. * If the current chain is shorter than the existing metadata, and
  83903. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  83904. * is extended to make the overall size the same as the existing data. If
  83905. * \a use_padding is \c true and the last block is not a PADDING block, a new
  83906. * PADDING block is added to the end of the new data to make it the same
  83907. * size as the existing data (if possible, see the note to
  83908. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  83909. * and the new data is written in place. If none of the above apply or
  83910. * \a use_padding is \c false, the entire FLAC file is rewritten.
  83911. *
  83912. * If \a preserve_file_stats is \c true, the owner and modification time will
  83913. * be preserved even if the FLAC file is written.
  83914. *
  83915. * For this write function to be used, the chain must have been read with
  83916. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  83917. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  83918. *
  83919. * \param chain A pointer to an existing chain.
  83920. * \param use_padding See above.
  83921. * \param preserve_file_stats See above.
  83922. * \assert
  83923. * \code chain != NULL \endcode
  83924. * \retval FLAC__bool
  83925. * \c true if the write succeeded, else \c false. On failure,
  83926. * check the status with FLAC__metadata_chain_status().
  83927. */
  83928. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  83929. /** Write all metadata out to a FLAC stream via callbacks.
  83930. *
  83931. * (See FLAC__metadata_chain_write() for the details on how padding is
  83932. * used to write metadata in place if possible.)
  83933. *
  83934. * The \a handle must be open for updating and be seekable. The
  83935. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  83936. * for Windows).
  83937. *
  83938. * For this write function to be used, the chain must have been read with
  83939. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83940. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83941. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83942. * \c false.
  83943. *
  83944. * \param chain A pointer to an existing chain.
  83945. * \param use_padding See FLAC__metadata_chain_write()
  83946. * \param handle The I/O handle of the FLAC stream to write. The
  83947. * handle will NOT be closed after the metadata is
  83948. * written; that is the duty of the caller.
  83949. * \param callbacks A set of callbacks to use for I/O. The mandatory
  83950. * callbacks are \a write and \a seek.
  83951. * \assert
  83952. * \code chain != NULL \endcode
  83953. * \retval FLAC__bool
  83954. * \c true if the write succeeded, else \c false. On failure,
  83955. * check the status with FLAC__metadata_chain_status().
  83956. */
  83957. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83958. /** Write all metadata out to a FLAC stream via callbacks.
  83959. *
  83960. * (See FLAC__metadata_chain_write() for the details on how padding is
  83961. * used to write metadata in place if possible.)
  83962. *
  83963. * This version of the write-with-callbacks function must be used when
  83964. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  83965. * this function, you must supply an I/O handle corresponding to the
  83966. * FLAC file to edit, and a temporary handle to which the new FLAC
  83967. * file will be written. It is the caller's job to move this temporary
  83968. * FLAC file on top of the original FLAC file to complete the metadata
  83969. * edit.
  83970. *
  83971. * The \a handle must be open for reading and be seekable. The
  83972. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83973. * for Windows).
  83974. *
  83975. * The \a temp_handle must be open for writing. The
  83976. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  83977. * for Windows). It should be an empty stream, or at least positioned
  83978. * at the start-of-file (in which case it is the caller's duty to
  83979. * truncate it on return).
  83980. *
  83981. * For this write function to be used, the chain must have been read with
  83982. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83983. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83984. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83985. * \c true.
  83986. *
  83987. * \param chain A pointer to an existing chain.
  83988. * \param use_padding See FLAC__metadata_chain_write()
  83989. * \param handle The I/O handle of the original FLAC stream to read.
  83990. * The handle will NOT be closed after the metadata is
  83991. * written; that is the duty of the caller.
  83992. * \param callbacks A set of callbacks to use for I/O on \a handle.
  83993. * The mandatory callbacks are \a read, \a seek, and
  83994. * \a eof.
  83995. * \param temp_handle The I/O handle of the FLAC stream to write. The
  83996. * handle will NOT be closed after the metadata is
  83997. * written; that is the duty of the caller.
  83998. * \param temp_callbacks
  83999. * A set of callbacks to use for I/O on temp_handle.
  84000. * The only mandatory callback is \a write.
  84001. * \assert
  84002. * \code chain != NULL \endcode
  84003. * \retval FLAC__bool
  84004. * \c true if the write succeeded, else \c false. On failure,
  84005. * check the status with FLAC__metadata_chain_status().
  84006. */
  84007. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks);
  84008. /** Merge adjacent PADDING blocks into a single block.
  84009. *
  84010. * \note This function does not write to the FLAC file, it only
  84011. * modifies the chain.
  84012. *
  84013. * \warning Any iterator on the current chain will become invalid after this
  84014. * call. You should delete the iterator and get a new one.
  84015. *
  84016. * \param chain A pointer to an existing chain.
  84017. * \assert
  84018. * \code chain != NULL \endcode
  84019. */
  84020. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  84021. /** This function will move all PADDING blocks to the end on the metadata,
  84022. * then merge them into a single block.
  84023. *
  84024. * \note This function does not write to the FLAC file, it only
  84025. * modifies the chain.
  84026. *
  84027. * \warning Any iterator on the current chain will become invalid after this
  84028. * call. You should delete the iterator and get a new one.
  84029. *
  84030. * \param chain A pointer to an existing chain.
  84031. * \assert
  84032. * \code chain != NULL \endcode
  84033. */
  84034. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  84035. /*********** FLAC__Metadata_Iterator ***********/
  84036. /** Create a new iterator instance.
  84037. *
  84038. * \retval FLAC__Metadata_Iterator*
  84039. * \c NULL if there was an error allocating memory, else the new instance.
  84040. */
  84041. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  84042. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84043. *
  84044. * \param iterator A pointer to an existing iterator.
  84045. * \assert
  84046. * \code iterator != NULL \endcode
  84047. */
  84048. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  84049. /** Initialize the iterator to point to the first metadata block in the
  84050. * given chain.
  84051. *
  84052. * \param iterator A pointer to an existing iterator.
  84053. * \param chain A pointer to an existing and initialized (read) chain.
  84054. * \assert
  84055. * \code iterator != NULL \endcode
  84056. * \code chain != NULL \endcode
  84057. */
  84058. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  84059. /** Moves the iterator forward one metadata block, returning \c false if
  84060. * already at the end.
  84061. *
  84062. * \param iterator A pointer to an existing initialized iterator.
  84063. * \assert
  84064. * \code iterator != NULL \endcode
  84065. * \a iterator has been successfully initialized with
  84066. * FLAC__metadata_iterator_init()
  84067. * \retval FLAC__bool
  84068. * \c false if already at the last metadata block of the chain, else
  84069. * \c true.
  84070. */
  84071. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  84072. /** Moves the iterator backward one metadata block, returning \c false if
  84073. * already at the beginning.
  84074. *
  84075. * \param iterator A pointer to an existing initialized iterator.
  84076. * \assert
  84077. * \code iterator != NULL \endcode
  84078. * \a iterator has been successfully initialized with
  84079. * FLAC__metadata_iterator_init()
  84080. * \retval FLAC__bool
  84081. * \c false if already at the first metadata block of the chain, else
  84082. * \c true.
  84083. */
  84084. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  84085. /** Get the type of the metadata block at the current position.
  84086. *
  84087. * \param iterator A pointer to an existing initialized iterator.
  84088. * \assert
  84089. * \code iterator != NULL \endcode
  84090. * \a iterator has been successfully initialized with
  84091. * FLAC__metadata_iterator_init()
  84092. * \retval FLAC__MetadataType
  84093. * The type of the metadata block at the current iterator position.
  84094. */
  84095. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  84096. /** Get the metadata block at the current position. You can modify
  84097. * the block in place but must write the chain before the changes
  84098. * are reflected to the FLAC file. You do not need to call
  84099. * FLAC__metadata_iterator_set_block() to reflect the changes;
  84100. * the pointer returned by FLAC__metadata_iterator_get_block()
  84101. * points directly into the chain.
  84102. *
  84103. * \warning
  84104. * Do not call FLAC__metadata_object_delete() on the returned object;
  84105. * to delete a block use FLAC__metadata_iterator_delete_block().
  84106. *
  84107. * \param iterator A pointer to an existing initialized iterator.
  84108. * \assert
  84109. * \code iterator != NULL \endcode
  84110. * \a iterator has been successfully initialized with
  84111. * FLAC__metadata_iterator_init()
  84112. * \retval FLAC__StreamMetadata*
  84113. * The current metadata block.
  84114. */
  84115. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  84116. /** Set the metadata block at the current position, replacing the existing
  84117. * block. The new block passed in becomes owned by the chain and it will be
  84118. * deleted when the chain is deleted.
  84119. *
  84120. * \param iterator A pointer to an existing initialized iterator.
  84121. * \param block A pointer to a metadata block.
  84122. * \assert
  84123. * \code iterator != NULL \endcode
  84124. * \a iterator has been successfully initialized with
  84125. * FLAC__metadata_iterator_init()
  84126. * \code block != NULL \endcode
  84127. * \retval FLAC__bool
  84128. * \c false if the conditions in the above description are not met, or
  84129. * a memory allocation error occurs, otherwise \c true.
  84130. */
  84131. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84132. /** Removes the current block from the chain. If \a replace_with_padding is
  84133. * \c true, the block will instead be replaced with a padding block of equal
  84134. * size. You can not delete the STREAMINFO block. The iterator will be
  84135. * left pointing to the block before the one just "deleted", even if
  84136. * \a replace_with_padding is \c true.
  84137. *
  84138. * \param iterator A pointer to an existing initialized iterator.
  84139. * \param replace_with_padding See above.
  84140. * \assert
  84141. * \code iterator != NULL \endcode
  84142. * \a iterator has been successfully initialized with
  84143. * FLAC__metadata_iterator_init()
  84144. * \retval FLAC__bool
  84145. * \c false if the conditions in the above description are not met,
  84146. * otherwise \c true.
  84147. */
  84148. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  84149. /** Insert a new block before the current block. You cannot insert a block
  84150. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  84151. * as there can be only one, the one that already exists at the head when you
  84152. * read in a chain. The chain takes ownership of the new block and it will be
  84153. * deleted when the chain is deleted. The iterator will be left pointing to
  84154. * the new block.
  84155. *
  84156. * \param iterator A pointer to an existing initialized iterator.
  84157. * \param block A pointer to a metadata block to insert.
  84158. * \assert
  84159. * \code iterator != NULL \endcode
  84160. * \a iterator has been successfully initialized with
  84161. * FLAC__metadata_iterator_init()
  84162. * \retval FLAC__bool
  84163. * \c false if the conditions in the above description are not met, or
  84164. * a memory allocation error occurs, otherwise \c true.
  84165. */
  84166. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84167. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  84168. * block as there can be only one, the one that already exists at the head when
  84169. * you read in a chain. The chain takes ownership of the new block and it will
  84170. * be deleted when the chain is deleted. The iterator will be left pointing to
  84171. * the new block.
  84172. *
  84173. * \param iterator A pointer to an existing initialized iterator.
  84174. * \param block A pointer to a metadata block to insert.
  84175. * \assert
  84176. * \code iterator != NULL \endcode
  84177. * \a iterator has been successfully initialized with
  84178. * FLAC__metadata_iterator_init()
  84179. * \retval FLAC__bool
  84180. * \c false if the conditions in the above description are not met, or
  84181. * a memory allocation error occurs, otherwise \c true.
  84182. */
  84183. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84184. /* \} */
  84185. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  84186. * \ingroup flac_metadata
  84187. *
  84188. * \brief
  84189. * This module contains methods for manipulating FLAC metadata objects.
  84190. *
  84191. * Since many are variable length we have to be careful about the memory
  84192. * management. We decree that all pointers to data in the object are
  84193. * owned by the object and memory-managed by the object.
  84194. *
  84195. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  84196. * functions to create all instances. When using the
  84197. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  84198. * \a copy to \c true to have the function make it's own copy of the data, or
  84199. * to \c false to give the object ownership of your data. In the latter case
  84200. * your pointer must be freeable by free() and will be free()d when the object
  84201. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  84202. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  84203. * the length argument is 0 and the \a copy argument is \c false.
  84204. *
  84205. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  84206. * will return \c NULL in the case of a memory allocation error, otherwise a new
  84207. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  84208. * case of a memory allocation error.
  84209. *
  84210. * We don't have the convenience of C++ here, so note that the library relies
  84211. * on you to keep the types straight. In other words, if you pass, for
  84212. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  84213. * FLAC__metadata_object_application_set_data(), you will get an assertion
  84214. * failure.
  84215. *
  84216. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  84217. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  84218. * toward the length or stored in the stream, but it can make working with plain
  84219. * comments (those that don't contain embedded-NULs in the value) easier.
  84220. * Entries passed into these functions have trailing NULs added if missing, and
  84221. * returned entries are guaranteed to have a trailing NUL.
  84222. *
  84223. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  84224. * comment entry/name/value will first validate that it complies with the Vorbis
  84225. * comment specification and return false if it does not.
  84226. *
  84227. * There is no need to recalculate the length field on metadata blocks you
  84228. * have modified. They will be calculated automatically before they are
  84229. * written back to a file.
  84230. *
  84231. * \{
  84232. */
  84233. /** Create a new metadata object instance of the given type.
  84234. *
  84235. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  84236. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  84237. * the vendor string set (but zero comments).
  84238. *
  84239. * Do not pass in a value greater than or equal to
  84240. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  84241. * doing.
  84242. *
  84243. * \param type Type of object to create
  84244. * \retval FLAC__StreamMetadata*
  84245. * \c NULL if there was an error allocating memory or the type code is
  84246. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  84247. */
  84248. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  84249. /** Create a copy of an existing metadata object.
  84250. *
  84251. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84252. * object is also copied. The caller takes ownership of the new block and
  84253. * is responsible for freeing it with FLAC__metadata_object_delete().
  84254. *
  84255. * \param object Pointer to object to copy.
  84256. * \assert
  84257. * \code object != NULL \endcode
  84258. * \retval FLAC__StreamMetadata*
  84259. * \c NULL if there was an error allocating memory, else the new instance.
  84260. */
  84261. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  84262. /** Free a metadata object. Deletes the object pointed to by \a object.
  84263. *
  84264. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  84265. * object is also deleted.
  84266. *
  84267. * \param object A pointer to an existing object.
  84268. * \assert
  84269. * \code object != NULL \endcode
  84270. */
  84271. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  84272. /** Compares two metadata objects.
  84273. *
  84274. * The compare is "deep", i.e. dynamically allocated data within the
  84275. * object is also compared.
  84276. *
  84277. * \param block1 A pointer to an existing object.
  84278. * \param block2 A pointer to an existing object.
  84279. * \assert
  84280. * \code block1 != NULL \endcode
  84281. * \code block2 != NULL \endcode
  84282. * \retval FLAC__bool
  84283. * \c true if objects are identical, else \c false.
  84284. */
  84285. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  84286. /** Sets the application data of an APPLICATION block.
  84287. *
  84288. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84289. * takes ownership of the pointer. The existing data will be freed if this
  84290. * function is successful, otherwise the original data will remain if \a copy
  84291. * is \c true and malloc() fails.
  84292. *
  84293. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84294. *
  84295. * \param object A pointer to an existing APPLICATION object.
  84296. * \param data A pointer to the data to set.
  84297. * \param length The length of \a data in bytes.
  84298. * \param copy See above.
  84299. * \assert
  84300. * \code object != NULL \endcode
  84301. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  84302. * \code (data != NULL && length > 0) ||
  84303. * (data == NULL && length == 0 && copy == false) \endcode
  84304. * \retval FLAC__bool
  84305. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84306. */
  84307. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  84308. /** Resize the seekpoint array.
  84309. *
  84310. * If the size shrinks, elements will truncated; if it grows, new placeholder
  84311. * points will be added to the end.
  84312. *
  84313. * \param object A pointer to an existing SEEKTABLE object.
  84314. * \param new_num_points The desired length of the array; may be \c 0.
  84315. * \assert
  84316. * \code object != NULL \endcode
  84317. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84318. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  84319. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  84320. * \retval FLAC__bool
  84321. * \c false if memory allocation error, else \c true.
  84322. */
  84323. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  84324. /** Set a seekpoint in a seektable.
  84325. *
  84326. * \param object A pointer to an existing SEEKTABLE object.
  84327. * \param point_num Index into seekpoint array to set.
  84328. * \param point The point to set.
  84329. * \assert
  84330. * \code object != NULL \endcode
  84331. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84332. * \code object->data.seek_table.num_points > point_num \endcode
  84333. */
  84334. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84335. /** Insert a seekpoint into a seektable.
  84336. *
  84337. * \param object A pointer to an existing SEEKTABLE object.
  84338. * \param point_num Index into seekpoint array to set.
  84339. * \param point The point to set.
  84340. * \assert
  84341. * \code object != NULL \endcode
  84342. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84343. * \code object->data.seek_table.num_points >= point_num \endcode
  84344. * \retval FLAC__bool
  84345. * \c false if memory allocation error, else \c true.
  84346. */
  84347. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84348. /** Delete a seekpoint from a seektable.
  84349. *
  84350. * \param object A pointer to an existing SEEKTABLE object.
  84351. * \param point_num Index into seekpoint array to set.
  84352. * \assert
  84353. * \code object != NULL \endcode
  84354. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84355. * \code object->data.seek_table.num_points > point_num \endcode
  84356. * \retval FLAC__bool
  84357. * \c false if memory allocation error, else \c true.
  84358. */
  84359. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  84360. /** Check a seektable to see if it conforms to the FLAC specification.
  84361. * See the format specification for limits on the contents of the
  84362. * seektable.
  84363. *
  84364. * \param object A pointer to an existing SEEKTABLE object.
  84365. * \assert
  84366. * \code object != NULL \endcode
  84367. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84368. * \retval FLAC__bool
  84369. * \c false if seek table is illegal, else \c true.
  84370. */
  84371. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  84372. /** Append a number of placeholder points to the end of a seek table.
  84373. *
  84374. * \note
  84375. * As with the other ..._seektable_template_... functions, you should
  84376. * call FLAC__metadata_object_seektable_template_sort() when finished
  84377. * to make the seek table legal.
  84378. *
  84379. * \param object A pointer to an existing SEEKTABLE object.
  84380. * \param num The number of placeholder points to append.
  84381. * \assert
  84382. * \code object != NULL \endcode
  84383. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84384. * \retval FLAC__bool
  84385. * \c false if memory allocation fails, else \c true.
  84386. */
  84387. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  84388. /** Append a specific seek point template to the end of a seek table.
  84389. *
  84390. * \note
  84391. * As with the other ..._seektable_template_... functions, you should
  84392. * call FLAC__metadata_object_seektable_template_sort() when finished
  84393. * to make the seek table legal.
  84394. *
  84395. * \param object A pointer to an existing SEEKTABLE object.
  84396. * \param sample_number The sample number of the seek point template.
  84397. * \assert
  84398. * \code object != NULL \endcode
  84399. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84400. * \retval FLAC__bool
  84401. * \c false if memory allocation fails, else \c true.
  84402. */
  84403. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  84404. /** Append specific seek point templates to the end of a seek table.
  84405. *
  84406. * \note
  84407. * As with the other ..._seektable_template_... functions, you should
  84408. * call FLAC__metadata_object_seektable_template_sort() when finished
  84409. * to make the seek table legal.
  84410. *
  84411. * \param object A pointer to an existing SEEKTABLE object.
  84412. * \param sample_numbers An array of sample numbers for the seek points.
  84413. * \param num The number of seek point templates to append.
  84414. * \assert
  84415. * \code object != NULL \endcode
  84416. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84417. * \retval FLAC__bool
  84418. * \c false if memory allocation fails, else \c true.
  84419. */
  84420. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  84421. /** Append a set of evenly-spaced seek point templates to the end of a
  84422. * seek table.
  84423. *
  84424. * \note
  84425. * As with the other ..._seektable_template_... functions, you should
  84426. * call FLAC__metadata_object_seektable_template_sort() when finished
  84427. * to make the seek table legal.
  84428. *
  84429. * \param object A pointer to an existing SEEKTABLE object.
  84430. * \param num The number of placeholder points to append.
  84431. * \param total_samples The total number of samples to be encoded;
  84432. * the seekpoints will be spaced approximately
  84433. * \a total_samples / \a num samples apart.
  84434. * \assert
  84435. * \code object != NULL \endcode
  84436. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84437. * \code total_samples > 0 \endcode
  84438. * \retval FLAC__bool
  84439. * \c false if memory allocation fails, else \c true.
  84440. */
  84441. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  84442. /** Append a set of evenly-spaced seek point templates to the end of a
  84443. * seek table.
  84444. *
  84445. * \note
  84446. * As with the other ..._seektable_template_... functions, you should
  84447. * call FLAC__metadata_object_seektable_template_sort() when finished
  84448. * to make the seek table legal.
  84449. *
  84450. * \param object A pointer to an existing SEEKTABLE object.
  84451. * \param samples The number of samples apart to space the placeholder
  84452. * points. The first point will be at sample \c 0, the
  84453. * second at sample \a samples, then 2*\a samples, and
  84454. * so on. As long as \a samples and \a total_samples
  84455. * are greater than \c 0, there will always be at least
  84456. * one seekpoint at sample \c 0.
  84457. * \param total_samples The total number of samples to be encoded;
  84458. * the seekpoints will be spaced
  84459. * \a samples samples apart.
  84460. * \assert
  84461. * \code object != NULL \endcode
  84462. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84463. * \code samples > 0 \endcode
  84464. * \code total_samples > 0 \endcode
  84465. * \retval FLAC__bool
  84466. * \c false if memory allocation fails, else \c true.
  84467. */
  84468. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  84469. /** Sort a seek table's seek points according to the format specification,
  84470. * removing duplicates.
  84471. *
  84472. * \param object A pointer to a seek table to be sorted.
  84473. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  84474. * If \c true, duplicates are deleted and the seek table is
  84475. * shrunk appropriately; the number of placeholder points
  84476. * present in the seek table will be the same after the call
  84477. * as before.
  84478. * \assert
  84479. * \code object != NULL \endcode
  84480. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84481. * \retval FLAC__bool
  84482. * \c false if realloc() fails, else \c true.
  84483. */
  84484. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  84485. /** Sets the vendor string in a VORBIS_COMMENT block.
  84486. *
  84487. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84488. * one already.
  84489. *
  84490. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84491. * takes ownership of the \c entry.entry pointer.
  84492. *
  84493. * \note If this function returns \c false, the caller still owns the
  84494. * pointer.
  84495. *
  84496. * \param object A pointer to an existing VORBIS_COMMENT object.
  84497. * \param entry The entry to set the vendor string to.
  84498. * \param copy See above.
  84499. * \assert
  84500. * \code object != NULL \endcode
  84501. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84502. * \code (entry.entry != NULL && entry.length > 0) ||
  84503. * (entry.entry == NULL && entry.length == 0) \endcode
  84504. * \retval FLAC__bool
  84505. * \c false if memory allocation fails or \a entry does not comply with the
  84506. * Vorbis comment specification, else \c true.
  84507. */
  84508. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84509. /** Resize the comment array.
  84510. *
  84511. * If the size shrinks, elements will truncated; if it grows, new empty
  84512. * fields will be added to the end.
  84513. *
  84514. * \param object A pointer to an existing VORBIS_COMMENT object.
  84515. * \param new_num_comments The desired length of the array; may be \c 0.
  84516. * \assert
  84517. * \code object != NULL \endcode
  84518. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84519. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  84520. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  84521. * \retval FLAC__bool
  84522. * \c false if memory allocation fails, else \c true.
  84523. */
  84524. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  84525. /** Sets a comment in a VORBIS_COMMENT block.
  84526. *
  84527. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84528. * one already.
  84529. *
  84530. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84531. * takes ownership of the \c entry.entry pointer.
  84532. *
  84533. * \note If this function returns \c false, the caller still owns the
  84534. * pointer.
  84535. *
  84536. * \param object A pointer to an existing VORBIS_COMMENT object.
  84537. * \param comment_num Index into comment array to set.
  84538. * \param entry The entry to set the comment to.
  84539. * \param copy See above.
  84540. * \assert
  84541. * \code object != NULL \endcode
  84542. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84543. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  84544. * \code (entry.entry != NULL && entry.length > 0) ||
  84545. * (entry.entry == NULL && entry.length == 0) \endcode
  84546. * \retval FLAC__bool
  84547. * \c false if memory allocation fails or \a entry does not comply with the
  84548. * Vorbis comment specification, else \c true.
  84549. */
  84550. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84551. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  84552. *
  84553. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84554. * one already.
  84555. *
  84556. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84557. * takes ownership of the \c entry.entry pointer.
  84558. *
  84559. * \note If this function returns \c false, the caller still owns the
  84560. * pointer.
  84561. *
  84562. * \param object A pointer to an existing VORBIS_COMMENT object.
  84563. * \param comment_num The index at which to insert the comment. The comments
  84564. * at and after \a comment_num move right one position.
  84565. * To append a comment to the end, set \a comment_num to
  84566. * \c object->data.vorbis_comment.num_comments .
  84567. * \param entry The comment to insert.
  84568. * \param copy See above.
  84569. * \assert
  84570. * \code object != NULL \endcode
  84571. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84572. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  84573. * \code (entry.entry != NULL && entry.length > 0) ||
  84574. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84575. * \retval FLAC__bool
  84576. * \c false if memory allocation fails or \a entry does not comply with the
  84577. * Vorbis comment specification, else \c true.
  84578. */
  84579. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84580. /** Appends a comment to a VORBIS_COMMENT block.
  84581. *
  84582. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84583. * one already.
  84584. *
  84585. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84586. * takes ownership of the \c entry.entry pointer.
  84587. *
  84588. * \note If this function returns \c false, the caller still owns the
  84589. * pointer.
  84590. *
  84591. * \param object A pointer to an existing VORBIS_COMMENT object.
  84592. * \param entry The comment to insert.
  84593. * \param copy See above.
  84594. * \assert
  84595. * \code object != NULL \endcode
  84596. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84597. * \code (entry.entry != NULL && entry.length > 0) ||
  84598. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84599. * \retval FLAC__bool
  84600. * \c false if memory allocation fails or \a entry does not comply with the
  84601. * Vorbis comment specification, else \c true.
  84602. */
  84603. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84604. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  84605. *
  84606. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84607. * one already.
  84608. *
  84609. * Depending on the the value of \a all, either all or just the first comment
  84610. * whose field name(s) match the given entry's name will be replaced by the
  84611. * given entry. If no comments match, \a entry will simply be appended.
  84612. *
  84613. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84614. * takes ownership of the \c entry.entry pointer.
  84615. *
  84616. * \note If this function returns \c false, the caller still owns the
  84617. * pointer.
  84618. *
  84619. * \param object A pointer to an existing VORBIS_COMMENT object.
  84620. * \param entry The comment to insert.
  84621. * \param all If \c true, all comments whose field name matches
  84622. * \a entry's field name will be removed, and \a entry will
  84623. * be inserted at the position of the first matching
  84624. * comment. If \c false, only the first comment whose
  84625. * field name matches \a entry's field name will be
  84626. * replaced with \a entry.
  84627. * \param copy See above.
  84628. * \assert
  84629. * \code object != NULL \endcode
  84630. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84631. * \code (entry.entry != NULL && entry.length > 0) ||
  84632. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84633. * \retval FLAC__bool
  84634. * \c false if memory allocation fails or \a entry does not comply with the
  84635. * Vorbis comment specification, else \c true.
  84636. */
  84637. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  84638. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  84639. *
  84640. * \param object A pointer to an existing VORBIS_COMMENT object.
  84641. * \param comment_num The index of the comment to delete.
  84642. * \assert
  84643. * \code object != NULL \endcode
  84644. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84645. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  84646. * \retval FLAC__bool
  84647. * \c false if realloc() fails, else \c true.
  84648. */
  84649. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  84650. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  84651. *
  84652. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  84653. * memory and shall be owned by the caller. For convenience the entry will
  84654. * have a terminating NUL.
  84655. *
  84656. * \param entry A pointer to a Vorbis comment entry. The entry's
  84657. * \c entry pointer should not point to allocated
  84658. * memory as it will be overwritten.
  84659. * \param field_name The field name in ASCII, \c NUL terminated.
  84660. * \param field_value The field value in UTF-8, \c NUL terminated.
  84661. * \assert
  84662. * \code entry != NULL \endcode
  84663. * \code field_name != NULL \endcode
  84664. * \code field_value != NULL \endcode
  84665. * \retval FLAC__bool
  84666. * \c false if malloc() fails, or if \a field_name or \a field_value does
  84667. * not comply with the Vorbis comment specification, else \c true.
  84668. */
  84669. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value);
  84670. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  84671. *
  84672. * The returned pointers to name and value will be allocated by malloc()
  84673. * and shall be owned by the caller.
  84674. *
  84675. * \param entry An existing Vorbis comment entry.
  84676. * \param field_name The address of where the returned pointer to the
  84677. * field name will be stored.
  84678. * \param field_value The address of where the returned pointer to the
  84679. * field value will be stored.
  84680. * \assert
  84681. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84682. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  84683. * \code field_name != NULL \endcode
  84684. * \code field_value != NULL \endcode
  84685. * \retval FLAC__bool
  84686. * \c false if memory allocation fails or \a entry does not comply with the
  84687. * Vorbis comment specification, else \c true.
  84688. */
  84689. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
  84690. /** Check if the given Vorbis comment entry's field name matches the given
  84691. * field name.
  84692. *
  84693. * \param entry An existing Vorbis comment entry.
  84694. * \param field_name The field name to check.
  84695. * \param field_name_length The length of \a field_name, not including the
  84696. * terminating \c NUL.
  84697. * \assert
  84698. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84699. * \retval FLAC__bool
  84700. * \c true if the field names match, else \c false
  84701. */
  84702. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  84703. /** Find a Vorbis comment with the given field name.
  84704. *
  84705. * The search begins at entry number \a offset; use an offset of 0 to
  84706. * search from the beginning of the comment array.
  84707. *
  84708. * \param object A pointer to an existing VORBIS_COMMENT object.
  84709. * \param offset The offset into the comment array from where to start
  84710. * the search.
  84711. * \param field_name The field name of the comment to find.
  84712. * \assert
  84713. * \code object != NULL \endcode
  84714. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84715. * \code field_name != NULL \endcode
  84716. * \retval int
  84717. * The offset in the comment array of the first comment whose field
  84718. * name matches \a field_name, or \c -1 if no match was found.
  84719. */
  84720. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  84721. /** Remove first Vorbis comment matching the given field name.
  84722. *
  84723. * \param object A pointer to an existing VORBIS_COMMENT object.
  84724. * \param field_name The field name of comment to delete.
  84725. * \assert
  84726. * \code object != NULL \endcode
  84727. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84728. * \retval int
  84729. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84730. * \c 1 for one matching entry deleted.
  84731. */
  84732. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  84733. /** Remove all Vorbis comments matching the given field name.
  84734. *
  84735. * \param object A pointer to an existing VORBIS_COMMENT object.
  84736. * \param field_name The field name of comments to delete.
  84737. * \assert
  84738. * \code object != NULL \endcode
  84739. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84740. * \retval int
  84741. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84742. * else the number of matching entries deleted.
  84743. */
  84744. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  84745. /** Create a new CUESHEET track instance.
  84746. *
  84747. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  84748. *
  84749. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84750. * \c NULL if there was an error allocating memory, else the new instance.
  84751. */
  84752. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  84753. /** Create a copy of an existing CUESHEET track object.
  84754. *
  84755. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84756. * object is also copied. The caller takes ownership of the new object and
  84757. * is responsible for freeing it with
  84758. * FLAC__metadata_object_cuesheet_track_delete().
  84759. *
  84760. * \param object Pointer to object to copy.
  84761. * \assert
  84762. * \code object != NULL \endcode
  84763. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84764. * \c NULL if there was an error allocating memory, else the new instance.
  84765. */
  84766. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  84767. /** Delete a CUESHEET track object
  84768. *
  84769. * \param object A pointer to an existing CUESHEET track object.
  84770. * \assert
  84771. * \code object != NULL \endcode
  84772. */
  84773. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  84774. /** Resize a track's index point array.
  84775. *
  84776. * If the size shrinks, elements will truncated; if it grows, new blank
  84777. * indices will be added to the end.
  84778. *
  84779. * \param object A pointer to an existing CUESHEET object.
  84780. * \param track_num The index of the track to modify. NOTE: this is not
  84781. * necessarily the same as the track's \a number field.
  84782. * \param new_num_indices The desired length of the array; may be \c 0.
  84783. * \assert
  84784. * \code object != NULL \endcode
  84785. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84786. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84787. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  84788. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  84789. * \retval FLAC__bool
  84790. * \c false if memory allocation error, else \c true.
  84791. */
  84792. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  84793. /** Insert an index point in a CUESHEET track at the given index.
  84794. *
  84795. * \param object A pointer to an existing CUESHEET object.
  84796. * \param track_num The index of the track to modify. NOTE: this is not
  84797. * necessarily the same as the track's \a number field.
  84798. * \param index_num The index into the track's index array at which to
  84799. * insert the index point. NOTE: this is not necessarily
  84800. * the same as the index point's \a number field. The
  84801. * indices at and after \a index_num move right one
  84802. * position. To append an index point to the end, set
  84803. * \a index_num to
  84804. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84805. * \param index The index point to insert.
  84806. * \assert
  84807. * \code object != NULL \endcode
  84808. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84809. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84810. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84811. * \retval FLAC__bool
  84812. * \c false if realloc() fails, else \c true.
  84813. */
  84814. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
  84815. /** Insert a blank index point in a CUESHEET track at the given index.
  84816. *
  84817. * A blank index point is one in which all field values are zero.
  84818. *
  84819. * \param object A pointer to an existing CUESHEET object.
  84820. * \param track_num The index of the track to modify. NOTE: this is not
  84821. * necessarily the same as the track's \a number field.
  84822. * \param index_num The index into the track's index array at which to
  84823. * insert the index point. NOTE: this is not necessarily
  84824. * the same as the index point's \a number field. The
  84825. * indices at and after \a index_num move right one
  84826. * position. To append an index point to the end, set
  84827. * \a index_num to
  84828. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84829. * \assert
  84830. * \code object != NULL \endcode
  84831. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84832. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84833. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84834. * \retval FLAC__bool
  84835. * \c false if realloc() fails, else \c true.
  84836. */
  84837. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84838. /** Delete an index point in a CUESHEET track at the given index.
  84839. *
  84840. * \param object A pointer to an existing CUESHEET object.
  84841. * \param track_num The index into the track array of the track to
  84842. * modify. NOTE: this is not necessarily the same
  84843. * as the track's \a number field.
  84844. * \param index_num The index into the track's index array of the index
  84845. * to delete. NOTE: this is not necessarily the same
  84846. * as the index's \a number field.
  84847. * \assert
  84848. * \code object != NULL \endcode
  84849. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84850. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84851. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  84852. * \retval FLAC__bool
  84853. * \c false if realloc() fails, else \c true.
  84854. */
  84855. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84856. /** Resize the track array.
  84857. *
  84858. * If the size shrinks, elements will truncated; if it grows, new blank
  84859. * tracks will be added to the end.
  84860. *
  84861. * \param object A pointer to an existing CUESHEET object.
  84862. * \param new_num_tracks The desired length of the array; may be \c 0.
  84863. * \assert
  84864. * \code object != NULL \endcode
  84865. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84866. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  84867. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  84868. * \retval FLAC__bool
  84869. * \c false if memory allocation error, else \c true.
  84870. */
  84871. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  84872. /** Sets a track in a CUESHEET block.
  84873. *
  84874. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84875. * takes ownership of the \a track pointer.
  84876. *
  84877. * \param object A pointer to an existing CUESHEET object.
  84878. * \param track_num Index into track array to set. NOTE: this is not
  84879. * necessarily the same as the track's \a number field.
  84880. * \param track The track to set the track to. You may safely pass in
  84881. * a const pointer if \a copy is \c true.
  84882. * \param copy See above.
  84883. * \assert
  84884. * \code object != NULL \endcode
  84885. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84886. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  84887. * \code (track->indices != NULL && track->num_indices > 0) ||
  84888. * (track->indices == NULL && track->num_indices == 0)
  84889. * \retval FLAC__bool
  84890. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84891. */
  84892. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84893. /** Insert a track in a CUESHEET block at the given index.
  84894. *
  84895. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84896. * takes ownership of the \a track pointer.
  84897. *
  84898. * \param object A pointer to an existing CUESHEET object.
  84899. * \param track_num The index at which to insert the track. NOTE: this
  84900. * is not necessarily the same as the track's \a number
  84901. * field. The tracks at and after \a track_num move right
  84902. * one position. To append a track to the end, set
  84903. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84904. * \param track The track to insert. You may safely pass in a const
  84905. * pointer if \a copy is \c true.
  84906. * \param copy See above.
  84907. * \assert
  84908. * \code object != NULL \endcode
  84909. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84910. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84911. * \retval FLAC__bool
  84912. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84913. */
  84914. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84915. /** Insert a blank track in a CUESHEET block at the given index.
  84916. *
  84917. * A blank track is one in which all field values are zero.
  84918. *
  84919. * \param object A pointer to an existing CUESHEET object.
  84920. * \param track_num The index at which to insert the track. NOTE: this
  84921. * is not necessarily the same as the track's \a number
  84922. * field. The tracks at and after \a track_num move right
  84923. * one position. To append a track to the end, set
  84924. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84925. * \assert
  84926. * \code object != NULL \endcode
  84927. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84928. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84929. * \retval FLAC__bool
  84930. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84931. */
  84932. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  84933. /** Delete a track in a CUESHEET block at the given index.
  84934. *
  84935. * \param object A pointer to an existing CUESHEET object.
  84936. * \param track_num The index into the track array of the track to
  84937. * delete. NOTE: this is not necessarily the same
  84938. * as the track's \a number field.
  84939. * \assert
  84940. * \code object != NULL \endcode
  84941. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84942. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84943. * \retval FLAC__bool
  84944. * \c false if realloc() fails, else \c true.
  84945. */
  84946. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  84947. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84948. * See the format specification for limits on the contents of the
  84949. * cue sheet.
  84950. *
  84951. * \param object A pointer to an existing CUESHEET object.
  84952. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84953. * stringent requirements for a CD-DA (audio) disc.
  84954. * \param violation Address of a pointer to a string. If there is a
  84955. * violation, a pointer to a string explanation of the
  84956. * violation will be returned here. \a violation may be
  84957. * \c NULL if you don't need the returned string. Do not
  84958. * free the returned string; it will always point to static
  84959. * data.
  84960. * \assert
  84961. * \code object != NULL \endcode
  84962. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84963. * \retval FLAC__bool
  84964. * \c false if cue sheet is illegal, else \c true.
  84965. */
  84966. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  84967. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  84968. * assumes the cue sheet corresponds to a CD; the result is undefined
  84969. * if the cuesheet's is_cd bit is not set.
  84970. *
  84971. * \param object A pointer to an existing CUESHEET object.
  84972. * \assert
  84973. * \code object != NULL \endcode
  84974. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84975. * \retval FLAC__uint32
  84976. * The unsigned integer representation of the CDDB/freedb ID
  84977. */
  84978. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  84979. /** Sets the MIME type of a PICTURE block.
  84980. *
  84981. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84982. * takes ownership of the pointer. The existing string will be freed if this
  84983. * function is successful, otherwise the original string will remain if \a copy
  84984. * is \c true and malloc() fails.
  84985. *
  84986. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  84987. *
  84988. * \param object A pointer to an existing PICTURE object.
  84989. * \param mime_type A pointer to the MIME type string. The string must be
  84990. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  84991. * is done.
  84992. * \param copy See above.
  84993. * \assert
  84994. * \code object != NULL \endcode
  84995. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84996. * \code (mime_type != NULL) \endcode
  84997. * \retval FLAC__bool
  84998. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84999. */
  85000. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  85001. /** Sets the description of a PICTURE block.
  85002. *
  85003. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85004. * takes ownership of the pointer. The existing string will be freed if this
  85005. * function is successful, otherwise the original string will remain if \a copy
  85006. * is \c true and malloc() fails.
  85007. *
  85008. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  85009. *
  85010. * \param object A pointer to an existing PICTURE object.
  85011. * \param description A pointer to the description string. The string must be
  85012. * valid UTF-8, NUL-terminated. No validation is done.
  85013. * \param copy See above.
  85014. * \assert
  85015. * \code object != NULL \endcode
  85016. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85017. * \code (description != NULL) \endcode
  85018. * \retval FLAC__bool
  85019. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85020. */
  85021. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  85022. /** Sets the picture data of a PICTURE block.
  85023. *
  85024. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85025. * takes ownership of the pointer. Also sets the \a data_length field of the
  85026. * metadata object to what is passed in as the \a length parameter. The
  85027. * existing data will be freed if this function is successful, otherwise the
  85028. * original data and data_length will remain if \a copy is \c true and
  85029. * malloc() fails.
  85030. *
  85031. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85032. *
  85033. * \param object A pointer to an existing PICTURE object.
  85034. * \param data A pointer to the data to set.
  85035. * \param length The length of \a data in bytes.
  85036. * \param copy See above.
  85037. * \assert
  85038. * \code object != NULL \endcode
  85039. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85040. * \code (data != NULL && length > 0) ||
  85041. * (data == NULL && length == 0 && copy == false) \endcode
  85042. * \retval FLAC__bool
  85043. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85044. */
  85045. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  85046. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  85047. * See the format specification for limits on the contents of the
  85048. * PICTURE block.
  85049. *
  85050. * \param object A pointer to existing PICTURE block to be checked.
  85051. * \param violation Address of a pointer to a string. If there is a
  85052. * violation, a pointer to a string explanation of the
  85053. * violation will be returned here. \a violation may be
  85054. * \c NULL if you don't need the returned string. Do not
  85055. * free the returned string; it will always point to static
  85056. * data.
  85057. * \assert
  85058. * \code object != NULL \endcode
  85059. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85060. * \retval FLAC__bool
  85061. * \c false if PICTURE block is illegal, else \c true.
  85062. */
  85063. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  85064. /* \} */
  85065. #ifdef __cplusplus
  85066. }
  85067. #endif
  85068. #endif
  85069. /********* End of inlined file: metadata.h *********/
  85070. /********* Start of inlined file: stream_decoder.h *********/
  85071. #ifndef FLAC__STREAM_DECODER_H
  85072. #define FLAC__STREAM_DECODER_H
  85073. #include <stdio.h> /* for FILE */
  85074. #ifdef __cplusplus
  85075. extern "C" {
  85076. #endif
  85077. /** \file include/FLAC/stream_decoder.h
  85078. *
  85079. * \brief
  85080. * This module contains the functions which implement the stream
  85081. * decoder.
  85082. *
  85083. * See the detailed documentation in the
  85084. * \link flac_stream_decoder stream decoder \endlink module.
  85085. */
  85086. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  85087. * \ingroup flac
  85088. *
  85089. * \brief
  85090. * This module describes the decoder layers provided by libFLAC.
  85091. *
  85092. * The stream decoder can be used to decode complete streams either from
  85093. * the client via callbacks, or directly from a file, depending on how
  85094. * it is initialized. When decoding via callbacks, the client provides
  85095. * callbacks for reading FLAC data and writing decoded samples, and
  85096. * handling metadata and errors. If the client also supplies seek-related
  85097. * callback, the decoder function for sample-accurate seeking within the
  85098. * FLAC input is also available. When decoding from a file, the client
  85099. * needs only supply a filename or open \c FILE* and write/metadata/error
  85100. * callbacks; the rest of the callbacks are supplied internally. For more
  85101. * info see the \link flac_stream_decoder stream decoder \endlink module.
  85102. */
  85103. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  85104. * \ingroup flac_decoder
  85105. *
  85106. * \brief
  85107. * This module contains the functions which implement the stream
  85108. * decoder.
  85109. *
  85110. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  85111. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85112. *
  85113. * The basic usage of this decoder is as follows:
  85114. * - The program creates an instance of a decoder using
  85115. * FLAC__stream_decoder_new().
  85116. * - The program overrides the default settings using
  85117. * FLAC__stream_decoder_set_*() functions.
  85118. * - The program initializes the instance to validate the settings and
  85119. * prepare for decoding using
  85120. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  85121. * or FLAC__stream_decoder_init_file() for native FLAC,
  85122. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  85123. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  85124. * - The program calls the FLAC__stream_decoder_process_*() functions
  85125. * to decode data, which subsequently calls the callbacks.
  85126. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  85127. * which flushes the input and output and resets the decoder to the
  85128. * uninitialized state.
  85129. * - The instance may be used again or deleted with
  85130. * FLAC__stream_decoder_delete().
  85131. *
  85132. * In more detail, the program will create a new instance by calling
  85133. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  85134. * functions to override the default decoder options, and call
  85135. * one of the FLAC__stream_decoder_init_*() functions.
  85136. *
  85137. * There are three initialization functions for native FLAC, one for
  85138. * setting up the decoder to decode FLAC data from the client via
  85139. * callbacks, and two for decoding directly from a FLAC file.
  85140. *
  85141. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  85142. * You must also supply several callbacks for handling I/O. Some (like
  85143. * seeking) are optional, depending on the capabilities of the input.
  85144. *
  85145. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  85146. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  85147. * \c FILE* or filename and fewer callbacks; the decoder will handle
  85148. * the other callbacks internally.
  85149. *
  85150. * There are three similarly-named init functions for decoding from Ogg
  85151. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85152. * library has been built with Ogg support.
  85153. *
  85154. * Once the decoder is initialized, your program will call one of several
  85155. * functions to start the decoding process:
  85156. *
  85157. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  85158. * most one metadata block or audio frame and return, calling either the
  85159. * metadata callback or write callback, respectively, once. If the decoder
  85160. * loses sync it will return with only the error callback being called.
  85161. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  85162. * to process the stream from the current location and stop upon reaching
  85163. * the first audio frame. The client will get one metadata, write, or error
  85164. * callback per metadata block, audio frame, or sync error, respectively.
  85165. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  85166. * to process the stream from the current location until the read callback
  85167. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  85168. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  85169. * write, or error callback per metadata block, audio frame, or sync error,
  85170. * respectively.
  85171. *
  85172. * When the decoder has finished decoding (normally or through an abort),
  85173. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  85174. * ensures the decoder is in the correct state and frees memory. Then the
  85175. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  85176. * again to decode another stream.
  85177. *
  85178. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  85179. * At any point after the stream decoder has been initialized, the client can
  85180. * call this function to seek to an exact sample within the stream.
  85181. * Subsequently, the first time the write callback is called it will be
  85182. * passed a (possibly partial) block starting at that sample.
  85183. *
  85184. * If the client cannot seek via the callback interface provided, but still
  85185. * has another way of seeking, it can flush the decoder using
  85186. * FLAC__stream_decoder_flush() and start feeding data from the new position
  85187. * through the read callback.
  85188. *
  85189. * The stream decoder also provides MD5 signature checking. If this is
  85190. * turned on before initialization, FLAC__stream_decoder_finish() will
  85191. * report when the decoded MD5 signature does not match the one stored
  85192. * in the STREAMINFO block. MD5 checking is automatically turned off
  85193. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  85194. * in the STREAMINFO block or when a seek is attempted.
  85195. *
  85196. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  85197. * attention. By default, the decoder only calls the metadata_callback for
  85198. * the STREAMINFO block. These functions allow you to tell the decoder
  85199. * explicitly which blocks to parse and return via the metadata_callback
  85200. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  85201. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  85202. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  85203. * which blocks to return. Remember that metadata blocks can potentially
  85204. * be big (for example, cover art) so filtering out the ones you don't
  85205. * use can reduce the memory requirements of the decoder. Also note the
  85206. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  85207. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  85208. * filtering APPLICATION blocks based on the application ID.
  85209. *
  85210. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  85211. * they still can legally be filtered from the metadata_callback.
  85212. *
  85213. * \note
  85214. * The "set" functions may only be called when the decoder is in the
  85215. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  85216. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  85217. * before FLAC__stream_decoder_init_*(). If this is the case they will
  85218. * return \c true, otherwise \c false.
  85219. *
  85220. * \note
  85221. * FLAC__stream_decoder_finish() resets all settings to the constructor
  85222. * defaults, including the callbacks.
  85223. *
  85224. * \{
  85225. */
  85226. /** State values for a FLAC__StreamDecoder
  85227. *
  85228. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  85229. */
  85230. typedef enum {
  85231. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  85232. /**< The decoder is ready to search for metadata. */
  85233. FLAC__STREAM_DECODER_READ_METADATA,
  85234. /**< The decoder is ready to or is in the process of reading metadata. */
  85235. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  85236. /**< The decoder is ready to or is in the process of searching for the
  85237. * frame sync code.
  85238. */
  85239. FLAC__STREAM_DECODER_READ_FRAME,
  85240. /**< The decoder is ready to or is in the process of reading a frame. */
  85241. FLAC__STREAM_DECODER_END_OF_STREAM,
  85242. /**< The decoder has reached the end of the stream. */
  85243. FLAC__STREAM_DECODER_OGG_ERROR,
  85244. /**< An error occurred in the underlying Ogg layer. */
  85245. FLAC__STREAM_DECODER_SEEK_ERROR,
  85246. /**< An error occurred while seeking. The decoder must be flushed
  85247. * with FLAC__stream_decoder_flush() or reset with
  85248. * FLAC__stream_decoder_reset() before decoding can continue.
  85249. */
  85250. FLAC__STREAM_DECODER_ABORTED,
  85251. /**< The decoder was aborted by the read callback. */
  85252. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  85253. /**< An error occurred allocating memory. The decoder is in an invalid
  85254. * state and can no longer be used.
  85255. */
  85256. FLAC__STREAM_DECODER_UNINITIALIZED
  85257. /**< The decoder is in the uninitialized state; one of the
  85258. * FLAC__stream_decoder_init_*() functions must be called before samples
  85259. * can be processed.
  85260. */
  85261. } FLAC__StreamDecoderState;
  85262. /** Maps a FLAC__StreamDecoderState to a C string.
  85263. *
  85264. * Using a FLAC__StreamDecoderState as the index to this array
  85265. * will give the string equivalent. The contents should not be modified.
  85266. */
  85267. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  85268. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  85269. */
  85270. typedef enum {
  85271. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  85272. /**< Initialization was successful. */
  85273. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85274. /**< The library was not compiled with support for the given container
  85275. * format.
  85276. */
  85277. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  85278. /**< A required callback was not supplied. */
  85279. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  85280. /**< An error occurred allocating memory. */
  85281. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  85282. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  85283. * FLAC__stream_decoder_init_ogg_file(). */
  85284. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  85285. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  85286. * already initialized, usually because
  85287. * FLAC__stream_decoder_finish() was not called.
  85288. */
  85289. } FLAC__StreamDecoderInitStatus;
  85290. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  85291. *
  85292. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  85293. * will give the string equivalent. The contents should not be modified.
  85294. */
  85295. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  85296. /** Return values for the FLAC__StreamDecoder read callback.
  85297. */
  85298. typedef enum {
  85299. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  85300. /**< The read was OK and decoding can continue. */
  85301. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  85302. /**< The read was attempted while at the end of the stream. Note that
  85303. * the client must only return this value when the read callback was
  85304. * called when already at the end of the stream. Otherwise, if the read
  85305. * itself moves to the end of the stream, the client should still return
  85306. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  85307. * the next read callback it should return
  85308. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  85309. * of \c 0.
  85310. */
  85311. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  85312. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85313. } FLAC__StreamDecoderReadStatus;
  85314. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  85315. *
  85316. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  85317. * will give the string equivalent. The contents should not be modified.
  85318. */
  85319. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  85320. /** Return values for the FLAC__StreamDecoder seek callback.
  85321. */
  85322. typedef enum {
  85323. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  85324. /**< The seek was OK and decoding can continue. */
  85325. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  85326. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85327. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85328. /**< Client does not support seeking. */
  85329. } FLAC__StreamDecoderSeekStatus;
  85330. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  85331. *
  85332. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  85333. * will give the string equivalent. The contents should not be modified.
  85334. */
  85335. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  85336. /** Return values for the FLAC__StreamDecoder tell callback.
  85337. */
  85338. typedef enum {
  85339. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  85340. /**< The tell was OK and decoding can continue. */
  85341. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  85342. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85343. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85344. /**< Client does not support telling the position. */
  85345. } FLAC__StreamDecoderTellStatus;
  85346. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  85347. *
  85348. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  85349. * will give the string equivalent. The contents should not be modified.
  85350. */
  85351. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  85352. /** Return values for the FLAC__StreamDecoder length callback.
  85353. */
  85354. typedef enum {
  85355. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  85356. /**< The length call was OK and decoding can continue. */
  85357. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  85358. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85359. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85360. /**< Client does not support reporting the length. */
  85361. } FLAC__StreamDecoderLengthStatus;
  85362. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  85363. *
  85364. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  85365. * will give the string equivalent. The contents should not be modified.
  85366. */
  85367. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  85368. /** Return values for the FLAC__StreamDecoder write callback.
  85369. */
  85370. typedef enum {
  85371. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  85372. /**< The write was OK and decoding can continue. */
  85373. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  85374. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85375. } FLAC__StreamDecoderWriteStatus;
  85376. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  85377. *
  85378. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  85379. * will give the string equivalent. The contents should not be modified.
  85380. */
  85381. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  85382. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  85383. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  85384. * all. The rest could be caused by bad sync (false synchronization on
  85385. * data that is not the start of a frame) or corrupted data. The error
  85386. * itself is the decoder's best guess at what happened assuming a correct
  85387. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  85388. * could be caused by a correct sync on the start of a frame, but some
  85389. * data in the frame header was corrupted. Or it could be the result of
  85390. * syncing on a point the stream that looked like the starting of a frame
  85391. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85392. * could be because the decoder encountered a valid frame made by a future
  85393. * version of the encoder which it cannot parse, or because of a false
  85394. * sync making it appear as though an encountered frame was generated by
  85395. * a future encoder.
  85396. */
  85397. typedef enum {
  85398. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  85399. /**< An error in the stream caused the decoder to lose synchronization. */
  85400. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  85401. /**< The decoder encountered a corrupted frame header. */
  85402. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  85403. /**< The frame's data did not match the CRC in the footer. */
  85404. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85405. /**< The decoder encountered reserved fields in use in the stream. */
  85406. } FLAC__StreamDecoderErrorStatus;
  85407. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  85408. *
  85409. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  85410. * will give the string equivalent. The contents should not be modified.
  85411. */
  85412. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  85413. /***********************************************************************
  85414. *
  85415. * class FLAC__StreamDecoder
  85416. *
  85417. ***********************************************************************/
  85418. struct FLAC__StreamDecoderProtected;
  85419. struct FLAC__StreamDecoderPrivate;
  85420. /** The opaque structure definition for the stream decoder type.
  85421. * See the \link flac_stream_decoder stream decoder module \endlink
  85422. * for a detailed description.
  85423. */
  85424. typedef struct {
  85425. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85426. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85427. } FLAC__StreamDecoder;
  85428. /** Signature for the read callback.
  85429. *
  85430. * A function pointer matching this signature must be passed to
  85431. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85432. * called when the decoder needs more input data. The address of the
  85433. * buffer to be filled is supplied, along with the number of bytes the
  85434. * buffer can hold. The callback may choose to supply less data and
  85435. * modify the byte count but must be careful not to overflow the buffer.
  85436. * The callback then returns a status code chosen from
  85437. * FLAC__StreamDecoderReadStatus.
  85438. *
  85439. * Here is an example of a read callback for stdio streams:
  85440. * \code
  85441. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85442. * {
  85443. * FILE *file = ((MyClientData*)client_data)->file;
  85444. * if(*bytes > 0) {
  85445. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85446. * if(ferror(file))
  85447. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85448. * else if(*bytes == 0)
  85449. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  85450. * else
  85451. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  85452. * }
  85453. * else
  85454. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85455. * }
  85456. * \endcode
  85457. *
  85458. * \note In general, FLAC__StreamDecoder functions which change the
  85459. * state should not be called on the \a decoder while in the callback.
  85460. *
  85461. * \param decoder The decoder instance calling the callback.
  85462. * \param buffer A pointer to a location for the callee to store
  85463. * data to be decoded.
  85464. * \param bytes A pointer to the size of the buffer. On entry
  85465. * to the callback, it contains the maximum number
  85466. * of bytes that may be stored in \a buffer. The
  85467. * callee must set it to the actual number of bytes
  85468. * stored (0 in case of error or end-of-stream) before
  85469. * returning.
  85470. * \param client_data The callee's client data set through
  85471. * FLAC__stream_decoder_init_*().
  85472. * \retval FLAC__StreamDecoderReadStatus
  85473. * The callee's return status. Note that the callback should return
  85474. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  85475. * zero bytes were read and there is no more data to be read.
  85476. */
  85477. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85478. /** Signature for the seek callback.
  85479. *
  85480. * A function pointer matching this signature may be passed to
  85481. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85482. * called when the decoder needs to seek the input stream. The decoder
  85483. * will pass the absolute byte offset to seek to, 0 meaning the
  85484. * beginning of the stream.
  85485. *
  85486. * Here is an example of a seek callback for stdio streams:
  85487. * \code
  85488. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85489. * {
  85490. * FILE *file = ((MyClientData*)client_data)->file;
  85491. * if(file == stdin)
  85492. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  85493. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85494. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  85495. * else
  85496. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  85497. * }
  85498. * \endcode
  85499. *
  85500. * \note In general, FLAC__StreamDecoder functions which change the
  85501. * state should not be called on the \a decoder while in the callback.
  85502. *
  85503. * \param decoder The decoder instance calling the callback.
  85504. * \param absolute_byte_offset The offset from the beginning of the stream
  85505. * to seek to.
  85506. * \param client_data The callee's client data set through
  85507. * FLAC__stream_decoder_init_*().
  85508. * \retval FLAC__StreamDecoderSeekStatus
  85509. * The callee's return status.
  85510. */
  85511. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85512. /** Signature for the tell callback.
  85513. *
  85514. * A function pointer matching this signature may be passed to
  85515. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85516. * called when the decoder wants to know the current position of the
  85517. * stream. The callback should return the byte offset from the
  85518. * beginning of the stream.
  85519. *
  85520. * Here is an example of a tell callback for stdio streams:
  85521. * \code
  85522. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85523. * {
  85524. * FILE *file = ((MyClientData*)client_data)->file;
  85525. * off_t pos;
  85526. * if(file == stdin)
  85527. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  85528. * else if((pos = ftello(file)) < 0)
  85529. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  85530. * else {
  85531. * *absolute_byte_offset = (FLAC__uint64)pos;
  85532. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  85533. * }
  85534. * }
  85535. * \endcode
  85536. *
  85537. * \note In general, FLAC__StreamDecoder functions which change the
  85538. * state should not be called on the \a decoder while in the callback.
  85539. *
  85540. * \param decoder The decoder instance calling the callback.
  85541. * \param absolute_byte_offset A pointer to storage for the current offset
  85542. * from the beginning of the stream.
  85543. * \param client_data The callee's client data set through
  85544. * FLAC__stream_decoder_init_*().
  85545. * \retval FLAC__StreamDecoderTellStatus
  85546. * The callee's return status.
  85547. */
  85548. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85549. /** Signature for the length callback.
  85550. *
  85551. * A function pointer matching this signature may be passed to
  85552. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85553. * called when the decoder wants to know the total length of the stream
  85554. * in bytes.
  85555. *
  85556. * Here is an example of a length callback for stdio streams:
  85557. * \code
  85558. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  85559. * {
  85560. * FILE *file = ((MyClientData*)client_data)->file;
  85561. * struct stat filestats;
  85562. *
  85563. * if(file == stdin)
  85564. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  85565. * else if(fstat(fileno(file), &filestats) != 0)
  85566. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  85567. * else {
  85568. * *stream_length = (FLAC__uint64)filestats.st_size;
  85569. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  85570. * }
  85571. * }
  85572. * \endcode
  85573. *
  85574. * \note In general, FLAC__StreamDecoder functions which change the
  85575. * state should not be called on the \a decoder while in the callback.
  85576. *
  85577. * \param decoder The decoder instance calling the callback.
  85578. * \param stream_length A pointer to storage for the length of the stream
  85579. * in bytes.
  85580. * \param client_data The callee's client data set through
  85581. * FLAC__stream_decoder_init_*().
  85582. * \retval FLAC__StreamDecoderLengthStatus
  85583. * The callee's return status.
  85584. */
  85585. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  85586. /** Signature for the EOF callback.
  85587. *
  85588. * A function pointer matching this signature may be passed to
  85589. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85590. * called when the decoder needs to know if the end of the stream has
  85591. * been reached.
  85592. *
  85593. * Here is an example of a EOF callback for stdio streams:
  85594. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  85595. * \code
  85596. * {
  85597. * FILE *file = ((MyClientData*)client_data)->file;
  85598. * return feof(file)? true : false;
  85599. * }
  85600. * \endcode
  85601. *
  85602. * \note In general, FLAC__StreamDecoder functions which change the
  85603. * state should not be called on the \a decoder while in the callback.
  85604. *
  85605. * \param decoder The decoder instance calling the callback.
  85606. * \param client_data The callee's client data set through
  85607. * FLAC__stream_decoder_init_*().
  85608. * \retval FLAC__bool
  85609. * \c true if the currently at the end of the stream, else \c false.
  85610. */
  85611. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  85612. /** Signature for the write callback.
  85613. *
  85614. * A function pointer matching this signature must be passed to one of
  85615. * the FLAC__stream_decoder_init_*() functions.
  85616. * The supplied function will be called when the decoder has decoded a
  85617. * single audio frame. The decoder will pass the frame metadata as well
  85618. * as an array of pointers (one for each channel) pointing to the
  85619. * decoded audio.
  85620. *
  85621. * \note In general, FLAC__StreamDecoder functions which change the
  85622. * state should not be called on the \a decoder while in the callback.
  85623. *
  85624. * \param decoder The decoder instance calling the callback.
  85625. * \param frame The description of the decoded frame. See
  85626. * FLAC__Frame.
  85627. * \param buffer An array of pointers to decoded channels of data.
  85628. * Each pointer will point to an array of signed
  85629. * samples of length \a frame->header.blocksize.
  85630. * Channels will be ordered according to the FLAC
  85631. * specification; see the documentation for the
  85632. * <A HREF="../format.html#frame_header">frame header</A>.
  85633. * \param client_data The callee's client data set through
  85634. * FLAC__stream_decoder_init_*().
  85635. * \retval FLAC__StreamDecoderWriteStatus
  85636. * The callee's return status.
  85637. */
  85638. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  85639. /** Signature for the metadata callback.
  85640. *
  85641. * A function pointer matching this signature must be passed to one of
  85642. * the FLAC__stream_decoder_init_*() functions.
  85643. * The supplied function will be called when the decoder has decoded a
  85644. * metadata block. In a valid FLAC file there will always be one
  85645. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  85646. * These will be supplied by the decoder in the same order as they
  85647. * appear in the stream and always before the first audio frame (i.e.
  85648. * write callback). The metadata block that is passed in must not be
  85649. * modified, and it doesn't live beyond the callback, so you should make
  85650. * a copy of it with FLAC__metadata_object_clone() if you will need it
  85651. * elsewhere. Since metadata blocks can potentially be large, by
  85652. * default the decoder only calls the metadata callback for the
  85653. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  85654. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  85655. *
  85656. * \note In general, FLAC__StreamDecoder functions which change the
  85657. * state should not be called on the \a decoder while in the callback.
  85658. *
  85659. * \param decoder The decoder instance calling the callback.
  85660. * \param metadata The decoded metadata block.
  85661. * \param client_data The callee's client data set through
  85662. * FLAC__stream_decoder_init_*().
  85663. */
  85664. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85665. /** Signature for the error callback.
  85666. *
  85667. * A function pointer matching this signature must be passed to one of
  85668. * the FLAC__stream_decoder_init_*() functions.
  85669. * The supplied function will be called whenever an error occurs during
  85670. * decoding.
  85671. *
  85672. * \note In general, FLAC__StreamDecoder functions which change the
  85673. * state should not be called on the \a decoder while in the callback.
  85674. *
  85675. * \param decoder The decoder instance calling the callback.
  85676. * \param status The error encountered by the decoder.
  85677. * \param client_data The callee's client data set through
  85678. * FLAC__stream_decoder_init_*().
  85679. */
  85680. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  85681. /***********************************************************************
  85682. *
  85683. * Class constructor/destructor
  85684. *
  85685. ***********************************************************************/
  85686. /** Create a new stream decoder instance. The instance is created with
  85687. * default settings; see the individual FLAC__stream_decoder_set_*()
  85688. * functions for each setting's default.
  85689. *
  85690. * \retval FLAC__StreamDecoder*
  85691. * \c NULL if there was an error allocating memory, else the new instance.
  85692. */
  85693. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  85694. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  85695. *
  85696. * \param decoder A pointer to an existing decoder.
  85697. * \assert
  85698. * \code decoder != NULL \endcode
  85699. */
  85700. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  85701. /***********************************************************************
  85702. *
  85703. * Public class method prototypes
  85704. *
  85705. ***********************************************************************/
  85706. /** Set the serial number for the FLAC stream within the Ogg container.
  85707. * The default behavior is to use the serial number of the first Ogg
  85708. * page. Setting a serial number here will explicitly specify which
  85709. * stream is to be decoded.
  85710. *
  85711. * \note
  85712. * This does not need to be set for native FLAC decoding.
  85713. *
  85714. * \default \c use serial number of first page
  85715. * \param decoder A decoder instance to set.
  85716. * \param serial_number See above.
  85717. * \assert
  85718. * \code decoder != NULL \endcode
  85719. * \retval FLAC__bool
  85720. * \c false if the decoder is already initialized, else \c true.
  85721. */
  85722. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  85723. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  85724. * compute the MD5 signature of the unencoded audio data while decoding
  85725. * and compare it to the signature from the STREAMINFO block, if it
  85726. * exists, during FLAC__stream_decoder_finish().
  85727. *
  85728. * MD5 signature checking will be turned off (until the next
  85729. * FLAC__stream_decoder_reset()) if there is no signature in the
  85730. * STREAMINFO block or when a seek is attempted.
  85731. *
  85732. * Clients that do not use the MD5 check should leave this off to speed
  85733. * up decoding.
  85734. *
  85735. * \default \c false
  85736. * \param decoder A decoder instance to set.
  85737. * \param value Flag value (see above).
  85738. * \assert
  85739. * \code decoder != NULL \endcode
  85740. * \retval FLAC__bool
  85741. * \c false if the decoder is already initialized, else \c true.
  85742. */
  85743. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  85744. /** Direct the decoder to pass on all metadata blocks of type \a type.
  85745. *
  85746. * \default By default, only the \c STREAMINFO block is returned via the
  85747. * metadata callback.
  85748. * \param decoder A decoder instance to set.
  85749. * \param type See above.
  85750. * \assert
  85751. * \code decoder != NULL \endcode
  85752. * \a type is valid
  85753. * \retval FLAC__bool
  85754. * \c false if the decoder is already initialized, else \c true.
  85755. */
  85756. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85757. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  85758. * given \a id.
  85759. *
  85760. * \default By default, only the \c STREAMINFO block is returned via the
  85761. * metadata callback.
  85762. * \param decoder A decoder instance to set.
  85763. * \param id See above.
  85764. * \assert
  85765. * \code decoder != NULL \endcode
  85766. * \code id != NULL \endcode
  85767. * \retval FLAC__bool
  85768. * \c false if the decoder is already initialized, else \c true.
  85769. */
  85770. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85771. /** Direct the decoder to pass on all metadata blocks of any type.
  85772. *
  85773. * \default By default, only the \c STREAMINFO block is returned via the
  85774. * metadata callback.
  85775. * \param decoder A decoder instance to set.
  85776. * \assert
  85777. * \code decoder != NULL \endcode
  85778. * \retval FLAC__bool
  85779. * \c false if the decoder is already initialized, else \c true.
  85780. */
  85781. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  85782. /** Direct the decoder to filter out all metadata blocks of type \a type.
  85783. *
  85784. * \default By default, only the \c STREAMINFO block is returned via the
  85785. * metadata callback.
  85786. * \param decoder A decoder instance to set.
  85787. * \param type See above.
  85788. * \assert
  85789. * \code decoder != NULL \endcode
  85790. * \a type is valid
  85791. * \retval FLAC__bool
  85792. * \c false if the decoder is already initialized, else \c true.
  85793. */
  85794. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85795. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  85796. * the given \a id.
  85797. *
  85798. * \default By default, only the \c STREAMINFO block is returned via the
  85799. * metadata callback.
  85800. * \param decoder A decoder instance to set.
  85801. * \param id See above.
  85802. * \assert
  85803. * \code decoder != NULL \endcode
  85804. * \code id != NULL \endcode
  85805. * \retval FLAC__bool
  85806. * \c false if the decoder is already initialized, else \c true.
  85807. */
  85808. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85809. /** Direct the decoder to filter out all metadata blocks of any type.
  85810. *
  85811. * \default By default, only the \c STREAMINFO block is returned via the
  85812. * metadata callback.
  85813. * \param decoder A decoder instance to set.
  85814. * \assert
  85815. * \code decoder != NULL \endcode
  85816. * \retval FLAC__bool
  85817. * \c false if the decoder is already initialized, else \c true.
  85818. */
  85819. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  85820. /** Get the current decoder state.
  85821. *
  85822. * \param decoder A decoder instance to query.
  85823. * \assert
  85824. * \code decoder != NULL \endcode
  85825. * \retval FLAC__StreamDecoderState
  85826. * The current decoder state.
  85827. */
  85828. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  85829. /** Get the current decoder state as a C string.
  85830. *
  85831. * \param decoder A decoder instance to query.
  85832. * \assert
  85833. * \code decoder != NULL \endcode
  85834. * \retval const char *
  85835. * The decoder state as a C string. Do not modify the contents.
  85836. */
  85837. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  85838. /** Get the "MD5 signature checking" flag.
  85839. * This is the value of the setting, not whether or not the decoder is
  85840. * currently checking the MD5 (remember, it can be turned off automatically
  85841. * by a seek). When the decoder is reset the flag will be restored to the
  85842. * value returned by this function.
  85843. *
  85844. * \param decoder A decoder instance to query.
  85845. * \assert
  85846. * \code decoder != NULL \endcode
  85847. * \retval FLAC__bool
  85848. * See above.
  85849. */
  85850. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  85851. /** Get the total number of samples in the stream being decoded.
  85852. * Will only be valid after decoding has started and will contain the
  85853. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  85854. *
  85855. * \param decoder A decoder instance to query.
  85856. * \assert
  85857. * \code decoder != NULL \endcode
  85858. * \retval unsigned
  85859. * See above.
  85860. */
  85861. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  85862. /** Get the current number of channels in the stream being decoded.
  85863. * Will only be valid after decoding has started and will contain the
  85864. * value from the most recently decoded frame header.
  85865. *
  85866. * \param decoder A decoder instance to query.
  85867. * \assert
  85868. * \code decoder != NULL \endcode
  85869. * \retval unsigned
  85870. * See above.
  85871. */
  85872. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  85873. /** Get the current channel assignment in the stream being decoded.
  85874. * Will only be valid after decoding has started and will contain the
  85875. * value from the most recently decoded frame header.
  85876. *
  85877. * \param decoder A decoder instance to query.
  85878. * \assert
  85879. * \code decoder != NULL \endcode
  85880. * \retval FLAC__ChannelAssignment
  85881. * See above.
  85882. */
  85883. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  85884. /** Get the current sample resolution in the stream being decoded.
  85885. * Will only be valid after decoding has started and will contain the
  85886. * value from the most recently decoded frame header.
  85887. *
  85888. * \param decoder A decoder instance to query.
  85889. * \assert
  85890. * \code decoder != NULL \endcode
  85891. * \retval unsigned
  85892. * See above.
  85893. */
  85894. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  85895. /** Get the current sample rate in Hz of the stream being decoded.
  85896. * Will only be valid after decoding has started and will contain the
  85897. * value from the most recently decoded frame header.
  85898. *
  85899. * \param decoder A decoder instance to query.
  85900. * \assert
  85901. * \code decoder != NULL \endcode
  85902. * \retval unsigned
  85903. * See above.
  85904. */
  85905. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  85906. /** Get the current blocksize of the stream being decoded.
  85907. * Will only be valid after decoding has started and will contain the
  85908. * value from the most recently decoded frame header.
  85909. *
  85910. * \param decoder A decoder instance to query.
  85911. * \assert
  85912. * \code decoder != NULL \endcode
  85913. * \retval unsigned
  85914. * See above.
  85915. */
  85916. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  85917. /** Returns the decoder's current read position within the stream.
  85918. * The position is the byte offset from the start of the stream.
  85919. * Bytes before this position have been fully decoded. Note that
  85920. * there may still be undecoded bytes in the decoder's read FIFO.
  85921. * The returned position is correct even after a seek.
  85922. *
  85923. * \warning This function currently only works for native FLAC,
  85924. * not Ogg FLAC streams.
  85925. *
  85926. * \param decoder A decoder instance to query.
  85927. * \param position Address at which to return the desired position.
  85928. * \assert
  85929. * \code decoder != NULL \endcode
  85930. * \code position != NULL \endcode
  85931. * \retval FLAC__bool
  85932. * \c true if successful, \c false if the stream is not native FLAC,
  85933. * or there was an error from the 'tell' callback or it returned
  85934. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  85935. */
  85936. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  85937. /** Initialize the decoder instance to decode native FLAC streams.
  85938. *
  85939. * This flavor of initialization sets up the decoder to decode from a
  85940. * native FLAC stream. I/O is performed via callbacks to the client.
  85941. * For decoding from a plain file via filename or open FILE*,
  85942. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  85943. * provide a simpler interface.
  85944. *
  85945. * This function should be called after FLAC__stream_decoder_new() and
  85946. * FLAC__stream_decoder_set_*() but before any of the
  85947. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85948. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85949. * if initialization succeeded.
  85950. *
  85951. * \param decoder An uninitialized decoder instance.
  85952. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85953. * pointer must not be \c NULL.
  85954. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85955. * pointer may be \c NULL if seeking is not
  85956. * supported. If \a seek_callback is not \c NULL then a
  85957. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85958. * Alternatively, a dummy seek callback that just
  85959. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85960. * may also be supplied, all though this is slightly
  85961. * less efficient for the decoder.
  85962. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85963. * pointer may be \c NULL if not supported by the client. If
  85964. * \a seek_callback is not \c NULL then a
  85965. * \a tell_callback must also be supplied.
  85966. * Alternatively, a dummy tell callback that just
  85967. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85968. * may also be supplied, all though this is slightly
  85969. * less efficient for the decoder.
  85970. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85971. * pointer may be \c NULL if not supported by the client. If
  85972. * \a seek_callback is not \c NULL then a
  85973. * \a length_callback must also be supplied.
  85974. * Alternatively, a dummy length callback that just
  85975. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85976. * may also be supplied, all though this is slightly
  85977. * less efficient for the decoder.
  85978. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85979. * pointer may be \c NULL if not supported by the client. If
  85980. * \a seek_callback is not \c NULL then a
  85981. * \a eof_callback must also be supplied.
  85982. * Alternatively, a dummy length callback that just
  85983. * returns \c false
  85984. * may also be supplied, all though this is slightly
  85985. * less efficient for the decoder.
  85986. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85987. * pointer must not be \c NULL.
  85988. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85989. * pointer may be \c NULL if the callback is not
  85990. * desired.
  85991. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85992. * pointer must not be \c NULL.
  85993. * \param client_data This value will be supplied to callbacks in their
  85994. * \a client_data argument.
  85995. * \assert
  85996. * \code decoder != NULL \endcode
  85997. * \retval FLAC__StreamDecoderInitStatus
  85998. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85999. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86000. */
  86001. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  86002. FLAC__StreamDecoder *decoder,
  86003. FLAC__StreamDecoderReadCallback read_callback,
  86004. FLAC__StreamDecoderSeekCallback seek_callback,
  86005. FLAC__StreamDecoderTellCallback tell_callback,
  86006. FLAC__StreamDecoderLengthCallback length_callback,
  86007. FLAC__StreamDecoderEofCallback eof_callback,
  86008. FLAC__StreamDecoderWriteCallback write_callback,
  86009. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86010. FLAC__StreamDecoderErrorCallback error_callback,
  86011. void *client_data
  86012. );
  86013. /** Initialize the decoder instance to decode Ogg FLAC streams.
  86014. *
  86015. * This flavor of initialization sets up the decoder to decode from a
  86016. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  86017. * client. For decoding from a plain file via filename or open FILE*,
  86018. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  86019. * provide a simpler interface.
  86020. *
  86021. * This function should be called after FLAC__stream_decoder_new() and
  86022. * FLAC__stream_decoder_set_*() but before any of the
  86023. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86024. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86025. * if initialization succeeded.
  86026. *
  86027. * \note Support for Ogg FLAC in the library is optional. If this
  86028. * library has been built without support for Ogg FLAC, this function
  86029. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86030. *
  86031. * \param decoder An uninitialized decoder instance.
  86032. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  86033. * pointer must not be \c NULL.
  86034. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  86035. * pointer may be \c NULL if seeking is not
  86036. * supported. If \a seek_callback is not \c NULL then a
  86037. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86038. * Alternatively, a dummy seek callback that just
  86039. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86040. * may also be supplied, all though this is slightly
  86041. * less efficient for the decoder.
  86042. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  86043. * pointer may be \c NULL if not supported by the client. If
  86044. * \a seek_callback is not \c NULL then a
  86045. * \a tell_callback must also be supplied.
  86046. * Alternatively, a dummy tell callback that just
  86047. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86048. * may also be supplied, all though this is slightly
  86049. * less efficient for the decoder.
  86050. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86051. * pointer may be \c NULL if not supported by the client. If
  86052. * \a seek_callback is not \c NULL then a
  86053. * \a length_callback must also be supplied.
  86054. * Alternatively, a dummy length callback that just
  86055. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86056. * may also be supplied, all though this is slightly
  86057. * less efficient for the decoder.
  86058. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86059. * pointer may be \c NULL if not supported by the client. If
  86060. * \a seek_callback is not \c NULL then a
  86061. * \a eof_callback must also be supplied.
  86062. * Alternatively, a dummy length callback that just
  86063. * returns \c false
  86064. * may also be supplied, all though this is slightly
  86065. * less efficient for the decoder.
  86066. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86067. * pointer must not be \c NULL.
  86068. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86069. * pointer may be \c NULL if the callback is not
  86070. * desired.
  86071. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86072. * pointer must not be \c NULL.
  86073. * \param client_data This value will be supplied to callbacks in their
  86074. * \a client_data argument.
  86075. * \assert
  86076. * \code decoder != NULL \endcode
  86077. * \retval FLAC__StreamDecoderInitStatus
  86078. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86079. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86080. */
  86081. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  86082. FLAC__StreamDecoder *decoder,
  86083. FLAC__StreamDecoderReadCallback read_callback,
  86084. FLAC__StreamDecoderSeekCallback seek_callback,
  86085. FLAC__StreamDecoderTellCallback tell_callback,
  86086. FLAC__StreamDecoderLengthCallback length_callback,
  86087. FLAC__StreamDecoderEofCallback eof_callback,
  86088. FLAC__StreamDecoderWriteCallback write_callback,
  86089. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86090. FLAC__StreamDecoderErrorCallback error_callback,
  86091. void *client_data
  86092. );
  86093. /** Initialize the decoder instance to decode native FLAC files.
  86094. *
  86095. * This flavor of initialization sets up the decoder to decode from a
  86096. * plain native FLAC file. For non-stdio streams, you must use
  86097. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  86098. *
  86099. * This function should be called after FLAC__stream_decoder_new() and
  86100. * FLAC__stream_decoder_set_*() but before any of the
  86101. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86102. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86103. * if initialization succeeded.
  86104. *
  86105. * \param decoder An uninitialized decoder instance.
  86106. * \param file An open FLAC file. The file should have been
  86107. * opened with mode \c "rb" and rewound. The file
  86108. * becomes owned by the decoder and should not be
  86109. * manipulated by the client while decoding.
  86110. * Unless \a file is \c stdin, it will be closed
  86111. * when FLAC__stream_decoder_finish() is called.
  86112. * Note however that seeking will not work when
  86113. * decoding from \c stdout since it is not seekable.
  86114. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86115. * pointer must not be \c NULL.
  86116. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86117. * pointer may be \c NULL if the callback is not
  86118. * desired.
  86119. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86120. * pointer must not be \c NULL.
  86121. * \param client_data This value will be supplied to callbacks in their
  86122. * \a client_data argument.
  86123. * \assert
  86124. * \code decoder != NULL \endcode
  86125. * \code file != NULL \endcode
  86126. * \retval FLAC__StreamDecoderInitStatus
  86127. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86128. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86129. */
  86130. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  86131. FLAC__StreamDecoder *decoder,
  86132. FILE *file,
  86133. FLAC__StreamDecoderWriteCallback write_callback,
  86134. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86135. FLAC__StreamDecoderErrorCallback error_callback,
  86136. void *client_data
  86137. );
  86138. /** Initialize the decoder instance to decode Ogg FLAC files.
  86139. *
  86140. * This flavor of initialization sets up the decoder to decode from a
  86141. * plain Ogg FLAC file. For non-stdio streams, you must use
  86142. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  86143. *
  86144. * This function should be called after FLAC__stream_decoder_new() and
  86145. * FLAC__stream_decoder_set_*() but before any of the
  86146. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86147. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86148. * if initialization succeeded.
  86149. *
  86150. * \note Support for Ogg FLAC in the library is optional. If this
  86151. * library has been built without support for Ogg FLAC, this function
  86152. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86153. *
  86154. * \param decoder An uninitialized decoder instance.
  86155. * \param file An open FLAC file. The file should have been
  86156. * opened with mode \c "rb" and rewound. The file
  86157. * becomes owned by the decoder and should not be
  86158. * manipulated by the client while decoding.
  86159. * Unless \a file is \c stdin, it will be closed
  86160. * when FLAC__stream_decoder_finish() is called.
  86161. * Note however that seeking will not work when
  86162. * decoding from \c stdout since it is not seekable.
  86163. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86164. * pointer must not be \c NULL.
  86165. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86166. * pointer may be \c NULL if the callback is not
  86167. * desired.
  86168. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86169. * pointer must not be \c NULL.
  86170. * \param client_data This value will be supplied to callbacks in their
  86171. * \a client_data argument.
  86172. * \assert
  86173. * \code decoder != NULL \endcode
  86174. * \code file != NULL \endcode
  86175. * \retval FLAC__StreamDecoderInitStatus
  86176. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86177. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86178. */
  86179. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  86180. FLAC__StreamDecoder *decoder,
  86181. FILE *file,
  86182. FLAC__StreamDecoderWriteCallback write_callback,
  86183. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86184. FLAC__StreamDecoderErrorCallback error_callback,
  86185. void *client_data
  86186. );
  86187. /** Initialize the decoder instance to decode native FLAC files.
  86188. *
  86189. * This flavor of initialization sets up the decoder to decode from a plain
  86190. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86191. * example, with Unicode filenames on Windows), you must use
  86192. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  86193. * and provide callbacks for the I/O.
  86194. *
  86195. * This function should be called after FLAC__stream_decoder_new() and
  86196. * FLAC__stream_decoder_set_*() but before any of the
  86197. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86198. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86199. * if initialization succeeded.
  86200. *
  86201. * \param decoder An uninitialized decoder instance.
  86202. * \param filename The name of the file to decode from. The file will
  86203. * be opened with fopen(). Use \c NULL to decode from
  86204. * \c stdin. Note that \c stdin is not seekable.
  86205. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86206. * pointer must not be \c NULL.
  86207. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86208. * pointer may be \c NULL if the callback is not
  86209. * desired.
  86210. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86211. * pointer must not be \c NULL.
  86212. * \param client_data This value will be supplied to callbacks in their
  86213. * \a client_data argument.
  86214. * \assert
  86215. * \code decoder != NULL \endcode
  86216. * \retval FLAC__StreamDecoderInitStatus
  86217. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86218. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86219. */
  86220. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  86221. FLAC__StreamDecoder *decoder,
  86222. const char *filename,
  86223. FLAC__StreamDecoderWriteCallback write_callback,
  86224. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86225. FLAC__StreamDecoderErrorCallback error_callback,
  86226. void *client_data
  86227. );
  86228. /** Initialize the decoder instance to decode Ogg FLAC files.
  86229. *
  86230. * This flavor of initialization sets up the decoder to decode from a plain
  86231. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86232. * example, with Unicode filenames on Windows), you must use
  86233. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  86234. * and provide callbacks for the I/O.
  86235. *
  86236. * This function should be called after FLAC__stream_decoder_new() and
  86237. * FLAC__stream_decoder_set_*() but before any of the
  86238. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86239. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86240. * if initialization succeeded.
  86241. *
  86242. * \note Support for Ogg FLAC in the library is optional. If this
  86243. * library has been built without support for Ogg FLAC, this function
  86244. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86245. *
  86246. * \param decoder An uninitialized decoder instance.
  86247. * \param filename The name of the file to decode from. The file will
  86248. * be opened with fopen(). Use \c NULL to decode from
  86249. * \c stdin. Note that \c stdin is not seekable.
  86250. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86251. * pointer must not be \c NULL.
  86252. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86253. * pointer may be \c NULL if the callback is not
  86254. * desired.
  86255. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86256. * pointer must not be \c NULL.
  86257. * \param client_data This value will be supplied to callbacks in their
  86258. * \a client_data argument.
  86259. * \assert
  86260. * \code decoder != NULL \endcode
  86261. * \retval FLAC__StreamDecoderInitStatus
  86262. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86263. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86264. */
  86265. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  86266. FLAC__StreamDecoder *decoder,
  86267. const char *filename,
  86268. FLAC__StreamDecoderWriteCallback write_callback,
  86269. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86270. FLAC__StreamDecoderErrorCallback error_callback,
  86271. void *client_data
  86272. );
  86273. /** Finish the decoding process.
  86274. * Flushes the decoding buffer, releases resources, resets the decoder
  86275. * settings to their defaults, and returns the decoder state to
  86276. * FLAC__STREAM_DECODER_UNINITIALIZED.
  86277. *
  86278. * In the event of a prematurely-terminated decode, it is not strictly
  86279. * necessary to call this immediately before FLAC__stream_decoder_delete()
  86280. * but it is good practice to match every FLAC__stream_decoder_init_*()
  86281. * with a FLAC__stream_decoder_finish().
  86282. *
  86283. * \param decoder An uninitialized decoder instance.
  86284. * \assert
  86285. * \code decoder != NULL \endcode
  86286. * \retval FLAC__bool
  86287. * \c false if MD5 checking is on AND a STREAMINFO block was available
  86288. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  86289. * signature does not match the one computed by the decoder; else
  86290. * \c true.
  86291. */
  86292. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  86293. /** Flush the stream input.
  86294. * The decoder's input buffer will be cleared and the state set to
  86295. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  86296. * off MD5 checking.
  86297. *
  86298. * \param decoder A decoder instance.
  86299. * \assert
  86300. * \code decoder != NULL \endcode
  86301. * \retval FLAC__bool
  86302. * \c true if successful, else \c false if a memory allocation
  86303. * error occurs (in which case the state will be set to
  86304. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  86305. */
  86306. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  86307. /** Reset the decoding process.
  86308. * The decoder's input buffer will be cleared and the state set to
  86309. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  86310. * FLAC__stream_decoder_finish() except that the settings are
  86311. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  86312. * before decoding again. MD5 checking will be restored to its original
  86313. * setting.
  86314. *
  86315. * If the decoder is seekable, or was initialized with
  86316. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  86317. * the decoder will also attempt to seek to the beginning of the file.
  86318. * If this rewind fails, this function will return \c false. It follows
  86319. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  86320. * \c stdin.
  86321. *
  86322. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  86323. * and is not seekable (i.e. no seek callback was provided or the seek
  86324. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  86325. * is the duty of the client to start feeding data from the beginning of
  86326. * the stream on the next FLAC__stream_decoder_process() or
  86327. * FLAC__stream_decoder_process_interleaved() call.
  86328. *
  86329. * \param decoder A decoder instance.
  86330. * \assert
  86331. * \code decoder != NULL \endcode
  86332. * \retval FLAC__bool
  86333. * \c true if successful, else \c false if a memory allocation occurs
  86334. * (in which case the state will be set to
  86335. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  86336. * occurs (the state will be unchanged).
  86337. */
  86338. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  86339. /** Decode one metadata block or audio frame.
  86340. * This version instructs the decoder to decode a either a single metadata
  86341. * block or a single frame and stop, unless the callbacks return a fatal
  86342. * error or the read callback returns
  86343. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86344. *
  86345. * As the decoder needs more input it will call the read callback.
  86346. * Depending on what was decoded, the metadata or write callback will be
  86347. * called with the decoded metadata block or audio frame.
  86348. *
  86349. * Unless there is a fatal read error or end of stream, this function
  86350. * will return once one whole frame is decoded. In other words, if the
  86351. * stream is not synchronized or points to a corrupt frame header, the
  86352. * decoder will continue to try and resync until it gets to a valid
  86353. * frame, then decode one frame, then return. If the decoder points to
  86354. * a frame whose frame CRC in the frame footer does not match the
  86355. * computed frame CRC, this function will issue a
  86356. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  86357. * error callback, and return, having decoded one complete, although
  86358. * corrupt, frame. (Such corrupted frames are sent as silence of the
  86359. * correct length to the write callback.)
  86360. *
  86361. * \param decoder An initialized decoder instance.
  86362. * \assert
  86363. * \code decoder != NULL \endcode
  86364. * \retval FLAC__bool
  86365. * \c false if any fatal read, write, or memory allocation error
  86366. * occurred (meaning decoding must stop), else \c true; for more
  86367. * information about the decoder, check the decoder state with
  86368. * FLAC__stream_decoder_get_state().
  86369. */
  86370. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  86371. /** Decode until the end of the metadata.
  86372. * This version instructs the decoder to decode from the current position
  86373. * and continue until all the metadata has been read, or until the
  86374. * callbacks return a fatal error or the read callback returns
  86375. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86376. *
  86377. * As the decoder needs more input it will call the read callback.
  86378. * As each metadata block is decoded, the metadata callback will be called
  86379. * with the decoded metadata.
  86380. *
  86381. * \param decoder An initialized decoder instance.
  86382. * \assert
  86383. * \code decoder != NULL \endcode
  86384. * \retval FLAC__bool
  86385. * \c false if any fatal read, write, or memory allocation error
  86386. * occurred (meaning decoding must stop), else \c true; for more
  86387. * information about the decoder, check the decoder state with
  86388. * FLAC__stream_decoder_get_state().
  86389. */
  86390. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  86391. /** Decode until the end of the stream.
  86392. * This version instructs the decoder to decode from the current position
  86393. * and continue until the end of stream (the read callback returns
  86394. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  86395. * callbacks return a fatal error.
  86396. *
  86397. * As the decoder needs more input it will call the read callback.
  86398. * As each metadata block and frame is decoded, the metadata or write
  86399. * callback will be called with the decoded metadata or frame.
  86400. *
  86401. * \param decoder An initialized decoder instance.
  86402. * \assert
  86403. * \code decoder != NULL \endcode
  86404. * \retval FLAC__bool
  86405. * \c false if any fatal read, write, or memory allocation error
  86406. * occurred (meaning decoding must stop), else \c true; for more
  86407. * information about the decoder, check the decoder state with
  86408. * FLAC__stream_decoder_get_state().
  86409. */
  86410. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  86411. /** Skip one audio frame.
  86412. * This version instructs the decoder to 'skip' a single frame and stop,
  86413. * unless the callbacks return a fatal error or the read callback returns
  86414. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86415. *
  86416. * The decoding flow is the same as what occurs when
  86417. * FLAC__stream_decoder_process_single() is called to process an audio
  86418. * frame, except that this function does not decode the parsed data into
  86419. * PCM or call the write callback. The integrity of the frame is still
  86420. * checked the same way as in the other process functions.
  86421. *
  86422. * This function will return once one whole frame is skipped, in the
  86423. * same way that FLAC__stream_decoder_process_single() will return once
  86424. * one whole frame is decoded.
  86425. *
  86426. * This function can be used in more quickly determining FLAC frame
  86427. * boundaries when decoding of the actual data is not needed, for
  86428. * example when an application is separating a FLAC stream into frames
  86429. * for editing or storing in a container. To do this, the application
  86430. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  86431. * to the next frame, then use
  86432. * FLAC__stream_decoder_get_decode_position() to find the new frame
  86433. * boundary.
  86434. *
  86435. * This function should only be called when the stream has advanced
  86436. * past all the metadata, otherwise it will return \c false.
  86437. *
  86438. * \param decoder An initialized decoder instance not in a metadata
  86439. * state.
  86440. * \assert
  86441. * \code decoder != NULL \endcode
  86442. * \retval FLAC__bool
  86443. * \c false if any fatal read, write, or memory allocation error
  86444. * occurred (meaning decoding must stop), or if the decoder
  86445. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  86446. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  86447. * information about the decoder, check the decoder state with
  86448. * FLAC__stream_decoder_get_state().
  86449. */
  86450. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  86451. /** Flush the input and seek to an absolute sample.
  86452. * Decoding will resume at the given sample. Note that because of
  86453. * this, the next write callback may contain a partial block. The
  86454. * client must support seeking the input or this function will fail
  86455. * and return \c false. Furthermore, if the decoder state is
  86456. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  86457. * with FLAC__stream_decoder_flush() or reset with
  86458. * FLAC__stream_decoder_reset() before decoding can continue.
  86459. *
  86460. * \param decoder A decoder instance.
  86461. * \param sample The target sample number to seek to.
  86462. * \assert
  86463. * \code decoder != NULL \endcode
  86464. * \retval FLAC__bool
  86465. * \c true if successful, else \c false.
  86466. */
  86467. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  86468. /* \} */
  86469. #ifdef __cplusplus
  86470. }
  86471. #endif
  86472. #endif
  86473. /********* End of inlined file: stream_decoder.h *********/
  86474. /********* Start of inlined file: stream_encoder.h *********/
  86475. #ifndef FLAC__STREAM_ENCODER_H
  86476. #define FLAC__STREAM_ENCODER_H
  86477. #include <stdio.h> /* for FILE */
  86478. #ifdef __cplusplus
  86479. extern "C" {
  86480. #endif
  86481. /** \file include/FLAC/stream_encoder.h
  86482. *
  86483. * \brief
  86484. * This module contains the functions which implement the stream
  86485. * encoder.
  86486. *
  86487. * See the detailed documentation in the
  86488. * \link flac_stream_encoder stream encoder \endlink module.
  86489. */
  86490. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  86491. * \ingroup flac
  86492. *
  86493. * \brief
  86494. * This module describes the encoder layers provided by libFLAC.
  86495. *
  86496. * The stream encoder can be used to encode complete streams either to the
  86497. * client via callbacks, or directly to a file, depending on how it is
  86498. * initialized. When encoding via callbacks, the client provides a write
  86499. * callback which will be called whenever FLAC data is ready to be written.
  86500. * If the client also supplies a seek callback, the encoder will also
  86501. * automatically handle the writing back of metadata discovered while
  86502. * encoding, like stream info, seek points offsets, etc. When encoding to
  86503. * a file, the client needs only supply a filename or open \c FILE* and an
  86504. * optional progress callback for periodic notification of progress; the
  86505. * write and seek callbacks are supplied internally. For more info see the
  86506. * \link flac_stream_encoder stream encoder \endlink module.
  86507. */
  86508. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  86509. * \ingroup flac_encoder
  86510. *
  86511. * \brief
  86512. * This module contains the functions which implement the stream
  86513. * encoder.
  86514. *
  86515. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  86516. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  86517. *
  86518. * The basic usage of this encoder is as follows:
  86519. * - The program creates an instance of an encoder using
  86520. * FLAC__stream_encoder_new().
  86521. * - The program overrides the default settings using
  86522. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  86523. * functions should be called:
  86524. * - FLAC__stream_encoder_set_channels()
  86525. * - FLAC__stream_encoder_set_bits_per_sample()
  86526. * - FLAC__stream_encoder_set_sample_rate()
  86527. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  86528. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  86529. * - If the application wants to control the compression level or set its own
  86530. * metadata, then the following should also be called:
  86531. * - FLAC__stream_encoder_set_compression_level()
  86532. * - FLAC__stream_encoder_set_verify()
  86533. * - FLAC__stream_encoder_set_metadata()
  86534. * - The rest of the set functions should only be called if the client needs
  86535. * exact control over how the audio is compressed; thorough understanding
  86536. * of the FLAC format is necessary to achieve good results.
  86537. * - The program initializes the instance to validate the settings and
  86538. * prepare for encoding using
  86539. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  86540. * or FLAC__stream_encoder_init_file() for native FLAC
  86541. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  86542. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  86543. * - The program calls FLAC__stream_encoder_process() or
  86544. * FLAC__stream_encoder_process_interleaved() to encode data, which
  86545. * subsequently calls the callbacks when there is encoder data ready
  86546. * to be written.
  86547. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  86548. * which causes the encoder to encode any data still in its input pipe,
  86549. * update the metadata with the final encoding statistics if output
  86550. * seeking is possible, and finally reset the encoder to the
  86551. * uninitialized state.
  86552. * - The instance may be used again or deleted with
  86553. * FLAC__stream_encoder_delete().
  86554. *
  86555. * In more detail, the stream encoder functions similarly to the
  86556. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  86557. * callbacks and more options. Typically the client will create a new
  86558. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  86559. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  86560. * calling one of the FLAC__stream_encoder_init_*() functions.
  86561. *
  86562. * Unlike the decoders, the stream encoder has many options that can
  86563. * affect the speed and compression ratio. When setting these parameters
  86564. * you should have some basic knowledge of the format (see the
  86565. * <A HREF="../documentation.html#format">user-level documentation</A>
  86566. * or the <A HREF="../format.html">formal description</A>). The
  86567. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  86568. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  86569. * functions will do this, so make sure to pay attention to the state
  86570. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  86571. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  86572. * before FLAC__stream_encoder_init_*() will take on the defaults from
  86573. * the constructor.
  86574. *
  86575. * There are three initialization functions for native FLAC, one for
  86576. * setting up the encoder to encode FLAC data to the client via
  86577. * callbacks, and two for encoding directly to a file.
  86578. *
  86579. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  86580. * You must also supply a write callback which will be called anytime
  86581. * there is raw encoded data to write. If the client can seek the output
  86582. * it is best to also supply seek and tell callbacks, as this allows the
  86583. * encoder to go back after encoding is finished to write back
  86584. * information that was collected while encoding, like seek point offsets,
  86585. * frame sizes, etc.
  86586. *
  86587. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  86588. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  86589. * filename or open \c FILE*; the encoder will handle all the callbacks
  86590. * internally. You may also supply a progress callback for periodic
  86591. * notification of the encoding progress.
  86592. *
  86593. * There are three similarly-named init functions for encoding to Ogg
  86594. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  86595. * library has been built with Ogg support.
  86596. *
  86597. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  86598. * call the write callback several times, once with the \c fLaC signature,
  86599. * and once for each encoded metadata block. Note that for Ogg FLAC
  86600. * encoding you will usually get at least twice the number of callbacks than
  86601. * with native FLAC, one for the Ogg page header and one for the page body.
  86602. *
  86603. * After initializing the instance, the client may feed audio data to the
  86604. * encoder in one of two ways:
  86605. *
  86606. * - Channel separate, through FLAC__stream_encoder_process() - The client
  86607. * will pass an array of pointers to buffers, one for each channel, to
  86608. * the encoder, each of the same length. The samples need not be
  86609. * block-aligned, but each channel should have the same number of samples.
  86610. * - Channel interleaved, through
  86611. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  86612. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  86613. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86614. * Again, the samples need not be block-aligned but they must be
  86615. * sample-aligned, i.e. the first value should be channel0_sample0 and
  86616. * the last value channelN_sampleM.
  86617. *
  86618. * Note that for either process call, each sample in the buffers should be a
  86619. * signed integer, right-justified to the resolution set by
  86620. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  86621. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  86622. *
  86623. * When the client is finished encoding data, it calls
  86624. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  86625. * data still in its input pipe, and call the metadata callback with the
  86626. * final encoding statistics. Then the instance may be deleted with
  86627. * FLAC__stream_encoder_delete() or initialized again to encode another
  86628. * stream.
  86629. *
  86630. * For programs that write their own metadata, but that do not know the
  86631. * actual metadata until after encoding, it is advantageous to instruct
  86632. * the encoder to write a PADDING block of the correct size, so that
  86633. * instead of rewriting the whole stream after encoding, the program can
  86634. * just overwrite the PADDING block. If only the maximum size of the
  86635. * metadata is known, the program can write a slightly larger padding
  86636. * block, then split it after encoding.
  86637. *
  86638. * Make sure you understand how lengths are calculated. All FLAC metadata
  86639. * blocks have a 4 byte header which contains the type and length. This
  86640. * length does not include the 4 bytes of the header. See the format page
  86641. * for the specification of metadata blocks and their lengths.
  86642. *
  86643. * \note
  86644. * If you are writing the FLAC data to a file via callbacks, make sure it
  86645. * is open for update (e.g. mode "w+" for stdio streams). This is because
  86646. * after the first encoding pass, the encoder will try to seek back to the
  86647. * beginning of the stream, to the STREAMINFO block, to write some data
  86648. * there. (If using FLAC__stream_encoder_init*_file() or
  86649. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  86650. *
  86651. * \note
  86652. * The "set" functions may only be called when the encoder is in the
  86653. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  86654. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  86655. * before FLAC__stream_encoder_init_*(). If this is the case they will
  86656. * return \c true, otherwise \c false.
  86657. *
  86658. * \note
  86659. * FLAC__stream_encoder_finish() resets all settings to the constructor
  86660. * defaults.
  86661. *
  86662. * \{
  86663. */
  86664. /** State values for a FLAC__StreamEncoder.
  86665. *
  86666. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  86667. *
  86668. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  86669. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  86670. * must be deleted with FLAC__stream_encoder_delete().
  86671. */
  86672. typedef enum {
  86673. FLAC__STREAM_ENCODER_OK = 0,
  86674. /**< The encoder is in the normal OK state and samples can be processed. */
  86675. FLAC__STREAM_ENCODER_UNINITIALIZED,
  86676. /**< The encoder is in the uninitialized state; one of the
  86677. * FLAC__stream_encoder_init_*() functions must be called before samples
  86678. * can be processed.
  86679. */
  86680. FLAC__STREAM_ENCODER_OGG_ERROR,
  86681. /**< An error occurred in the underlying Ogg layer. */
  86682. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  86683. /**< An error occurred in the underlying verify stream decoder;
  86684. * check FLAC__stream_encoder_get_verify_decoder_state().
  86685. */
  86686. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  86687. /**< The verify decoder detected a mismatch between the original
  86688. * audio signal and the decoded audio signal.
  86689. */
  86690. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  86691. /**< One of the callbacks returned a fatal error. */
  86692. FLAC__STREAM_ENCODER_IO_ERROR,
  86693. /**< An I/O error occurred while opening/reading/writing a file.
  86694. * Check \c errno.
  86695. */
  86696. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  86697. /**< An error occurred while writing the stream; usually, the
  86698. * write_callback returned an error.
  86699. */
  86700. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  86701. /**< Memory allocation failed. */
  86702. } FLAC__StreamEncoderState;
  86703. /** Maps a FLAC__StreamEncoderState to a C string.
  86704. *
  86705. * Using a FLAC__StreamEncoderState as the index to this array
  86706. * will give the string equivalent. The contents should not be modified.
  86707. */
  86708. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  86709. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  86710. */
  86711. typedef enum {
  86712. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  86713. /**< Initialization was successful. */
  86714. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  86715. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  86716. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86717. /**< The library was not compiled with support for the given container
  86718. * format.
  86719. */
  86720. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  86721. /**< A required callback was not supplied. */
  86722. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  86723. /**< The encoder has an invalid setting for number of channels. */
  86724. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  86725. /**< The encoder has an invalid setting for bits-per-sample.
  86726. * FLAC supports 4-32 bps but the reference encoder currently supports
  86727. * only up to 24 bps.
  86728. */
  86729. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  86730. /**< The encoder has an invalid setting for the input sample rate. */
  86731. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  86732. /**< The encoder has an invalid setting for the block size. */
  86733. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  86734. /**< The encoder has an invalid setting for the maximum LPC order. */
  86735. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  86736. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  86737. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  86738. /**< The specified block size is less than the maximum LPC order. */
  86739. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  86740. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  86741. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  86742. /**< The metadata input to the encoder is invalid, in one of the following ways:
  86743. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  86744. * - One of the metadata blocks contains an undefined type
  86745. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  86746. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  86747. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  86748. */
  86749. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  86750. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  86751. * already initialized, usually because
  86752. * FLAC__stream_encoder_finish() was not called.
  86753. */
  86754. } FLAC__StreamEncoderInitStatus;
  86755. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  86756. *
  86757. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  86758. * will give the string equivalent. The contents should not be modified.
  86759. */
  86760. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  86761. /** Return values for the FLAC__StreamEncoder read callback.
  86762. */
  86763. typedef enum {
  86764. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  86765. /**< The read was OK and decoding can continue. */
  86766. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  86767. /**< The read was attempted at the end of the stream. */
  86768. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  86769. /**< An unrecoverable error occurred. */
  86770. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  86771. /**< Client does not support reading back from the output. */
  86772. } FLAC__StreamEncoderReadStatus;
  86773. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  86774. *
  86775. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  86776. * will give the string equivalent. The contents should not be modified.
  86777. */
  86778. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  86779. /** Return values for the FLAC__StreamEncoder write callback.
  86780. */
  86781. typedef enum {
  86782. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  86783. /**< The write was OK and encoding can continue. */
  86784. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  86785. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  86786. } FLAC__StreamEncoderWriteStatus;
  86787. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  86788. *
  86789. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  86790. * will give the string equivalent. The contents should not be modified.
  86791. */
  86792. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  86793. /** Return values for the FLAC__StreamEncoder seek callback.
  86794. */
  86795. typedef enum {
  86796. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  86797. /**< The seek was OK and encoding can continue. */
  86798. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  86799. /**< An unrecoverable error occurred. */
  86800. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86801. /**< Client does not support seeking. */
  86802. } FLAC__StreamEncoderSeekStatus;
  86803. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  86804. *
  86805. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  86806. * will give the string equivalent. The contents should not be modified.
  86807. */
  86808. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  86809. /** Return values for the FLAC__StreamEncoder tell callback.
  86810. */
  86811. typedef enum {
  86812. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  86813. /**< The tell was OK and encoding can continue. */
  86814. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  86815. /**< An unrecoverable error occurred. */
  86816. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86817. /**< Client does not support seeking. */
  86818. } FLAC__StreamEncoderTellStatus;
  86819. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  86820. *
  86821. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  86822. * will give the string equivalent. The contents should not be modified.
  86823. */
  86824. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  86825. /***********************************************************************
  86826. *
  86827. * class FLAC__StreamEncoder
  86828. *
  86829. ***********************************************************************/
  86830. struct FLAC__StreamEncoderProtected;
  86831. struct FLAC__StreamEncoderPrivate;
  86832. /** The opaque structure definition for the stream encoder type.
  86833. * See the \link flac_stream_encoder stream encoder module \endlink
  86834. * for a detailed description.
  86835. */
  86836. typedef struct {
  86837. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86838. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86839. } FLAC__StreamEncoder;
  86840. /** Signature for the read callback.
  86841. *
  86842. * A function pointer matching this signature must be passed to
  86843. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  86844. * The supplied function will be called when the encoder needs to read back
  86845. * encoded data. This happens during the metadata callback, when the encoder
  86846. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  86847. * while encoding. The address of the buffer to be filled is supplied, along
  86848. * with the number of bytes the buffer can hold. The callback may choose to
  86849. * supply less data and modify the byte count but must be careful not to
  86850. * overflow the buffer. The callback then returns a status code chosen from
  86851. * FLAC__StreamEncoderReadStatus.
  86852. *
  86853. * Here is an example of a read callback for stdio streams:
  86854. * \code
  86855. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86856. * {
  86857. * FILE *file = ((MyClientData*)client_data)->file;
  86858. * if(*bytes > 0) {
  86859. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86860. * if(ferror(file))
  86861. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86862. * else if(*bytes == 0)
  86863. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  86864. * else
  86865. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  86866. * }
  86867. * else
  86868. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86869. * }
  86870. * \endcode
  86871. *
  86872. * \note In general, FLAC__StreamEncoder functions which change the
  86873. * state should not be called on the \a encoder while in the callback.
  86874. *
  86875. * \param encoder The encoder instance calling the callback.
  86876. * \param buffer A pointer to a location for the callee to store
  86877. * data to be encoded.
  86878. * \param bytes A pointer to the size of the buffer. On entry
  86879. * to the callback, it contains the maximum number
  86880. * of bytes that may be stored in \a buffer. The
  86881. * callee must set it to the actual number of bytes
  86882. * stored (0 in case of error or end-of-stream) before
  86883. * returning.
  86884. * \param client_data The callee's client data set through
  86885. * FLAC__stream_encoder_set_client_data().
  86886. * \retval FLAC__StreamEncoderReadStatus
  86887. * The callee's return status.
  86888. */
  86889. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86890. /** Signature for the write callback.
  86891. *
  86892. * A function pointer matching this signature must be passed to
  86893. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86894. * by the encoder anytime there is raw encoded data ready to write. It may
  86895. * include metadata mixed with encoded audio frames and the data is not
  86896. * guaranteed to be aligned on frame or metadata block boundaries.
  86897. *
  86898. * The only duty of the callback is to write out the \a bytes worth of data
  86899. * in \a buffer to the current position in the output stream. The arguments
  86900. * \a samples and \a current_frame are purely informational. If \a samples
  86901. * is greater than \c 0, then \a current_frame will hold the current frame
  86902. * number that is being written; otherwise it indicates that the write
  86903. * callback is being called to write metadata.
  86904. *
  86905. * \note
  86906. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  86907. * write callback will be called twice when writing each audio
  86908. * frame; once for the page header, and once for the page body.
  86909. * When writing the page header, the \a samples argument to the
  86910. * write callback will be \c 0.
  86911. *
  86912. * \note In general, FLAC__StreamEncoder functions which change the
  86913. * state should not be called on the \a encoder while in the callback.
  86914. *
  86915. * \param encoder The encoder instance calling the callback.
  86916. * \param buffer An array of encoded data of length \a bytes.
  86917. * \param bytes The byte length of \a buffer.
  86918. * \param samples The number of samples encoded by \a buffer.
  86919. * \c 0 has a special meaning; see above.
  86920. * \param current_frame The number of the current frame being encoded.
  86921. * \param client_data The callee's client data set through
  86922. * FLAC__stream_encoder_init_*().
  86923. * \retval FLAC__StreamEncoderWriteStatus
  86924. * The callee's return status.
  86925. */
  86926. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  86927. /** Signature for the seek callback.
  86928. *
  86929. * A function pointer matching this signature may be passed to
  86930. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86931. * when the encoder needs to seek the output stream. The encoder will pass
  86932. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  86933. *
  86934. * Here is an example of a seek callback for stdio streams:
  86935. * \code
  86936. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86937. * {
  86938. * FILE *file = ((MyClientData*)client_data)->file;
  86939. * if(file == stdin)
  86940. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  86941. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86942. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  86943. * else
  86944. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  86945. * }
  86946. * \endcode
  86947. *
  86948. * \note In general, FLAC__StreamEncoder functions which change the
  86949. * state should not be called on the \a encoder while in the callback.
  86950. *
  86951. * \param encoder The encoder instance calling the callback.
  86952. * \param absolute_byte_offset The offset from the beginning of the stream
  86953. * to seek to.
  86954. * \param client_data The callee's client data set through
  86955. * FLAC__stream_encoder_init_*().
  86956. * \retval FLAC__StreamEncoderSeekStatus
  86957. * The callee's return status.
  86958. */
  86959. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86960. /** Signature for the tell callback.
  86961. *
  86962. * A function pointer matching this signature may be passed to
  86963. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86964. * when the encoder needs to know the current position of the output stream.
  86965. *
  86966. * \warning
  86967. * The callback must return the true current byte offset of the output to
  86968. * which the encoder is writing. If you are buffering the output, make
  86969. * sure and take this into account. If you are writing directly to a
  86970. * FILE* from your write callback, ftell() is sufficient. If you are
  86971. * writing directly to a file descriptor from your write callback, you
  86972. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  86973. * these points to rewrite metadata after encoding.
  86974. *
  86975. * Here is an example of a tell callback for stdio streams:
  86976. * \code
  86977. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86978. * {
  86979. * FILE *file = ((MyClientData*)client_data)->file;
  86980. * off_t pos;
  86981. * if(file == stdin)
  86982. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  86983. * else if((pos = ftello(file)) < 0)
  86984. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  86985. * else {
  86986. * *absolute_byte_offset = (FLAC__uint64)pos;
  86987. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  86988. * }
  86989. * }
  86990. * \endcode
  86991. *
  86992. * \note In general, FLAC__StreamEncoder functions which change the
  86993. * state should not be called on the \a encoder while in the callback.
  86994. *
  86995. * \param encoder The encoder instance calling the callback.
  86996. * \param absolute_byte_offset The address at which to store the current
  86997. * position of the output.
  86998. * \param client_data The callee's client data set through
  86999. * FLAC__stream_encoder_init_*().
  87000. * \retval FLAC__StreamEncoderTellStatus
  87001. * The callee's return status.
  87002. */
  87003. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  87004. /** Signature for the metadata callback.
  87005. *
  87006. * A function pointer matching this signature may be passed to
  87007. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87008. * once at the end of encoding with the populated STREAMINFO structure. This
  87009. * is so the client can seek back to the beginning of the file and write the
  87010. * STREAMINFO block with the correct statistics after encoding (like
  87011. * minimum/maximum frame size and total samples).
  87012. *
  87013. * \note In general, FLAC__StreamEncoder functions which change the
  87014. * state should not be called on the \a encoder while in the callback.
  87015. *
  87016. * \param encoder The encoder instance calling the callback.
  87017. * \param metadata The final populated STREAMINFO block.
  87018. * \param client_data The callee's client data set through
  87019. * FLAC__stream_encoder_init_*().
  87020. */
  87021. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  87022. /** Signature for the progress callback.
  87023. *
  87024. * A function pointer matching this signature may be passed to
  87025. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  87026. * The supplied function will be called when the encoder has finished
  87027. * writing a frame. The \c total_frames_estimate argument to the
  87028. * callback will be based on the value from
  87029. * FLAC__stream_encoder_set_total_samples_estimate().
  87030. *
  87031. * \note In general, FLAC__StreamEncoder functions which change the
  87032. * state should not be called on the \a encoder while in the callback.
  87033. *
  87034. * \param encoder The encoder instance calling the callback.
  87035. * \param bytes_written Bytes written so far.
  87036. * \param samples_written Samples written so far.
  87037. * \param frames_written Frames written so far.
  87038. * \param total_frames_estimate The estimate of the total number of
  87039. * frames to be written.
  87040. * \param client_data The callee's client data set through
  87041. * FLAC__stream_encoder_init_*().
  87042. */
  87043. typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
  87044. /***********************************************************************
  87045. *
  87046. * Class constructor/destructor
  87047. *
  87048. ***********************************************************************/
  87049. /** Create a new stream encoder instance. The instance is created with
  87050. * default settings; see the individual FLAC__stream_encoder_set_*()
  87051. * functions for each setting's default.
  87052. *
  87053. * \retval FLAC__StreamEncoder*
  87054. * \c NULL if there was an error allocating memory, else the new instance.
  87055. */
  87056. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  87057. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  87058. *
  87059. * \param encoder A pointer to an existing encoder.
  87060. * \assert
  87061. * \code encoder != NULL \endcode
  87062. */
  87063. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  87064. /***********************************************************************
  87065. *
  87066. * Public class method prototypes
  87067. *
  87068. ***********************************************************************/
  87069. /** Set the serial number for the FLAC stream to use in the Ogg container.
  87070. *
  87071. * \note
  87072. * This does not need to be set for native FLAC encoding.
  87073. *
  87074. * \note
  87075. * It is recommended to set a serial number explicitly as the default of '0'
  87076. * may collide with other streams.
  87077. *
  87078. * \default \c 0
  87079. * \param encoder An encoder instance to set.
  87080. * \param serial_number See above.
  87081. * \assert
  87082. * \code encoder != NULL \endcode
  87083. * \retval FLAC__bool
  87084. * \c false if the encoder is already initialized, else \c true.
  87085. */
  87086. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  87087. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  87088. * encoded output by feeding it through an internal decoder and comparing
  87089. * the original signal against the decoded signal. If a mismatch occurs,
  87090. * the process call will return \c false. Note that this will slow the
  87091. * encoding process by the extra time required for decoding and comparison.
  87092. *
  87093. * \default \c false
  87094. * \param encoder An encoder instance to set.
  87095. * \param value Flag value (see above).
  87096. * \assert
  87097. * \code encoder != NULL \endcode
  87098. * \retval FLAC__bool
  87099. * \c false if the encoder is already initialized, else \c true.
  87100. */
  87101. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87102. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  87103. * the encoder will comply with the Subset and will check the
  87104. * settings during FLAC__stream_encoder_init_*() to see if all settings
  87105. * comply. If \c false, the settings may take advantage of the full
  87106. * range that the format allows.
  87107. *
  87108. * Make sure you know what it entails before setting this to \c false.
  87109. *
  87110. * \default \c true
  87111. * \param encoder An encoder instance to set.
  87112. * \param value Flag value (see above).
  87113. * \assert
  87114. * \code encoder != NULL \endcode
  87115. * \retval FLAC__bool
  87116. * \c false if the encoder is already initialized, else \c true.
  87117. */
  87118. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87119. /** Set the number of channels to be encoded.
  87120. *
  87121. * \default \c 2
  87122. * \param encoder An encoder instance to set.
  87123. * \param value See above.
  87124. * \assert
  87125. * \code encoder != NULL \endcode
  87126. * \retval FLAC__bool
  87127. * \c false if the encoder is already initialized, else \c true.
  87128. */
  87129. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  87130. /** Set the sample resolution of the input to be encoded.
  87131. *
  87132. * \warning
  87133. * Do not feed the encoder data that is wider than the value you
  87134. * set here or you will generate an invalid stream.
  87135. *
  87136. * \default \c 16
  87137. * \param encoder An encoder instance to set.
  87138. * \param value See above.
  87139. * \assert
  87140. * \code encoder != NULL \endcode
  87141. * \retval FLAC__bool
  87142. * \c false if the encoder is already initialized, else \c true.
  87143. */
  87144. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  87145. /** Set the sample rate (in Hz) of the input to be encoded.
  87146. *
  87147. * \default \c 44100
  87148. * \param encoder An encoder instance to set.
  87149. * \param value See above.
  87150. * \assert
  87151. * \code encoder != NULL \endcode
  87152. * \retval FLAC__bool
  87153. * \c false if the encoder is already initialized, else \c true.
  87154. */
  87155. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  87156. /** Set the compression level
  87157. *
  87158. * The compression level is roughly proportional to the amount of effort
  87159. * the encoder expends to compress the file. A higher level usually
  87160. * means more computation but higher compression. The default level is
  87161. * suitable for most applications.
  87162. *
  87163. * Currently the levels range from \c 0 (fastest, least compression) to
  87164. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  87165. * treated as \c 8.
  87166. *
  87167. * This function automatically calls the following other \c _set_
  87168. * functions with appropriate values, so the client does not need to
  87169. * unless it specifically wants to override them:
  87170. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  87171. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  87172. * - FLAC__stream_encoder_set_apodization()
  87173. * - FLAC__stream_encoder_set_max_lpc_order()
  87174. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  87175. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  87176. * - FLAC__stream_encoder_set_do_escape_coding()
  87177. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  87178. * - FLAC__stream_encoder_set_min_residual_partition_order()
  87179. * - FLAC__stream_encoder_set_max_residual_partition_order()
  87180. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  87181. *
  87182. * The actual values set for each level are:
  87183. * <table>
  87184. * <tr>
  87185. * <td><b>level</b><td>
  87186. * <td>do mid-side stereo<td>
  87187. * <td>loose mid-side stereo<td>
  87188. * <td>apodization<td>
  87189. * <td>max lpc order<td>
  87190. * <td>qlp coeff precision<td>
  87191. * <td>qlp coeff prec search<td>
  87192. * <td>escape coding<td>
  87193. * <td>exhaustive model search<td>
  87194. * <td>min residual partition order<td>
  87195. * <td>max residual partition order<td>
  87196. * <td>rice parameter search dist<td>
  87197. * </tr>
  87198. * <tr> <td><b>0</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  87199. * <tr> <td><b>1</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  87200. * <tr> <td><b>2</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  87201. * <tr> <td><b>3</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>6<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  87202. * <tr> <td><b>4</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  87203. * <tr> <td><b>5</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>5<td> <td>0<td> </tr>
  87204. * <tr> <td><b>6</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  87205. * <tr> <td><b>7</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  87206. * <tr> <td><b>8</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>12<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  87207. * </table>
  87208. *
  87209. * \default \c 5
  87210. * \param encoder An encoder instance to set.
  87211. * \param value See above.
  87212. * \assert
  87213. * \code encoder != NULL \endcode
  87214. * \retval FLAC__bool
  87215. * \c false if the encoder is already initialized, else \c true.
  87216. */
  87217. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  87218. /** Set the blocksize to use while encoding.
  87219. *
  87220. * The number of samples to use per frame. Use \c 0 to let the encoder
  87221. * estimate a blocksize; this is usually best.
  87222. *
  87223. * \default \c 0
  87224. * \param encoder An encoder instance to set.
  87225. * \param value See above.
  87226. * \assert
  87227. * \code encoder != NULL \endcode
  87228. * \retval FLAC__bool
  87229. * \c false if the encoder is already initialized, else \c true.
  87230. */
  87231. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  87232. /** Set to \c true to enable mid-side encoding on stereo input. The
  87233. * number of channels must be 2 for this to have any effect. Set to
  87234. * \c false to use only independent channel coding.
  87235. *
  87236. * \default \c false
  87237. * \param encoder An encoder instance to set.
  87238. * \param value Flag value (see above).
  87239. * \assert
  87240. * \code encoder != NULL \endcode
  87241. * \retval FLAC__bool
  87242. * \c false if the encoder is already initialized, else \c true.
  87243. */
  87244. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87245. /** Set to \c true to enable adaptive switching between mid-side and
  87246. * left-right encoding on stereo input. Set to \c false to use
  87247. * exhaustive searching. Setting this to \c true requires
  87248. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  87249. * \c true in order to have any effect.
  87250. *
  87251. * \default \c false
  87252. * \param encoder An encoder instance to set.
  87253. * \param value Flag value (see above).
  87254. * \assert
  87255. * \code encoder != NULL \endcode
  87256. * \retval FLAC__bool
  87257. * \c false if the encoder is already initialized, else \c true.
  87258. */
  87259. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87260. /** Sets the apodization function(s) the encoder will use when windowing
  87261. * audio data for LPC analysis.
  87262. *
  87263. * The \a specification is a plain ASCII string which specifies exactly
  87264. * which functions to use. There may be more than one (up to 32),
  87265. * separated by \c ';' characters. Some functions take one or more
  87266. * comma-separated arguments in parentheses.
  87267. *
  87268. * The available functions are \c bartlett, \c bartlett_hann,
  87269. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  87270. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  87271. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  87272. *
  87273. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  87274. * (0<STDDEV<=0.5).
  87275. *
  87276. * For \c tukey(P), P specifies the fraction of the window that is
  87277. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  87278. * corresponds to \c hann.
  87279. *
  87280. * Example specifications are \c "blackman" or
  87281. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  87282. *
  87283. * Any function that is specified erroneously is silently dropped. Up
  87284. * to 32 functions are kept, the rest are dropped. If the specification
  87285. * is empty the encoder defaults to \c "tukey(0.5)".
  87286. *
  87287. * When more than one function is specified, then for every subframe the
  87288. * encoder will try each of them separately and choose the window that
  87289. * results in the smallest compressed subframe.
  87290. *
  87291. * Note that each function specified causes the encoder to occupy a
  87292. * floating point array in which to store the window.
  87293. *
  87294. * \default \c "tukey(0.5)"
  87295. * \param encoder An encoder instance to set.
  87296. * \param specification See above.
  87297. * \assert
  87298. * \code encoder != NULL \endcode
  87299. * \code specification != NULL \endcode
  87300. * \retval FLAC__bool
  87301. * \c false if the encoder is already initialized, else \c true.
  87302. */
  87303. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  87304. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  87305. *
  87306. * \default \c 0
  87307. * \param encoder An encoder instance to set.
  87308. * \param value See above.
  87309. * \assert
  87310. * \code encoder != NULL \endcode
  87311. * \retval FLAC__bool
  87312. * \c false if the encoder is already initialized, else \c true.
  87313. */
  87314. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  87315. /** Set the precision, in bits, of the quantized linear predictor
  87316. * coefficients, or \c 0 to let the encoder select it based on the
  87317. * blocksize.
  87318. *
  87319. * \note
  87320. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  87321. * be less than 32.
  87322. *
  87323. * \default \c 0
  87324. * \param encoder An encoder instance to set.
  87325. * \param value See above.
  87326. * \assert
  87327. * \code encoder != NULL \endcode
  87328. * \retval FLAC__bool
  87329. * \c false if the encoder is already initialized, else \c true.
  87330. */
  87331. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  87332. /** Set to \c false to use only the specified quantized linear predictor
  87333. * coefficient precision, or \c true to search neighboring precision
  87334. * values and use the best one.
  87335. *
  87336. * \default \c false
  87337. * \param encoder An encoder instance to set.
  87338. * \param value See above.
  87339. * \assert
  87340. * \code encoder != NULL \endcode
  87341. * \retval FLAC__bool
  87342. * \c false if the encoder is already initialized, else \c true.
  87343. */
  87344. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87345. /** Deprecated. Setting this value has no effect.
  87346. *
  87347. * \default \c false
  87348. * \param encoder An encoder instance to set.
  87349. * \param value See above.
  87350. * \assert
  87351. * \code encoder != NULL \endcode
  87352. * \retval FLAC__bool
  87353. * \c false if the encoder is already initialized, else \c true.
  87354. */
  87355. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87356. /** Set to \c false to let the encoder estimate the best model order
  87357. * based on the residual signal energy, or \c true to force the
  87358. * encoder to evaluate all order models and select the best.
  87359. *
  87360. * \default \c false
  87361. * \param encoder An encoder instance to set.
  87362. * \param value See above.
  87363. * \assert
  87364. * \code encoder != NULL \endcode
  87365. * \retval FLAC__bool
  87366. * \c false if the encoder is already initialized, else \c true.
  87367. */
  87368. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87369. /** Set the minimum partition order to search when coding the residual.
  87370. * This is used in tandem with
  87371. * FLAC__stream_encoder_set_max_residual_partition_order().
  87372. *
  87373. * The partition order determines the context size in the residual.
  87374. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87375. *
  87376. * Set both min and max values to \c 0 to force a single context,
  87377. * whose Rice parameter is based on the residual signal variance.
  87378. * Otherwise, set a min and max order, and the encoder will search
  87379. * all orders, using the mean of each context for its Rice parameter,
  87380. * and use the best.
  87381. *
  87382. * \default \c 0
  87383. * \param encoder An encoder instance to set.
  87384. * \param value See above.
  87385. * \assert
  87386. * \code encoder != NULL \endcode
  87387. * \retval FLAC__bool
  87388. * \c false if the encoder is already initialized, else \c true.
  87389. */
  87390. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87391. /** Set the maximum partition order to search when coding the residual.
  87392. * This is used in tandem with
  87393. * FLAC__stream_encoder_set_min_residual_partition_order().
  87394. *
  87395. * The partition order determines the context size in the residual.
  87396. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87397. *
  87398. * Set both min and max values to \c 0 to force a single context,
  87399. * whose Rice parameter is based on the residual signal variance.
  87400. * Otherwise, set a min and max order, and the encoder will search
  87401. * all orders, using the mean of each context for its Rice parameter,
  87402. * and use the best.
  87403. *
  87404. * \default \c 0
  87405. * \param encoder An encoder instance to set.
  87406. * \param value See above.
  87407. * \assert
  87408. * \code encoder != NULL \endcode
  87409. * \retval FLAC__bool
  87410. * \c false if the encoder is already initialized, else \c true.
  87411. */
  87412. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87413. /** Deprecated. Setting this value has no effect.
  87414. *
  87415. * \default \c 0
  87416. * \param encoder An encoder instance to set.
  87417. * \param value See above.
  87418. * \assert
  87419. * \code encoder != NULL \endcode
  87420. * \retval FLAC__bool
  87421. * \c false if the encoder is already initialized, else \c true.
  87422. */
  87423. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  87424. /** Set an estimate of the total samples that will be encoded.
  87425. * This is merely an estimate and may be set to \c 0 if unknown.
  87426. * This value will be written to the STREAMINFO block before encoding,
  87427. * and can remove the need for the caller to rewrite the value later
  87428. * if the value is known before encoding.
  87429. *
  87430. * \default \c 0
  87431. * \param encoder An encoder instance to set.
  87432. * \param value See above.
  87433. * \assert
  87434. * \code encoder != NULL \endcode
  87435. * \retval FLAC__bool
  87436. * \c false if the encoder is already initialized, else \c true.
  87437. */
  87438. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  87439. /** Set the metadata blocks to be emitted to the stream before encoding.
  87440. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  87441. * array of pointers to metadata blocks. The array is non-const since
  87442. * the encoder may need to change the \a is_last flag inside them, and
  87443. * in some cases update seek point offsets. Otherwise, the encoder will
  87444. * not modify or free the blocks. It is up to the caller to free the
  87445. * metadata blocks after encoding finishes.
  87446. *
  87447. * \note
  87448. * The encoder stores only copies of the pointers in the \a metadata array;
  87449. * the metadata blocks themselves must survive at least until after
  87450. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  87451. *
  87452. * \note
  87453. * The STREAMINFO block is always written and no STREAMINFO block may
  87454. * occur in the supplied array.
  87455. *
  87456. * \note
  87457. * By default the encoder does not create a SEEKTABLE. If one is supplied
  87458. * in the \a metadata array, but the client has specified that it does not
  87459. * support seeking, then the SEEKTABLE will be written verbatim. However
  87460. * by itself this is not very useful as the client will not know the stream
  87461. * offsets for the seekpoints ahead of time. In order to get a proper
  87462. * seektable the client must support seeking. See next note.
  87463. *
  87464. * \note
  87465. * SEEKTABLE blocks are handled specially. Since you will not know
  87466. * the values for the seek point stream offsets, you should pass in
  87467. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  87468. * required sample numbers (or placeholder points), with \c 0 for the
  87469. * \a frame_samples and \a stream_offset fields for each point. If the
  87470. * client has specified that it supports seeking by providing a seek
  87471. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  87472. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  87473. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  87474. * then while it is encoding the encoder will fill the stream offsets in
  87475. * for you and when encoding is finished, it will seek back and write the
  87476. * real values into the SEEKTABLE block in the stream. There are helper
  87477. * routines for manipulating seektable template blocks; see metadata.h:
  87478. * FLAC__metadata_object_seektable_template_*(). If the client does
  87479. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  87480. * will slow down or remove the ability to seek in the FLAC stream.
  87481. *
  87482. * \note
  87483. * The encoder instance \b will modify the first \c SEEKTABLE block
  87484. * as it transforms the template to a valid seektable while encoding,
  87485. * but it is still up to the caller to free all metadata blocks after
  87486. * encoding.
  87487. *
  87488. * \note
  87489. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  87490. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  87491. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  87492. * will simply write it's own into the stream. If no VORBIS_COMMENT
  87493. * block is present in the \a metadata array, libFLAC will write an
  87494. * empty one, containing only the vendor string.
  87495. *
  87496. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  87497. * the second metadata block of the stream. The encoder already supplies
  87498. * the STREAMINFO block automatically. If \a metadata does not contain a
  87499. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  87500. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  87501. * first, the init function will reorder \a metadata by moving the
  87502. * VORBIS_COMMENT block to the front; the relative ordering of the other
  87503. * blocks will remain as they were.
  87504. *
  87505. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  87506. * stream to \c 65535. If \a num_blocks exceeds this the function will
  87507. * return \c false.
  87508. *
  87509. * \default \c NULL, 0
  87510. * \param encoder An encoder instance to set.
  87511. * \param metadata See above.
  87512. * \param num_blocks See above.
  87513. * \assert
  87514. * \code encoder != NULL \endcode
  87515. * \retval FLAC__bool
  87516. * \c false if the encoder is already initialized, else \c true.
  87517. * \c false if the encoder is already initialized, or if
  87518. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  87519. */
  87520. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  87521. /** Get the current encoder state.
  87522. *
  87523. * \param encoder An encoder instance to query.
  87524. * \assert
  87525. * \code encoder != NULL \endcode
  87526. * \retval FLAC__StreamEncoderState
  87527. * The current encoder state.
  87528. */
  87529. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  87530. /** Get the state of the verify stream decoder.
  87531. * Useful when the stream encoder state is
  87532. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  87533. *
  87534. * \param encoder An encoder instance to query.
  87535. * \assert
  87536. * \code encoder != NULL \endcode
  87537. * \retval FLAC__StreamDecoderState
  87538. * The verify stream decoder state.
  87539. */
  87540. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  87541. /** Get the current encoder state as a C string.
  87542. * This version automatically resolves
  87543. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  87544. * verify decoder's state.
  87545. *
  87546. * \param encoder A encoder instance to query.
  87547. * \assert
  87548. * \code encoder != NULL \endcode
  87549. * \retval const char *
  87550. * The encoder state as a C string. Do not modify the contents.
  87551. */
  87552. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  87553. /** Get relevant values about the nature of a verify decoder error.
  87554. * Useful when the stream encoder state is
  87555. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  87556. * be addresses in which the stats will be returned, or NULL if value
  87557. * is not desired.
  87558. *
  87559. * \param encoder An encoder instance to query.
  87560. * \param absolute_sample The absolute sample number of the mismatch.
  87561. * \param frame_number The number of the frame in which the mismatch occurred.
  87562. * \param channel The channel in which the mismatch occurred.
  87563. * \param sample The number of the sample (relative to the frame) in
  87564. * which the mismatch occurred.
  87565. * \param expected The expected value for the sample in question.
  87566. * \param got The actual value returned by the decoder.
  87567. * \assert
  87568. * \code encoder != NULL \endcode
  87569. */
  87570. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
  87571. /** Get the "verify" flag.
  87572. *
  87573. * \param encoder An encoder instance to query.
  87574. * \assert
  87575. * \code encoder != NULL \endcode
  87576. * \retval FLAC__bool
  87577. * See FLAC__stream_encoder_set_verify().
  87578. */
  87579. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  87580. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  87581. *
  87582. * \param encoder An encoder instance to query.
  87583. * \assert
  87584. * \code encoder != NULL \endcode
  87585. * \retval FLAC__bool
  87586. * See FLAC__stream_encoder_set_streamable_subset().
  87587. */
  87588. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  87589. /** Get the number of input channels being processed.
  87590. *
  87591. * \param encoder An encoder instance to query.
  87592. * \assert
  87593. * \code encoder != NULL \endcode
  87594. * \retval unsigned
  87595. * See FLAC__stream_encoder_set_channels().
  87596. */
  87597. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  87598. /** Get the input sample resolution setting.
  87599. *
  87600. * \param encoder An encoder instance to query.
  87601. * \assert
  87602. * \code encoder != NULL \endcode
  87603. * \retval unsigned
  87604. * See FLAC__stream_encoder_set_bits_per_sample().
  87605. */
  87606. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  87607. /** Get the input sample rate setting.
  87608. *
  87609. * \param encoder An encoder instance to query.
  87610. * \assert
  87611. * \code encoder != NULL \endcode
  87612. * \retval unsigned
  87613. * See FLAC__stream_encoder_set_sample_rate().
  87614. */
  87615. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  87616. /** Get the blocksize setting.
  87617. *
  87618. * \param encoder An encoder instance to query.
  87619. * \assert
  87620. * \code encoder != NULL \endcode
  87621. * \retval unsigned
  87622. * See FLAC__stream_encoder_set_blocksize().
  87623. */
  87624. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  87625. /** Get the "mid/side stereo coding" flag.
  87626. *
  87627. * \param encoder An encoder instance to query.
  87628. * \assert
  87629. * \code encoder != NULL \endcode
  87630. * \retval FLAC__bool
  87631. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  87632. */
  87633. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87634. /** Get the "adaptive mid/side switching" flag.
  87635. *
  87636. * \param encoder An encoder instance to query.
  87637. * \assert
  87638. * \code encoder != NULL \endcode
  87639. * \retval FLAC__bool
  87640. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  87641. */
  87642. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87643. /** Get the maximum LPC order setting.
  87644. *
  87645. * \param encoder An encoder instance to query.
  87646. * \assert
  87647. * \code encoder != NULL \endcode
  87648. * \retval unsigned
  87649. * See FLAC__stream_encoder_set_max_lpc_order().
  87650. */
  87651. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  87652. /** Get the quantized linear predictor coefficient precision setting.
  87653. *
  87654. * \param encoder An encoder instance to query.
  87655. * \assert
  87656. * \code encoder != NULL \endcode
  87657. * \retval unsigned
  87658. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  87659. */
  87660. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  87661. /** Get the qlp coefficient precision search flag.
  87662. *
  87663. * \param encoder An encoder instance to query.
  87664. * \assert
  87665. * \code encoder != NULL \endcode
  87666. * \retval FLAC__bool
  87667. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  87668. */
  87669. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  87670. /** Get the "escape coding" flag.
  87671. *
  87672. * \param encoder An encoder instance to query.
  87673. * \assert
  87674. * \code encoder != NULL \endcode
  87675. * \retval FLAC__bool
  87676. * See FLAC__stream_encoder_set_do_escape_coding().
  87677. */
  87678. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  87679. /** Get the exhaustive model search flag.
  87680. *
  87681. * \param encoder An encoder instance to query.
  87682. * \assert
  87683. * \code encoder != NULL \endcode
  87684. * \retval FLAC__bool
  87685. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  87686. */
  87687. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  87688. /** Get the minimum residual partition order setting.
  87689. *
  87690. * \param encoder An encoder instance to query.
  87691. * \assert
  87692. * \code encoder != NULL \endcode
  87693. * \retval unsigned
  87694. * See FLAC__stream_encoder_set_min_residual_partition_order().
  87695. */
  87696. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87697. /** Get maximum residual partition order setting.
  87698. *
  87699. * \param encoder An encoder instance to query.
  87700. * \assert
  87701. * \code encoder != NULL \endcode
  87702. * \retval unsigned
  87703. * See FLAC__stream_encoder_set_max_residual_partition_order().
  87704. */
  87705. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87706. /** Get the Rice parameter search distance setting.
  87707. *
  87708. * \param encoder An encoder instance to query.
  87709. * \assert
  87710. * \code encoder != NULL \endcode
  87711. * \retval unsigned
  87712. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  87713. */
  87714. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  87715. /** Get the previously set estimate of the total samples to be encoded.
  87716. * The encoder merely mimics back the value given to
  87717. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  87718. * other way of knowing how many samples the client will encode.
  87719. *
  87720. * \param encoder An encoder instance to set.
  87721. * \assert
  87722. * \code encoder != NULL \endcode
  87723. * \retval FLAC__uint64
  87724. * See FLAC__stream_encoder_get_total_samples_estimate().
  87725. */
  87726. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  87727. /** Initialize the encoder instance to encode native FLAC streams.
  87728. *
  87729. * This flavor of initialization sets up the encoder to encode to a
  87730. * native FLAC stream. I/O is performed via callbacks to the client.
  87731. * For encoding to a plain file via filename or open \c FILE*,
  87732. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  87733. * provide a simpler interface.
  87734. *
  87735. * This function should be called after FLAC__stream_encoder_new() and
  87736. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87737. * or FLAC__stream_encoder_process_interleaved().
  87738. * initialization succeeded.
  87739. *
  87740. * The call to FLAC__stream_encoder_init_stream() currently will also
  87741. * immediately call the write callback several times, once with the \c fLaC
  87742. * signature, and once for each encoded metadata block.
  87743. *
  87744. * \param encoder An uninitialized encoder instance.
  87745. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87746. * pointer must not be \c NULL.
  87747. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87748. * pointer may be \c NULL if seeking is not
  87749. * supported. The encoder uses seeking to go back
  87750. * and write some some stream statistics to the
  87751. * STREAMINFO block; this is recommended but not
  87752. * necessary to create a valid FLAC stream. If
  87753. * \a seek_callback is not \c NULL then a
  87754. * \a tell_callback must also be supplied.
  87755. * Alternatively, a dummy seek callback that just
  87756. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87757. * may also be supplied, all though this is slightly
  87758. * less efficient for the encoder.
  87759. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87760. * pointer may be \c NULL if seeking is not
  87761. * supported. If \a seek_callback is \c NULL then
  87762. * this argument will be ignored. If
  87763. * \a seek_callback is not \c NULL then a
  87764. * \a tell_callback must also be supplied.
  87765. * Alternatively, a dummy tell callback that just
  87766. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87767. * may also be supplied, all though this is slightly
  87768. * less efficient for the encoder.
  87769. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87770. * pointer may be \c NULL if the callback is not
  87771. * desired. If the client provides a seek callback,
  87772. * this function is not necessary as the encoder
  87773. * will automatically seek back and update the
  87774. * STREAMINFO block. It may also be \c NULL if the
  87775. * client does not support seeking, since it will
  87776. * have no way of going back to update the
  87777. * STREAMINFO. However the client can still supply
  87778. * a callback if it would like to know the details
  87779. * from the STREAMINFO.
  87780. * \param client_data This value will be supplied to callbacks in their
  87781. * \a client_data argument.
  87782. * \assert
  87783. * \code encoder != NULL \endcode
  87784. * \retval FLAC__StreamEncoderInitStatus
  87785. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87786. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87787. */
  87788. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  87789. /** Initialize the encoder instance to encode Ogg FLAC streams.
  87790. *
  87791. * This flavor of initialization sets up the encoder to encode to a FLAC
  87792. * stream in an Ogg container. I/O is performed via callbacks to the
  87793. * client. For encoding to a plain file via filename or open \c FILE*,
  87794. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  87795. * provide a simpler interface.
  87796. *
  87797. * This function should be called after FLAC__stream_encoder_new() and
  87798. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87799. * or FLAC__stream_encoder_process_interleaved().
  87800. * initialization succeeded.
  87801. *
  87802. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  87803. * immediately call the write callback several times to write the metadata
  87804. * packets.
  87805. *
  87806. * \param encoder An uninitialized encoder instance.
  87807. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  87808. * pointer must not be \c NULL if \a seek_callback
  87809. * is non-NULL since they are both needed to be
  87810. * able to write data back to the Ogg FLAC stream
  87811. * in the post-encode phase.
  87812. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87813. * pointer must not be \c NULL.
  87814. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87815. * pointer may be \c NULL if seeking is not
  87816. * supported. The encoder uses seeking to go back
  87817. * and write some some stream statistics to the
  87818. * STREAMINFO block; this is recommended but not
  87819. * necessary to create a valid FLAC stream. If
  87820. * \a seek_callback is not \c NULL then a
  87821. * \a tell_callback must also be supplied.
  87822. * Alternatively, a dummy seek callback that just
  87823. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87824. * may also be supplied, all though this is slightly
  87825. * less efficient for the encoder.
  87826. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87827. * pointer may be \c NULL if seeking is not
  87828. * supported. If \a seek_callback is \c NULL then
  87829. * this argument will be ignored. If
  87830. * \a seek_callback is not \c NULL then a
  87831. * \a tell_callback must also be supplied.
  87832. * Alternatively, a dummy tell callback that just
  87833. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87834. * may also be supplied, all though this is slightly
  87835. * less efficient for the encoder.
  87836. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87837. * pointer may be \c NULL if the callback is not
  87838. * desired. If the client provides a seek callback,
  87839. * this function is not necessary as the encoder
  87840. * will automatically seek back and update the
  87841. * STREAMINFO block. It may also be \c NULL if the
  87842. * client does not support seeking, since it will
  87843. * have no way of going back to update the
  87844. * STREAMINFO. However the client can still supply
  87845. * a callback if it would like to know the details
  87846. * from the STREAMINFO.
  87847. * \param client_data This value will be supplied to callbacks in their
  87848. * \a client_data argument.
  87849. * \assert
  87850. * \code encoder != NULL \endcode
  87851. * \retval FLAC__StreamEncoderInitStatus
  87852. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87853. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87854. */
  87855. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderReadCallback read_callback, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  87856. /** Initialize the encoder instance to encode native FLAC files.
  87857. *
  87858. * This flavor of initialization sets up the encoder to encode to a
  87859. * plain native FLAC file. For non-stdio streams, you must use
  87860. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  87861. *
  87862. * This function should be called after FLAC__stream_encoder_new() and
  87863. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87864. * or FLAC__stream_encoder_process_interleaved().
  87865. * initialization succeeded.
  87866. *
  87867. * \param encoder An uninitialized encoder instance.
  87868. * \param file An open file. The file should have been opened
  87869. * with mode \c "w+b" and rewound. The file
  87870. * becomes owned by the encoder and should not be
  87871. * manipulated by the client while encoding.
  87872. * Unless \a file is \c stdout, it will be closed
  87873. * when FLAC__stream_encoder_finish() is called.
  87874. * Note however that a proper SEEKTABLE cannot be
  87875. * created when encoding to \c stdout since it is
  87876. * not seekable.
  87877. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87878. * pointer may be \c NULL if the callback is not
  87879. * desired.
  87880. * \param client_data This value will be supplied to callbacks in their
  87881. * \a client_data argument.
  87882. * \assert
  87883. * \code encoder != NULL \endcode
  87884. * \code file != NULL \endcode
  87885. * \retval FLAC__StreamEncoderInitStatus
  87886. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87887. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87888. */
  87889. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87890. /** Initialize the encoder instance to encode Ogg FLAC files.
  87891. *
  87892. * This flavor of initialization sets up the encoder to encode to a
  87893. * plain Ogg FLAC file. For non-stdio streams, you must use
  87894. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  87895. *
  87896. * This function should be called after FLAC__stream_encoder_new() and
  87897. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87898. * or FLAC__stream_encoder_process_interleaved().
  87899. * initialization succeeded.
  87900. *
  87901. * \param encoder An uninitialized encoder instance.
  87902. * \param file An open file. The file should have been opened
  87903. * with mode \c "w+b" and rewound. The file
  87904. * becomes owned by the encoder and should not be
  87905. * manipulated by the client while encoding.
  87906. * Unless \a file is \c stdout, it will be closed
  87907. * when FLAC__stream_encoder_finish() is called.
  87908. * Note however that a proper SEEKTABLE cannot be
  87909. * created when encoding to \c stdout since it is
  87910. * not seekable.
  87911. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87912. * pointer may be \c NULL if the callback is not
  87913. * desired.
  87914. * \param client_data This value will be supplied to callbacks in their
  87915. * \a client_data argument.
  87916. * \assert
  87917. * \code encoder != NULL \endcode
  87918. * \code file != NULL \endcode
  87919. * \retval FLAC__StreamEncoderInitStatus
  87920. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87921. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87922. */
  87923. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87924. /** Initialize the encoder instance to encode native FLAC files.
  87925. *
  87926. * This flavor of initialization sets up the encoder to encode to a plain
  87927. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87928. * with Unicode filenames on Windows), you must use
  87929. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  87930. * and provide callbacks for the I/O.
  87931. *
  87932. * This function should be called after FLAC__stream_encoder_new() and
  87933. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87934. * or FLAC__stream_encoder_process_interleaved().
  87935. * initialization succeeded.
  87936. *
  87937. * \param encoder An uninitialized encoder instance.
  87938. * \param filename The name of the file to encode to. The file will
  87939. * be opened with fopen(). Use \c NULL to encode to
  87940. * \c stdout. Note however that a proper SEEKTABLE
  87941. * cannot be created when encoding to \c stdout since
  87942. * it is not seekable.
  87943. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87944. * pointer may be \c NULL if the callback is not
  87945. * desired.
  87946. * \param client_data This value will be supplied to callbacks in their
  87947. * \a client_data argument.
  87948. * \assert
  87949. * \code encoder != NULL \endcode
  87950. * \retval FLAC__StreamEncoderInitStatus
  87951. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87952. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87953. */
  87954. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87955. /** Initialize the encoder instance to encode Ogg FLAC files.
  87956. *
  87957. * This flavor of initialization sets up the encoder to encode to a plain
  87958. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87959. * with Unicode filenames on Windows), you must use
  87960. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  87961. * and provide callbacks for the I/O.
  87962. *
  87963. * This function should be called after FLAC__stream_encoder_new() and
  87964. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87965. * or FLAC__stream_encoder_process_interleaved().
  87966. * initialization succeeded.
  87967. *
  87968. * \param encoder An uninitialized encoder instance.
  87969. * \param filename The name of the file to encode to. The file will
  87970. * be opened with fopen(). Use \c NULL to encode to
  87971. * \c stdout. Note however that a proper SEEKTABLE
  87972. * cannot be created when encoding to \c stdout since
  87973. * it is not seekable.
  87974. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87975. * pointer may be \c NULL if the callback is not
  87976. * desired.
  87977. * \param client_data This value will be supplied to callbacks in their
  87978. * \a client_data argument.
  87979. * \assert
  87980. * \code encoder != NULL \endcode
  87981. * \retval FLAC__StreamEncoderInitStatus
  87982. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87983. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87984. */
  87985. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87986. /** Finish the encoding process.
  87987. * Flushes the encoding buffer, releases resources, resets the encoder
  87988. * settings to their defaults, and returns the encoder state to
  87989. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  87990. * one or more write callbacks before returning, and will generate
  87991. * a metadata callback.
  87992. *
  87993. * Note that in the course of processing the last frame, errors can
  87994. * occur, so the caller should be sure to check the return value to
  87995. * ensure the file was encoded properly.
  87996. *
  87997. * In the event of a prematurely-terminated encode, it is not strictly
  87998. * necessary to call this immediately before FLAC__stream_encoder_delete()
  87999. * but it is good practice to match every FLAC__stream_encoder_init_*()
  88000. * with a FLAC__stream_encoder_finish().
  88001. *
  88002. * \param encoder An uninitialized encoder instance.
  88003. * \assert
  88004. * \code encoder != NULL \endcode
  88005. * \retval FLAC__bool
  88006. * \c false if an error occurred processing the last frame; or if verify
  88007. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  88008. * verify mismatch; else \c true. If \c false, caller should check the
  88009. * state with FLAC__stream_encoder_get_state() for more information
  88010. * about the error.
  88011. */
  88012. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  88013. /** Submit data for encoding.
  88014. * This version allows you to supply the input data via an array of
  88015. * pointers, each pointer pointing to an array of \a samples samples
  88016. * representing one channel. The samples need not be block-aligned,
  88017. * but each channel should have the same number of samples. Each sample
  88018. * should be a signed integer, right-justified to the resolution set by
  88019. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88020. * resolution is 16 bits per sample, the samples should all be in the
  88021. * range [-32768,32767].
  88022. *
  88023. * For applications where channel order is important, channels must
  88024. * follow the order as described in the
  88025. * <A HREF="../format.html#frame_header">frame header</A>.
  88026. *
  88027. * \param encoder An initialized encoder instance in the OK state.
  88028. * \param buffer An array of pointers to each channel's signal.
  88029. * \param samples The number of samples in one channel.
  88030. * \assert
  88031. * \code encoder != NULL \endcode
  88032. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88033. * \retval FLAC__bool
  88034. * \c true if successful, else \c false; in this case, check the
  88035. * encoder state with FLAC__stream_encoder_get_state() to see what
  88036. * went wrong.
  88037. */
  88038. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  88039. /** Submit data for encoding.
  88040. * This version allows you to supply the input data where the channels
  88041. * are interleaved into a single array (i.e. channel0_sample0,
  88042. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  88043. * The samples need not be block-aligned but they must be
  88044. * sample-aligned, i.e. the first value should be channel0_sample0
  88045. * and the last value channelN_sampleM. Each sample should be a signed
  88046. * integer, right-justified to the resolution set by
  88047. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88048. * resolution is 16 bits per sample, the samples should all be in the
  88049. * range [-32768,32767].
  88050. *
  88051. * For applications where channel order is important, channels must
  88052. * follow the order as described in the
  88053. * <A HREF="../format.html#frame_header">frame header</A>.
  88054. *
  88055. * \param encoder An initialized encoder instance in the OK state.
  88056. * \param buffer An array of channel-interleaved data (see above).
  88057. * \param samples The number of samples in one channel, the same as for
  88058. * FLAC__stream_encoder_process(). For example, if
  88059. * encoding two channels, \c 1000 \a samples corresponds
  88060. * to a \a buffer of 2000 values.
  88061. * \assert
  88062. * \code encoder != NULL \endcode
  88063. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88064. * \retval FLAC__bool
  88065. * \c true if successful, else \c false; in this case, check the
  88066. * encoder state with FLAC__stream_encoder_get_state() to see what
  88067. * went wrong.
  88068. */
  88069. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  88070. /* \} */
  88071. #ifdef __cplusplus
  88072. }
  88073. #endif
  88074. #endif
  88075. /********* End of inlined file: stream_encoder.h *********/
  88076. #ifdef _MSC_VER
  88077. /* OPT: an MSVC built-in would be better */
  88078. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  88079. {
  88080. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  88081. return (x>>16) | (x<<16);
  88082. }
  88083. #endif
  88084. #if defined(_MSC_VER) && defined(_X86_)
  88085. /* OPT: an MSVC built-in would be better */
  88086. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  88087. {
  88088. __asm {
  88089. mov edx, start
  88090. mov ecx, len
  88091. test ecx, ecx
  88092. loop1:
  88093. jz done1
  88094. mov eax, [edx]
  88095. bswap eax
  88096. mov [edx], eax
  88097. add edx, 4
  88098. dec ecx
  88099. jmp short loop1
  88100. done1:
  88101. }
  88102. }
  88103. #endif
  88104. /** \mainpage
  88105. *
  88106. * \section intro Introduction
  88107. *
  88108. * This is the documentation for the FLAC C and C++ APIs. It is
  88109. * highly interconnected; this introduction should give you a top
  88110. * level idea of the structure and how to find the information you
  88111. * need. As a prerequisite you should have at least a basic
  88112. * knowledge of the FLAC format, documented
  88113. * <A HREF="../format.html">here</A>.
  88114. *
  88115. * \section c_api FLAC C API
  88116. *
  88117. * The FLAC C API is the interface to libFLAC, a set of structures
  88118. * describing the components of FLAC streams, and functions for
  88119. * encoding and decoding streams, as well as manipulating FLAC
  88120. * metadata in files. The public include files will be installed
  88121. * in your include area (for example /usr/include/FLAC/...).
  88122. *
  88123. * By writing a little code and linking against libFLAC, it is
  88124. * relatively easy to add FLAC support to another program. The
  88125. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  88126. * Complete source code of libFLAC as well as the command-line
  88127. * encoder and plugins is available and is a useful source of
  88128. * examples.
  88129. *
  88130. * Aside from encoders and decoders, libFLAC provides a powerful
  88131. * metadata interface for manipulating metadata in FLAC files. It
  88132. * allows the user to add, delete, and modify FLAC metadata blocks
  88133. * and it can automatically take advantage of PADDING blocks to avoid
  88134. * rewriting the entire FLAC file when changing the size of the
  88135. * metadata.
  88136. *
  88137. * libFLAC usually only requires the standard C library and C math
  88138. * library. In particular, threading is not used so there is no
  88139. * dependency on a thread library. However, libFLAC does not use
  88140. * global variables and should be thread-safe.
  88141. *
  88142. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  88143. * However the metadata editing interfaces currently have limited
  88144. * read-only support for Ogg FLAC files.
  88145. *
  88146. * \section cpp_api FLAC C++ API
  88147. *
  88148. * The FLAC C++ API is a set of classes that encapsulate the
  88149. * structures and functions in libFLAC. They provide slightly more
  88150. * functionality with respect to metadata but are otherwise
  88151. * equivalent. For the most part, they share the same usage as
  88152. * their counterparts in libFLAC, and the FLAC C API documentation
  88153. * can be used as a supplement. The public include files
  88154. * for the C++ API will be installed in your include area (for
  88155. * example /usr/include/FLAC++/...).
  88156. *
  88157. * libFLAC++ is also licensed under
  88158. * <A HREF="../license.html">Xiph's BSD license</A>.
  88159. *
  88160. * \section getting_started Getting Started
  88161. *
  88162. * A good starting point for learning the API is to browse through
  88163. * the <A HREF="modules.html">modules</A>. Modules are logical
  88164. * groupings of related functions or classes, which correspond roughly
  88165. * to header files or sections of header files. Each module includes a
  88166. * detailed description of the general usage of its functions or
  88167. * classes.
  88168. *
  88169. * From there you can go on to look at the documentation of
  88170. * individual functions. You can see different views of the individual
  88171. * functions through the links in top bar across this page.
  88172. *
  88173. * If you prefer a more hands-on approach, you can jump right to some
  88174. * <A HREF="../documentation_example_code.html">example code</A>.
  88175. *
  88176. * \section porting_guide Porting Guide
  88177. *
  88178. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  88179. * has been introduced which gives detailed instructions on how to
  88180. * port your code to newer versions of FLAC.
  88181. *
  88182. * \section embedded_developers Embedded Developers
  88183. *
  88184. * libFLAC has grown larger over time as more functionality has been
  88185. * included, but much of it may be unnecessary for a particular embedded
  88186. * implementation. Unused parts may be pruned by some simple editing of
  88187. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  88188. * metadata interface are all independent from each other.
  88189. *
  88190. * It is easiest to just describe the dependencies:
  88191. *
  88192. * - All modules depend on the \link flac_format Format \endlink module.
  88193. * - The decoders and encoders depend on the bitbuffer.
  88194. * - The decoder is independent of the encoder. The encoder uses the
  88195. * decoder because of the verify feature, but this can be removed if
  88196. * not needed.
  88197. * - Parts of the metadata interface require the stream decoder (but not
  88198. * the encoder).
  88199. * - Ogg support is selectable through the compile time macro
  88200. * \c FLAC__HAS_OGG.
  88201. *
  88202. * For example, if your application only requires the stream decoder, no
  88203. * encoder, and no metadata interface, you can remove the stream encoder
  88204. * and the metadata interface, which will greatly reduce the size of the
  88205. * library.
  88206. *
  88207. * Also, there are several places in the libFLAC code with comments marked
  88208. * with "OPT:" where a #define can be changed to enable code that might be
  88209. * faster on a specific platform. Experimenting with these can yield faster
  88210. * binaries.
  88211. */
  88212. /** \defgroup porting Porting Guide for New Versions
  88213. *
  88214. * This module describes differences in the library interfaces from
  88215. * version to version. It assists in the porting of code that uses
  88216. * the libraries to newer versions of FLAC.
  88217. *
  88218. * One simple facility for making porting easier that has been added
  88219. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  88220. * library's includes (e.g. \c include/FLAC/export.h). The
  88221. * \c #defines mirror the libraries'
  88222. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  88223. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  88224. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  88225. * These can be used to support multiple versions of an API during the
  88226. * transition phase, e.g.
  88227. *
  88228. * \code
  88229. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  88230. * legacy code
  88231. * #else
  88232. * new code
  88233. * #endif
  88234. * \endcode
  88235. *
  88236. * The the source will work for multiple versions and the legacy code can
  88237. * easily be removed when the transition is complete.
  88238. *
  88239. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  88240. * include/FLAC/export.h), which can be used to determine whether or not
  88241. * the library has been compiled with support for Ogg FLAC. This is
  88242. * simpler than trying to call an Ogg init function and catching the
  88243. * error.
  88244. */
  88245. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  88246. * \ingroup porting
  88247. *
  88248. * \brief
  88249. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  88250. *
  88251. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  88252. * been simplified. First, libOggFLAC has been merged into libFLAC and
  88253. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  88254. * decoding layers and three encoding layers have been merged into a
  88255. * single stream decoder and stream encoder. That is, the functionality
  88256. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  88257. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  88258. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  88259. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  88260. * is there is now a single API that can be used to encode or decode
  88261. * streams to/from native FLAC or Ogg FLAC and the single API can work
  88262. * on both seekable and non-seekable streams.
  88263. *
  88264. * Instead of creating an encoder or decoder of a certain layer, now the
  88265. * client will always create a FLAC__StreamEncoder or
  88266. * FLAC__StreamDecoder. The old layers are now differentiated by the
  88267. * initialization function. For example, for the decoder,
  88268. * FLAC__stream_decoder_init() has been replaced by
  88269. * FLAC__stream_decoder_init_stream(). This init function takes
  88270. * callbacks for the I/O, and the seeking callbacks are optional. This
  88271. * allows the client to use the same object for seekable and
  88272. * non-seekable streams. For decoding a FLAC file directly, the client
  88273. * can use FLAC__stream_decoder_init_file() and pass just a filename
  88274. * and fewer callbacks; most of the other callbacks are supplied
  88275. * internally. For situations where fopen()ing by filename is not
  88276. * possible (e.g. Unicode filenames on Windows) the client can instead
  88277. * open the file itself and supply the FILE* to
  88278. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  88279. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  88280. * Since the callbacks and client data are now passed to the init
  88281. * function, the FLAC__stream_decoder_set_*_callback() functions and
  88282. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  88283. * rest of the calls to the decoder are the same as before.
  88284. *
  88285. * There are counterpart init functions for Ogg FLAC, e.g.
  88286. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  88287. * and callbacks are the same as for native FLAC.
  88288. *
  88289. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  88290. * been set up like so:
  88291. *
  88292. * \code
  88293. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  88294. * if(decoder == NULL) do_something;
  88295. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  88296. * [... other settings ...]
  88297. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  88298. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  88299. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  88300. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  88301. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  88302. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  88303. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  88304. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  88305. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  88306. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  88307. * \endcode
  88308. *
  88309. * In FLAC 1.1.3 it is like this:
  88310. *
  88311. * \code
  88312. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  88313. * if(decoder == NULL) do_something;
  88314. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  88315. * [... other settings ...]
  88316. * if(FLAC__stream_decoder_init_stream(
  88317. * decoder,
  88318. * my_read_callback,
  88319. * my_seek_callback, // or NULL
  88320. * my_tell_callback, // or NULL
  88321. * my_length_callback, // or NULL
  88322. * my_eof_callback, // or NULL
  88323. * my_write_callback,
  88324. * my_metadata_callback, // or NULL
  88325. * my_error_callback,
  88326. * my_client_data
  88327. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88328. * \endcode
  88329. *
  88330. * or you could do;
  88331. *
  88332. * \code
  88333. * [...]
  88334. * FILE *file = fopen("somefile.flac","rb");
  88335. * if(file == NULL) do_somthing;
  88336. * if(FLAC__stream_decoder_init_FILE(
  88337. * decoder,
  88338. * file,
  88339. * my_write_callback,
  88340. * my_metadata_callback, // or NULL
  88341. * my_error_callback,
  88342. * my_client_data
  88343. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88344. * \endcode
  88345. *
  88346. * or just:
  88347. *
  88348. * \code
  88349. * [...]
  88350. * if(FLAC__stream_decoder_init_file(
  88351. * decoder,
  88352. * "somefile.flac",
  88353. * my_write_callback,
  88354. * my_metadata_callback, // or NULL
  88355. * my_error_callback,
  88356. * my_client_data
  88357. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88358. * \endcode
  88359. *
  88360. * Another small change to the decoder is in how it handles unparseable
  88361. * streams. Before, when the decoder found an unparseable stream
  88362. * (reserved for when the decoder encounters a stream from a future
  88363. * encoder that it can't parse), it changed the state to
  88364. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  88365. * drops sync and calls the error callback with a new error code
  88366. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  88367. * more robust. If your error callback does not discriminate on the the
  88368. * error state, your code does not need to be changed.
  88369. *
  88370. * The encoder now has a new setting:
  88371. * FLAC__stream_encoder_set_apodization(). This is for setting the
  88372. * method used to window the data before LPC analysis. You only need to
  88373. * add a call to this function if the default is not suitable. There
  88374. * are also two new convenience functions that may be useful:
  88375. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  88376. * FLAC__metadata_get_cuesheet().
  88377. *
  88378. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  88379. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  88380. * is now \c size_t instead of \c unsigned.
  88381. */
  88382. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  88383. * \ingroup porting
  88384. *
  88385. * \brief
  88386. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  88387. *
  88388. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  88389. * There was a slight change in the implementation of
  88390. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  88391. * of the \a metadata array of pointers so the client no longer needs
  88392. * to maintain it after the call. The objects themselves that are
  88393. * pointed to by the array are still not copied though and must be
  88394. * maintained until the call to FLAC__stream_encoder_finish().
  88395. */
  88396. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  88397. * \ingroup porting
  88398. *
  88399. * \brief
  88400. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  88401. *
  88402. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  88403. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  88404. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  88405. *
  88406. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  88407. * has changed to reflect the conversion of one of the reserved bits
  88408. * into active use. It used to be \c 2 and now is \c 1. However the
  88409. * FLAC frame header length has not changed, so to skip the proper
  88410. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  88411. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  88412. */
  88413. /** \defgroup flac FLAC C API
  88414. *
  88415. * The FLAC C API is the interface to libFLAC, a set of structures
  88416. * describing the components of FLAC streams, and functions for
  88417. * encoding and decoding streams, as well as manipulating FLAC
  88418. * metadata in files.
  88419. *
  88420. * You should start with the format components as all other modules
  88421. * are dependent on it.
  88422. */
  88423. #endif
  88424. /********* End of inlined file: all.h *********/
  88425. /********* Start of inlined file: bitmath.c *********/
  88426. /********* Start of inlined file: juce_FlacHeader.h *********/
  88427. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88428. // tasks..
  88429. #define VERSION "1.2.1"
  88430. #define FLAC__NO_DLL 1
  88431. #if JUCE_MSVC
  88432. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88433. #endif
  88434. #if JUCE_MAC
  88435. #define FLAC__SYS_DARWIN 1
  88436. #endif
  88437. /********* End of inlined file: juce_FlacHeader.h *********/
  88438. #if JUCE_USE_FLAC
  88439. #if HAVE_CONFIG_H
  88440. # include <config.h>
  88441. #endif
  88442. /********* Start of inlined file: bitmath.h *********/
  88443. #ifndef FLAC__PRIVATE__BITMATH_H
  88444. #define FLAC__PRIVATE__BITMATH_H
  88445. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  88446. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  88447. unsigned FLAC__bitmath_silog2(int v);
  88448. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  88449. #endif
  88450. /********* End of inlined file: bitmath.h *********/
  88451. /* An example of what FLAC__bitmath_ilog2() computes:
  88452. *
  88453. * ilog2( 0) = assertion failure
  88454. * ilog2( 1) = 0
  88455. * ilog2( 2) = 1
  88456. * ilog2( 3) = 1
  88457. * ilog2( 4) = 2
  88458. * ilog2( 5) = 2
  88459. * ilog2( 6) = 2
  88460. * ilog2( 7) = 2
  88461. * ilog2( 8) = 3
  88462. * ilog2( 9) = 3
  88463. * ilog2(10) = 3
  88464. * ilog2(11) = 3
  88465. * ilog2(12) = 3
  88466. * ilog2(13) = 3
  88467. * ilog2(14) = 3
  88468. * ilog2(15) = 3
  88469. * ilog2(16) = 4
  88470. * ilog2(17) = 4
  88471. * ilog2(18) = 4
  88472. */
  88473. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  88474. {
  88475. unsigned l = 0;
  88476. FLAC__ASSERT(v > 0);
  88477. while(v >>= 1)
  88478. l++;
  88479. return l;
  88480. }
  88481. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  88482. {
  88483. unsigned l = 0;
  88484. FLAC__ASSERT(v > 0);
  88485. while(v >>= 1)
  88486. l++;
  88487. return l;
  88488. }
  88489. /* An example of what FLAC__bitmath_silog2() computes:
  88490. *
  88491. * silog2(-10) = 5
  88492. * silog2(- 9) = 5
  88493. * silog2(- 8) = 4
  88494. * silog2(- 7) = 4
  88495. * silog2(- 6) = 4
  88496. * silog2(- 5) = 4
  88497. * silog2(- 4) = 3
  88498. * silog2(- 3) = 3
  88499. * silog2(- 2) = 2
  88500. * silog2(- 1) = 2
  88501. * silog2( 0) = 0
  88502. * silog2( 1) = 2
  88503. * silog2( 2) = 3
  88504. * silog2( 3) = 3
  88505. * silog2( 4) = 4
  88506. * silog2( 5) = 4
  88507. * silog2( 6) = 4
  88508. * silog2( 7) = 4
  88509. * silog2( 8) = 5
  88510. * silog2( 9) = 5
  88511. * silog2( 10) = 5
  88512. */
  88513. unsigned FLAC__bitmath_silog2(int v)
  88514. {
  88515. while(1) {
  88516. if(v == 0) {
  88517. return 0;
  88518. }
  88519. else if(v > 0) {
  88520. unsigned l = 0;
  88521. while(v) {
  88522. l++;
  88523. v >>= 1;
  88524. }
  88525. return l+1;
  88526. }
  88527. else if(v == -1) {
  88528. return 2;
  88529. }
  88530. else {
  88531. v++;
  88532. v = -v;
  88533. }
  88534. }
  88535. }
  88536. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  88537. {
  88538. while(1) {
  88539. if(v == 0) {
  88540. return 0;
  88541. }
  88542. else if(v > 0) {
  88543. unsigned l = 0;
  88544. while(v) {
  88545. l++;
  88546. v >>= 1;
  88547. }
  88548. return l+1;
  88549. }
  88550. else if(v == -1) {
  88551. return 2;
  88552. }
  88553. else {
  88554. v++;
  88555. v = -v;
  88556. }
  88557. }
  88558. }
  88559. #endif
  88560. /********* End of inlined file: bitmath.c *********/
  88561. /********* Start of inlined file: bitreader.c *********/
  88562. /********* Start of inlined file: juce_FlacHeader.h *********/
  88563. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88564. // tasks..
  88565. #define VERSION "1.2.1"
  88566. #define FLAC__NO_DLL 1
  88567. #if JUCE_MSVC
  88568. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88569. #endif
  88570. #if JUCE_MAC
  88571. #define FLAC__SYS_DARWIN 1
  88572. #endif
  88573. /********* End of inlined file: juce_FlacHeader.h *********/
  88574. #if JUCE_USE_FLAC
  88575. #if HAVE_CONFIG_H
  88576. # include <config.h>
  88577. #endif
  88578. #include <stdlib.h> /* for malloc() */
  88579. #include <string.h> /* for memcpy(), memset() */
  88580. #ifdef _MSC_VER
  88581. #include <winsock.h> /* for ntohl() */
  88582. #elif defined FLAC__SYS_DARWIN
  88583. #include <machine/endian.h> /* for ntohl() */
  88584. #elif defined __MINGW32__
  88585. #include <winsock.h> /* for ntohl() */
  88586. #else
  88587. #include <netinet/in.h> /* for ntohl() */
  88588. #endif
  88589. /********* Start of inlined file: bitreader.h *********/
  88590. #ifndef FLAC__PRIVATE__BITREADER_H
  88591. #define FLAC__PRIVATE__BITREADER_H
  88592. #include <stdio.h> /* for FILE */
  88593. /********* Start of inlined file: cpu.h *********/
  88594. #ifndef FLAC__PRIVATE__CPU_H
  88595. #define FLAC__PRIVATE__CPU_H
  88596. #ifdef HAVE_CONFIG_H
  88597. #include <config.h>
  88598. #endif
  88599. typedef enum {
  88600. FLAC__CPUINFO_TYPE_IA32,
  88601. FLAC__CPUINFO_TYPE_PPC,
  88602. FLAC__CPUINFO_TYPE_UNKNOWN
  88603. } FLAC__CPUInfo_Type;
  88604. typedef struct {
  88605. FLAC__bool cpuid;
  88606. FLAC__bool bswap;
  88607. FLAC__bool cmov;
  88608. FLAC__bool mmx;
  88609. FLAC__bool fxsr;
  88610. FLAC__bool sse;
  88611. FLAC__bool sse2;
  88612. FLAC__bool sse3;
  88613. FLAC__bool ssse3;
  88614. FLAC__bool _3dnow;
  88615. FLAC__bool ext3dnow;
  88616. FLAC__bool extmmx;
  88617. } FLAC__CPUInfo_IA32;
  88618. typedef struct {
  88619. FLAC__bool altivec;
  88620. FLAC__bool ppc64;
  88621. } FLAC__CPUInfo_PPC;
  88622. typedef struct {
  88623. FLAC__bool use_asm;
  88624. FLAC__CPUInfo_Type type;
  88625. union {
  88626. FLAC__CPUInfo_IA32 ia32;
  88627. FLAC__CPUInfo_PPC ppc;
  88628. } data;
  88629. } FLAC__CPUInfo;
  88630. void FLAC__cpu_info(FLAC__CPUInfo *info);
  88631. #ifndef FLAC__NO_ASM
  88632. #ifdef FLAC__CPU_IA32
  88633. #ifdef FLAC__HAS_NASM
  88634. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  88635. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  88636. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  88637. #endif
  88638. #endif
  88639. #endif
  88640. #endif
  88641. /********* End of inlined file: cpu.h *********/
  88642. /*
  88643. * opaque structure definition
  88644. */
  88645. struct FLAC__BitReader;
  88646. typedef struct FLAC__BitReader FLAC__BitReader;
  88647. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  88648. /*
  88649. * construction, deletion, initialization, etc functions
  88650. */
  88651. FLAC__BitReader *FLAC__bitreader_new(void);
  88652. void FLAC__bitreader_delete(FLAC__BitReader *br);
  88653. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  88654. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  88655. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  88656. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  88657. /*
  88658. * CRC functions
  88659. */
  88660. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  88661. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  88662. /*
  88663. * info functions
  88664. */
  88665. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  88666. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  88667. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  88668. /*
  88669. * read functions
  88670. */
  88671. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  88672. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  88673. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  88674. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  88675. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  88676. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88677. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88678. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  88679. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88680. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88681. #ifndef FLAC__NO_ASM
  88682. # ifdef FLAC__CPU_IA32
  88683. # ifdef FLAC__HAS_NASM
  88684. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88685. # endif
  88686. # endif
  88687. #endif
  88688. #if 0 /* UNUSED */
  88689. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88690. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  88691. #endif
  88692. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  88693. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  88694. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  88695. #endif
  88696. /********* End of inlined file: bitreader.h *********/
  88697. /********* Start of inlined file: crc.h *********/
  88698. #ifndef FLAC__PRIVATE__CRC_H
  88699. #define FLAC__PRIVATE__CRC_H
  88700. /* 8 bit CRC generator, MSB shifted first
  88701. ** polynomial = x^8 + x^2 + x^1 + x^0
  88702. ** init = 0
  88703. */
  88704. extern FLAC__byte const FLAC__crc8_table[256];
  88705. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  88706. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  88707. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  88708. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  88709. /* 16 bit CRC generator, MSB shifted first
  88710. ** polynomial = x^16 + x^15 + x^2 + x^0
  88711. ** init = 0
  88712. */
  88713. extern unsigned FLAC__crc16_table[256];
  88714. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  88715. /* this alternate may be faster on some systems/compilers */
  88716. #if 0
  88717. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  88718. #endif
  88719. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  88720. #endif
  88721. /********* End of inlined file: crc.h *********/
  88722. /* Things should be fastest when this matches the machine word size */
  88723. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  88724. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  88725. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  88726. typedef FLAC__uint32 brword;
  88727. #define FLAC__BYTES_PER_WORD 4
  88728. #define FLAC__BITS_PER_WORD 32
  88729. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88730. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  88731. #if WORDS_BIGENDIAN
  88732. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88733. #else
  88734. #if defined (_MSC_VER) && defined (_X86_)
  88735. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88736. #else
  88737. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88738. #endif
  88739. #endif
  88740. /* counts the # of zero MSBs in a word */
  88741. #define COUNT_ZERO_MSBS(word) ( \
  88742. (word) <= 0xffff ? \
  88743. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  88744. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  88745. )
  88746. /* this alternate might be slightly faster on some systems/compilers: */
  88747. #define COUNT_ZERO_MSBS2(word) ( (word) <= 0xff ? byte_to_unary_table[word] + 24 : ((word) <= 0xffff ? byte_to_unary_table[(word) >> 8] + 16 : ((word) <= 0xffffff ? byte_to_unary_table[(word) >> 16] + 8 : byte_to_unary_table[(word) >> 24])) )
  88748. /*
  88749. * This should be at least twice as large as the largest number of words
  88750. * required to represent any 'number' (in any encoding) you are going to
  88751. * read. With FLAC this is on the order of maybe a few hundred bits.
  88752. * If the buffer is smaller than that, the decoder won't be able to read
  88753. * in a whole number that is in a variable length encoding (e.g. Rice).
  88754. * But to be practical it should be at least 1K bytes.
  88755. *
  88756. * Increase this number to decrease the number of read callbacks, at the
  88757. * expense of using more memory. Or decrease for the reverse effect,
  88758. * keeping in mind the limit from the first paragraph. The optimal size
  88759. * also depends on the CPU cache size and other factors; some twiddling
  88760. * may be necessary to squeeze out the best performance.
  88761. */
  88762. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  88763. static const unsigned char byte_to_unary_table[] = {
  88764. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  88765. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88766. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88767. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88768. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88769. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88770. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88771. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  88780. };
  88781. #ifdef min
  88782. #undef min
  88783. #endif
  88784. #define min(x,y) ((x)<(y)?(x):(y))
  88785. #ifdef max
  88786. #undef max
  88787. #endif
  88788. #define max(x,y) ((x)>(y)?(x):(y))
  88789. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88790. #ifdef _MSC_VER
  88791. #define FLAC__U64L(x) x
  88792. #else
  88793. #define FLAC__U64L(x) x##LLU
  88794. #endif
  88795. #ifndef FLaC__INLINE
  88796. #define FLaC__INLINE
  88797. #endif
  88798. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  88799. struct FLAC__BitReader {
  88800. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  88801. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  88802. brword *buffer;
  88803. unsigned capacity; /* in words */
  88804. unsigned words; /* # of completed words in buffer */
  88805. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  88806. unsigned consumed_words; /* #words ... */
  88807. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  88808. unsigned read_crc16; /* the running frame CRC */
  88809. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  88810. FLAC__BitReaderReadCallback read_callback;
  88811. void *client_data;
  88812. FLAC__CPUInfo cpu_info;
  88813. };
  88814. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  88815. {
  88816. register unsigned crc = br->read_crc16;
  88817. #if FLAC__BYTES_PER_WORD == 4
  88818. switch(br->crc16_align) {
  88819. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  88820. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88821. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88822. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88823. }
  88824. #elif FLAC__BYTES_PER_WORD == 8
  88825. switch(br->crc16_align) {
  88826. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  88827. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  88828. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  88829. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  88830. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  88831. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88832. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88833. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88834. }
  88835. #else
  88836. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  88837. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  88838. br->read_crc16 = crc;
  88839. #endif
  88840. br->crc16_align = 0;
  88841. }
  88842. /* would be static except it needs to be called by asm routines */
  88843. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  88844. {
  88845. unsigned start, end;
  88846. size_t bytes;
  88847. FLAC__byte *target;
  88848. /* first shift the unconsumed buffer data toward the front as much as possible */
  88849. if(br->consumed_words > 0) {
  88850. start = br->consumed_words;
  88851. end = br->words + (br->bytes? 1:0);
  88852. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  88853. br->words -= start;
  88854. br->consumed_words = 0;
  88855. }
  88856. /*
  88857. * set the target for reading, taking into account word alignment and endianness
  88858. */
  88859. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  88860. if(bytes == 0)
  88861. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  88862. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  88863. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  88864. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  88865. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  88866. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  88867. * ^^-------target, bytes=3
  88868. * on LE machines, have to byteswap the odd tail word so nothing is
  88869. * overwritten:
  88870. */
  88871. #if WORDS_BIGENDIAN
  88872. #else
  88873. if(br->bytes)
  88874. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  88875. #endif
  88876. /* now it looks like:
  88877. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  88878. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  88879. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  88880. * ^^-------target, bytes=3
  88881. */
  88882. /* read in the data; note that the callback may return a smaller number of bytes */
  88883. if(!br->read_callback(target, &bytes, br->client_data))
  88884. return false;
  88885. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  88886. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88887. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88888. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  88889. * now have to byteswap on LE machines:
  88890. */
  88891. #if WORDS_BIGENDIAN
  88892. #else
  88893. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88894. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88895. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88896. start = br->words;
  88897. local_swap32_block_(br->buffer + start, end - start);
  88898. }
  88899. else
  88900. # endif
  88901. for(start = br->words; start < end; start++)
  88902. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88903. #endif
  88904. /* now it looks like:
  88905. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88906. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88907. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88908. * finally we'll update the reader values:
  88909. */
  88910. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88911. br->words = end / FLAC__BYTES_PER_WORD;
  88912. br->bytes = end % FLAC__BYTES_PER_WORD;
  88913. return true;
  88914. }
  88915. /***********************************************************************
  88916. *
  88917. * Class constructor/destructor
  88918. *
  88919. ***********************************************************************/
  88920. FLAC__BitReader *FLAC__bitreader_new(void)
  88921. {
  88922. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88923. /* calloc() implies:
  88924. memset(br, 0, sizeof(FLAC__BitReader));
  88925. br->buffer = 0;
  88926. br->capacity = 0;
  88927. br->words = br->bytes = 0;
  88928. br->consumed_words = br->consumed_bits = 0;
  88929. br->read_callback = 0;
  88930. br->client_data = 0;
  88931. */
  88932. return br;
  88933. }
  88934. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88935. {
  88936. FLAC__ASSERT(0 != br);
  88937. FLAC__bitreader_free(br);
  88938. free(br);
  88939. }
  88940. /***********************************************************************
  88941. *
  88942. * Public class methods
  88943. *
  88944. ***********************************************************************/
  88945. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88946. {
  88947. FLAC__ASSERT(0 != br);
  88948. br->words = br->bytes = 0;
  88949. br->consumed_words = br->consumed_bits = 0;
  88950. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88951. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88952. if(br->buffer == 0)
  88953. return false;
  88954. br->read_callback = rcb;
  88955. br->client_data = cd;
  88956. br->cpu_info = cpu;
  88957. return true;
  88958. }
  88959. void FLAC__bitreader_free(FLAC__BitReader *br)
  88960. {
  88961. FLAC__ASSERT(0 != br);
  88962. if(0 != br->buffer)
  88963. free(br->buffer);
  88964. br->buffer = 0;
  88965. br->capacity = 0;
  88966. br->words = br->bytes = 0;
  88967. br->consumed_words = br->consumed_bits = 0;
  88968. br->read_callback = 0;
  88969. br->client_data = 0;
  88970. }
  88971. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  88972. {
  88973. br->words = br->bytes = 0;
  88974. br->consumed_words = br->consumed_bits = 0;
  88975. return true;
  88976. }
  88977. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  88978. {
  88979. unsigned i, j;
  88980. if(br == 0) {
  88981. fprintf(out, "bitreader is NULL\n");
  88982. }
  88983. else {
  88984. fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits);
  88985. for(i = 0; i < br->words; i++) {
  88986. fprintf(out, "%08X: ", i);
  88987. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88988. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88989. fprintf(out, ".");
  88990. else
  88991. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88992. fprintf(out, "\n");
  88993. }
  88994. if(br->bytes > 0) {
  88995. fprintf(out, "%08X: ", i);
  88996. for(j = 0; j < br->bytes*8; j++)
  88997. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88998. fprintf(out, ".");
  88999. else
  89000. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  89001. fprintf(out, "\n");
  89002. }
  89003. }
  89004. }
  89005. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  89006. {
  89007. FLAC__ASSERT(0 != br);
  89008. FLAC__ASSERT(0 != br->buffer);
  89009. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89010. br->read_crc16 = (unsigned)seed;
  89011. br->crc16_align = br->consumed_bits;
  89012. }
  89013. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  89014. {
  89015. FLAC__ASSERT(0 != br);
  89016. FLAC__ASSERT(0 != br->buffer);
  89017. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89018. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  89019. /* CRC any tail bytes in a partially-consumed word */
  89020. if(br->consumed_bits) {
  89021. const brword tail = br->buffer[br->consumed_words];
  89022. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  89023. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  89024. }
  89025. return br->read_crc16;
  89026. }
  89027. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  89028. {
  89029. return ((br->consumed_bits & 7) == 0);
  89030. }
  89031. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  89032. {
  89033. return 8 - (br->consumed_bits & 7);
  89034. }
  89035. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  89036. {
  89037. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  89038. }
  89039. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  89040. {
  89041. FLAC__ASSERT(0 != br);
  89042. FLAC__ASSERT(0 != br->buffer);
  89043. FLAC__ASSERT(bits <= 32);
  89044. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  89045. FLAC__ASSERT(br->consumed_words <= br->words);
  89046. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89047. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89048. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  89049. *val = 0;
  89050. return true;
  89051. }
  89052. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  89053. if(!bitreader_read_from_client_(br))
  89054. return false;
  89055. }
  89056. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89057. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89058. if(br->consumed_bits) {
  89059. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89060. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  89061. const brword word = br->buffer[br->consumed_words];
  89062. if(bits < n) {
  89063. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  89064. br->consumed_bits += bits;
  89065. return true;
  89066. }
  89067. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  89068. bits -= n;
  89069. crc16_update_word_(br, word);
  89070. br->consumed_words++;
  89071. br->consumed_bits = 0;
  89072. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  89073. *val <<= bits;
  89074. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  89075. br->consumed_bits = bits;
  89076. }
  89077. return true;
  89078. }
  89079. else {
  89080. const brword word = br->buffer[br->consumed_words];
  89081. if(bits < FLAC__BITS_PER_WORD) {
  89082. *val = word >> (FLAC__BITS_PER_WORD-bits);
  89083. br->consumed_bits = bits;
  89084. return true;
  89085. }
  89086. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  89087. *val = word;
  89088. crc16_update_word_(br, word);
  89089. br->consumed_words++;
  89090. return true;
  89091. }
  89092. }
  89093. else {
  89094. /* in this case we're starting our read at a partial tail word;
  89095. * the reader has guaranteed that we have at least 'bits' bits
  89096. * available to read, which makes this case simpler.
  89097. */
  89098. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89099. if(br->consumed_bits) {
  89100. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89101. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  89102. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  89103. br->consumed_bits += bits;
  89104. return true;
  89105. }
  89106. else {
  89107. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  89108. br->consumed_bits += bits;
  89109. return true;
  89110. }
  89111. }
  89112. }
  89113. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  89114. {
  89115. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  89116. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  89117. return false;
  89118. /* sign-extend: */
  89119. *val <<= (32-bits);
  89120. *val >>= (32-bits);
  89121. return true;
  89122. }
  89123. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  89124. {
  89125. FLAC__uint32 hi, lo;
  89126. if(bits > 32) {
  89127. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  89128. return false;
  89129. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  89130. return false;
  89131. *val = hi;
  89132. *val <<= 32;
  89133. *val |= lo;
  89134. }
  89135. else {
  89136. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  89137. return false;
  89138. *val = lo;
  89139. }
  89140. return true;
  89141. }
  89142. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  89143. {
  89144. FLAC__uint32 x8, x32 = 0;
  89145. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89146. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  89147. return false;
  89148. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89149. return false;
  89150. x32 |= (x8 << 8);
  89151. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89152. return false;
  89153. x32 |= (x8 << 16);
  89154. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89155. return false;
  89156. x32 |= (x8 << 24);
  89157. *val = x32;
  89158. return true;
  89159. }
  89160. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  89161. {
  89162. /*
  89163. * OPT: a faster implementation is possible but probably not that useful
  89164. * since this is only called a couple of times in the metadata readers.
  89165. */
  89166. FLAC__ASSERT(0 != br);
  89167. FLAC__ASSERT(0 != br->buffer);
  89168. if(bits > 0) {
  89169. const unsigned n = br->consumed_bits & 7;
  89170. unsigned m;
  89171. FLAC__uint32 x;
  89172. if(n != 0) {
  89173. m = min(8-n, bits);
  89174. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  89175. return false;
  89176. bits -= m;
  89177. }
  89178. m = bits / 8;
  89179. if(m > 0) {
  89180. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  89181. return false;
  89182. bits %= 8;
  89183. }
  89184. if(bits > 0) {
  89185. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  89186. return false;
  89187. }
  89188. }
  89189. return true;
  89190. }
  89191. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  89192. {
  89193. FLAC__uint32 x;
  89194. FLAC__ASSERT(0 != br);
  89195. FLAC__ASSERT(0 != br->buffer);
  89196. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89197. /* step 1: skip over partial head word to get word aligned */
  89198. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89199. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89200. return false;
  89201. nvals--;
  89202. }
  89203. if(0 == nvals)
  89204. return true;
  89205. /* step 2: skip whole words in chunks */
  89206. while(nvals >= FLAC__BYTES_PER_WORD) {
  89207. if(br->consumed_words < br->words) {
  89208. br->consumed_words++;
  89209. nvals -= FLAC__BYTES_PER_WORD;
  89210. }
  89211. else if(!bitreader_read_from_client_(br))
  89212. return false;
  89213. }
  89214. /* step 3: skip any remainder from partial tail bytes */
  89215. while(nvals) {
  89216. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89217. return false;
  89218. nvals--;
  89219. }
  89220. return true;
  89221. }
  89222. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  89223. {
  89224. FLAC__uint32 x;
  89225. FLAC__ASSERT(0 != br);
  89226. FLAC__ASSERT(0 != br->buffer);
  89227. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89228. /* step 1: read from partial head word to get word aligned */
  89229. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89230. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89231. return false;
  89232. *val++ = (FLAC__byte)x;
  89233. nvals--;
  89234. }
  89235. if(0 == nvals)
  89236. return true;
  89237. /* step 2: read whole words in chunks */
  89238. while(nvals >= FLAC__BYTES_PER_WORD) {
  89239. if(br->consumed_words < br->words) {
  89240. const brword word = br->buffer[br->consumed_words++];
  89241. #if FLAC__BYTES_PER_WORD == 4
  89242. val[0] = (FLAC__byte)(word >> 24);
  89243. val[1] = (FLAC__byte)(word >> 16);
  89244. val[2] = (FLAC__byte)(word >> 8);
  89245. val[3] = (FLAC__byte)word;
  89246. #elif FLAC__BYTES_PER_WORD == 8
  89247. val[0] = (FLAC__byte)(word >> 56);
  89248. val[1] = (FLAC__byte)(word >> 48);
  89249. val[2] = (FLAC__byte)(word >> 40);
  89250. val[3] = (FLAC__byte)(word >> 32);
  89251. val[4] = (FLAC__byte)(word >> 24);
  89252. val[5] = (FLAC__byte)(word >> 16);
  89253. val[6] = (FLAC__byte)(word >> 8);
  89254. val[7] = (FLAC__byte)word;
  89255. #else
  89256. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  89257. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  89258. #endif
  89259. val += FLAC__BYTES_PER_WORD;
  89260. nvals -= FLAC__BYTES_PER_WORD;
  89261. }
  89262. else if(!bitreader_read_from_client_(br))
  89263. return false;
  89264. }
  89265. /* step 3: read any remainder from partial tail bytes */
  89266. while(nvals) {
  89267. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89268. return false;
  89269. *val++ = (FLAC__byte)x;
  89270. nvals--;
  89271. }
  89272. return true;
  89273. }
  89274. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  89275. #if 0 /* slow but readable version */
  89276. {
  89277. unsigned bit;
  89278. FLAC__ASSERT(0 != br);
  89279. FLAC__ASSERT(0 != br->buffer);
  89280. *val = 0;
  89281. while(1) {
  89282. if(!FLAC__bitreader_read_bit(br, &bit))
  89283. return false;
  89284. if(bit)
  89285. break;
  89286. else
  89287. *val++;
  89288. }
  89289. return true;
  89290. }
  89291. #else
  89292. {
  89293. unsigned i;
  89294. FLAC__ASSERT(0 != br);
  89295. FLAC__ASSERT(0 != br->buffer);
  89296. *val = 0;
  89297. while(1) {
  89298. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89299. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  89300. if(b) {
  89301. i = COUNT_ZERO_MSBS(b);
  89302. *val += i;
  89303. i++;
  89304. br->consumed_bits += i;
  89305. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  89306. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89307. br->consumed_words++;
  89308. br->consumed_bits = 0;
  89309. }
  89310. return true;
  89311. }
  89312. else {
  89313. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  89314. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89315. br->consumed_words++;
  89316. br->consumed_bits = 0;
  89317. /* didn't find stop bit yet, have to keep going... */
  89318. }
  89319. }
  89320. /* at this point we've eaten up all the whole words; have to try
  89321. * reading through any tail bytes before calling the read callback.
  89322. * this is a repeat of the above logic adjusted for the fact we
  89323. * don't have a whole word. note though if the client is feeding
  89324. * us data a byte at a time (unlikely), br->consumed_bits may not
  89325. * be zero.
  89326. */
  89327. if(br->bytes) {
  89328. const unsigned end = br->bytes * 8;
  89329. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  89330. if(b) {
  89331. i = COUNT_ZERO_MSBS(b);
  89332. *val += i;
  89333. i++;
  89334. br->consumed_bits += i;
  89335. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89336. return true;
  89337. }
  89338. else {
  89339. *val += end - br->consumed_bits;
  89340. br->consumed_bits += end;
  89341. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89342. /* didn't find stop bit yet, have to keep going... */
  89343. }
  89344. }
  89345. if(!bitreader_read_from_client_(br))
  89346. return false;
  89347. }
  89348. }
  89349. #endif
  89350. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89351. {
  89352. FLAC__uint32 lsbs = 0, msbs = 0;
  89353. unsigned uval;
  89354. FLAC__ASSERT(0 != br);
  89355. FLAC__ASSERT(0 != br->buffer);
  89356. FLAC__ASSERT(parameter <= 31);
  89357. /* read the unary MSBs and end bit */
  89358. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  89359. return false;
  89360. /* read the binary LSBs */
  89361. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  89362. return false;
  89363. /* compose the value */
  89364. uval = (msbs << parameter) | lsbs;
  89365. if(uval & 1)
  89366. *val = -((int)(uval >> 1)) - 1;
  89367. else
  89368. *val = (int)(uval >> 1);
  89369. return true;
  89370. }
  89371. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  89372. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  89373. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  89374. /* OPT: possibly faster version for use with MSVC */
  89375. #ifdef _MSC_VER
  89376. {
  89377. unsigned i;
  89378. unsigned uval = 0;
  89379. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  89380. /* try and get br->consumed_words and br->consumed_bits into register;
  89381. * must remember to flush them back to *br before calling other
  89382. * bitwriter functions that use them, and before returning */
  89383. register unsigned cwords;
  89384. register unsigned cbits;
  89385. FLAC__ASSERT(0 != br);
  89386. FLAC__ASSERT(0 != br->buffer);
  89387. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89388. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89389. FLAC__ASSERT(parameter < 32);
  89390. /* the above two asserts also guarantee that the binary part never straddles more that 2 words, so we don't have to loop to read it */
  89391. if(nvals == 0)
  89392. return true;
  89393. cbits = br->consumed_bits;
  89394. cwords = br->consumed_words;
  89395. while(1) {
  89396. /* read unary part */
  89397. while(1) {
  89398. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89399. brword b = br->buffer[cwords] << cbits;
  89400. if(b) {
  89401. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  89402. __asm {
  89403. bsr eax, b
  89404. not eax
  89405. and eax, 31
  89406. mov i, eax
  89407. }
  89408. #else
  89409. i = COUNT_ZERO_MSBS(b);
  89410. #endif
  89411. uval += i;
  89412. bits = parameter;
  89413. i++;
  89414. cbits += i;
  89415. if(cbits == FLAC__BITS_PER_WORD) {
  89416. crc16_update_word_(br, br->buffer[cwords]);
  89417. cwords++;
  89418. cbits = 0;
  89419. }
  89420. goto break1;
  89421. }
  89422. else {
  89423. uval += FLAC__BITS_PER_WORD - cbits;
  89424. crc16_update_word_(br, br->buffer[cwords]);
  89425. cwords++;
  89426. cbits = 0;
  89427. /* didn't find stop bit yet, have to keep going... */
  89428. }
  89429. }
  89430. /* at this point we've eaten up all the whole words; have to try
  89431. * reading through any tail bytes before calling the read callback.
  89432. * this is a repeat of the above logic adjusted for the fact we
  89433. * don't have a whole word. note though if the client is feeding
  89434. * us data a byte at a time (unlikely), br->consumed_bits may not
  89435. * be zero.
  89436. */
  89437. if(br->bytes) {
  89438. const unsigned end = br->bytes * 8;
  89439. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  89440. if(b) {
  89441. i = COUNT_ZERO_MSBS(b);
  89442. uval += i;
  89443. bits = parameter;
  89444. i++;
  89445. cbits += i;
  89446. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89447. goto break1;
  89448. }
  89449. else {
  89450. uval += end - cbits;
  89451. cbits += end;
  89452. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89453. /* didn't find stop bit yet, have to keep going... */
  89454. }
  89455. }
  89456. /* flush registers and read; bitreader_read_from_client_() does
  89457. * not touch br->consumed_bits at all but we still need to set
  89458. * it in case it fails and we have to return false.
  89459. */
  89460. br->consumed_bits = cbits;
  89461. br->consumed_words = cwords;
  89462. if(!bitreader_read_from_client_(br))
  89463. return false;
  89464. cwords = br->consumed_words;
  89465. }
  89466. break1:
  89467. /* read binary part */
  89468. FLAC__ASSERT(cwords <= br->words);
  89469. if(bits) {
  89470. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  89471. /* flush registers and read; bitreader_read_from_client_() does
  89472. * not touch br->consumed_bits at all but we still need to set
  89473. * it in case it fails and we have to return false.
  89474. */
  89475. br->consumed_bits = cbits;
  89476. br->consumed_words = cwords;
  89477. if(!bitreader_read_from_client_(br))
  89478. return false;
  89479. cwords = br->consumed_words;
  89480. }
  89481. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89482. if(cbits) {
  89483. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89484. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89485. const brword word = br->buffer[cwords];
  89486. if(bits < n) {
  89487. uval <<= bits;
  89488. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  89489. cbits += bits;
  89490. goto break2;
  89491. }
  89492. uval <<= n;
  89493. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89494. bits -= n;
  89495. crc16_update_word_(br, word);
  89496. cwords++;
  89497. cbits = 0;
  89498. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  89499. uval <<= bits;
  89500. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  89501. cbits = bits;
  89502. }
  89503. goto break2;
  89504. }
  89505. else {
  89506. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  89507. uval <<= bits;
  89508. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89509. cbits = bits;
  89510. goto break2;
  89511. }
  89512. }
  89513. else {
  89514. /* in this case we're starting our read at a partial tail word;
  89515. * the reader has guaranteed that we have at least 'bits' bits
  89516. * available to read, which makes this case simpler.
  89517. */
  89518. uval <<= bits;
  89519. if(cbits) {
  89520. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89521. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  89522. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  89523. cbits += bits;
  89524. goto break2;
  89525. }
  89526. else {
  89527. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89528. cbits += bits;
  89529. goto break2;
  89530. }
  89531. }
  89532. }
  89533. break2:
  89534. /* compose the value */
  89535. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89536. /* are we done? */
  89537. --nvals;
  89538. if(nvals == 0) {
  89539. br->consumed_bits = cbits;
  89540. br->consumed_words = cwords;
  89541. return true;
  89542. }
  89543. uval = 0;
  89544. ++vals;
  89545. }
  89546. }
  89547. #else
  89548. {
  89549. unsigned i;
  89550. unsigned uval = 0;
  89551. /* try and get br->consumed_words and br->consumed_bits into register;
  89552. * must remember to flush them back to *br before calling other
  89553. * bitwriter functions that use them, and before returning */
  89554. register unsigned cwords;
  89555. register unsigned cbits;
  89556. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  89557. FLAC__ASSERT(0 != br);
  89558. FLAC__ASSERT(0 != br->buffer);
  89559. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89560. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89561. FLAC__ASSERT(parameter < 32);
  89562. /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */
  89563. if(nvals == 0)
  89564. return true;
  89565. cbits = br->consumed_bits;
  89566. cwords = br->consumed_words;
  89567. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89568. while(1) {
  89569. /* read unary part */
  89570. while(1) {
  89571. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89572. brword b = br->buffer[cwords] << cbits;
  89573. if(b) {
  89574. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  89575. asm volatile (
  89576. "bsrl %1, %0;"
  89577. "notl %0;"
  89578. "andl $31, %0;"
  89579. : "=r"(i)
  89580. : "r"(b)
  89581. );
  89582. #else
  89583. i = COUNT_ZERO_MSBS(b);
  89584. #endif
  89585. uval += i;
  89586. cbits += i;
  89587. cbits++; /* skip over stop bit */
  89588. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  89589. crc16_update_word_(br, br->buffer[cwords]);
  89590. cwords++;
  89591. cbits = 0;
  89592. }
  89593. goto break1;
  89594. }
  89595. else {
  89596. uval += FLAC__BITS_PER_WORD - cbits;
  89597. crc16_update_word_(br, br->buffer[cwords]);
  89598. cwords++;
  89599. cbits = 0;
  89600. /* didn't find stop bit yet, have to keep going... */
  89601. }
  89602. }
  89603. /* at this point we've eaten up all the whole words; have to try
  89604. * reading through any tail bytes before calling the read callback.
  89605. * this is a repeat of the above logic adjusted for the fact we
  89606. * don't have a whole word. note though if the client is feeding
  89607. * us data a byte at a time (unlikely), br->consumed_bits may not
  89608. * be zero.
  89609. */
  89610. if(br->bytes) {
  89611. const unsigned end = br->bytes * 8;
  89612. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  89613. if(b) {
  89614. i = COUNT_ZERO_MSBS(b);
  89615. uval += i;
  89616. cbits += i;
  89617. cbits++; /* skip over stop bit */
  89618. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89619. goto break1;
  89620. }
  89621. else {
  89622. uval += end - cbits;
  89623. cbits += end;
  89624. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89625. /* didn't find stop bit yet, have to keep going... */
  89626. }
  89627. }
  89628. /* flush registers and read; bitreader_read_from_client_() does
  89629. * not touch br->consumed_bits at all but we still need to set
  89630. * it in case it fails and we have to return false.
  89631. */
  89632. br->consumed_bits = cbits;
  89633. br->consumed_words = cwords;
  89634. if(!bitreader_read_from_client_(br))
  89635. return false;
  89636. cwords = br->consumed_words;
  89637. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  89638. /* + uval to offset our count by the # of unary bits already
  89639. * consumed before the read, because we will add these back
  89640. * in all at once at break1
  89641. */
  89642. }
  89643. break1:
  89644. ucbits -= uval;
  89645. ucbits--; /* account for stop bit */
  89646. /* read binary part */
  89647. FLAC__ASSERT(cwords <= br->words);
  89648. if(parameter) {
  89649. while(ucbits < parameter) {
  89650. /* flush registers and read; bitreader_read_from_client_() does
  89651. * not touch br->consumed_bits at all but we still need to set
  89652. * it in case it fails and we have to return false.
  89653. */
  89654. br->consumed_bits = cbits;
  89655. br->consumed_words = cwords;
  89656. if(!bitreader_read_from_client_(br))
  89657. return false;
  89658. cwords = br->consumed_words;
  89659. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89660. }
  89661. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89662. if(cbits) {
  89663. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  89664. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89665. const brword word = br->buffer[cwords];
  89666. if(parameter < n) {
  89667. uval <<= parameter;
  89668. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  89669. cbits += parameter;
  89670. }
  89671. else {
  89672. uval <<= n;
  89673. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89674. crc16_update_word_(br, word);
  89675. cwords++;
  89676. cbits = parameter - n;
  89677. if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  89678. uval <<= cbits;
  89679. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  89680. }
  89681. }
  89682. }
  89683. else {
  89684. cbits = parameter;
  89685. uval <<= parameter;
  89686. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89687. }
  89688. }
  89689. else {
  89690. /* in this case we're starting our read at a partial tail word;
  89691. * the reader has guaranteed that we have at least 'parameter'
  89692. * bits available to read, which makes this case simpler.
  89693. */
  89694. uval <<= parameter;
  89695. if(cbits) {
  89696. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89697. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  89698. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  89699. cbits += parameter;
  89700. }
  89701. else {
  89702. cbits = parameter;
  89703. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89704. }
  89705. }
  89706. }
  89707. ucbits -= parameter;
  89708. /* compose the value */
  89709. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89710. /* are we done? */
  89711. --nvals;
  89712. if(nvals == 0) {
  89713. br->consumed_bits = cbits;
  89714. br->consumed_words = cwords;
  89715. return true;
  89716. }
  89717. uval = 0;
  89718. ++vals;
  89719. }
  89720. }
  89721. #endif
  89722. #if 0 /* UNUSED */
  89723. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89724. {
  89725. FLAC__uint32 lsbs = 0, msbs = 0;
  89726. unsigned bit, uval, k;
  89727. FLAC__ASSERT(0 != br);
  89728. FLAC__ASSERT(0 != br->buffer);
  89729. k = FLAC__bitmath_ilog2(parameter);
  89730. /* read the unary MSBs and end bit */
  89731. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89732. return false;
  89733. /* read the binary LSBs */
  89734. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89735. return false;
  89736. if(parameter == 1u<<k) {
  89737. /* compose the value */
  89738. uval = (msbs << k) | lsbs;
  89739. }
  89740. else {
  89741. unsigned d = (1 << (k+1)) - parameter;
  89742. if(lsbs >= d) {
  89743. if(!FLAC__bitreader_read_bit(br, &bit))
  89744. return false;
  89745. lsbs <<= 1;
  89746. lsbs |= bit;
  89747. lsbs -= d;
  89748. }
  89749. /* compose the value */
  89750. uval = msbs * parameter + lsbs;
  89751. }
  89752. /* unfold unsigned to signed */
  89753. if(uval & 1)
  89754. *val = -((int)(uval >> 1)) - 1;
  89755. else
  89756. *val = (int)(uval >> 1);
  89757. return true;
  89758. }
  89759. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  89760. {
  89761. FLAC__uint32 lsbs, msbs = 0;
  89762. unsigned bit, k;
  89763. FLAC__ASSERT(0 != br);
  89764. FLAC__ASSERT(0 != br->buffer);
  89765. k = FLAC__bitmath_ilog2(parameter);
  89766. /* read the unary MSBs and end bit */
  89767. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89768. return false;
  89769. /* read the binary LSBs */
  89770. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89771. return false;
  89772. if(parameter == 1u<<k) {
  89773. /* compose the value */
  89774. *val = (msbs << k) | lsbs;
  89775. }
  89776. else {
  89777. unsigned d = (1 << (k+1)) - parameter;
  89778. if(lsbs >= d) {
  89779. if(!FLAC__bitreader_read_bit(br, &bit))
  89780. return false;
  89781. lsbs <<= 1;
  89782. lsbs |= bit;
  89783. lsbs -= d;
  89784. }
  89785. /* compose the value */
  89786. *val = msbs * parameter + lsbs;
  89787. }
  89788. return true;
  89789. }
  89790. #endif /* UNUSED */
  89791. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89792. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  89793. {
  89794. FLAC__uint32 v = 0;
  89795. FLAC__uint32 x;
  89796. unsigned i;
  89797. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89798. return false;
  89799. if(raw)
  89800. raw[(*rawlen)++] = (FLAC__byte)x;
  89801. if(!(x & 0x80)) { /* 0xxxxxxx */
  89802. v = x;
  89803. i = 0;
  89804. }
  89805. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89806. v = x & 0x1F;
  89807. i = 1;
  89808. }
  89809. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89810. v = x & 0x0F;
  89811. i = 2;
  89812. }
  89813. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89814. v = x & 0x07;
  89815. i = 3;
  89816. }
  89817. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89818. v = x & 0x03;
  89819. i = 4;
  89820. }
  89821. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89822. v = x & 0x01;
  89823. i = 5;
  89824. }
  89825. else {
  89826. *val = 0xffffffff;
  89827. return true;
  89828. }
  89829. for( ; i; i--) {
  89830. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89831. return false;
  89832. if(raw)
  89833. raw[(*rawlen)++] = (FLAC__byte)x;
  89834. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89835. *val = 0xffffffff;
  89836. return true;
  89837. }
  89838. v <<= 6;
  89839. v |= (x & 0x3F);
  89840. }
  89841. *val = v;
  89842. return true;
  89843. }
  89844. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89845. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  89846. {
  89847. FLAC__uint64 v = 0;
  89848. FLAC__uint32 x;
  89849. unsigned i;
  89850. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89851. return false;
  89852. if(raw)
  89853. raw[(*rawlen)++] = (FLAC__byte)x;
  89854. if(!(x & 0x80)) { /* 0xxxxxxx */
  89855. v = x;
  89856. i = 0;
  89857. }
  89858. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89859. v = x & 0x1F;
  89860. i = 1;
  89861. }
  89862. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89863. v = x & 0x0F;
  89864. i = 2;
  89865. }
  89866. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89867. v = x & 0x07;
  89868. i = 3;
  89869. }
  89870. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89871. v = x & 0x03;
  89872. i = 4;
  89873. }
  89874. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89875. v = x & 0x01;
  89876. i = 5;
  89877. }
  89878. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  89879. v = 0;
  89880. i = 6;
  89881. }
  89882. else {
  89883. *val = FLAC__U64L(0xffffffffffffffff);
  89884. return true;
  89885. }
  89886. for( ; i; i--) {
  89887. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89888. return false;
  89889. if(raw)
  89890. raw[(*rawlen)++] = (FLAC__byte)x;
  89891. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89892. *val = FLAC__U64L(0xffffffffffffffff);
  89893. return true;
  89894. }
  89895. v <<= 6;
  89896. v |= (x & 0x3F);
  89897. }
  89898. *val = v;
  89899. return true;
  89900. }
  89901. #endif
  89902. /********* End of inlined file: bitreader.c *********/
  89903. /********* Start of inlined file: bitwriter.c *********/
  89904. /********* Start of inlined file: juce_FlacHeader.h *********/
  89905. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89906. // tasks..
  89907. #define VERSION "1.2.1"
  89908. #define FLAC__NO_DLL 1
  89909. #if JUCE_MSVC
  89910. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89911. #endif
  89912. #if JUCE_MAC
  89913. #define FLAC__SYS_DARWIN 1
  89914. #endif
  89915. /********* End of inlined file: juce_FlacHeader.h *********/
  89916. #if JUCE_USE_FLAC
  89917. #if HAVE_CONFIG_H
  89918. # include <config.h>
  89919. #endif
  89920. #include <stdlib.h> /* for malloc() */
  89921. #include <string.h> /* for memcpy(), memset() */
  89922. #ifdef _MSC_VER
  89923. #include <winsock.h> /* for ntohl() */
  89924. #elif defined FLAC__SYS_DARWIN
  89925. #include <machine/endian.h> /* for ntohl() */
  89926. #elif defined __MINGW32__
  89927. #include <winsock.h> /* for ntohl() */
  89928. #else
  89929. #include <netinet/in.h> /* for ntohl() */
  89930. #endif
  89931. #if 0 /* UNUSED */
  89932. #endif
  89933. /********* Start of inlined file: bitwriter.h *********/
  89934. #ifndef FLAC__PRIVATE__BITWRITER_H
  89935. #define FLAC__PRIVATE__BITWRITER_H
  89936. #include <stdio.h> /* for FILE */
  89937. /*
  89938. * opaque structure definition
  89939. */
  89940. struct FLAC__BitWriter;
  89941. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89942. /*
  89943. * construction, deletion, initialization, etc functions
  89944. */
  89945. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89946. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89947. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89948. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89949. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89950. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89951. /*
  89952. * CRC functions
  89953. *
  89954. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89955. */
  89956. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89957. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  89958. /*
  89959. * info functions
  89960. */
  89961. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  89962. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  89963. /*
  89964. * direct buffer access
  89965. *
  89966. * there may be no calls on the bitwriter between get and release.
  89967. * the bitwriter continues to own the returned buffer.
  89968. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  89969. */
  89970. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  89971. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  89972. /*
  89973. * write functions
  89974. */
  89975. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  89976. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  89977. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  89978. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  89979. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  89980. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  89981. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  89982. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  89983. #if 0 /* UNUSED */
  89984. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  89985. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  89986. #endif
  89987. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  89988. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  89989. #if 0 /* UNUSED */
  89990. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  89991. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  89992. #endif
  89993. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  89994. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  89995. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  89996. #endif
  89997. /********* End of inlined file: bitwriter.h *********/
  89998. /********* Start of inlined file: alloc.h *********/
  89999. #ifndef FLAC__SHARE__ALLOC_H
  90000. #define FLAC__SHARE__ALLOC_H
  90001. #if HAVE_CONFIG_H
  90002. # include <config.h>
  90003. #endif
  90004. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  90005. * before #including this file, otherwise SIZE_MAX might not be defined
  90006. */
  90007. #include <limits.h> /* for SIZE_MAX */
  90008. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  90009. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  90010. #endif
  90011. #include <stdlib.h> /* for size_t, malloc(), etc */
  90012. #ifndef SIZE_MAX
  90013. # ifndef SIZE_T_MAX
  90014. # ifdef _MSC_VER
  90015. # define SIZE_T_MAX UINT_MAX
  90016. # else
  90017. # error
  90018. # endif
  90019. # endif
  90020. # define SIZE_MAX SIZE_T_MAX
  90021. #endif
  90022. #ifndef FLaC__INLINE
  90023. #define FLaC__INLINE
  90024. #endif
  90025. /* avoid malloc()ing 0 bytes, see:
  90026. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  90027. */
  90028. static FLaC__INLINE void *safe_malloc_(size_t size)
  90029. {
  90030. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90031. if(!size)
  90032. size++;
  90033. return malloc(size);
  90034. }
  90035. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  90036. {
  90037. if(!nmemb || !size)
  90038. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90039. return calloc(nmemb, size);
  90040. }
  90041. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  90042. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  90043. {
  90044. size2 += size1;
  90045. if(size2 < size1)
  90046. return 0;
  90047. return safe_malloc_(size2);
  90048. }
  90049. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  90050. {
  90051. size2 += size1;
  90052. if(size2 < size1)
  90053. return 0;
  90054. size3 += size2;
  90055. if(size3 < size2)
  90056. return 0;
  90057. return safe_malloc_(size3);
  90058. }
  90059. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  90060. {
  90061. size2 += size1;
  90062. if(size2 < size1)
  90063. return 0;
  90064. size3 += size2;
  90065. if(size3 < size2)
  90066. return 0;
  90067. size4 += size3;
  90068. if(size4 < size3)
  90069. return 0;
  90070. return safe_malloc_(size4);
  90071. }
  90072. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  90073. #if 0
  90074. needs support for cases where sizeof(size_t) != 4
  90075. {
  90076. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  90077. if(sizeof(size_t) == 4) {
  90078. if ((double)size1 * (double)size2 < 4294967296.0)
  90079. return malloc(size1*size2);
  90080. }
  90081. return 0;
  90082. }
  90083. #else
  90084. /* better? */
  90085. {
  90086. if(!size1 || !size2)
  90087. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90088. if(size1 > SIZE_MAX / size2)
  90089. return 0;
  90090. return malloc(size1*size2);
  90091. }
  90092. #endif
  90093. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  90094. {
  90095. if(!size1 || !size2 || !size3)
  90096. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90097. if(size1 > SIZE_MAX / size2)
  90098. return 0;
  90099. size1 *= size2;
  90100. if(size1 > SIZE_MAX / size3)
  90101. return 0;
  90102. return malloc(size1*size3);
  90103. }
  90104. /* size1*size2 + size3 */
  90105. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  90106. {
  90107. if(!size1 || !size2)
  90108. return safe_malloc_(size3);
  90109. if(size1 > SIZE_MAX / size2)
  90110. return 0;
  90111. return safe_malloc_add_2op_(size1*size2, size3);
  90112. }
  90113. /* size1 * (size2 + size3) */
  90114. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  90115. {
  90116. if(!size1 || (!size2 && !size3))
  90117. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90118. size2 += size3;
  90119. if(size2 < size3)
  90120. return 0;
  90121. return safe_malloc_mul_2op_(size1, size2);
  90122. }
  90123. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  90124. {
  90125. size2 += size1;
  90126. if(size2 < size1)
  90127. return 0;
  90128. return realloc(ptr, size2);
  90129. }
  90130. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  90131. {
  90132. size2 += size1;
  90133. if(size2 < size1)
  90134. return 0;
  90135. size3 += size2;
  90136. if(size3 < size2)
  90137. return 0;
  90138. return realloc(ptr, size3);
  90139. }
  90140. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  90141. {
  90142. size2 += size1;
  90143. if(size2 < size1)
  90144. return 0;
  90145. size3 += size2;
  90146. if(size3 < size2)
  90147. return 0;
  90148. size4 += size3;
  90149. if(size4 < size3)
  90150. return 0;
  90151. return realloc(ptr, size4);
  90152. }
  90153. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  90154. {
  90155. if(!size1 || !size2)
  90156. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90157. if(size1 > SIZE_MAX / size2)
  90158. return 0;
  90159. return realloc(ptr, size1*size2);
  90160. }
  90161. /* size1 * (size2 + size3) */
  90162. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  90163. {
  90164. if(!size1 || (!size2 && !size3))
  90165. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90166. size2 += size3;
  90167. if(size2 < size3)
  90168. return 0;
  90169. return safe_realloc_mul_2op_(ptr, size1, size2);
  90170. }
  90171. #endif
  90172. /********* End of inlined file: alloc.h *********/
  90173. /* Things should be fastest when this matches the machine word size */
  90174. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  90175. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  90176. typedef FLAC__uint32 bwword;
  90177. #define FLAC__BYTES_PER_WORD 4
  90178. #define FLAC__BITS_PER_WORD 32
  90179. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90180. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  90181. #if WORDS_BIGENDIAN
  90182. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90183. #else
  90184. #ifdef _MSC_VER
  90185. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90186. #else
  90187. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90188. #endif
  90189. #endif
  90190. /*
  90191. * The default capacity here doesn't matter too much. The buffer always grows
  90192. * to hold whatever is written to it. Usually the encoder will stop adding at
  90193. * a frame or metadata block, then write that out and clear the buffer for the
  90194. * next one.
  90195. */
  90196. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  90197. /* When growing, increment 4K at a time */
  90198. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  90199. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  90200. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  90201. #ifdef min
  90202. #undef min
  90203. #endif
  90204. #define min(x,y) ((x)<(y)?(x):(y))
  90205. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90206. #ifdef _MSC_VER
  90207. #define FLAC__U64L(x) x
  90208. #else
  90209. #define FLAC__U64L(x) x##LLU
  90210. #endif
  90211. #ifndef FLaC__INLINE
  90212. #define FLaC__INLINE
  90213. #endif
  90214. struct FLAC__BitWriter {
  90215. bwword *buffer;
  90216. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  90217. unsigned capacity; /* capacity of buffer in words */
  90218. unsigned words; /* # of complete words in buffer */
  90219. unsigned bits; /* # of used bits in accum */
  90220. };
  90221. /* * WATCHOUT: The current implementation only grows the buffer. */
  90222. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  90223. {
  90224. unsigned new_capacity;
  90225. bwword *new_buffer;
  90226. FLAC__ASSERT(0 != bw);
  90227. FLAC__ASSERT(0 != bw->buffer);
  90228. /* calculate total words needed to store 'bits_to_add' additional bits */
  90229. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  90230. /* it's possible (due to pessimism in the growth estimation that
  90231. * leads to this call) that we don't actually need to grow
  90232. */
  90233. if(bw->capacity >= new_capacity)
  90234. return true;
  90235. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  90236. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  90237. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90238. /* make sure we got everything right */
  90239. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90240. FLAC__ASSERT(new_capacity > bw->capacity);
  90241. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  90242. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  90243. if(new_buffer == 0)
  90244. return false;
  90245. bw->buffer = new_buffer;
  90246. bw->capacity = new_capacity;
  90247. return true;
  90248. }
  90249. /***********************************************************************
  90250. *
  90251. * Class constructor/destructor
  90252. *
  90253. ***********************************************************************/
  90254. FLAC__BitWriter *FLAC__bitwriter_new(void)
  90255. {
  90256. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  90257. /* note that calloc() sets all members to 0 for us */
  90258. return bw;
  90259. }
  90260. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  90261. {
  90262. FLAC__ASSERT(0 != bw);
  90263. FLAC__bitwriter_free(bw);
  90264. free(bw);
  90265. }
  90266. /***********************************************************************
  90267. *
  90268. * Public class methods
  90269. *
  90270. ***********************************************************************/
  90271. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  90272. {
  90273. FLAC__ASSERT(0 != bw);
  90274. bw->words = bw->bits = 0;
  90275. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  90276. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  90277. if(bw->buffer == 0)
  90278. return false;
  90279. return true;
  90280. }
  90281. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  90282. {
  90283. FLAC__ASSERT(0 != bw);
  90284. if(0 != bw->buffer)
  90285. free(bw->buffer);
  90286. bw->buffer = 0;
  90287. bw->capacity = 0;
  90288. bw->words = bw->bits = 0;
  90289. }
  90290. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  90291. {
  90292. bw->words = bw->bits = 0;
  90293. }
  90294. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  90295. {
  90296. unsigned i, j;
  90297. if(bw == 0) {
  90298. fprintf(out, "bitwriter is NULL\n");
  90299. }
  90300. else {
  90301. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  90302. for(i = 0; i < bw->words; i++) {
  90303. fprintf(out, "%08X: ", i);
  90304. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  90305. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  90306. fprintf(out, "\n");
  90307. }
  90308. if(bw->bits > 0) {
  90309. fprintf(out, "%08X: ", i);
  90310. for(j = 0; j < bw->bits; j++)
  90311. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  90312. fprintf(out, "\n");
  90313. }
  90314. }
  90315. }
  90316. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  90317. {
  90318. const FLAC__byte *buffer;
  90319. size_t bytes;
  90320. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90321. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90322. return false;
  90323. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  90324. FLAC__bitwriter_release_buffer(bw);
  90325. return true;
  90326. }
  90327. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  90328. {
  90329. const FLAC__byte *buffer;
  90330. size_t bytes;
  90331. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90332. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90333. return false;
  90334. *crc = FLAC__crc8(buffer, bytes);
  90335. FLAC__bitwriter_release_buffer(bw);
  90336. return true;
  90337. }
  90338. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  90339. {
  90340. return ((bw->bits & 7) == 0);
  90341. }
  90342. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  90343. {
  90344. return FLAC__TOTAL_BITS(bw);
  90345. }
  90346. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  90347. {
  90348. FLAC__ASSERT((bw->bits & 7) == 0);
  90349. /* double protection */
  90350. if(bw->bits & 7)
  90351. return false;
  90352. /* if we have bits in the accumulator we have to flush those to the buffer first */
  90353. if(bw->bits) {
  90354. FLAC__ASSERT(bw->words <= bw->capacity);
  90355. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  90356. return false;
  90357. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  90358. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  90359. }
  90360. /* now we can just return what we have */
  90361. *buffer = (FLAC__byte*)bw->buffer;
  90362. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  90363. return true;
  90364. }
  90365. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  90366. {
  90367. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  90368. * get-mode' flag could be added everywhere and then cleared here
  90369. */
  90370. (void)bw;
  90371. }
  90372. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  90373. {
  90374. unsigned n;
  90375. FLAC__ASSERT(0 != bw);
  90376. FLAC__ASSERT(0 != bw->buffer);
  90377. if(bits == 0)
  90378. return true;
  90379. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90380. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90381. return false;
  90382. /* first part gets to word alignment */
  90383. if(bw->bits) {
  90384. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  90385. bw->accum <<= n;
  90386. bits -= n;
  90387. bw->bits += n;
  90388. if(bw->bits == FLAC__BITS_PER_WORD) {
  90389. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90390. bw->bits = 0;
  90391. }
  90392. else
  90393. return true;
  90394. }
  90395. /* do whole words */
  90396. while(bits >= FLAC__BITS_PER_WORD) {
  90397. bw->buffer[bw->words++] = 0;
  90398. bits -= FLAC__BITS_PER_WORD;
  90399. }
  90400. /* do any leftovers */
  90401. if(bits > 0) {
  90402. bw->accum = 0;
  90403. bw->bits = bits;
  90404. }
  90405. return true;
  90406. }
  90407. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  90408. {
  90409. register unsigned left;
  90410. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90411. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90412. FLAC__ASSERT(0 != bw);
  90413. FLAC__ASSERT(0 != bw->buffer);
  90414. FLAC__ASSERT(bits <= 32);
  90415. if(bits == 0)
  90416. return true;
  90417. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90418. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90419. return false;
  90420. left = FLAC__BITS_PER_WORD - bw->bits;
  90421. if(bits < left) {
  90422. bw->accum <<= bits;
  90423. bw->accum |= val;
  90424. bw->bits += bits;
  90425. }
  90426. else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
  90427. bw->accum <<= left;
  90428. bw->accum |= val >> (bw->bits = bits - left);
  90429. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90430. bw->accum = val;
  90431. }
  90432. else {
  90433. bw->accum = val;
  90434. bw->bits = 0;
  90435. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  90436. }
  90437. return true;
  90438. }
  90439. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  90440. {
  90441. /* zero-out unused bits */
  90442. if(bits < 32)
  90443. val &= (~(0xffffffff << bits));
  90444. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90445. }
  90446. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  90447. {
  90448. /* this could be a little faster but it's not used for much */
  90449. if(bits > 32) {
  90450. return
  90451. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  90452. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  90453. }
  90454. else
  90455. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90456. }
  90457. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  90458. {
  90459. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  90460. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  90461. return false;
  90462. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  90463. return false;
  90464. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  90465. return false;
  90466. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  90467. return false;
  90468. return true;
  90469. }
  90470. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  90471. {
  90472. unsigned i;
  90473. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  90474. for(i = 0; i < nvals; i++) {
  90475. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  90476. return false;
  90477. }
  90478. return true;
  90479. }
  90480. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  90481. {
  90482. if(val < 32)
  90483. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  90484. else
  90485. return
  90486. FLAC__bitwriter_write_zeroes(bw, val) &&
  90487. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  90488. }
  90489. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  90490. {
  90491. FLAC__uint32 uval;
  90492. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  90493. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90494. uval = (val<<1) ^ (val>>31);
  90495. return 1 + parameter + (uval >> parameter);
  90496. }
  90497. #if 0 /* UNUSED */
  90498. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  90499. {
  90500. unsigned bits, msbs, uval;
  90501. unsigned k;
  90502. FLAC__ASSERT(parameter > 0);
  90503. /* fold signed to unsigned */
  90504. if(val < 0)
  90505. uval = (unsigned)(((-(++val)) << 1) + 1);
  90506. else
  90507. uval = (unsigned)(val << 1);
  90508. k = FLAC__bitmath_ilog2(parameter);
  90509. if(parameter == 1u<<k) {
  90510. FLAC__ASSERT(k <= 30);
  90511. msbs = uval >> k;
  90512. bits = 1 + k + msbs;
  90513. }
  90514. else {
  90515. unsigned q, r, d;
  90516. d = (1 << (k+1)) - parameter;
  90517. q = uval / parameter;
  90518. r = uval - (q * parameter);
  90519. bits = 1 + q + k;
  90520. if(r >= d)
  90521. bits++;
  90522. }
  90523. return bits;
  90524. }
  90525. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  90526. {
  90527. unsigned bits, msbs;
  90528. unsigned k;
  90529. FLAC__ASSERT(parameter > 0);
  90530. k = FLAC__bitmath_ilog2(parameter);
  90531. if(parameter == 1u<<k) {
  90532. FLAC__ASSERT(k <= 30);
  90533. msbs = uval >> k;
  90534. bits = 1 + k + msbs;
  90535. }
  90536. else {
  90537. unsigned q, r, d;
  90538. d = (1 << (k+1)) - parameter;
  90539. q = uval / parameter;
  90540. r = uval - (q * parameter);
  90541. bits = 1 + q + k;
  90542. if(r >= d)
  90543. bits++;
  90544. }
  90545. return bits;
  90546. }
  90547. #endif /* UNUSED */
  90548. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  90549. {
  90550. unsigned total_bits, interesting_bits, msbs;
  90551. FLAC__uint32 uval, pattern;
  90552. FLAC__ASSERT(0 != bw);
  90553. FLAC__ASSERT(0 != bw->buffer);
  90554. FLAC__ASSERT(parameter < 8*sizeof(uval));
  90555. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90556. uval = (val<<1) ^ (val>>31);
  90557. msbs = uval >> parameter;
  90558. interesting_bits = 1 + parameter;
  90559. total_bits = interesting_bits + msbs;
  90560. pattern = 1 << parameter; /* the unary end bit */
  90561. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  90562. if(total_bits <= 32)
  90563. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  90564. else
  90565. return
  90566. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  90567. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  90568. }
  90569. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  90570. {
  90571. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  90572. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  90573. FLAC__uint32 uval;
  90574. unsigned left;
  90575. const unsigned lsbits = 1 + parameter;
  90576. unsigned msbits;
  90577. FLAC__ASSERT(0 != bw);
  90578. FLAC__ASSERT(0 != bw->buffer);
  90579. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  90580. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90581. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90582. while(nvals) {
  90583. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90584. uval = (*vals<<1) ^ (*vals>>31);
  90585. msbits = uval >> parameter;
  90586. #if 0 /* OPT: can remove this special case if it doesn't make up for the extra compare (doesn't make a statistically significant difference with msvc or gcc/x86) */
  90587. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90588. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90589. bw->bits = bw->bits + msbits + lsbits;
  90590. uval |= mask1; /* set stop bit */
  90591. uval &= mask2; /* mask off unused top bits */
  90592. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  90593. bw->accum <<= msbits;
  90594. bw->accum <<= lsbits;
  90595. bw->accum |= uval;
  90596. if(bw->bits == FLAC__BITS_PER_WORD) {
  90597. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90598. bw->bits = 0;
  90599. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  90600. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  90601. FLAC__ASSERT(bw->capacity == bw->words);
  90602. return false;
  90603. }
  90604. }
  90605. }
  90606. else {
  90607. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  90608. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90609. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90610. bw->bits = bw->bits + msbits + lsbits;
  90611. uval |= mask1; /* set stop bit */
  90612. uval &= mask2; /* mask off unused top bits */
  90613. bw->accum <<= msbits + lsbits;
  90614. bw->accum |= uval;
  90615. }
  90616. else {
  90617. #endif
  90618. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90619. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  90620. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  90621. return false;
  90622. if(msbits) {
  90623. /* first part gets to word alignment */
  90624. if(bw->bits) {
  90625. left = FLAC__BITS_PER_WORD - bw->bits;
  90626. if(msbits < left) {
  90627. bw->accum <<= msbits;
  90628. bw->bits += msbits;
  90629. goto break1;
  90630. }
  90631. else {
  90632. bw->accum <<= left;
  90633. msbits -= left;
  90634. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90635. bw->bits = 0;
  90636. }
  90637. }
  90638. /* do whole words */
  90639. while(msbits >= FLAC__BITS_PER_WORD) {
  90640. bw->buffer[bw->words++] = 0;
  90641. msbits -= FLAC__BITS_PER_WORD;
  90642. }
  90643. /* do any leftovers */
  90644. if(msbits > 0) {
  90645. bw->accum = 0;
  90646. bw->bits = msbits;
  90647. }
  90648. }
  90649. break1:
  90650. uval |= mask1; /* set stop bit */
  90651. uval &= mask2; /* mask off unused top bits */
  90652. left = FLAC__BITS_PER_WORD - bw->bits;
  90653. if(lsbits < left) {
  90654. bw->accum <<= lsbits;
  90655. bw->accum |= uval;
  90656. bw->bits += lsbits;
  90657. }
  90658. else {
  90659. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  90660. * be > lsbits (because of previous assertions) so it would have
  90661. * triggered the (lsbits<left) case above.
  90662. */
  90663. FLAC__ASSERT(bw->bits);
  90664. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  90665. bw->accum <<= left;
  90666. bw->accum |= uval >> (bw->bits = lsbits - left);
  90667. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90668. bw->accum = uval;
  90669. }
  90670. #if 1
  90671. }
  90672. #endif
  90673. vals++;
  90674. nvals--;
  90675. }
  90676. return true;
  90677. }
  90678. #if 0 /* UNUSED */
  90679. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  90680. {
  90681. unsigned total_bits, msbs, uval;
  90682. unsigned k;
  90683. FLAC__ASSERT(0 != bw);
  90684. FLAC__ASSERT(0 != bw->buffer);
  90685. FLAC__ASSERT(parameter > 0);
  90686. /* fold signed to unsigned */
  90687. if(val < 0)
  90688. uval = (unsigned)(((-(++val)) << 1) + 1);
  90689. else
  90690. uval = (unsigned)(val << 1);
  90691. k = FLAC__bitmath_ilog2(parameter);
  90692. if(parameter == 1u<<k) {
  90693. unsigned pattern;
  90694. FLAC__ASSERT(k <= 30);
  90695. msbs = uval >> k;
  90696. total_bits = 1 + k + msbs;
  90697. pattern = 1 << k; /* the unary end bit */
  90698. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90699. if(total_bits <= 32) {
  90700. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90701. return false;
  90702. }
  90703. else {
  90704. /* write the unary MSBs */
  90705. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90706. return false;
  90707. /* write the unary end bit and binary LSBs */
  90708. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90709. return false;
  90710. }
  90711. }
  90712. else {
  90713. unsigned q, r, d;
  90714. d = (1 << (k+1)) - parameter;
  90715. q = uval / parameter;
  90716. r = uval - (q * parameter);
  90717. /* write the unary MSBs */
  90718. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90719. return false;
  90720. /* write the unary end bit */
  90721. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90722. return false;
  90723. /* write the binary LSBs */
  90724. if(r >= d) {
  90725. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90726. return false;
  90727. }
  90728. else {
  90729. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90730. return false;
  90731. }
  90732. }
  90733. return true;
  90734. }
  90735. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  90736. {
  90737. unsigned total_bits, msbs;
  90738. unsigned k;
  90739. FLAC__ASSERT(0 != bw);
  90740. FLAC__ASSERT(0 != bw->buffer);
  90741. FLAC__ASSERT(parameter > 0);
  90742. k = FLAC__bitmath_ilog2(parameter);
  90743. if(parameter == 1u<<k) {
  90744. unsigned pattern;
  90745. FLAC__ASSERT(k <= 30);
  90746. msbs = uval >> k;
  90747. total_bits = 1 + k + msbs;
  90748. pattern = 1 << k; /* the unary end bit */
  90749. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90750. if(total_bits <= 32) {
  90751. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90752. return false;
  90753. }
  90754. else {
  90755. /* write the unary MSBs */
  90756. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90757. return false;
  90758. /* write the unary end bit and binary LSBs */
  90759. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90760. return false;
  90761. }
  90762. }
  90763. else {
  90764. unsigned q, r, d;
  90765. d = (1 << (k+1)) - parameter;
  90766. q = uval / parameter;
  90767. r = uval - (q * parameter);
  90768. /* write the unary MSBs */
  90769. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90770. return false;
  90771. /* write the unary end bit */
  90772. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90773. return false;
  90774. /* write the binary LSBs */
  90775. if(r >= d) {
  90776. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90777. return false;
  90778. }
  90779. else {
  90780. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90781. return false;
  90782. }
  90783. }
  90784. return true;
  90785. }
  90786. #endif /* UNUSED */
  90787. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  90788. {
  90789. FLAC__bool ok = 1;
  90790. FLAC__ASSERT(0 != bw);
  90791. FLAC__ASSERT(0 != bw->buffer);
  90792. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  90793. if(val < 0x80) {
  90794. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  90795. }
  90796. else if(val < 0x800) {
  90797. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  90798. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90799. }
  90800. else if(val < 0x10000) {
  90801. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  90802. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90803. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90804. }
  90805. else if(val < 0x200000) {
  90806. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  90807. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90808. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90809. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90810. }
  90811. else if(val < 0x4000000) {
  90812. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  90813. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90814. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90815. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90816. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90817. }
  90818. else {
  90819. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  90820. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  90821. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90822. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90823. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90824. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90825. }
  90826. return ok;
  90827. }
  90828. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90829. {
  90830. FLAC__bool ok = 1;
  90831. FLAC__ASSERT(0 != bw);
  90832. FLAC__ASSERT(0 != bw->buffer);
  90833. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90834. if(val < 0x80) {
  90835. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90836. }
  90837. else if(val < 0x800) {
  90838. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90839. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90840. }
  90841. else if(val < 0x10000) {
  90842. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90843. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90844. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90845. }
  90846. else if(val < 0x200000) {
  90847. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90848. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90849. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90850. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90851. }
  90852. else if(val < 0x4000000) {
  90853. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90854. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90855. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90856. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90857. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90858. }
  90859. else if(val < 0x80000000) {
  90860. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90861. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90862. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90863. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90864. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90865. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90866. }
  90867. else {
  90868. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90869. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90870. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90871. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90872. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90873. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90874. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90875. }
  90876. return ok;
  90877. }
  90878. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90879. {
  90880. /* 0-pad to byte boundary */
  90881. if(bw->bits & 7u)
  90882. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90883. else
  90884. return true;
  90885. }
  90886. #endif
  90887. /********* End of inlined file: bitwriter.c *********/
  90888. /********* Start of inlined file: cpu.c *********/
  90889. /********* Start of inlined file: juce_FlacHeader.h *********/
  90890. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90891. // tasks..
  90892. #define VERSION "1.2.1"
  90893. #define FLAC__NO_DLL 1
  90894. #if JUCE_MSVC
  90895. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90896. #endif
  90897. #if JUCE_MAC
  90898. #define FLAC__SYS_DARWIN 1
  90899. #endif
  90900. /********* End of inlined file: juce_FlacHeader.h *********/
  90901. #if JUCE_USE_FLAC
  90902. #if HAVE_CONFIG_H
  90903. # include <config.h>
  90904. #endif
  90905. #include <stdlib.h>
  90906. #include <stdio.h>
  90907. #if defined FLAC__CPU_IA32
  90908. # include <signal.h>
  90909. #elif defined FLAC__CPU_PPC
  90910. # if !defined FLAC__NO_ASM
  90911. # if defined FLAC__SYS_DARWIN
  90912. # include <sys/sysctl.h>
  90913. # include <mach/mach.h>
  90914. # include <mach/mach_host.h>
  90915. # include <mach/host_info.h>
  90916. # include <mach/machine.h>
  90917. # ifndef CPU_SUBTYPE_POWERPC_970
  90918. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90919. # endif
  90920. # else /* FLAC__SYS_DARWIN */
  90921. # include <signal.h>
  90922. # include <setjmp.h>
  90923. static sigjmp_buf jmpbuf;
  90924. static volatile sig_atomic_t canjump = 0;
  90925. static void sigill_handler (int sig)
  90926. {
  90927. if (!canjump) {
  90928. signal (sig, SIG_DFL);
  90929. raise (sig);
  90930. }
  90931. canjump = 0;
  90932. siglongjmp (jmpbuf, 1);
  90933. }
  90934. # endif /* FLAC__SYS_DARWIN */
  90935. # endif /* FLAC__NO_ASM */
  90936. #endif /* FLAC__CPU_PPC */
  90937. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90938. #include <sys/param.h>
  90939. #include <sys/sysctl.h>
  90940. #include <machine/cpu.h>
  90941. #endif
  90942. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90943. #include <sys/types.h>
  90944. #include <sys/sysctl.h>
  90945. #endif
  90946. #if defined(__APPLE__)
  90947. /* how to get sysctlbyname()? */
  90948. #endif
  90949. /* these are flags in EDX of CPUID AX=00000001 */
  90950. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90951. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90952. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90953. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90954. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90955. /* these are flags in ECX of CPUID AX=00000001 */
  90956. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90957. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  90958. /* these are flags in EDX of CPUID AX=80000001 */
  90959. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  90960. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  90961. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  90962. /*
  90963. * Extra stuff needed for detection of OS support for SSE on IA-32
  90964. */
  90965. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  90966. # if defined(__linux__)
  90967. /*
  90968. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  90969. * modify the return address to jump over the offending SSE instruction
  90970. * and also the operation following it that indicates the instruction
  90971. * executed successfully. In this way we use no global variables and
  90972. * stay thread-safe.
  90973. *
  90974. * 3 + 3 + 6:
  90975. * 3 bytes for "xorps xmm0,xmm0"
  90976. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  90977. * 6 bytes extra in case our estimate is wrong
  90978. * 12 bytes puts us in the NOP "landing zone"
  90979. */
  90980. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  90981. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90982. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  90983. {
  90984. (void)signal;
  90985. sc.eip += 3 + 3 + 6;
  90986. }
  90987. # else
  90988. # include <sys/ucontext.h>
  90989. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  90990. {
  90991. (void)signal, (void)si;
  90992. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  90993. }
  90994. # endif
  90995. # elif defined(_MSC_VER)
  90996. # include <windows.h>
  90997. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  90998. # ifdef USE_TRY_CATCH_FLAVOR
  90999. # else
  91000. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  91001. {
  91002. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  91003. ep->ContextRecord->Eip += 3 + 3 + 6;
  91004. return EXCEPTION_CONTINUE_EXECUTION;
  91005. }
  91006. return EXCEPTION_CONTINUE_SEARCH;
  91007. }
  91008. # endif
  91009. # endif
  91010. #endif
  91011. void FLAC__cpu_info(FLAC__CPUInfo *info)
  91012. {
  91013. /*
  91014. * IA32-specific
  91015. */
  91016. #ifdef FLAC__CPU_IA32
  91017. info->type = FLAC__CPUINFO_TYPE_IA32;
  91018. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  91019. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  91020. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  91021. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  91022. info->data.ia32.cmov = false;
  91023. info->data.ia32.mmx = false;
  91024. info->data.ia32.fxsr = false;
  91025. info->data.ia32.sse = false;
  91026. info->data.ia32.sse2 = false;
  91027. info->data.ia32.sse3 = false;
  91028. info->data.ia32.ssse3 = false;
  91029. info->data.ia32._3dnow = false;
  91030. info->data.ia32.ext3dnow = false;
  91031. info->data.ia32.extmmx = false;
  91032. if(info->data.ia32.cpuid) {
  91033. /* http://www.sandpile.org/ia32/cpuid.htm */
  91034. FLAC__uint32 flags_edx, flags_ecx;
  91035. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  91036. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  91037. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  91038. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  91039. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  91040. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  91041. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  91042. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  91043. #ifdef FLAC__USE_3DNOW
  91044. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  91045. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  91046. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  91047. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  91048. #else
  91049. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  91050. #endif
  91051. #ifdef DEBUG
  91052. fprintf(stderr, "CPU info (IA-32):\n");
  91053. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  91054. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  91055. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  91056. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  91057. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  91058. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91059. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  91060. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  91061. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  91062. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  91063. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  91064. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  91065. #endif
  91066. /*
  91067. * now have to check for OS support of SSE/SSE2
  91068. */
  91069. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  91070. #if defined FLAC__NO_SSE_OS
  91071. /* assume user knows better than us; turn it off */
  91072. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91073. #elif defined FLAC__SSE_OS
  91074. /* assume user knows better than us; leave as detected above */
  91075. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  91076. int sse = 0;
  91077. size_t len;
  91078. /* at least one of these must work: */
  91079. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  91080. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  91081. if(!sse)
  91082. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91083. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  91084. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  91085. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  91086. size_t len = sizeof(val);
  91087. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91088. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91089. else { /* double-check SSE2 */
  91090. mib[1] = CPU_SSE2;
  91091. len = sizeof(val);
  91092. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91093. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91094. }
  91095. # else
  91096. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91097. # endif
  91098. #elif defined(__linux__)
  91099. int sse = 0;
  91100. struct sigaction sigill_save;
  91101. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91102. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  91103. #else
  91104. struct sigaction sigill_sse;
  91105. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  91106. __sigemptyset(&sigill_sse.sa_mask);
  91107. sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
  91108. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  91109. #endif
  91110. {
  91111. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  91112. /* see sigill_handler_sse_os() for an explanation of the following: */
  91113. asm volatile (
  91114. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  91115. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  91116. "incl %0\n\t" /* SIGILL handler will jump over this */
  91117. /* landing zone */
  91118. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  91119. "nop\n\t"
  91120. "nop\n\t"
  91121. "nop\n\t"
  91122. "nop\n\t"
  91123. "nop\n\t"
  91124. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  91125. "nop\n\t"
  91126. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  91127. : "=r"(sse)
  91128. : "r"(sse)
  91129. );
  91130. sigaction(SIGILL, &sigill_save, NULL);
  91131. }
  91132. if(!sse)
  91133. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91134. #elif defined(_MSC_VER)
  91135. # ifdef USE_TRY_CATCH_FLAVOR
  91136. _try {
  91137. __asm {
  91138. # if _MSC_VER <= 1200
  91139. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91140. _emit 0x0F
  91141. _emit 0x57
  91142. _emit 0xC0
  91143. # else
  91144. xorps xmm0,xmm0
  91145. # endif
  91146. }
  91147. }
  91148. _except(EXCEPTION_EXECUTE_HANDLER) {
  91149. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  91150. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91151. }
  91152. # else
  91153. int sse = 0;
  91154. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  91155. /* see GCC version above for explanation */
  91156. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  91157. /* http://www.codeproject.com/cpp/gccasm.asp */
  91158. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  91159. __asm {
  91160. # if _MSC_VER <= 1200
  91161. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91162. _emit 0x0F
  91163. _emit 0x57
  91164. _emit 0xC0
  91165. # else
  91166. xorps xmm0,xmm0
  91167. # endif
  91168. inc sse
  91169. nop
  91170. nop
  91171. nop
  91172. nop
  91173. nop
  91174. nop
  91175. nop
  91176. nop
  91177. nop
  91178. }
  91179. SetUnhandledExceptionFilter(save);
  91180. if(!sse)
  91181. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91182. # endif
  91183. #else
  91184. /* no way to test, disable to be safe */
  91185. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91186. #endif
  91187. #ifdef DEBUG
  91188. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91189. #endif
  91190. }
  91191. }
  91192. #else
  91193. info->use_asm = false;
  91194. #endif
  91195. /*
  91196. * PPC-specific
  91197. */
  91198. #elif defined FLAC__CPU_PPC
  91199. info->type = FLAC__CPUINFO_TYPE_PPC;
  91200. # if !defined FLAC__NO_ASM
  91201. info->use_asm = true;
  91202. # ifdef FLAC__USE_ALTIVEC
  91203. # if defined FLAC__SYS_DARWIN
  91204. {
  91205. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  91206. size_t len = sizeof(val);
  91207. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  91208. }
  91209. {
  91210. host_basic_info_data_t hostInfo;
  91211. mach_msg_type_number_t infoCount;
  91212. infoCount = HOST_BASIC_INFO_COUNT;
  91213. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  91214. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  91215. }
  91216. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  91217. {
  91218. /* no Darwin, do it the brute-force way */
  91219. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  91220. info->data.ppc.altivec = 0;
  91221. info->data.ppc.ppc64 = 0;
  91222. signal (SIGILL, sigill_handler);
  91223. canjump = 0;
  91224. if (!sigsetjmp (jmpbuf, 1)) {
  91225. canjump = 1;
  91226. asm volatile (
  91227. "mtspr 256, %0\n\t"
  91228. "vand %%v0, %%v0, %%v0"
  91229. :
  91230. : "r" (-1)
  91231. );
  91232. info->data.ppc.altivec = 1;
  91233. }
  91234. canjump = 0;
  91235. if (!sigsetjmp (jmpbuf, 1)) {
  91236. int x = 0;
  91237. canjump = 1;
  91238. /* PPC64 hardware implements the cntlzd instruction */
  91239. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  91240. info->data.ppc.ppc64 = 1;
  91241. }
  91242. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  91243. }
  91244. # endif
  91245. # else /* !FLAC__USE_ALTIVEC */
  91246. info->data.ppc.altivec = 0;
  91247. info->data.ppc.ppc64 = 0;
  91248. # endif
  91249. # else
  91250. info->use_asm = false;
  91251. # endif
  91252. /*
  91253. * unknown CPI
  91254. */
  91255. #else
  91256. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  91257. info->use_asm = false;
  91258. #endif
  91259. }
  91260. #endif
  91261. /********* End of inlined file: cpu.c *********/
  91262. /********* Start of inlined file: crc.c *********/
  91263. /********* Start of inlined file: juce_FlacHeader.h *********/
  91264. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91265. // tasks..
  91266. #define VERSION "1.2.1"
  91267. #define FLAC__NO_DLL 1
  91268. #if JUCE_MSVC
  91269. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91270. #endif
  91271. #if JUCE_MAC
  91272. #define FLAC__SYS_DARWIN 1
  91273. #endif
  91274. /********* End of inlined file: juce_FlacHeader.h *********/
  91275. #if JUCE_USE_FLAC
  91276. #if HAVE_CONFIG_H
  91277. # include <config.h>
  91278. #endif
  91279. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  91280. FLAC__byte const FLAC__crc8_table[256] = {
  91281. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  91282. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  91283. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  91284. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  91285. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  91286. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  91287. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  91288. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  91289. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  91290. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  91291. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  91292. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  91293. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  91294. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  91295. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  91296. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  91297. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  91298. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  91299. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  91300. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  91301. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  91302. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  91303. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  91304. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  91305. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  91306. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  91307. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  91308. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  91309. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  91310. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  91311. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  91312. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  91313. };
  91314. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  91315. unsigned FLAC__crc16_table[256] = {
  91316. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  91317. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  91318. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  91319. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  91320. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  91321. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  91322. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  91323. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  91324. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  91325. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  91326. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  91327. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  91328. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  91329. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  91330. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  91331. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  91332. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  91333. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  91334. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  91335. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  91336. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  91337. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  91338. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  91339. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  91340. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  91341. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  91342. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  91343. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  91344. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  91345. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  91346. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  91347. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  91348. };
  91349. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  91350. {
  91351. *crc = FLAC__crc8_table[*crc ^ data];
  91352. }
  91353. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  91354. {
  91355. while(len--)
  91356. *crc = FLAC__crc8_table[*crc ^ *data++];
  91357. }
  91358. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  91359. {
  91360. FLAC__uint8 crc = 0;
  91361. while(len--)
  91362. crc = FLAC__crc8_table[crc ^ *data++];
  91363. return crc;
  91364. }
  91365. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  91366. {
  91367. unsigned crc = 0;
  91368. while(len--)
  91369. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  91370. return crc;
  91371. }
  91372. #endif
  91373. /********* End of inlined file: crc.c *********/
  91374. /********* Start of inlined file: fixed.c *********/
  91375. /********* Start of inlined file: juce_FlacHeader.h *********/
  91376. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91377. // tasks..
  91378. #define VERSION "1.2.1"
  91379. #define FLAC__NO_DLL 1
  91380. #if JUCE_MSVC
  91381. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91382. #endif
  91383. #if JUCE_MAC
  91384. #define FLAC__SYS_DARWIN 1
  91385. #endif
  91386. /********* End of inlined file: juce_FlacHeader.h *********/
  91387. #if JUCE_USE_FLAC
  91388. #if HAVE_CONFIG_H
  91389. # include <config.h>
  91390. #endif
  91391. #include <math.h>
  91392. #include <string.h>
  91393. /********* Start of inlined file: fixed.h *********/
  91394. #ifndef FLAC__PRIVATE__FIXED_H
  91395. #define FLAC__PRIVATE__FIXED_H
  91396. #ifdef HAVE_CONFIG_H
  91397. #include <config.h>
  91398. #endif
  91399. /********* Start of inlined file: float.h *********/
  91400. #ifndef FLAC__PRIVATE__FLOAT_H
  91401. #define FLAC__PRIVATE__FLOAT_H
  91402. #ifdef HAVE_CONFIG_H
  91403. #include <config.h>
  91404. #endif
  91405. /*
  91406. * These typedefs make it easier to ensure that integer versions of
  91407. * the library really only contain integer operations. All the code
  91408. * in libFLAC should use FLAC__float and FLAC__double in place of
  91409. * float and double, and be protected by checks of the macro
  91410. * FLAC__INTEGER_ONLY_LIBRARY.
  91411. *
  91412. * FLAC__real is the basic floating point type used in LPC analysis.
  91413. */
  91414. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91415. typedef double FLAC__double;
  91416. typedef float FLAC__float;
  91417. /*
  91418. * WATCHOUT: changing FLAC__real will change the signatures of many
  91419. * functions that have assembly language equivalents and break them.
  91420. */
  91421. typedef float FLAC__real;
  91422. #else
  91423. /*
  91424. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  91425. * for the integer part and lower 16 bits for the fractional part.
  91426. */
  91427. typedef FLAC__int32 FLAC__fixedpoint;
  91428. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  91429. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  91430. extern const FLAC__fixedpoint FLAC__FP_ONE;
  91431. extern const FLAC__fixedpoint FLAC__FP_LN2;
  91432. extern const FLAC__fixedpoint FLAC__FP_E;
  91433. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  91434. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  91435. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  91436. /*
  91437. * FLAC__fixedpoint_log2()
  91438. * --------------------------------------------------------------------
  91439. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  91440. * algorithm by Knuth for x >= 1.0
  91441. *
  91442. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  91443. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  91444. *
  91445. * 'precision' roughly limits the number of iterations that are done;
  91446. * use (unsigned)(-1) for maximum precision.
  91447. *
  91448. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  91449. * function will punt and return 0.
  91450. *
  91451. * The return value will also have 'fracbits' fractional bits.
  91452. */
  91453. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  91454. #endif
  91455. #endif
  91456. /********* End of inlined file: float.h *********/
  91457. /********* Start of inlined file: format.h *********/
  91458. #ifndef FLAC__PRIVATE__FORMAT_H
  91459. #define FLAC__PRIVATE__FORMAT_H
  91460. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  91461. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  91462. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  91463. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91464. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91465. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  91466. #endif
  91467. /********* End of inlined file: format.h *********/
  91468. /*
  91469. * FLAC__fixed_compute_best_predictor()
  91470. * --------------------------------------------------------------------
  91471. * Compute the best fixed predictor and the expected bits-per-sample
  91472. * of the residual signal for each order. The _wide() version uses
  91473. * 64-bit integers which is statistically necessary when bits-per-
  91474. * sample + log2(blocksize) > 30
  91475. *
  91476. * IN data[0,data_len-1]
  91477. * IN data_len
  91478. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  91479. */
  91480. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91481. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91482. # ifndef FLAC__NO_ASM
  91483. # ifdef FLAC__CPU_IA32
  91484. # ifdef FLAC__HAS_NASM
  91485. unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91486. # endif
  91487. # endif
  91488. # endif
  91489. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91490. #else
  91491. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91492. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91493. #endif
  91494. /*
  91495. * FLAC__fixed_compute_residual()
  91496. * --------------------------------------------------------------------
  91497. * Compute the residual signal obtained from sutracting the predicted
  91498. * signal from the original.
  91499. *
  91500. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91501. * IN data_len length of original signal
  91502. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91503. * OUT residual[0,data_len-1] residual signal
  91504. */
  91505. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  91506. /*
  91507. * FLAC__fixed_restore_signal()
  91508. * --------------------------------------------------------------------
  91509. * Restore the original signal by summing the residual and the
  91510. * predictor.
  91511. *
  91512. * IN residual[0,data_len-1] residual signal
  91513. * IN data_len length of original signal
  91514. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91515. * *** IMPORTANT: the caller must pass in the historical samples:
  91516. * IN data[-order,-1] previously-reconstructed historical samples
  91517. * OUT data[0,data_len-1] original signal
  91518. */
  91519. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  91520. #endif
  91521. /********* End of inlined file: fixed.h *********/
  91522. #ifndef M_LN2
  91523. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91524. #define M_LN2 0.69314718055994530942
  91525. #endif
  91526. #ifdef min
  91527. #undef min
  91528. #endif
  91529. #define min(x,y) ((x) < (y)? (x) : (y))
  91530. #ifdef local_abs
  91531. #undef local_abs
  91532. #endif
  91533. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  91534. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91535. /* rbps stands for residual bits per sample
  91536. *
  91537. * (ln(2) * err)
  91538. * rbps = log (-----------)
  91539. * 2 ( n )
  91540. */
  91541. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  91542. {
  91543. FLAC__uint32 rbps;
  91544. unsigned bits; /* the number of bits required to represent a number */
  91545. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91546. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91547. FLAC__ASSERT(err > 0);
  91548. FLAC__ASSERT(n > 0);
  91549. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91550. if(err <= n)
  91551. return 0;
  91552. /*
  91553. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91554. * These allow us later to know we won't lose too much precision in the
  91555. * fixed-point division (err<<fracbits)/n.
  91556. */
  91557. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  91558. err <<= fracbits;
  91559. err /= n;
  91560. /* err now holds err/n with fracbits fractional bits */
  91561. /*
  91562. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91563. * our purposes.
  91564. */
  91565. FLAC__ASSERT(err > 0);
  91566. bits = FLAC__bitmath_ilog2(err)+1;
  91567. if(bits > 16) {
  91568. err >>= (bits-16);
  91569. fracbits -= (bits-16);
  91570. }
  91571. rbps = (FLAC__uint32)err;
  91572. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91573. rbps *= FLAC__FP_LN2;
  91574. fracbits += 16;
  91575. FLAC__ASSERT(fracbits >= 0);
  91576. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91577. {
  91578. const int f = fracbits & 3;
  91579. if(f) {
  91580. rbps >>= f;
  91581. fracbits -= f;
  91582. }
  91583. }
  91584. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91585. if(rbps == 0)
  91586. return 0;
  91587. /*
  91588. * The return value must have 16 fractional bits. Since the whole part
  91589. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91590. * must be >= -3, these assertion allows us to be able to shift rbps
  91591. * left if necessary to get 16 fracbits without losing any bits of the
  91592. * whole part of rbps.
  91593. *
  91594. * There is a slight chance due to accumulated error that the whole part
  91595. * will require 6 bits, so we use 6 in the assertion. Really though as
  91596. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91597. */
  91598. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91599. FLAC__ASSERT(fracbits >= -3);
  91600. /* now shift the decimal point into place */
  91601. if(fracbits < 16)
  91602. return rbps << (16-fracbits);
  91603. else if(fracbits > 16)
  91604. return rbps >> (fracbits-16);
  91605. else
  91606. return rbps;
  91607. }
  91608. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  91609. {
  91610. FLAC__uint32 rbps;
  91611. unsigned bits; /* the number of bits required to represent a number */
  91612. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91613. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91614. FLAC__ASSERT(err > 0);
  91615. FLAC__ASSERT(n > 0);
  91616. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91617. if(err <= n)
  91618. return 0;
  91619. /*
  91620. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91621. * These allow us later to know we won't lose too much precision in the
  91622. * fixed-point division (err<<fracbits)/n.
  91623. */
  91624. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  91625. err <<= fracbits;
  91626. err /= n;
  91627. /* err now holds err/n with fracbits fractional bits */
  91628. /*
  91629. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91630. * our purposes.
  91631. */
  91632. FLAC__ASSERT(err > 0);
  91633. bits = FLAC__bitmath_ilog2_wide(err)+1;
  91634. if(bits > 16) {
  91635. err >>= (bits-16);
  91636. fracbits -= (bits-16);
  91637. }
  91638. rbps = (FLAC__uint32)err;
  91639. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91640. rbps *= FLAC__FP_LN2;
  91641. fracbits += 16;
  91642. FLAC__ASSERT(fracbits >= 0);
  91643. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91644. {
  91645. const int f = fracbits & 3;
  91646. if(f) {
  91647. rbps >>= f;
  91648. fracbits -= f;
  91649. }
  91650. }
  91651. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91652. if(rbps == 0)
  91653. return 0;
  91654. /*
  91655. * The return value must have 16 fractional bits. Since the whole part
  91656. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91657. * must be >= -3, these assertion allows us to be able to shift rbps
  91658. * left if necessary to get 16 fracbits without losing any bits of the
  91659. * whole part of rbps.
  91660. *
  91661. * There is a slight chance due to accumulated error that the whole part
  91662. * will require 6 bits, so we use 6 in the assertion. Really though as
  91663. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91664. */
  91665. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91666. FLAC__ASSERT(fracbits >= -3);
  91667. /* now shift the decimal point into place */
  91668. if(fracbits < 16)
  91669. return rbps << (16-fracbits);
  91670. else if(fracbits > 16)
  91671. return rbps >> (fracbits-16);
  91672. else
  91673. return rbps;
  91674. }
  91675. #endif
  91676. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91677. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91678. #else
  91679. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91680. #endif
  91681. {
  91682. FLAC__int32 last_error_0 = data[-1];
  91683. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91684. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91685. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91686. FLAC__int32 error, save;
  91687. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91688. unsigned i, order;
  91689. for(i = 0; i < data_len; i++) {
  91690. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91691. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91692. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91693. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91694. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91695. }
  91696. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91697. order = 0;
  91698. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91699. order = 1;
  91700. else if(total_error_2 < min(total_error_3, total_error_4))
  91701. order = 2;
  91702. else if(total_error_3 < total_error_4)
  91703. order = 3;
  91704. else
  91705. order = 4;
  91706. /* Estimate the expected number of bits per residual signal sample. */
  91707. /* 'total_error*' is linearly related to the variance of the residual */
  91708. /* signal, so we use it directly to compute E(|x|) */
  91709. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91710. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91711. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91712. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91713. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91714. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91715. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91716. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91717. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91718. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91719. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91720. #else
  91721. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  91722. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  91723. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  91724. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  91725. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  91726. #endif
  91727. return order;
  91728. }
  91729. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91730. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91731. #else
  91732. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91733. #endif
  91734. {
  91735. FLAC__int32 last_error_0 = data[-1];
  91736. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91737. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91738. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91739. FLAC__int32 error, save;
  91740. /* total_error_* are 64-bits to avoid overflow when encoding
  91741. * erratic signals when the bits-per-sample and blocksize are
  91742. * large.
  91743. */
  91744. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91745. unsigned i, order;
  91746. for(i = 0; i < data_len; i++) {
  91747. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91748. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91749. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91750. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91751. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91752. }
  91753. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91754. order = 0;
  91755. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91756. order = 1;
  91757. else if(total_error_2 < min(total_error_3, total_error_4))
  91758. order = 2;
  91759. else if(total_error_3 < total_error_4)
  91760. order = 3;
  91761. else
  91762. order = 4;
  91763. /* Estimate the expected number of bits per residual signal sample. */
  91764. /* 'total_error*' is linearly related to the variance of the residual */
  91765. /* signal, so we use it directly to compute E(|x|) */
  91766. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91767. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91768. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91769. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91770. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91771. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91772. #if defined _MSC_VER || defined __MINGW32__
  91773. /* with MSVC you have to spoon feed it the casting */
  91774. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91775. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91776. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91777. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91778. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91779. #else
  91780. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91781. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91782. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91783. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91784. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91785. #endif
  91786. #else
  91787. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  91788. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  91789. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  91790. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  91791. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  91792. #endif
  91793. return order;
  91794. }
  91795. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  91796. {
  91797. const int idata_len = (int)data_len;
  91798. int i;
  91799. switch(order) {
  91800. case 0:
  91801. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91802. memcpy(residual, data, sizeof(residual[0])*data_len);
  91803. break;
  91804. case 1:
  91805. for(i = 0; i < idata_len; i++)
  91806. residual[i] = data[i] - data[i-1];
  91807. break;
  91808. case 2:
  91809. for(i = 0; i < idata_len; i++)
  91810. #if 1 /* OPT: may be faster with some compilers on some systems */
  91811. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  91812. #else
  91813. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  91814. #endif
  91815. break;
  91816. case 3:
  91817. for(i = 0; i < idata_len; i++)
  91818. #if 1 /* OPT: may be faster with some compilers on some systems */
  91819. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  91820. #else
  91821. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  91822. #endif
  91823. break;
  91824. case 4:
  91825. for(i = 0; i < idata_len; i++)
  91826. #if 1 /* OPT: may be faster with some compilers on some systems */
  91827. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91828. #else
  91829. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91830. #endif
  91831. break;
  91832. default:
  91833. FLAC__ASSERT(0);
  91834. }
  91835. }
  91836. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91837. {
  91838. int i, idata_len = (int)data_len;
  91839. switch(order) {
  91840. case 0:
  91841. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91842. memcpy(data, residual, sizeof(residual[0])*data_len);
  91843. break;
  91844. case 1:
  91845. for(i = 0; i < idata_len; i++)
  91846. data[i] = residual[i] + data[i-1];
  91847. break;
  91848. case 2:
  91849. for(i = 0; i < idata_len; i++)
  91850. #if 1 /* OPT: may be faster with some compilers on some systems */
  91851. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91852. #else
  91853. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91854. #endif
  91855. break;
  91856. case 3:
  91857. for(i = 0; i < idata_len; i++)
  91858. #if 1 /* OPT: may be faster with some compilers on some systems */
  91859. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91860. #else
  91861. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91862. #endif
  91863. break;
  91864. case 4:
  91865. for(i = 0; i < idata_len; i++)
  91866. #if 1 /* OPT: may be faster with some compilers on some systems */
  91867. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91868. #else
  91869. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91870. #endif
  91871. break;
  91872. default:
  91873. FLAC__ASSERT(0);
  91874. }
  91875. }
  91876. #endif
  91877. /********* End of inlined file: fixed.c *********/
  91878. /********* Start of inlined file: float.c *********/
  91879. /********* Start of inlined file: juce_FlacHeader.h *********/
  91880. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91881. // tasks..
  91882. #define VERSION "1.2.1"
  91883. #define FLAC__NO_DLL 1
  91884. #if JUCE_MSVC
  91885. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91886. #endif
  91887. #if JUCE_MAC
  91888. #define FLAC__SYS_DARWIN 1
  91889. #endif
  91890. /********* End of inlined file: juce_FlacHeader.h *********/
  91891. #if JUCE_USE_FLAC
  91892. #if HAVE_CONFIG_H
  91893. # include <config.h>
  91894. #endif
  91895. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91896. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91897. #ifdef _MSC_VER
  91898. #define FLAC__U64L(x) x
  91899. #else
  91900. #define FLAC__U64L(x) x##LLU
  91901. #endif
  91902. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91903. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91904. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91905. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91906. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91907. /* Lookup tables for Knuth's logarithm algorithm */
  91908. #define LOG2_LOOKUP_PRECISION 16
  91909. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91910. {
  91911. /*
  91912. * 0 fraction bits
  91913. */
  91914. /* undefined */ 0x00000000,
  91915. /* lg(2/1) = */ 0x00000001,
  91916. /* lg(4/3) = */ 0x00000000,
  91917. /* lg(8/7) = */ 0x00000000,
  91918. /* lg(16/15) = */ 0x00000000,
  91919. /* lg(32/31) = */ 0x00000000,
  91920. /* lg(64/63) = */ 0x00000000,
  91921. /* lg(128/127) = */ 0x00000000,
  91922. /* lg(256/255) = */ 0x00000000,
  91923. /* lg(512/511) = */ 0x00000000,
  91924. /* lg(1024/1023) = */ 0x00000000,
  91925. /* lg(2048/2047) = */ 0x00000000,
  91926. /* lg(4096/4095) = */ 0x00000000,
  91927. /* lg(8192/8191) = */ 0x00000000,
  91928. /* lg(16384/16383) = */ 0x00000000,
  91929. /* lg(32768/32767) = */ 0x00000000
  91930. },
  91931. {
  91932. /*
  91933. * 4 fraction bits
  91934. */
  91935. /* undefined */ 0x00000000,
  91936. /* lg(2/1) = */ 0x00000010,
  91937. /* lg(4/3) = */ 0x00000007,
  91938. /* lg(8/7) = */ 0x00000003,
  91939. /* lg(16/15) = */ 0x00000001,
  91940. /* lg(32/31) = */ 0x00000001,
  91941. /* lg(64/63) = */ 0x00000000,
  91942. /* lg(128/127) = */ 0x00000000,
  91943. /* lg(256/255) = */ 0x00000000,
  91944. /* lg(512/511) = */ 0x00000000,
  91945. /* lg(1024/1023) = */ 0x00000000,
  91946. /* lg(2048/2047) = */ 0x00000000,
  91947. /* lg(4096/4095) = */ 0x00000000,
  91948. /* lg(8192/8191) = */ 0x00000000,
  91949. /* lg(16384/16383) = */ 0x00000000,
  91950. /* lg(32768/32767) = */ 0x00000000
  91951. },
  91952. {
  91953. /*
  91954. * 8 fraction bits
  91955. */
  91956. /* undefined */ 0x00000000,
  91957. /* lg(2/1) = */ 0x00000100,
  91958. /* lg(4/3) = */ 0x0000006a,
  91959. /* lg(8/7) = */ 0x00000031,
  91960. /* lg(16/15) = */ 0x00000018,
  91961. /* lg(32/31) = */ 0x0000000c,
  91962. /* lg(64/63) = */ 0x00000006,
  91963. /* lg(128/127) = */ 0x00000003,
  91964. /* lg(256/255) = */ 0x00000001,
  91965. /* lg(512/511) = */ 0x00000001,
  91966. /* lg(1024/1023) = */ 0x00000000,
  91967. /* lg(2048/2047) = */ 0x00000000,
  91968. /* lg(4096/4095) = */ 0x00000000,
  91969. /* lg(8192/8191) = */ 0x00000000,
  91970. /* lg(16384/16383) = */ 0x00000000,
  91971. /* lg(32768/32767) = */ 0x00000000
  91972. },
  91973. {
  91974. /*
  91975. * 12 fraction bits
  91976. */
  91977. /* undefined */ 0x00000000,
  91978. /* lg(2/1) = */ 0x00001000,
  91979. /* lg(4/3) = */ 0x000006a4,
  91980. /* lg(8/7) = */ 0x00000315,
  91981. /* lg(16/15) = */ 0x0000017d,
  91982. /* lg(32/31) = */ 0x000000bc,
  91983. /* lg(64/63) = */ 0x0000005d,
  91984. /* lg(128/127) = */ 0x0000002e,
  91985. /* lg(256/255) = */ 0x00000017,
  91986. /* lg(512/511) = */ 0x0000000c,
  91987. /* lg(1024/1023) = */ 0x00000006,
  91988. /* lg(2048/2047) = */ 0x00000003,
  91989. /* lg(4096/4095) = */ 0x00000001,
  91990. /* lg(8192/8191) = */ 0x00000001,
  91991. /* lg(16384/16383) = */ 0x00000000,
  91992. /* lg(32768/32767) = */ 0x00000000
  91993. },
  91994. {
  91995. /*
  91996. * 16 fraction bits
  91997. */
  91998. /* undefined */ 0x00000000,
  91999. /* lg(2/1) = */ 0x00010000,
  92000. /* lg(4/3) = */ 0x00006a40,
  92001. /* lg(8/7) = */ 0x00003151,
  92002. /* lg(16/15) = */ 0x000017d6,
  92003. /* lg(32/31) = */ 0x00000bba,
  92004. /* lg(64/63) = */ 0x000005d1,
  92005. /* lg(128/127) = */ 0x000002e6,
  92006. /* lg(256/255) = */ 0x00000172,
  92007. /* lg(512/511) = */ 0x000000b9,
  92008. /* lg(1024/1023) = */ 0x0000005c,
  92009. /* lg(2048/2047) = */ 0x0000002e,
  92010. /* lg(4096/4095) = */ 0x00000017,
  92011. /* lg(8192/8191) = */ 0x0000000c,
  92012. /* lg(16384/16383) = */ 0x00000006,
  92013. /* lg(32768/32767) = */ 0x00000003
  92014. },
  92015. {
  92016. /*
  92017. * 20 fraction bits
  92018. */
  92019. /* undefined */ 0x00000000,
  92020. /* lg(2/1) = */ 0x00100000,
  92021. /* lg(4/3) = */ 0x0006a3fe,
  92022. /* lg(8/7) = */ 0x00031513,
  92023. /* lg(16/15) = */ 0x00017d60,
  92024. /* lg(32/31) = */ 0x0000bb9d,
  92025. /* lg(64/63) = */ 0x00005d10,
  92026. /* lg(128/127) = */ 0x00002e59,
  92027. /* lg(256/255) = */ 0x00001721,
  92028. /* lg(512/511) = */ 0x00000b8e,
  92029. /* lg(1024/1023) = */ 0x000005c6,
  92030. /* lg(2048/2047) = */ 0x000002e3,
  92031. /* lg(4096/4095) = */ 0x00000171,
  92032. /* lg(8192/8191) = */ 0x000000b9,
  92033. /* lg(16384/16383) = */ 0x0000005c,
  92034. /* lg(32768/32767) = */ 0x0000002e
  92035. },
  92036. {
  92037. /*
  92038. * 24 fraction bits
  92039. */
  92040. /* undefined */ 0x00000000,
  92041. /* lg(2/1) = */ 0x01000000,
  92042. /* lg(4/3) = */ 0x006a3fe6,
  92043. /* lg(8/7) = */ 0x00315130,
  92044. /* lg(16/15) = */ 0x0017d605,
  92045. /* lg(32/31) = */ 0x000bb9ca,
  92046. /* lg(64/63) = */ 0x0005d0fc,
  92047. /* lg(128/127) = */ 0x0002e58f,
  92048. /* lg(256/255) = */ 0x0001720e,
  92049. /* lg(512/511) = */ 0x0000b8d8,
  92050. /* lg(1024/1023) = */ 0x00005c61,
  92051. /* lg(2048/2047) = */ 0x00002e2d,
  92052. /* lg(4096/4095) = */ 0x00001716,
  92053. /* lg(8192/8191) = */ 0x00000b8b,
  92054. /* lg(16384/16383) = */ 0x000005c5,
  92055. /* lg(32768/32767) = */ 0x000002e3
  92056. },
  92057. {
  92058. /*
  92059. * 28 fraction bits
  92060. */
  92061. /* undefined */ 0x00000000,
  92062. /* lg(2/1) = */ 0x10000000,
  92063. /* lg(4/3) = */ 0x06a3fe5c,
  92064. /* lg(8/7) = */ 0x03151301,
  92065. /* lg(16/15) = */ 0x017d6049,
  92066. /* lg(32/31) = */ 0x00bb9ca6,
  92067. /* lg(64/63) = */ 0x005d0fba,
  92068. /* lg(128/127) = */ 0x002e58f7,
  92069. /* lg(256/255) = */ 0x001720da,
  92070. /* lg(512/511) = */ 0x000b8d87,
  92071. /* lg(1024/1023) = */ 0x0005c60b,
  92072. /* lg(2048/2047) = */ 0x0002e2d7,
  92073. /* lg(4096/4095) = */ 0x00017160,
  92074. /* lg(8192/8191) = */ 0x0000b8ad,
  92075. /* lg(16384/16383) = */ 0x00005c56,
  92076. /* lg(32768/32767) = */ 0x00002e2b
  92077. }
  92078. };
  92079. #if 0
  92080. static const FLAC__uint64 log2_lookup_wide[] = {
  92081. {
  92082. /*
  92083. * 32 fraction bits
  92084. */
  92085. /* undefined */ 0x00000000,
  92086. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  92087. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  92088. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  92089. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  92090. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  92091. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  92092. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  92093. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  92094. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  92095. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  92096. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  92097. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  92098. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  92099. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  92100. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  92101. },
  92102. {
  92103. /*
  92104. * 48 fraction bits
  92105. */
  92106. /* undefined */ 0x00000000,
  92107. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  92108. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  92109. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  92110. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  92111. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  92112. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  92113. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  92114. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  92115. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  92116. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  92117. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  92118. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  92119. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  92120. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  92121. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  92122. }
  92123. };
  92124. #endif
  92125. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  92126. {
  92127. const FLAC__uint32 ONE = (1u << fracbits);
  92128. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  92129. FLAC__ASSERT(fracbits < 32);
  92130. FLAC__ASSERT((fracbits & 0x3) == 0);
  92131. if(x < ONE)
  92132. return 0;
  92133. if(precision > LOG2_LOOKUP_PRECISION)
  92134. precision = LOG2_LOOKUP_PRECISION;
  92135. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  92136. {
  92137. FLAC__uint32 y = 0;
  92138. FLAC__uint32 z = x >> 1, k = 1;
  92139. while (x > ONE && k < precision) {
  92140. if (x - z >= ONE) {
  92141. x -= z;
  92142. z = x >> k;
  92143. y += table[k];
  92144. }
  92145. else {
  92146. z >>= 1;
  92147. k++;
  92148. }
  92149. }
  92150. return y;
  92151. }
  92152. }
  92153. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92154. #endif
  92155. /********* End of inlined file: float.c *********/
  92156. /********* Start of inlined file: format.c *********/
  92157. /********* Start of inlined file: juce_FlacHeader.h *********/
  92158. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92159. // tasks..
  92160. #define VERSION "1.2.1"
  92161. #define FLAC__NO_DLL 1
  92162. #if JUCE_MSVC
  92163. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92164. #endif
  92165. #if JUCE_MAC
  92166. #define FLAC__SYS_DARWIN 1
  92167. #endif
  92168. /********* End of inlined file: juce_FlacHeader.h *********/
  92169. #if JUCE_USE_FLAC
  92170. #if HAVE_CONFIG_H
  92171. # include <config.h>
  92172. #endif
  92173. #include <stdio.h>
  92174. #include <stdlib.h> /* for qsort() */
  92175. #include <string.h> /* for memset() */
  92176. #ifndef FLaC__INLINE
  92177. #define FLaC__INLINE
  92178. #endif
  92179. #ifdef min
  92180. #undef min
  92181. #endif
  92182. #define min(a,b) ((a)<(b)?(a):(b))
  92183. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92184. #ifdef _MSC_VER
  92185. #define FLAC__U64L(x) x
  92186. #else
  92187. #define FLAC__U64L(x) x##LLU
  92188. #endif
  92189. /* VERSION should come from configure */
  92190. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92191. ;
  92192. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92193. /* yet one more hack because of MSVC6: */
  92194. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92195. #else
  92196. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92197. #endif
  92198. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92199. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92200. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92201. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92202. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92203. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92204. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92205. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92206. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92207. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92208. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92209. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92210. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92211. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92212. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92213. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92214. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92215. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92216. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92217. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92218. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92219. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92220. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92221. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92222. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92223. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92224. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92225. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92226. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92227. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  92228. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  92229. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  92230. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  92231. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  92232. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  92233. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  92234. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  92235. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  92236. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  92237. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  92238. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  92239. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  92240. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  92241. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  92242. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  92243. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  92244. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  92245. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  92246. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  92247. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  92248. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  92249. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  92250. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  92251. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  92252. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  92253. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  92254. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  92255. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  92256. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  92257. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  92258. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  92259. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  92260. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  92261. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  92262. "PARTITIONED_RICE",
  92263. "PARTITIONED_RICE2"
  92264. };
  92265. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  92266. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  92267. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  92268. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  92269. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  92270. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  92271. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  92272. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  92273. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  92274. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  92275. "CONSTANT",
  92276. "VERBATIM",
  92277. "FIXED",
  92278. "LPC"
  92279. };
  92280. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  92281. "INDEPENDENT",
  92282. "LEFT_SIDE",
  92283. "RIGHT_SIDE",
  92284. "MID_SIDE"
  92285. };
  92286. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  92287. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  92288. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  92289. };
  92290. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  92291. "STREAMINFO",
  92292. "PADDING",
  92293. "APPLICATION",
  92294. "SEEKTABLE",
  92295. "VORBIS_COMMENT",
  92296. "CUESHEET",
  92297. "PICTURE"
  92298. };
  92299. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  92300. "Other",
  92301. "32x32 pixels 'file icon' (PNG only)",
  92302. "Other file icon",
  92303. "Cover (front)",
  92304. "Cover (back)",
  92305. "Leaflet page",
  92306. "Media (e.g. label side of CD)",
  92307. "Lead artist/lead performer/soloist",
  92308. "Artist/performer",
  92309. "Conductor",
  92310. "Band/Orchestra",
  92311. "Composer",
  92312. "Lyricist/text writer",
  92313. "Recording Location",
  92314. "During recording",
  92315. "During performance",
  92316. "Movie/video screen capture",
  92317. "A bright coloured fish",
  92318. "Illustration",
  92319. "Band/artist logotype",
  92320. "Publisher/Studio logotype"
  92321. };
  92322. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  92323. {
  92324. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  92325. return false;
  92326. }
  92327. else
  92328. return true;
  92329. }
  92330. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  92331. {
  92332. if(
  92333. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  92334. (
  92335. sample_rate >= (1u << 16) &&
  92336. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  92337. )
  92338. ) {
  92339. return false;
  92340. }
  92341. else
  92342. return true;
  92343. }
  92344. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92345. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  92346. {
  92347. unsigned i;
  92348. FLAC__uint64 prev_sample_number = 0;
  92349. FLAC__bool got_prev = false;
  92350. FLAC__ASSERT(0 != seek_table);
  92351. for(i = 0; i < seek_table->num_points; i++) {
  92352. if(got_prev) {
  92353. if(
  92354. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  92355. seek_table->points[i].sample_number <= prev_sample_number
  92356. )
  92357. return false;
  92358. }
  92359. prev_sample_number = seek_table->points[i].sample_number;
  92360. got_prev = true;
  92361. }
  92362. return true;
  92363. }
  92364. /* used as the sort predicate for qsort() */
  92365. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  92366. {
  92367. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  92368. if(l->sample_number == r->sample_number)
  92369. return 0;
  92370. else if(l->sample_number < r->sample_number)
  92371. return -1;
  92372. else
  92373. return 1;
  92374. }
  92375. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92376. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  92377. {
  92378. unsigned i, j;
  92379. FLAC__bool first;
  92380. FLAC__ASSERT(0 != seek_table);
  92381. /* sort the seekpoints */
  92382. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  92383. /* uniquify the seekpoints */
  92384. first = true;
  92385. for(i = j = 0; i < seek_table->num_points; i++) {
  92386. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  92387. if(!first) {
  92388. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  92389. continue;
  92390. }
  92391. }
  92392. first = false;
  92393. seek_table->points[j++] = seek_table->points[i];
  92394. }
  92395. for(i = j; i < seek_table->num_points; i++) {
  92396. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  92397. seek_table->points[i].stream_offset = 0;
  92398. seek_table->points[i].frame_samples = 0;
  92399. }
  92400. return j;
  92401. }
  92402. /*
  92403. * also disallows non-shortest-form encodings, c.f.
  92404. * http://www.unicode.org/versions/corrigendum1.html
  92405. * and a more clear explanation at the end of this section:
  92406. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  92407. */
  92408. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  92409. {
  92410. FLAC__ASSERT(0 != utf8);
  92411. if ((utf8[0] & 0x80) == 0) {
  92412. return 1;
  92413. }
  92414. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  92415. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  92416. return 0;
  92417. return 2;
  92418. }
  92419. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  92420. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  92421. return 0;
  92422. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  92423. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  92424. return 0;
  92425. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  92426. return 0;
  92427. return 3;
  92428. }
  92429. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  92430. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  92431. return 0;
  92432. return 4;
  92433. }
  92434. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  92435. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  92436. return 0;
  92437. return 5;
  92438. }
  92439. else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) {
  92440. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  92441. return 0;
  92442. return 6;
  92443. }
  92444. else {
  92445. return 0;
  92446. }
  92447. }
  92448. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  92449. {
  92450. char c;
  92451. for(c = *name; c; c = *(++name))
  92452. if(c < 0x20 || c == 0x3d || c > 0x7d)
  92453. return false;
  92454. return true;
  92455. }
  92456. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  92457. {
  92458. if(length == (unsigned)(-1)) {
  92459. while(*value) {
  92460. unsigned n = utf8len_(value);
  92461. if(n == 0)
  92462. return false;
  92463. value += n;
  92464. }
  92465. }
  92466. else {
  92467. const FLAC__byte *end = value + length;
  92468. while(value < end) {
  92469. unsigned n = utf8len_(value);
  92470. if(n == 0)
  92471. return false;
  92472. value += n;
  92473. }
  92474. if(value != end)
  92475. return false;
  92476. }
  92477. return true;
  92478. }
  92479. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  92480. {
  92481. const FLAC__byte *s, *end;
  92482. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  92483. if(*s < 0x20 || *s > 0x7D)
  92484. return false;
  92485. }
  92486. if(s == end)
  92487. return false;
  92488. s++; /* skip '=' */
  92489. while(s < end) {
  92490. unsigned n = utf8len_(s);
  92491. if(n == 0)
  92492. return false;
  92493. s += n;
  92494. }
  92495. if(s != end)
  92496. return false;
  92497. return true;
  92498. }
  92499. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92500. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  92501. {
  92502. unsigned i, j;
  92503. if(check_cd_da_subset) {
  92504. if(cue_sheet->lead_in < 2 * 44100) {
  92505. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  92506. return false;
  92507. }
  92508. if(cue_sheet->lead_in % 588 != 0) {
  92509. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  92510. return false;
  92511. }
  92512. }
  92513. if(cue_sheet->num_tracks == 0) {
  92514. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  92515. return false;
  92516. }
  92517. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  92518. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  92519. return false;
  92520. }
  92521. for(i = 0; i < cue_sheet->num_tracks; i++) {
  92522. if(cue_sheet->tracks[i].number == 0) {
  92523. if(violation) *violation = "cue sheet may not have a track number 0";
  92524. return false;
  92525. }
  92526. if(check_cd_da_subset) {
  92527. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  92528. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  92529. return false;
  92530. }
  92531. }
  92532. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  92533. if(violation) {
  92534. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  92535. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  92536. else
  92537. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  92538. }
  92539. return false;
  92540. }
  92541. if(i < cue_sheet->num_tracks - 1) {
  92542. if(cue_sheet->tracks[i].num_indices == 0) {
  92543. if(violation) *violation = "cue sheet track must have at least one index point";
  92544. return false;
  92545. }
  92546. if(cue_sheet->tracks[i].indices[0].number > 1) {
  92547. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  92548. return false;
  92549. }
  92550. }
  92551. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  92552. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  92553. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  92554. return false;
  92555. }
  92556. if(j > 0) {
  92557. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  92558. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  92559. return false;
  92560. }
  92561. }
  92562. }
  92563. }
  92564. return true;
  92565. }
  92566. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92567. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  92568. {
  92569. char *p;
  92570. FLAC__byte *b;
  92571. for(p = picture->mime_type; *p; p++) {
  92572. if(*p < 0x20 || *p > 0x7e) {
  92573. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  92574. return false;
  92575. }
  92576. }
  92577. for(b = picture->description; *b; ) {
  92578. unsigned n = utf8len_(b);
  92579. if(n == 0) {
  92580. if(violation) *violation = "description string must be valid UTF-8";
  92581. return false;
  92582. }
  92583. b += n;
  92584. }
  92585. return true;
  92586. }
  92587. /*
  92588. * These routines are private to libFLAC
  92589. */
  92590. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  92591. {
  92592. return
  92593. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  92594. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  92595. blocksize,
  92596. predictor_order
  92597. );
  92598. }
  92599. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  92600. {
  92601. unsigned max_rice_partition_order = 0;
  92602. while(!(blocksize & 1)) {
  92603. max_rice_partition_order++;
  92604. blocksize >>= 1;
  92605. }
  92606. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  92607. }
  92608. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  92609. {
  92610. unsigned max_rice_partition_order = limit;
  92611. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  92612. max_rice_partition_order--;
  92613. FLAC__ASSERT(
  92614. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  92615. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  92616. );
  92617. return max_rice_partition_order;
  92618. }
  92619. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92620. {
  92621. FLAC__ASSERT(0 != object);
  92622. object->parameters = 0;
  92623. object->raw_bits = 0;
  92624. object->capacity_by_order = 0;
  92625. }
  92626. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92627. {
  92628. FLAC__ASSERT(0 != object);
  92629. if(0 != object->parameters)
  92630. free(object->parameters);
  92631. if(0 != object->raw_bits)
  92632. free(object->raw_bits);
  92633. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  92634. }
  92635. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  92636. {
  92637. FLAC__ASSERT(0 != object);
  92638. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  92639. if(object->capacity_by_order < max_partition_order) {
  92640. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  92641. return false;
  92642. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  92643. return false;
  92644. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  92645. object->capacity_by_order = max_partition_order;
  92646. }
  92647. return true;
  92648. }
  92649. #endif
  92650. /********* End of inlined file: format.c *********/
  92651. /********* Start of inlined file: lpc_flac.c *********/
  92652. /********* Start of inlined file: juce_FlacHeader.h *********/
  92653. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92654. // tasks..
  92655. #define VERSION "1.2.1"
  92656. #define FLAC__NO_DLL 1
  92657. #if JUCE_MSVC
  92658. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92659. #endif
  92660. #if JUCE_MAC
  92661. #define FLAC__SYS_DARWIN 1
  92662. #endif
  92663. /********* End of inlined file: juce_FlacHeader.h *********/
  92664. #if JUCE_USE_FLAC
  92665. #if HAVE_CONFIG_H
  92666. # include <config.h>
  92667. #endif
  92668. #include <math.h>
  92669. /********* Start of inlined file: lpc.h *********/
  92670. #ifndef FLAC__PRIVATE__LPC_H
  92671. #define FLAC__PRIVATE__LPC_H
  92672. #ifdef HAVE_CONFIG_H
  92673. #include <config.h>
  92674. #endif
  92675. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92676. /*
  92677. * FLAC__lpc_window_data()
  92678. * --------------------------------------------------------------------
  92679. * Applies the given window to the data.
  92680. * OPT: asm implementation
  92681. *
  92682. * IN in[0,data_len-1]
  92683. * IN window[0,data_len-1]
  92684. * OUT out[0,lag-1]
  92685. * IN data_len
  92686. */
  92687. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  92688. /*
  92689. * FLAC__lpc_compute_autocorrelation()
  92690. * --------------------------------------------------------------------
  92691. * Compute the autocorrelation for lags between 0 and lag-1.
  92692. * Assumes data[] outside of [0,data_len-1] == 0.
  92693. * Asserts that lag > 0.
  92694. *
  92695. * IN data[0,data_len-1]
  92696. * IN data_len
  92697. * IN 0 < lag <= data_len
  92698. * OUT autoc[0,lag-1]
  92699. */
  92700. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92701. #ifndef FLAC__NO_ASM
  92702. # ifdef FLAC__CPU_IA32
  92703. # ifdef FLAC__HAS_NASM
  92704. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92705. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92706. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92707. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92708. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92709. # endif
  92710. # endif
  92711. #endif
  92712. /*
  92713. * FLAC__lpc_compute_lp_coefficients()
  92714. * --------------------------------------------------------------------
  92715. * Computes LP coefficients for orders 1..max_order.
  92716. * Do not call if autoc[0] == 0.0. This means the signal is zero
  92717. * and there is no point in calculating a predictor.
  92718. *
  92719. * IN autoc[0,max_order] autocorrelation values
  92720. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  92721. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  92722. * *** IMPORTANT:
  92723. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  92724. * OUT error[0,max_order-1] error for each order (more
  92725. * specifically, the variance of
  92726. * the error signal times # of
  92727. * samples in the signal)
  92728. *
  92729. * Example: if max_order is 9, the LP coefficients for order 9 will be
  92730. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  92731. * in lp_coeff[7][0,7], etc.
  92732. */
  92733. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  92734. /*
  92735. * FLAC__lpc_quantize_coefficients()
  92736. * --------------------------------------------------------------------
  92737. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  92738. * must be less than 32 (sizeof(FLAC__int32)*8).
  92739. *
  92740. * IN lp_coeff[0,order-1] LP coefficients
  92741. * IN order LP order
  92742. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  92743. * desired precision (in bits, including sign
  92744. * bit) of largest coefficient
  92745. * OUT qlp_coeff[0,order-1] quantized coefficients
  92746. * OUT shift # of bits to shift right to get approximated
  92747. * LP coefficients. NOTE: could be negative.
  92748. * RETURN 0 => quantization OK
  92749. * 1 => coefficients require too much shifting for *shift to
  92750. * fit in the LPC subframe header. 'shift' is unset.
  92751. * 2 => coefficients are all zero, which is bad. 'shift' is
  92752. * unset.
  92753. */
  92754. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  92755. /*
  92756. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  92757. * --------------------------------------------------------------------
  92758. * Compute the residual signal obtained from sutracting the predicted
  92759. * signal from the original.
  92760. *
  92761. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92762. * IN data_len length of original signal
  92763. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92764. * IN order > 0 LP order
  92765. * IN lp_quantization quantization of LP coefficients in bits
  92766. * OUT residual[0,data_len-1] residual signal
  92767. */
  92768. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92769. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92770. #ifndef FLAC__NO_ASM
  92771. # ifdef FLAC__CPU_IA32
  92772. # ifdef FLAC__HAS_NASM
  92773. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92774. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92775. # endif
  92776. # endif
  92777. #endif
  92778. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92779. /*
  92780. * FLAC__lpc_restore_signal()
  92781. * --------------------------------------------------------------------
  92782. * Restore the original signal by summing the residual and the
  92783. * predictor.
  92784. *
  92785. * IN residual[0,data_len-1] residual signal
  92786. * IN data_len length of original signal
  92787. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92788. * IN order > 0 LP order
  92789. * IN lp_quantization quantization of LP coefficients in bits
  92790. * *** IMPORTANT: the caller must pass in the historical samples:
  92791. * IN data[-order,-1] previously-reconstructed historical samples
  92792. * OUT data[0,data_len-1] original signal
  92793. */
  92794. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92795. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92796. #ifndef FLAC__NO_ASM
  92797. # ifdef FLAC__CPU_IA32
  92798. # ifdef FLAC__HAS_NASM
  92799. void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92800. void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92801. # endif /* FLAC__HAS_NASM */
  92802. # elif defined FLAC__CPU_PPC
  92803. void FLAC__lpc_restore_signal_asm_ppc_altivec_16(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92804. void FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92805. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  92806. #endif /* FLAC__NO_ASM */
  92807. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92808. /*
  92809. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  92810. * --------------------------------------------------------------------
  92811. * Compute the expected number of bits per residual signal sample
  92812. * based on the LP error (which is related to the residual variance).
  92813. *
  92814. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  92815. * IN total_samples > 0 # of samples in residual signal
  92816. * RETURN expected bits per sample
  92817. */
  92818. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  92819. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  92820. /*
  92821. * FLAC__lpc_compute_best_order()
  92822. * --------------------------------------------------------------------
  92823. * Compute the best order from the array of signal errors returned
  92824. * during coefficient computation.
  92825. *
  92826. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  92827. * IN max_order > 0 max LP order
  92828. * IN total_samples > 0 # of samples in residual signal
  92829. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  92830. * (includes warmup sample size and quantized LP coefficient)
  92831. * RETURN [1,max_order] best order
  92832. */
  92833. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  92834. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92835. #endif
  92836. /********* End of inlined file: lpc.h *********/
  92837. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  92838. #include <stdio.h>
  92839. #endif
  92840. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92841. #ifndef M_LN2
  92842. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92843. #define M_LN2 0.69314718055994530942
  92844. #endif
  92845. /* OPT: #undef'ing this may improve the speed on some architectures */
  92846. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  92847. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  92848. {
  92849. unsigned i;
  92850. for(i = 0; i < data_len; i++)
  92851. out[i] = in[i] * window[i];
  92852. }
  92853. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  92854. {
  92855. /* a readable, but slower, version */
  92856. #if 0
  92857. FLAC__real d;
  92858. unsigned i;
  92859. FLAC__ASSERT(lag > 0);
  92860. FLAC__ASSERT(lag <= data_len);
  92861. /*
  92862. * Technically we should subtract the mean first like so:
  92863. * for(i = 0; i < data_len; i++)
  92864. * data[i] -= mean;
  92865. * but it appears not to make enough of a difference to matter, and
  92866. * most signals are already closely centered around zero
  92867. */
  92868. while(lag--) {
  92869. for(i = lag, d = 0.0; i < data_len; i++)
  92870. d += data[i] * data[i - lag];
  92871. autoc[lag] = d;
  92872. }
  92873. #endif
  92874. /*
  92875. * this version tends to run faster because of better data locality
  92876. * ('data_len' is usually much larger than 'lag')
  92877. */
  92878. FLAC__real d;
  92879. unsigned sample, coeff;
  92880. const unsigned limit = data_len - lag;
  92881. FLAC__ASSERT(lag > 0);
  92882. FLAC__ASSERT(lag <= data_len);
  92883. for(coeff = 0; coeff < lag; coeff++)
  92884. autoc[coeff] = 0.0;
  92885. for(sample = 0; sample <= limit; sample++) {
  92886. d = data[sample];
  92887. for(coeff = 0; coeff < lag; coeff++)
  92888. autoc[coeff] += d * data[sample+coeff];
  92889. }
  92890. for(; sample < data_len; sample++) {
  92891. d = data[sample];
  92892. for(coeff = 0; coeff < data_len - sample; coeff++)
  92893. autoc[coeff] += d * data[sample+coeff];
  92894. }
  92895. }
  92896. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  92897. {
  92898. unsigned i, j;
  92899. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  92900. FLAC__ASSERT(0 != max_order);
  92901. FLAC__ASSERT(0 < *max_order);
  92902. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  92903. FLAC__ASSERT(autoc[0] != 0.0);
  92904. err = autoc[0];
  92905. for(i = 0; i < *max_order; i++) {
  92906. /* Sum up this iteration's reflection coefficient. */
  92907. r = -autoc[i+1];
  92908. for(j = 0; j < i; j++)
  92909. r -= lpc[j] * autoc[i-j];
  92910. ref[i] = (r/=err);
  92911. /* Update LPC coefficients and total error. */
  92912. lpc[i]=r;
  92913. for(j = 0; j < (i>>1); j++) {
  92914. FLAC__double tmp = lpc[j];
  92915. lpc[j] += r * lpc[i-1-j];
  92916. lpc[i-1-j] += r * tmp;
  92917. }
  92918. if(i & 1)
  92919. lpc[j] += lpc[j] * r;
  92920. err *= (1.0 - r * r);
  92921. /* save this order */
  92922. for(j = 0; j <= i; j++)
  92923. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  92924. error[i] = err;
  92925. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  92926. if(err == 0.0) {
  92927. *max_order = i+1;
  92928. return;
  92929. }
  92930. }
  92931. }
  92932. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  92933. {
  92934. unsigned i;
  92935. FLAC__double cmax;
  92936. FLAC__int32 qmax, qmin;
  92937. FLAC__ASSERT(precision > 0);
  92938. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  92939. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  92940. precision--;
  92941. qmax = 1 << precision;
  92942. qmin = -qmax;
  92943. qmax--;
  92944. /* calc cmax = max( |lp_coeff[i]| ) */
  92945. cmax = 0.0;
  92946. for(i = 0; i < order; i++) {
  92947. const FLAC__double d = fabs(lp_coeff[i]);
  92948. if(d > cmax)
  92949. cmax = d;
  92950. }
  92951. if(cmax <= 0.0) {
  92952. /* => coefficients are all 0, which means our constant-detect didn't work */
  92953. return 2;
  92954. }
  92955. else {
  92956. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  92957. const int min_shiftlimit = -max_shiftlimit - 1;
  92958. int log2cmax;
  92959. (void)frexp(cmax, &log2cmax);
  92960. log2cmax--;
  92961. *shift = (int)precision - log2cmax - 1;
  92962. if(*shift > max_shiftlimit)
  92963. *shift = max_shiftlimit;
  92964. else if(*shift < min_shiftlimit)
  92965. return 1;
  92966. }
  92967. if(*shift >= 0) {
  92968. FLAC__double error = 0.0;
  92969. FLAC__int32 q;
  92970. for(i = 0; i < order; i++) {
  92971. error += lp_coeff[i] * (1 << *shift);
  92972. #if 1 /* unfortunately lround() is C99 */
  92973. if(error >= 0.0)
  92974. q = (FLAC__int32)(error + 0.5);
  92975. else
  92976. q = (FLAC__int32)(error - 0.5);
  92977. #else
  92978. q = lround(error);
  92979. #endif
  92980. #ifdef FLAC__OVERFLOW_DETECT
  92981. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92982. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  92983. else if(q < qmin)
  92984. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  92985. #endif
  92986. if(q > qmax)
  92987. q = qmax;
  92988. else if(q < qmin)
  92989. q = qmin;
  92990. error -= q;
  92991. qlp_coeff[i] = q;
  92992. }
  92993. }
  92994. /* negative shift is very rare but due to design flaw, negative shift is
  92995. * a NOP in the decoder, so it must be handled specially by scaling down
  92996. * coeffs
  92997. */
  92998. else {
  92999. const int nshift = -(*shift);
  93000. FLAC__double error = 0.0;
  93001. FLAC__int32 q;
  93002. #ifdef DEBUG
  93003. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  93004. #endif
  93005. for(i = 0; i < order; i++) {
  93006. error += lp_coeff[i] / (1 << nshift);
  93007. #if 1 /* unfortunately lround() is C99 */
  93008. if(error >= 0.0)
  93009. q = (FLAC__int32)(error + 0.5);
  93010. else
  93011. q = (FLAC__int32)(error - 0.5);
  93012. #else
  93013. q = lround(error);
  93014. #endif
  93015. #ifdef FLAC__OVERFLOW_DETECT
  93016. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93017. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  93018. else if(q < qmin)
  93019. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  93020. #endif
  93021. if(q > qmax)
  93022. q = qmax;
  93023. else if(q < qmin)
  93024. q = qmin;
  93025. error -= q;
  93026. qlp_coeff[i] = q;
  93027. }
  93028. *shift = 0;
  93029. }
  93030. return 0;
  93031. }
  93032. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  93033. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93034. {
  93035. FLAC__int64 sumo;
  93036. unsigned i, j;
  93037. FLAC__int32 sum;
  93038. const FLAC__int32 *history;
  93039. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93040. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93041. for(i=0;i<order;i++)
  93042. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93043. fprintf(stderr,"\n");
  93044. #endif
  93045. FLAC__ASSERT(order > 0);
  93046. for(i = 0; i < data_len; i++) {
  93047. sumo = 0;
  93048. sum = 0;
  93049. history = data;
  93050. for(j = 0; j < order; j++) {
  93051. sum += qlp_coeff[j] * (*(--history));
  93052. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93053. #if defined _MSC_VER
  93054. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93055. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  93056. #else
  93057. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93058. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  93059. #endif
  93060. }
  93061. *(residual++) = *(data++) - (sum >> lp_quantization);
  93062. }
  93063. /* Here's a slower but clearer version:
  93064. for(i = 0; i < data_len; i++) {
  93065. sum = 0;
  93066. for(j = 0; j < order; j++)
  93067. sum += qlp_coeff[j] * data[i-j-1];
  93068. residual[i] = data[i] - (sum >> lp_quantization);
  93069. }
  93070. */
  93071. }
  93072. #else /* fully unrolled version for normal use */
  93073. {
  93074. int i;
  93075. FLAC__int32 sum;
  93076. FLAC__ASSERT(order > 0);
  93077. FLAC__ASSERT(order <= 32);
  93078. /*
  93079. * We do unique versions up to 12th order since that's the subset limit.
  93080. * Also they are roughly ordered to match frequency of occurrence to
  93081. * minimize branching.
  93082. */
  93083. if(order <= 12) {
  93084. if(order > 8) {
  93085. if(order > 10) {
  93086. if(order == 12) {
  93087. for(i = 0; i < (int)data_len; i++) {
  93088. sum = 0;
  93089. sum += qlp_coeff[11] * data[i-12];
  93090. sum += qlp_coeff[10] * data[i-11];
  93091. sum += qlp_coeff[9] * data[i-10];
  93092. sum += qlp_coeff[8] * data[i-9];
  93093. sum += qlp_coeff[7] * data[i-8];
  93094. sum += qlp_coeff[6] * data[i-7];
  93095. sum += qlp_coeff[5] * data[i-6];
  93096. sum += qlp_coeff[4] * data[i-5];
  93097. sum += qlp_coeff[3] * data[i-4];
  93098. sum += qlp_coeff[2] * data[i-3];
  93099. sum += qlp_coeff[1] * data[i-2];
  93100. sum += qlp_coeff[0] * data[i-1];
  93101. residual[i] = data[i] - (sum >> lp_quantization);
  93102. }
  93103. }
  93104. else { /* order == 11 */
  93105. for(i = 0; i < (int)data_len; i++) {
  93106. sum = 0;
  93107. sum += qlp_coeff[10] * data[i-11];
  93108. sum += qlp_coeff[9] * data[i-10];
  93109. sum += qlp_coeff[8] * data[i-9];
  93110. sum += qlp_coeff[7] * data[i-8];
  93111. sum += qlp_coeff[6] * data[i-7];
  93112. sum += qlp_coeff[5] * data[i-6];
  93113. sum += qlp_coeff[4] * data[i-5];
  93114. sum += qlp_coeff[3] * data[i-4];
  93115. sum += qlp_coeff[2] * data[i-3];
  93116. sum += qlp_coeff[1] * data[i-2];
  93117. sum += qlp_coeff[0] * data[i-1];
  93118. residual[i] = data[i] - (sum >> lp_quantization);
  93119. }
  93120. }
  93121. }
  93122. else {
  93123. if(order == 10) {
  93124. for(i = 0; i < (int)data_len; i++) {
  93125. sum = 0;
  93126. sum += qlp_coeff[9] * data[i-10];
  93127. sum += qlp_coeff[8] * data[i-9];
  93128. sum += qlp_coeff[7] * data[i-8];
  93129. sum += qlp_coeff[6] * data[i-7];
  93130. sum += qlp_coeff[5] * data[i-6];
  93131. sum += qlp_coeff[4] * data[i-5];
  93132. sum += qlp_coeff[3] * data[i-4];
  93133. sum += qlp_coeff[2] * data[i-3];
  93134. sum += qlp_coeff[1] * data[i-2];
  93135. sum += qlp_coeff[0] * data[i-1];
  93136. residual[i] = data[i] - (sum >> lp_quantization);
  93137. }
  93138. }
  93139. else { /* order == 9 */
  93140. for(i = 0; i < (int)data_len; i++) {
  93141. sum = 0;
  93142. sum += qlp_coeff[8] * data[i-9];
  93143. sum += qlp_coeff[7] * data[i-8];
  93144. sum += qlp_coeff[6] * data[i-7];
  93145. sum += qlp_coeff[5] * data[i-6];
  93146. sum += qlp_coeff[4] * data[i-5];
  93147. sum += qlp_coeff[3] * data[i-4];
  93148. sum += qlp_coeff[2] * data[i-3];
  93149. sum += qlp_coeff[1] * data[i-2];
  93150. sum += qlp_coeff[0] * data[i-1];
  93151. residual[i] = data[i] - (sum >> lp_quantization);
  93152. }
  93153. }
  93154. }
  93155. }
  93156. else if(order > 4) {
  93157. if(order > 6) {
  93158. if(order == 8) {
  93159. for(i = 0; i < (int)data_len; i++) {
  93160. sum = 0;
  93161. sum += qlp_coeff[7] * data[i-8];
  93162. sum += qlp_coeff[6] * data[i-7];
  93163. sum += qlp_coeff[5] * data[i-6];
  93164. sum += qlp_coeff[4] * data[i-5];
  93165. sum += qlp_coeff[3] * data[i-4];
  93166. sum += qlp_coeff[2] * data[i-3];
  93167. sum += qlp_coeff[1] * data[i-2];
  93168. sum += qlp_coeff[0] * data[i-1];
  93169. residual[i] = data[i] - (sum >> lp_quantization);
  93170. }
  93171. }
  93172. else { /* order == 7 */
  93173. for(i = 0; i < (int)data_len; i++) {
  93174. sum = 0;
  93175. sum += qlp_coeff[6] * data[i-7];
  93176. sum += qlp_coeff[5] * data[i-6];
  93177. sum += qlp_coeff[4] * data[i-5];
  93178. sum += qlp_coeff[3] * data[i-4];
  93179. sum += qlp_coeff[2] * data[i-3];
  93180. sum += qlp_coeff[1] * data[i-2];
  93181. sum += qlp_coeff[0] * data[i-1];
  93182. residual[i] = data[i] - (sum >> lp_quantization);
  93183. }
  93184. }
  93185. }
  93186. else {
  93187. if(order == 6) {
  93188. for(i = 0; i < (int)data_len; i++) {
  93189. sum = 0;
  93190. sum += qlp_coeff[5] * data[i-6];
  93191. sum += qlp_coeff[4] * data[i-5];
  93192. sum += qlp_coeff[3] * data[i-4];
  93193. sum += qlp_coeff[2] * data[i-3];
  93194. sum += qlp_coeff[1] * data[i-2];
  93195. sum += qlp_coeff[0] * data[i-1];
  93196. residual[i] = data[i] - (sum >> lp_quantization);
  93197. }
  93198. }
  93199. else { /* order == 5 */
  93200. for(i = 0; i < (int)data_len; i++) {
  93201. sum = 0;
  93202. sum += qlp_coeff[4] * data[i-5];
  93203. sum += qlp_coeff[3] * data[i-4];
  93204. sum += qlp_coeff[2] * data[i-3];
  93205. sum += qlp_coeff[1] * data[i-2];
  93206. sum += qlp_coeff[0] * data[i-1];
  93207. residual[i] = data[i] - (sum >> lp_quantization);
  93208. }
  93209. }
  93210. }
  93211. }
  93212. else {
  93213. if(order > 2) {
  93214. if(order == 4) {
  93215. for(i = 0; i < (int)data_len; i++) {
  93216. sum = 0;
  93217. sum += qlp_coeff[3] * data[i-4];
  93218. sum += qlp_coeff[2] * data[i-3];
  93219. sum += qlp_coeff[1] * data[i-2];
  93220. sum += qlp_coeff[0] * data[i-1];
  93221. residual[i] = data[i] - (sum >> lp_quantization);
  93222. }
  93223. }
  93224. else { /* order == 3 */
  93225. for(i = 0; i < (int)data_len; i++) {
  93226. sum = 0;
  93227. sum += qlp_coeff[2] * data[i-3];
  93228. sum += qlp_coeff[1] * data[i-2];
  93229. sum += qlp_coeff[0] * data[i-1];
  93230. residual[i] = data[i] - (sum >> lp_quantization);
  93231. }
  93232. }
  93233. }
  93234. else {
  93235. if(order == 2) {
  93236. for(i = 0; i < (int)data_len; i++) {
  93237. sum = 0;
  93238. sum += qlp_coeff[1] * data[i-2];
  93239. sum += qlp_coeff[0] * data[i-1];
  93240. residual[i] = data[i] - (sum >> lp_quantization);
  93241. }
  93242. }
  93243. else { /* order == 1 */
  93244. for(i = 0; i < (int)data_len; i++)
  93245. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93246. }
  93247. }
  93248. }
  93249. }
  93250. else { /* order > 12 */
  93251. for(i = 0; i < (int)data_len; i++) {
  93252. sum = 0;
  93253. switch(order) {
  93254. case 32: sum += qlp_coeff[31] * data[i-32];
  93255. case 31: sum += qlp_coeff[30] * data[i-31];
  93256. case 30: sum += qlp_coeff[29] * data[i-30];
  93257. case 29: sum += qlp_coeff[28] * data[i-29];
  93258. case 28: sum += qlp_coeff[27] * data[i-28];
  93259. case 27: sum += qlp_coeff[26] * data[i-27];
  93260. case 26: sum += qlp_coeff[25] * data[i-26];
  93261. case 25: sum += qlp_coeff[24] * data[i-25];
  93262. case 24: sum += qlp_coeff[23] * data[i-24];
  93263. case 23: sum += qlp_coeff[22] * data[i-23];
  93264. case 22: sum += qlp_coeff[21] * data[i-22];
  93265. case 21: sum += qlp_coeff[20] * data[i-21];
  93266. case 20: sum += qlp_coeff[19] * data[i-20];
  93267. case 19: sum += qlp_coeff[18] * data[i-19];
  93268. case 18: sum += qlp_coeff[17] * data[i-18];
  93269. case 17: sum += qlp_coeff[16] * data[i-17];
  93270. case 16: sum += qlp_coeff[15] * data[i-16];
  93271. case 15: sum += qlp_coeff[14] * data[i-15];
  93272. case 14: sum += qlp_coeff[13] * data[i-14];
  93273. case 13: sum += qlp_coeff[12] * data[i-13];
  93274. sum += qlp_coeff[11] * data[i-12];
  93275. sum += qlp_coeff[10] * data[i-11];
  93276. sum += qlp_coeff[ 9] * data[i-10];
  93277. sum += qlp_coeff[ 8] * data[i- 9];
  93278. sum += qlp_coeff[ 7] * data[i- 8];
  93279. sum += qlp_coeff[ 6] * data[i- 7];
  93280. sum += qlp_coeff[ 5] * data[i- 6];
  93281. sum += qlp_coeff[ 4] * data[i- 5];
  93282. sum += qlp_coeff[ 3] * data[i- 4];
  93283. sum += qlp_coeff[ 2] * data[i- 3];
  93284. sum += qlp_coeff[ 1] * data[i- 2];
  93285. sum += qlp_coeff[ 0] * data[i- 1];
  93286. }
  93287. residual[i] = data[i] - (sum >> lp_quantization);
  93288. }
  93289. }
  93290. }
  93291. #endif
  93292. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  93293. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93294. {
  93295. unsigned i, j;
  93296. FLAC__int64 sum;
  93297. const FLAC__int32 *history;
  93298. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93299. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93300. for(i=0;i<order;i++)
  93301. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93302. fprintf(stderr,"\n");
  93303. #endif
  93304. FLAC__ASSERT(order > 0);
  93305. for(i = 0; i < data_len; i++) {
  93306. sum = 0;
  93307. history = data;
  93308. for(j = 0; j < order; j++)
  93309. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93310. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93311. #if defined _MSC_VER
  93312. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93313. #else
  93314. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93315. #endif
  93316. break;
  93317. }
  93318. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  93319. #if defined _MSC_VER
  93320. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%I64d, residual=%I64d\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization));
  93321. #else
  93322. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization)));
  93323. #endif
  93324. break;
  93325. }
  93326. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  93327. }
  93328. }
  93329. #else /* fully unrolled version for normal use */
  93330. {
  93331. int i;
  93332. FLAC__int64 sum;
  93333. FLAC__ASSERT(order > 0);
  93334. FLAC__ASSERT(order <= 32);
  93335. /*
  93336. * We do unique versions up to 12th order since that's the subset limit.
  93337. * Also they are roughly ordered to match frequency of occurrence to
  93338. * minimize branching.
  93339. */
  93340. if(order <= 12) {
  93341. if(order > 8) {
  93342. if(order > 10) {
  93343. if(order == 12) {
  93344. for(i = 0; i < (int)data_len; i++) {
  93345. sum = 0;
  93346. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93347. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93348. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93349. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93350. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93351. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93352. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93353. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93354. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93355. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93356. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93357. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93358. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93359. }
  93360. }
  93361. else { /* order == 11 */
  93362. for(i = 0; i < (int)data_len; i++) {
  93363. sum = 0;
  93364. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93365. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93366. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93367. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93368. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93369. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93370. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93371. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93372. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93373. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93374. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93375. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93376. }
  93377. }
  93378. }
  93379. else {
  93380. if(order == 10) {
  93381. for(i = 0; i < (int)data_len; i++) {
  93382. sum = 0;
  93383. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93384. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93385. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93386. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93387. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93388. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93389. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93390. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93391. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93392. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93393. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93394. }
  93395. }
  93396. else { /* order == 9 */
  93397. for(i = 0; i < (int)data_len; i++) {
  93398. sum = 0;
  93399. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93400. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93401. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93402. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93403. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93404. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93405. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93406. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93407. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93408. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93409. }
  93410. }
  93411. }
  93412. }
  93413. else if(order > 4) {
  93414. if(order > 6) {
  93415. if(order == 8) {
  93416. for(i = 0; i < (int)data_len; i++) {
  93417. sum = 0;
  93418. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93419. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93420. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93421. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93422. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93423. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93424. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93425. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93426. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93427. }
  93428. }
  93429. else { /* order == 7 */
  93430. for(i = 0; i < (int)data_len; i++) {
  93431. sum = 0;
  93432. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93433. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93434. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93435. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93436. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93437. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93438. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93439. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93440. }
  93441. }
  93442. }
  93443. else {
  93444. if(order == 6) {
  93445. for(i = 0; i < (int)data_len; i++) {
  93446. sum = 0;
  93447. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93448. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93449. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93450. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93451. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93452. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93453. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93454. }
  93455. }
  93456. else { /* order == 5 */
  93457. for(i = 0; i < (int)data_len; i++) {
  93458. sum = 0;
  93459. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93460. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93461. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93462. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93463. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93464. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93465. }
  93466. }
  93467. }
  93468. }
  93469. else {
  93470. if(order > 2) {
  93471. if(order == 4) {
  93472. for(i = 0; i < (int)data_len; i++) {
  93473. sum = 0;
  93474. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93475. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93476. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93477. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93478. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93479. }
  93480. }
  93481. else { /* order == 3 */
  93482. for(i = 0; i < (int)data_len; i++) {
  93483. sum = 0;
  93484. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93485. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93486. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93487. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93488. }
  93489. }
  93490. }
  93491. else {
  93492. if(order == 2) {
  93493. for(i = 0; i < (int)data_len; i++) {
  93494. sum = 0;
  93495. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93496. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93497. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93498. }
  93499. }
  93500. else { /* order == 1 */
  93501. for(i = 0; i < (int)data_len; i++)
  93502. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93503. }
  93504. }
  93505. }
  93506. }
  93507. else { /* order > 12 */
  93508. for(i = 0; i < (int)data_len; i++) {
  93509. sum = 0;
  93510. switch(order) {
  93511. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93512. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93513. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93514. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93515. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93516. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93517. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93518. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93519. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93520. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93521. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93522. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93523. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93524. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93525. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93526. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93527. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93528. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93529. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93530. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93531. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93532. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93533. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93534. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93535. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93536. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93537. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93538. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93539. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93540. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93541. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93542. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93543. }
  93544. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93545. }
  93546. }
  93547. }
  93548. #endif
  93549. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93550. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  93551. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93552. {
  93553. FLAC__int64 sumo;
  93554. unsigned i, j;
  93555. FLAC__int32 sum;
  93556. const FLAC__int32 *r = residual, *history;
  93557. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93558. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93559. for(i=0;i<order;i++)
  93560. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93561. fprintf(stderr,"\n");
  93562. #endif
  93563. FLAC__ASSERT(order > 0);
  93564. for(i = 0; i < data_len; i++) {
  93565. sumo = 0;
  93566. sum = 0;
  93567. history = data;
  93568. for(j = 0; j < order; j++) {
  93569. sum += qlp_coeff[j] * (*(--history));
  93570. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93571. #if defined _MSC_VER
  93572. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93573. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  93574. #else
  93575. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93576. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  93577. #endif
  93578. }
  93579. *(data++) = *(r++) + (sum >> lp_quantization);
  93580. }
  93581. /* Here's a slower but clearer version:
  93582. for(i = 0; i < data_len; i++) {
  93583. sum = 0;
  93584. for(j = 0; j < order; j++)
  93585. sum += qlp_coeff[j] * data[i-j-1];
  93586. data[i] = residual[i] + (sum >> lp_quantization);
  93587. }
  93588. */
  93589. }
  93590. #else /* fully unrolled version for normal use */
  93591. {
  93592. int i;
  93593. FLAC__int32 sum;
  93594. FLAC__ASSERT(order > 0);
  93595. FLAC__ASSERT(order <= 32);
  93596. /*
  93597. * We do unique versions up to 12th order since that's the subset limit.
  93598. * Also they are roughly ordered to match frequency of occurrence to
  93599. * minimize branching.
  93600. */
  93601. if(order <= 12) {
  93602. if(order > 8) {
  93603. if(order > 10) {
  93604. if(order == 12) {
  93605. for(i = 0; i < (int)data_len; i++) {
  93606. sum = 0;
  93607. sum += qlp_coeff[11] * data[i-12];
  93608. sum += qlp_coeff[10] * data[i-11];
  93609. sum += qlp_coeff[9] * data[i-10];
  93610. sum += qlp_coeff[8] * data[i-9];
  93611. sum += qlp_coeff[7] * data[i-8];
  93612. sum += qlp_coeff[6] * data[i-7];
  93613. sum += qlp_coeff[5] * data[i-6];
  93614. sum += qlp_coeff[4] * data[i-5];
  93615. sum += qlp_coeff[3] * data[i-4];
  93616. sum += qlp_coeff[2] * data[i-3];
  93617. sum += qlp_coeff[1] * data[i-2];
  93618. sum += qlp_coeff[0] * data[i-1];
  93619. data[i] = residual[i] + (sum >> lp_quantization);
  93620. }
  93621. }
  93622. else { /* order == 11 */
  93623. for(i = 0; i < (int)data_len; i++) {
  93624. sum = 0;
  93625. sum += qlp_coeff[10] * data[i-11];
  93626. sum += qlp_coeff[9] * data[i-10];
  93627. sum += qlp_coeff[8] * data[i-9];
  93628. sum += qlp_coeff[7] * data[i-8];
  93629. sum += qlp_coeff[6] * data[i-7];
  93630. sum += qlp_coeff[5] * data[i-6];
  93631. sum += qlp_coeff[4] * data[i-5];
  93632. sum += qlp_coeff[3] * data[i-4];
  93633. sum += qlp_coeff[2] * data[i-3];
  93634. sum += qlp_coeff[1] * data[i-2];
  93635. sum += qlp_coeff[0] * data[i-1];
  93636. data[i] = residual[i] + (sum >> lp_quantization);
  93637. }
  93638. }
  93639. }
  93640. else {
  93641. if(order == 10) {
  93642. for(i = 0; i < (int)data_len; i++) {
  93643. sum = 0;
  93644. sum += qlp_coeff[9] * data[i-10];
  93645. sum += qlp_coeff[8] * data[i-9];
  93646. sum += qlp_coeff[7] * data[i-8];
  93647. sum += qlp_coeff[6] * data[i-7];
  93648. sum += qlp_coeff[5] * data[i-6];
  93649. sum += qlp_coeff[4] * data[i-5];
  93650. sum += qlp_coeff[3] * data[i-4];
  93651. sum += qlp_coeff[2] * data[i-3];
  93652. sum += qlp_coeff[1] * data[i-2];
  93653. sum += qlp_coeff[0] * data[i-1];
  93654. data[i] = residual[i] + (sum >> lp_quantization);
  93655. }
  93656. }
  93657. else { /* order == 9 */
  93658. for(i = 0; i < (int)data_len; i++) {
  93659. sum = 0;
  93660. sum += qlp_coeff[8] * data[i-9];
  93661. sum += qlp_coeff[7] * data[i-8];
  93662. sum += qlp_coeff[6] * data[i-7];
  93663. sum += qlp_coeff[5] * data[i-6];
  93664. sum += qlp_coeff[4] * data[i-5];
  93665. sum += qlp_coeff[3] * data[i-4];
  93666. sum += qlp_coeff[2] * data[i-3];
  93667. sum += qlp_coeff[1] * data[i-2];
  93668. sum += qlp_coeff[0] * data[i-1];
  93669. data[i] = residual[i] + (sum >> lp_quantization);
  93670. }
  93671. }
  93672. }
  93673. }
  93674. else if(order > 4) {
  93675. if(order > 6) {
  93676. if(order == 8) {
  93677. for(i = 0; i < (int)data_len; i++) {
  93678. sum = 0;
  93679. sum += qlp_coeff[7] * data[i-8];
  93680. sum += qlp_coeff[6] * data[i-7];
  93681. sum += qlp_coeff[5] * data[i-6];
  93682. sum += qlp_coeff[4] * data[i-5];
  93683. sum += qlp_coeff[3] * data[i-4];
  93684. sum += qlp_coeff[2] * data[i-3];
  93685. sum += qlp_coeff[1] * data[i-2];
  93686. sum += qlp_coeff[0] * data[i-1];
  93687. data[i] = residual[i] + (sum >> lp_quantization);
  93688. }
  93689. }
  93690. else { /* order == 7 */
  93691. for(i = 0; i < (int)data_len; i++) {
  93692. sum = 0;
  93693. sum += qlp_coeff[6] * data[i-7];
  93694. sum += qlp_coeff[5] * data[i-6];
  93695. sum += qlp_coeff[4] * data[i-5];
  93696. sum += qlp_coeff[3] * data[i-4];
  93697. sum += qlp_coeff[2] * data[i-3];
  93698. sum += qlp_coeff[1] * data[i-2];
  93699. sum += qlp_coeff[0] * data[i-1];
  93700. data[i] = residual[i] + (sum >> lp_quantization);
  93701. }
  93702. }
  93703. }
  93704. else {
  93705. if(order == 6) {
  93706. for(i = 0; i < (int)data_len; i++) {
  93707. sum = 0;
  93708. sum += qlp_coeff[5] * data[i-6];
  93709. sum += qlp_coeff[4] * data[i-5];
  93710. sum += qlp_coeff[3] * data[i-4];
  93711. sum += qlp_coeff[2] * data[i-3];
  93712. sum += qlp_coeff[1] * data[i-2];
  93713. sum += qlp_coeff[0] * data[i-1];
  93714. data[i] = residual[i] + (sum >> lp_quantization);
  93715. }
  93716. }
  93717. else { /* order == 5 */
  93718. for(i = 0; i < (int)data_len; i++) {
  93719. sum = 0;
  93720. sum += qlp_coeff[4] * data[i-5];
  93721. sum += qlp_coeff[3] * data[i-4];
  93722. sum += qlp_coeff[2] * data[i-3];
  93723. sum += qlp_coeff[1] * data[i-2];
  93724. sum += qlp_coeff[0] * data[i-1];
  93725. data[i] = residual[i] + (sum >> lp_quantization);
  93726. }
  93727. }
  93728. }
  93729. }
  93730. else {
  93731. if(order > 2) {
  93732. if(order == 4) {
  93733. for(i = 0; i < (int)data_len; i++) {
  93734. sum = 0;
  93735. sum += qlp_coeff[3] * data[i-4];
  93736. sum += qlp_coeff[2] * data[i-3];
  93737. sum += qlp_coeff[1] * data[i-2];
  93738. sum += qlp_coeff[0] * data[i-1];
  93739. data[i] = residual[i] + (sum >> lp_quantization);
  93740. }
  93741. }
  93742. else { /* order == 3 */
  93743. for(i = 0; i < (int)data_len; i++) {
  93744. sum = 0;
  93745. sum += qlp_coeff[2] * data[i-3];
  93746. sum += qlp_coeff[1] * data[i-2];
  93747. sum += qlp_coeff[0] * data[i-1];
  93748. data[i] = residual[i] + (sum >> lp_quantization);
  93749. }
  93750. }
  93751. }
  93752. else {
  93753. if(order == 2) {
  93754. for(i = 0; i < (int)data_len; i++) {
  93755. sum = 0;
  93756. sum += qlp_coeff[1] * data[i-2];
  93757. sum += qlp_coeff[0] * data[i-1];
  93758. data[i] = residual[i] + (sum >> lp_quantization);
  93759. }
  93760. }
  93761. else { /* order == 1 */
  93762. for(i = 0; i < (int)data_len; i++)
  93763. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93764. }
  93765. }
  93766. }
  93767. }
  93768. else { /* order > 12 */
  93769. for(i = 0; i < (int)data_len; i++) {
  93770. sum = 0;
  93771. switch(order) {
  93772. case 32: sum += qlp_coeff[31] * data[i-32];
  93773. case 31: sum += qlp_coeff[30] * data[i-31];
  93774. case 30: sum += qlp_coeff[29] * data[i-30];
  93775. case 29: sum += qlp_coeff[28] * data[i-29];
  93776. case 28: sum += qlp_coeff[27] * data[i-28];
  93777. case 27: sum += qlp_coeff[26] * data[i-27];
  93778. case 26: sum += qlp_coeff[25] * data[i-26];
  93779. case 25: sum += qlp_coeff[24] * data[i-25];
  93780. case 24: sum += qlp_coeff[23] * data[i-24];
  93781. case 23: sum += qlp_coeff[22] * data[i-23];
  93782. case 22: sum += qlp_coeff[21] * data[i-22];
  93783. case 21: sum += qlp_coeff[20] * data[i-21];
  93784. case 20: sum += qlp_coeff[19] * data[i-20];
  93785. case 19: sum += qlp_coeff[18] * data[i-19];
  93786. case 18: sum += qlp_coeff[17] * data[i-18];
  93787. case 17: sum += qlp_coeff[16] * data[i-17];
  93788. case 16: sum += qlp_coeff[15] * data[i-16];
  93789. case 15: sum += qlp_coeff[14] * data[i-15];
  93790. case 14: sum += qlp_coeff[13] * data[i-14];
  93791. case 13: sum += qlp_coeff[12] * data[i-13];
  93792. sum += qlp_coeff[11] * data[i-12];
  93793. sum += qlp_coeff[10] * data[i-11];
  93794. sum += qlp_coeff[ 9] * data[i-10];
  93795. sum += qlp_coeff[ 8] * data[i- 9];
  93796. sum += qlp_coeff[ 7] * data[i- 8];
  93797. sum += qlp_coeff[ 6] * data[i- 7];
  93798. sum += qlp_coeff[ 5] * data[i- 6];
  93799. sum += qlp_coeff[ 4] * data[i- 5];
  93800. sum += qlp_coeff[ 3] * data[i- 4];
  93801. sum += qlp_coeff[ 2] * data[i- 3];
  93802. sum += qlp_coeff[ 1] * data[i- 2];
  93803. sum += qlp_coeff[ 0] * data[i- 1];
  93804. }
  93805. data[i] = residual[i] + (sum >> lp_quantization);
  93806. }
  93807. }
  93808. }
  93809. #endif
  93810. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  93811. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93812. {
  93813. unsigned i, j;
  93814. FLAC__int64 sum;
  93815. const FLAC__int32 *r = residual, *history;
  93816. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93817. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93818. for(i=0;i<order;i++)
  93819. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93820. fprintf(stderr,"\n");
  93821. #endif
  93822. FLAC__ASSERT(order > 0);
  93823. for(i = 0; i < data_len; i++) {
  93824. sum = 0;
  93825. history = data;
  93826. for(j = 0; j < order; j++)
  93827. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93828. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93829. #ifdef _MSC_VER
  93830. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93831. #else
  93832. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93833. #endif
  93834. break;
  93835. }
  93836. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  93837. #ifdef _MSC_VER
  93838. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%I64d, data=%I64d\n", i, *r, sum >> lp_quantization, (FLAC__int64)(*r) + (sum >> lp_quantization));
  93839. #else
  93840. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization)));
  93841. #endif
  93842. break;
  93843. }
  93844. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  93845. }
  93846. }
  93847. #else /* fully unrolled version for normal use */
  93848. {
  93849. int i;
  93850. FLAC__int64 sum;
  93851. FLAC__ASSERT(order > 0);
  93852. FLAC__ASSERT(order <= 32);
  93853. /*
  93854. * We do unique versions up to 12th order since that's the subset limit.
  93855. * Also they are roughly ordered to match frequency of occurrence to
  93856. * minimize branching.
  93857. */
  93858. if(order <= 12) {
  93859. if(order > 8) {
  93860. if(order > 10) {
  93861. if(order == 12) {
  93862. for(i = 0; i < (int)data_len; i++) {
  93863. sum = 0;
  93864. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93865. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93866. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93867. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93868. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93869. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93870. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93871. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93872. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93873. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93874. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93875. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93876. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93877. }
  93878. }
  93879. else { /* order == 11 */
  93880. for(i = 0; i < (int)data_len; i++) {
  93881. sum = 0;
  93882. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93883. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93884. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93885. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93886. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93887. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93888. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93889. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93890. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93891. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93892. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93893. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93894. }
  93895. }
  93896. }
  93897. else {
  93898. if(order == 10) {
  93899. for(i = 0; i < (int)data_len; i++) {
  93900. sum = 0;
  93901. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93902. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93903. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93904. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93905. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93906. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93907. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93908. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93909. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93910. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93911. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93912. }
  93913. }
  93914. else { /* order == 9 */
  93915. for(i = 0; i < (int)data_len; i++) {
  93916. sum = 0;
  93917. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93918. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93919. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93920. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93921. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93922. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93923. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93924. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93925. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93926. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93927. }
  93928. }
  93929. }
  93930. }
  93931. else if(order > 4) {
  93932. if(order > 6) {
  93933. if(order == 8) {
  93934. for(i = 0; i < (int)data_len; i++) {
  93935. sum = 0;
  93936. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93937. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93938. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93939. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93940. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93941. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93942. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93943. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93944. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93945. }
  93946. }
  93947. else { /* order == 7 */
  93948. for(i = 0; i < (int)data_len; i++) {
  93949. sum = 0;
  93950. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93951. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93952. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93953. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93954. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93955. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93956. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93957. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93958. }
  93959. }
  93960. }
  93961. else {
  93962. if(order == 6) {
  93963. for(i = 0; i < (int)data_len; i++) {
  93964. sum = 0;
  93965. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93966. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93967. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93968. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93969. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93970. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93971. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93972. }
  93973. }
  93974. else { /* order == 5 */
  93975. for(i = 0; i < (int)data_len; i++) {
  93976. sum = 0;
  93977. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93978. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93979. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93980. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93981. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93982. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93983. }
  93984. }
  93985. }
  93986. }
  93987. else {
  93988. if(order > 2) {
  93989. if(order == 4) {
  93990. for(i = 0; i < (int)data_len; i++) {
  93991. sum = 0;
  93992. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93993. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93994. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93995. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93996. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93997. }
  93998. }
  93999. else { /* order == 3 */
  94000. for(i = 0; i < (int)data_len; i++) {
  94001. sum = 0;
  94002. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94003. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94004. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94005. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94006. }
  94007. }
  94008. }
  94009. else {
  94010. if(order == 2) {
  94011. for(i = 0; i < (int)data_len; i++) {
  94012. sum = 0;
  94013. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94014. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94015. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94016. }
  94017. }
  94018. else { /* order == 1 */
  94019. for(i = 0; i < (int)data_len; i++)
  94020. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94021. }
  94022. }
  94023. }
  94024. }
  94025. else { /* order > 12 */
  94026. for(i = 0; i < (int)data_len; i++) {
  94027. sum = 0;
  94028. switch(order) {
  94029. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94030. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94031. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94032. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94033. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94034. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94035. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94036. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94037. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94038. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94039. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94040. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94041. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94042. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94043. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94044. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94045. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94046. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94047. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94048. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94049. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94050. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94051. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94052. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94053. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94054. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94055. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94056. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94057. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94058. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94059. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94060. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94061. }
  94062. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94063. }
  94064. }
  94065. }
  94066. #endif
  94067. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94068. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  94069. {
  94070. FLAC__double error_scale;
  94071. FLAC__ASSERT(total_samples > 0);
  94072. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94073. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  94074. }
  94075. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  94076. {
  94077. if(lpc_error > 0.0) {
  94078. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  94079. if(bps >= 0.0)
  94080. return bps;
  94081. else
  94082. return 0.0;
  94083. }
  94084. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  94085. return 1e32;
  94086. }
  94087. else {
  94088. return 0.0;
  94089. }
  94090. }
  94091. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  94092. {
  94093. unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
  94094. FLAC__double bits, best_bits, error_scale;
  94095. FLAC__ASSERT(max_order > 0);
  94096. FLAC__ASSERT(total_samples > 0);
  94097. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94098. best_index = 0;
  94099. best_bits = (unsigned)(-1);
  94100. for(index = 0, order = 1; index < max_order; index++, order++) {
  94101. bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order);
  94102. if(bits < best_bits) {
  94103. best_index = index;
  94104. best_bits = bits;
  94105. }
  94106. }
  94107. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  94108. }
  94109. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94110. #endif
  94111. /********* End of inlined file: lpc_flac.c *********/
  94112. /********* Start of inlined file: md5.c *********/
  94113. /********* Start of inlined file: juce_FlacHeader.h *********/
  94114. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94115. // tasks..
  94116. #define VERSION "1.2.1"
  94117. #define FLAC__NO_DLL 1
  94118. #if JUCE_MSVC
  94119. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94120. #endif
  94121. #if JUCE_MAC
  94122. #define FLAC__SYS_DARWIN 1
  94123. #endif
  94124. /********* End of inlined file: juce_FlacHeader.h *********/
  94125. #if JUCE_USE_FLAC
  94126. #if HAVE_CONFIG_H
  94127. # include <config.h>
  94128. #endif
  94129. #include <stdlib.h> /* for malloc() */
  94130. #include <string.h> /* for memcpy() */
  94131. /********* Start of inlined file: md5.h *********/
  94132. #ifndef FLAC__PRIVATE__MD5_H
  94133. #define FLAC__PRIVATE__MD5_H
  94134. /*
  94135. * This is the header file for the MD5 message-digest algorithm.
  94136. * The algorithm is due to Ron Rivest. This code was
  94137. * written by Colin Plumb in 1993, no copyright is claimed.
  94138. * This code is in the public domain; do with it what you wish.
  94139. *
  94140. * Equivalent code is available from RSA Data Security, Inc.
  94141. * This code has been tested against that, and is equivalent,
  94142. * except that you don't need to include two pages of legalese
  94143. * with every copy.
  94144. *
  94145. * To compute the message digest of a chunk of bytes, declare an
  94146. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94147. * needed on buffers full of bytes, and then call MD5Final, which
  94148. * will fill a supplied 16-byte array with the digest.
  94149. *
  94150. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94151. * header definitions; now uses stuff from dpkg's config.h
  94152. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94153. * Still in the public domain.
  94154. *
  94155. * Josh Coalson: made some changes to integrate with libFLAC.
  94156. * Still in the public domain, with no warranty.
  94157. */
  94158. typedef struct {
  94159. FLAC__uint32 in[16];
  94160. FLAC__uint32 buf[4];
  94161. FLAC__uint32 bytes[2];
  94162. FLAC__byte *internal_buf;
  94163. size_t capacity;
  94164. } FLAC__MD5Context;
  94165. void FLAC__MD5Init(FLAC__MD5Context *context);
  94166. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94167. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94168. #endif
  94169. /********* End of inlined file: md5.h *********/
  94170. #ifndef FLaC__INLINE
  94171. #define FLaC__INLINE
  94172. #endif
  94173. /*
  94174. * This code implements the MD5 message-digest algorithm.
  94175. * The algorithm is due to Ron Rivest. This code was
  94176. * written by Colin Plumb in 1993, no copyright is claimed.
  94177. * This code is in the public domain; do with it what you wish.
  94178. *
  94179. * Equivalent code is available from RSA Data Security, Inc.
  94180. * This code has been tested against that, and is equivalent,
  94181. * except that you don't need to include two pages of legalese
  94182. * with every copy.
  94183. *
  94184. * To compute the message digest of a chunk of bytes, declare an
  94185. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94186. * needed on buffers full of bytes, and then call MD5Final, which
  94187. * will fill a supplied 16-byte array with the digest.
  94188. *
  94189. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94190. * definitions; now uses stuff from dpkg's config.h.
  94191. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94192. * Still in the public domain.
  94193. *
  94194. * Josh Coalson: made some changes to integrate with libFLAC.
  94195. * Still in the public domain.
  94196. */
  94197. /* The four core functions - F1 is optimized somewhat */
  94198. /* #define F1(x, y, z) (x & y | ~x & z) */
  94199. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94200. #define F2(x, y, z) F1(z, x, y)
  94201. #define F3(x, y, z) (x ^ y ^ z)
  94202. #define F4(x, y, z) (y ^ (x | ~z))
  94203. /* This is the central step in the MD5 algorithm. */
  94204. #define MD5STEP(f,w,x,y,z,in,s) \
  94205. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94206. /*
  94207. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94208. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94209. * the data and converts bytes into longwords for this routine.
  94210. */
  94211. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94212. {
  94213. register FLAC__uint32 a, b, c, d;
  94214. a = buf[0];
  94215. b = buf[1];
  94216. c = buf[2];
  94217. d = buf[3];
  94218. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94219. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94220. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94221. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94222. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94223. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94224. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94225. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94226. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94227. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  94228. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  94229. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  94230. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  94231. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  94232. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  94233. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  94234. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  94235. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  94236. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  94237. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  94238. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  94239. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  94240. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  94241. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  94242. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  94243. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  94244. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  94245. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  94246. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  94247. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  94248. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  94249. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  94250. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  94251. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  94252. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  94253. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  94254. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  94255. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  94256. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  94257. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  94258. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  94259. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  94260. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  94261. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  94262. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  94263. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  94264. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  94265. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  94266. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  94267. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  94268. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  94269. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  94270. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  94271. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  94272. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  94273. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  94274. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  94275. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  94276. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  94277. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  94278. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  94279. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  94280. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  94281. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  94282. buf[0] += a;
  94283. buf[1] += b;
  94284. buf[2] += c;
  94285. buf[3] += d;
  94286. }
  94287. #if WORDS_BIGENDIAN
  94288. //@@@@@@ OPT: use bswap/intrinsics
  94289. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  94290. {
  94291. register FLAC__uint32 x;
  94292. do {
  94293. x = *buf;
  94294. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  94295. *buf++ = (x >> 16) | (x << 16);
  94296. } while (--words);
  94297. }
  94298. static void byteSwapX16(FLAC__uint32 *buf)
  94299. {
  94300. register FLAC__uint32 x;
  94301. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94302. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94303. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94304. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94305. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94306. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94307. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94308. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94309. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94310. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94311. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94312. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94313. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94314. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94315. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94316. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  94317. }
  94318. #else
  94319. #define byteSwap(buf, words)
  94320. #define byteSwapX16(buf)
  94321. #endif
  94322. /*
  94323. * Update context to reflect the concatenation of another buffer full
  94324. * of bytes.
  94325. */
  94326. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  94327. {
  94328. FLAC__uint32 t;
  94329. /* Update byte count */
  94330. t = ctx->bytes[0];
  94331. if ((ctx->bytes[0] = t + len) < t)
  94332. ctx->bytes[1]++; /* Carry from low to high */
  94333. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  94334. if (t > len) {
  94335. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  94336. return;
  94337. }
  94338. /* First chunk is an odd size */
  94339. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  94340. byteSwapX16(ctx->in);
  94341. FLAC__MD5Transform(ctx->buf, ctx->in);
  94342. buf += t;
  94343. len -= t;
  94344. /* Process data in 64-byte chunks */
  94345. while (len >= 64) {
  94346. memcpy(ctx->in, buf, 64);
  94347. byteSwapX16(ctx->in);
  94348. FLAC__MD5Transform(ctx->buf, ctx->in);
  94349. buf += 64;
  94350. len -= 64;
  94351. }
  94352. /* Handle any remaining bytes of data. */
  94353. memcpy(ctx->in, buf, len);
  94354. }
  94355. /*
  94356. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  94357. * initialization constants.
  94358. */
  94359. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  94360. {
  94361. ctx->buf[0] = 0x67452301;
  94362. ctx->buf[1] = 0xefcdab89;
  94363. ctx->buf[2] = 0x98badcfe;
  94364. ctx->buf[3] = 0x10325476;
  94365. ctx->bytes[0] = 0;
  94366. ctx->bytes[1] = 0;
  94367. ctx->internal_buf = 0;
  94368. ctx->capacity = 0;
  94369. }
  94370. /*
  94371. * Final wrapup - pad to 64-byte boundary with the bit pattern
  94372. * 1 0* (64-bit count of bits processed, MSB-first)
  94373. */
  94374. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  94375. {
  94376. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  94377. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  94378. /* Set the first char of padding to 0x80. There is always room. */
  94379. *p++ = 0x80;
  94380. /* Bytes of padding needed to make 56 bytes (-8..55) */
  94381. count = 56 - 1 - count;
  94382. if (count < 0) { /* Padding forces an extra block */
  94383. memset(p, 0, count + 8);
  94384. byteSwapX16(ctx->in);
  94385. FLAC__MD5Transform(ctx->buf, ctx->in);
  94386. p = (FLAC__byte *)ctx->in;
  94387. count = 56;
  94388. }
  94389. memset(p, 0, count);
  94390. byteSwap(ctx->in, 14);
  94391. /* Append length in bits and transform */
  94392. ctx->in[14] = ctx->bytes[0] << 3;
  94393. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  94394. FLAC__MD5Transform(ctx->buf, ctx->in);
  94395. byteSwap(ctx->buf, 4);
  94396. memcpy(digest, ctx->buf, 16);
  94397. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  94398. if(0 != ctx->internal_buf) {
  94399. free(ctx->internal_buf);
  94400. ctx->internal_buf = 0;
  94401. ctx->capacity = 0;
  94402. }
  94403. }
  94404. /*
  94405. * Convert the incoming audio signal to a byte stream
  94406. */
  94407. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94408. {
  94409. unsigned channel, sample;
  94410. register FLAC__int32 a_word;
  94411. register FLAC__byte *buf_ = buf;
  94412. #if WORDS_BIGENDIAN
  94413. #else
  94414. if(channels == 2 && bytes_per_sample == 2) {
  94415. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  94416. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  94417. for(sample = 0; sample < samples; sample++, buf1_+=2)
  94418. *buf1_ = (FLAC__int16)signal[1][sample];
  94419. }
  94420. else if(channels == 1 && bytes_per_sample == 2) {
  94421. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  94422. for(sample = 0; sample < samples; sample++)
  94423. *buf1_++ = (FLAC__int16)signal[0][sample];
  94424. }
  94425. else
  94426. #endif
  94427. if(bytes_per_sample == 2) {
  94428. if(channels == 2) {
  94429. for(sample = 0; sample < samples; sample++) {
  94430. a_word = signal[0][sample];
  94431. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94432. *buf_++ = (FLAC__byte)a_word;
  94433. a_word = signal[1][sample];
  94434. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94435. *buf_++ = (FLAC__byte)a_word;
  94436. }
  94437. }
  94438. else if(channels == 1) {
  94439. for(sample = 0; sample < samples; sample++) {
  94440. a_word = signal[0][sample];
  94441. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94442. *buf_++ = (FLAC__byte)a_word;
  94443. }
  94444. }
  94445. else {
  94446. for(sample = 0; sample < samples; sample++) {
  94447. for(channel = 0; channel < channels; channel++) {
  94448. a_word = signal[channel][sample];
  94449. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94450. *buf_++ = (FLAC__byte)a_word;
  94451. }
  94452. }
  94453. }
  94454. }
  94455. else if(bytes_per_sample == 3) {
  94456. if(channels == 2) {
  94457. for(sample = 0; sample < samples; sample++) {
  94458. a_word = signal[0][sample];
  94459. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94460. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94461. *buf_++ = (FLAC__byte)a_word;
  94462. a_word = signal[1][sample];
  94463. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94464. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94465. *buf_++ = (FLAC__byte)a_word;
  94466. }
  94467. }
  94468. else if(channels == 1) {
  94469. for(sample = 0; sample < samples; sample++) {
  94470. a_word = signal[0][sample];
  94471. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94472. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94473. *buf_++ = (FLAC__byte)a_word;
  94474. }
  94475. }
  94476. else {
  94477. for(sample = 0; sample < samples; sample++) {
  94478. for(channel = 0; channel < channels; channel++) {
  94479. a_word = signal[channel][sample];
  94480. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94481. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94482. *buf_++ = (FLAC__byte)a_word;
  94483. }
  94484. }
  94485. }
  94486. }
  94487. else if(bytes_per_sample == 1) {
  94488. if(channels == 2) {
  94489. for(sample = 0; sample < samples; sample++) {
  94490. a_word = signal[0][sample];
  94491. *buf_++ = (FLAC__byte)a_word;
  94492. a_word = signal[1][sample];
  94493. *buf_++ = (FLAC__byte)a_word;
  94494. }
  94495. }
  94496. else if(channels == 1) {
  94497. for(sample = 0; sample < samples; sample++) {
  94498. a_word = signal[0][sample];
  94499. *buf_++ = (FLAC__byte)a_word;
  94500. }
  94501. }
  94502. else {
  94503. for(sample = 0; sample < samples; sample++) {
  94504. for(channel = 0; channel < channels; channel++) {
  94505. a_word = signal[channel][sample];
  94506. *buf_++ = (FLAC__byte)a_word;
  94507. }
  94508. }
  94509. }
  94510. }
  94511. else { /* bytes_per_sample == 4, maybe optimize more later */
  94512. for(sample = 0; sample < samples; sample++) {
  94513. for(channel = 0; channel < channels; channel++) {
  94514. a_word = signal[channel][sample];
  94515. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94516. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94517. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94518. *buf_++ = (FLAC__byte)a_word;
  94519. }
  94520. }
  94521. }
  94522. }
  94523. /*
  94524. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  94525. */
  94526. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94527. {
  94528. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  94529. /* overflow check */
  94530. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  94531. return false;
  94532. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  94533. return false;
  94534. if(ctx->capacity < bytes_needed) {
  94535. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  94536. if(0 == tmp) {
  94537. free(ctx->internal_buf);
  94538. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  94539. return false;
  94540. }
  94541. ctx->internal_buf = tmp;
  94542. ctx->capacity = bytes_needed;
  94543. }
  94544. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  94545. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  94546. return true;
  94547. }
  94548. #endif
  94549. /********* End of inlined file: md5.c *********/
  94550. /********* Start of inlined file: memory.c *********/
  94551. /********* Start of inlined file: juce_FlacHeader.h *********/
  94552. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94553. // tasks..
  94554. #define VERSION "1.2.1"
  94555. #define FLAC__NO_DLL 1
  94556. #if JUCE_MSVC
  94557. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94558. #endif
  94559. #if JUCE_MAC
  94560. #define FLAC__SYS_DARWIN 1
  94561. #endif
  94562. /********* End of inlined file: juce_FlacHeader.h *********/
  94563. #if JUCE_USE_FLAC
  94564. #if HAVE_CONFIG_H
  94565. # include <config.h>
  94566. #endif
  94567. /********* Start of inlined file: memory.h *********/
  94568. #ifndef FLAC__PRIVATE__MEMORY_H
  94569. #define FLAC__PRIVATE__MEMORY_H
  94570. #ifdef HAVE_CONFIG_H
  94571. #include <config.h>
  94572. #endif
  94573. #include <stdlib.h> /* for size_t */
  94574. /* Returns the unaligned address returned by malloc.
  94575. * Use free() on this address to deallocate.
  94576. */
  94577. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  94578. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  94579. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  94580. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  94581. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  94582. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94583. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  94584. #endif
  94585. #endif
  94586. /********* End of inlined file: memory.h *********/
  94587. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  94588. {
  94589. void *x;
  94590. FLAC__ASSERT(0 != aligned_address);
  94591. #ifdef FLAC__ALIGN_MALLOC_DATA
  94592. /* align on 32-byte (256-bit) boundary */
  94593. x = safe_malloc_add_2op_(bytes, /*+*/31);
  94594. #ifdef SIZEOF_VOIDP
  94595. #if SIZEOF_VOIDP == 4
  94596. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  94597. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94598. #elif SIZEOF_VOIDP == 8
  94599. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94600. #else
  94601. # error Unsupported sizeof(void*)
  94602. #endif
  94603. #else
  94604. /* there's got to be a better way to do this right for all archs */
  94605. if(sizeof(void*) == sizeof(unsigned))
  94606. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94607. else if(sizeof(void*) == sizeof(FLAC__uint64))
  94608. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94609. else
  94610. return 0;
  94611. #endif
  94612. #else
  94613. x = safe_malloc_(bytes);
  94614. *aligned_address = x;
  94615. #endif
  94616. return x;
  94617. }
  94618. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  94619. {
  94620. FLAC__int32 *pu; /* unaligned pointer */
  94621. union { /* union needed to comply with C99 pointer aliasing rules */
  94622. FLAC__int32 *pa; /* aligned pointer */
  94623. void *pv; /* aligned pointer alias */
  94624. } u;
  94625. FLAC__ASSERT(elements > 0);
  94626. FLAC__ASSERT(0 != unaligned_pointer);
  94627. FLAC__ASSERT(0 != aligned_pointer);
  94628. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94629. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94630. return false;
  94631. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  94632. if(0 == pu) {
  94633. return false;
  94634. }
  94635. else {
  94636. if(*unaligned_pointer != 0)
  94637. free(*unaligned_pointer);
  94638. *unaligned_pointer = pu;
  94639. *aligned_pointer = u.pa;
  94640. return true;
  94641. }
  94642. }
  94643. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  94644. {
  94645. FLAC__uint32 *pu; /* unaligned pointer */
  94646. union { /* union needed to comply with C99 pointer aliasing rules */
  94647. FLAC__uint32 *pa; /* aligned pointer */
  94648. void *pv; /* aligned pointer alias */
  94649. } u;
  94650. FLAC__ASSERT(elements > 0);
  94651. FLAC__ASSERT(0 != unaligned_pointer);
  94652. FLAC__ASSERT(0 != aligned_pointer);
  94653. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94654. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94655. return false;
  94656. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94657. if(0 == pu) {
  94658. return false;
  94659. }
  94660. else {
  94661. if(*unaligned_pointer != 0)
  94662. free(*unaligned_pointer);
  94663. *unaligned_pointer = pu;
  94664. *aligned_pointer = u.pa;
  94665. return true;
  94666. }
  94667. }
  94668. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  94669. {
  94670. FLAC__uint64 *pu; /* unaligned pointer */
  94671. union { /* union needed to comply with C99 pointer aliasing rules */
  94672. FLAC__uint64 *pa; /* aligned pointer */
  94673. void *pv; /* aligned pointer alias */
  94674. } u;
  94675. FLAC__ASSERT(elements > 0);
  94676. FLAC__ASSERT(0 != unaligned_pointer);
  94677. FLAC__ASSERT(0 != aligned_pointer);
  94678. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94679. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94680. return false;
  94681. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94682. if(0 == pu) {
  94683. return false;
  94684. }
  94685. else {
  94686. if(*unaligned_pointer != 0)
  94687. free(*unaligned_pointer);
  94688. *unaligned_pointer = pu;
  94689. *aligned_pointer = u.pa;
  94690. return true;
  94691. }
  94692. }
  94693. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  94694. {
  94695. unsigned *pu; /* unaligned pointer */
  94696. union { /* union needed to comply with C99 pointer aliasing rules */
  94697. unsigned *pa; /* aligned pointer */
  94698. void *pv; /* aligned pointer alias */
  94699. } u;
  94700. FLAC__ASSERT(elements > 0);
  94701. FLAC__ASSERT(0 != unaligned_pointer);
  94702. FLAC__ASSERT(0 != aligned_pointer);
  94703. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94704. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94705. return false;
  94706. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94707. if(0 == pu) {
  94708. return false;
  94709. }
  94710. else {
  94711. if(*unaligned_pointer != 0)
  94712. free(*unaligned_pointer);
  94713. *unaligned_pointer = pu;
  94714. *aligned_pointer = u.pa;
  94715. return true;
  94716. }
  94717. }
  94718. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94719. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  94720. {
  94721. FLAC__real *pu; /* unaligned pointer */
  94722. union { /* union needed to comply with C99 pointer aliasing rules */
  94723. FLAC__real *pa; /* aligned pointer */
  94724. void *pv; /* aligned pointer alias */
  94725. } u;
  94726. FLAC__ASSERT(elements > 0);
  94727. FLAC__ASSERT(0 != unaligned_pointer);
  94728. FLAC__ASSERT(0 != aligned_pointer);
  94729. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94730. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94731. return false;
  94732. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94733. if(0 == pu) {
  94734. return false;
  94735. }
  94736. else {
  94737. if(*unaligned_pointer != 0)
  94738. free(*unaligned_pointer);
  94739. *unaligned_pointer = pu;
  94740. *aligned_pointer = u.pa;
  94741. return true;
  94742. }
  94743. }
  94744. #endif
  94745. #endif
  94746. /********* End of inlined file: memory.c *********/
  94747. /********* Start of inlined file: stream_decoder.c *********/
  94748. /********* Start of inlined file: juce_FlacHeader.h *********/
  94749. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94750. // tasks..
  94751. #define VERSION "1.2.1"
  94752. #define FLAC__NO_DLL 1
  94753. #if JUCE_MSVC
  94754. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94755. #endif
  94756. #if JUCE_MAC
  94757. #define FLAC__SYS_DARWIN 1
  94758. #endif
  94759. /********* End of inlined file: juce_FlacHeader.h *********/
  94760. #if JUCE_USE_FLAC
  94761. #if HAVE_CONFIG_H
  94762. # include <config.h>
  94763. #endif
  94764. #if defined _MSC_VER || defined __MINGW32__
  94765. #include <io.h> /* for _setmode() */
  94766. #include <fcntl.h> /* for _O_BINARY */
  94767. #endif
  94768. #if defined __CYGWIN__ || defined __EMX__
  94769. #include <io.h> /* for setmode(), O_BINARY */
  94770. #include <fcntl.h> /* for _O_BINARY */
  94771. #endif
  94772. #include <stdio.h>
  94773. #include <stdlib.h> /* for malloc() */
  94774. #include <string.h> /* for memset/memcpy() */
  94775. #include <sys/stat.h> /* for stat() */
  94776. #include <sys/types.h> /* for off_t */
  94777. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  94778. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  94779. #define fseeko fseek
  94780. #define ftello ftell
  94781. #endif
  94782. #endif
  94783. /********* Start of inlined file: stream_decoder.h *********/
  94784. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  94785. #define FLAC__PROTECTED__STREAM_DECODER_H
  94786. #if FLAC__HAS_OGG
  94787. #include "include/private/ogg_decoder_aspect.h"
  94788. #endif
  94789. typedef struct FLAC__StreamDecoderProtected {
  94790. FLAC__StreamDecoderState state;
  94791. unsigned channels;
  94792. FLAC__ChannelAssignment channel_assignment;
  94793. unsigned bits_per_sample;
  94794. unsigned sample_rate; /* in Hz */
  94795. unsigned blocksize; /* in samples (per channel) */
  94796. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  94797. #if FLAC__HAS_OGG
  94798. FLAC__OggDecoderAspect ogg_decoder_aspect;
  94799. #endif
  94800. } FLAC__StreamDecoderProtected;
  94801. /*
  94802. * return the number of input bytes consumed
  94803. */
  94804. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  94805. #endif
  94806. /********* End of inlined file: stream_decoder.h *********/
  94807. #ifdef max
  94808. #undef max
  94809. #endif
  94810. #define max(a,b) ((a)>(b)?(a):(b))
  94811. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94812. #ifdef _MSC_VER
  94813. #define FLAC__U64L(x) x
  94814. #else
  94815. #define FLAC__U64L(x) x##LLU
  94816. #endif
  94817. /* technically this should be in an "export.c" but this is convenient enough */
  94818. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  94819. #if FLAC__HAS_OGG
  94820. 1
  94821. #else
  94822. 0
  94823. #endif
  94824. ;
  94825. /***********************************************************************
  94826. *
  94827. * Private static data
  94828. *
  94829. ***********************************************************************/
  94830. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  94831. /***********************************************************************
  94832. *
  94833. * Private class method prototypes
  94834. *
  94835. ***********************************************************************/
  94836. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  94837. static FILE *get_binary_stdin_(void);
  94838. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  94839. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  94840. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  94841. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  94842. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94843. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94844. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  94845. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  94846. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  94847. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  94848. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  94849. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  94850. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  94851. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94852. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94853. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94854. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94855. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94856. static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
  94857. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  94858. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  94859. #if FLAC__HAS_OGG
  94860. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  94861. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94862. #endif
  94863. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  94864. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  94865. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94866. #if FLAC__HAS_OGG
  94867. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94868. #endif
  94869. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94870. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  94871. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  94872. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  94873. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  94874. /***********************************************************************
  94875. *
  94876. * Private class data
  94877. *
  94878. ***********************************************************************/
  94879. typedef struct FLAC__StreamDecoderPrivate {
  94880. #if FLAC__HAS_OGG
  94881. FLAC__bool is_ogg;
  94882. #endif
  94883. FLAC__StreamDecoderReadCallback read_callback;
  94884. FLAC__StreamDecoderSeekCallback seek_callback;
  94885. FLAC__StreamDecoderTellCallback tell_callback;
  94886. FLAC__StreamDecoderLengthCallback length_callback;
  94887. FLAC__StreamDecoderEofCallback eof_callback;
  94888. FLAC__StreamDecoderWriteCallback write_callback;
  94889. FLAC__StreamDecoderMetadataCallback metadata_callback;
  94890. FLAC__StreamDecoderErrorCallback error_callback;
  94891. /* generic 32-bit datapath: */
  94892. void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94893. /* generic 64-bit datapath: */
  94894. void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94895. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  94896. void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94897. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
  94898. void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94899. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  94900. void *client_data;
  94901. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  94902. FLAC__BitReader *input;
  94903. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  94904. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  94905. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  94906. unsigned output_capacity, output_channels;
  94907. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  94908. FLAC__uint64 samples_decoded;
  94909. FLAC__bool has_stream_info, has_seek_table;
  94910. FLAC__StreamMetadata stream_info;
  94911. FLAC__StreamMetadata seek_table;
  94912. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  94913. FLAC__byte *metadata_filter_ids;
  94914. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  94915. FLAC__Frame frame;
  94916. FLAC__bool cached; /* true if there is a byte in lookahead */
  94917. FLAC__CPUInfo cpuinfo;
  94918. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  94919. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  94920. /* unaligned (original) pointers to allocated data */
  94921. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  94922. FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
  94923. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  94924. FLAC__bool is_seeking;
  94925. FLAC__MD5Context md5context;
  94926. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  94927. /* (the rest of these are only used for seeking) */
  94928. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  94929. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  94930. FLAC__uint64 target_sample;
  94931. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  94932. #if FLAC__HAS_OGG
  94933. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  94934. #endif
  94935. } FLAC__StreamDecoderPrivate;
  94936. /***********************************************************************
  94937. *
  94938. * Public static class data
  94939. *
  94940. ***********************************************************************/
  94941. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  94942. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  94943. "FLAC__STREAM_DECODER_READ_METADATA",
  94944. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  94945. "FLAC__STREAM_DECODER_READ_FRAME",
  94946. "FLAC__STREAM_DECODER_END_OF_STREAM",
  94947. "FLAC__STREAM_DECODER_OGG_ERROR",
  94948. "FLAC__STREAM_DECODER_SEEK_ERROR",
  94949. "FLAC__STREAM_DECODER_ABORTED",
  94950. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  94951. "FLAC__STREAM_DECODER_UNINITIALIZED"
  94952. };
  94953. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  94954. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  94955. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  94956. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  94957. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  94958. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  94959. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  94960. };
  94961. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  94962. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  94963. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  94964. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  94965. };
  94966. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  94967. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  94968. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  94969. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  94970. };
  94971. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  94972. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  94973. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  94974. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  94975. };
  94976. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  94977. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  94978. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  94979. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  94980. };
  94981. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  94982. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  94983. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  94984. };
  94985. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  94986. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  94987. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  94988. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  94989. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  94990. };
  94991. /***********************************************************************
  94992. *
  94993. * Class constructor/destructor
  94994. *
  94995. ***********************************************************************/
  94996. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  94997. {
  94998. FLAC__StreamDecoder *decoder;
  94999. unsigned i;
  95000. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95001. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  95002. if(decoder == 0) {
  95003. return 0;
  95004. }
  95005. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  95006. if(decoder->protected_ == 0) {
  95007. free(decoder);
  95008. return 0;
  95009. }
  95010. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  95011. if(decoder->private_ == 0) {
  95012. free(decoder->protected_);
  95013. free(decoder);
  95014. return 0;
  95015. }
  95016. decoder->private_->input = FLAC__bitreader_new();
  95017. if(decoder->private_->input == 0) {
  95018. free(decoder->private_);
  95019. free(decoder->protected_);
  95020. free(decoder);
  95021. return 0;
  95022. }
  95023. decoder->private_->metadata_filter_ids_capacity = 16;
  95024. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  95025. FLAC__bitreader_delete(decoder->private_->input);
  95026. free(decoder->private_);
  95027. free(decoder->protected_);
  95028. free(decoder);
  95029. return 0;
  95030. }
  95031. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95032. decoder->private_->output[i] = 0;
  95033. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95034. }
  95035. decoder->private_->output_capacity = 0;
  95036. decoder->private_->output_channels = 0;
  95037. decoder->private_->has_seek_table = false;
  95038. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95039. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  95040. decoder->private_->file = 0;
  95041. set_defaults_dec(decoder);
  95042. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95043. return decoder;
  95044. }
  95045. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  95046. {
  95047. unsigned i;
  95048. FLAC__ASSERT(0 != decoder);
  95049. FLAC__ASSERT(0 != decoder->protected_);
  95050. FLAC__ASSERT(0 != decoder->private_);
  95051. FLAC__ASSERT(0 != decoder->private_->input);
  95052. (void)FLAC__stream_decoder_finish(decoder);
  95053. if(0 != decoder->private_->metadata_filter_ids)
  95054. free(decoder->private_->metadata_filter_ids);
  95055. FLAC__bitreader_delete(decoder->private_->input);
  95056. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95057. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  95058. free(decoder->private_);
  95059. free(decoder->protected_);
  95060. free(decoder);
  95061. }
  95062. /***********************************************************************
  95063. *
  95064. * Public class methods
  95065. *
  95066. ***********************************************************************/
  95067. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  95068. FLAC__StreamDecoder *decoder,
  95069. FLAC__StreamDecoderReadCallback read_callback,
  95070. FLAC__StreamDecoderSeekCallback seek_callback,
  95071. FLAC__StreamDecoderTellCallback tell_callback,
  95072. FLAC__StreamDecoderLengthCallback length_callback,
  95073. FLAC__StreamDecoderEofCallback eof_callback,
  95074. FLAC__StreamDecoderWriteCallback write_callback,
  95075. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95076. FLAC__StreamDecoderErrorCallback error_callback,
  95077. void *client_data,
  95078. FLAC__bool is_ogg
  95079. )
  95080. {
  95081. FLAC__ASSERT(0 != decoder);
  95082. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95083. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  95084. #if !FLAC__HAS_OGG
  95085. if(is_ogg)
  95086. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  95087. #endif
  95088. if(
  95089. 0 == read_callback ||
  95090. 0 == write_callback ||
  95091. 0 == error_callback ||
  95092. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  95093. )
  95094. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  95095. #if FLAC__HAS_OGG
  95096. decoder->private_->is_ogg = is_ogg;
  95097. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  95098. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  95099. #endif
  95100. /*
  95101. * get the CPU info and set the function pointers
  95102. */
  95103. FLAC__cpu_info(&decoder->private_->cpuinfo);
  95104. /* first default to the non-asm routines */
  95105. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  95106. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  95107. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  95108. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  95109. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  95110. /* now override with asm where appropriate */
  95111. #ifndef FLAC__NO_ASM
  95112. if(decoder->private_->cpuinfo.use_asm) {
  95113. #ifdef FLAC__CPU_IA32
  95114. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  95115. #ifdef FLAC__HAS_NASM
  95116. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  95117. if(decoder->private_->cpuinfo.data.ia32.bswap)
  95118. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  95119. #endif
  95120. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  95121. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95122. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95123. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95124. }
  95125. else {
  95126. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95127. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  95128. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  95129. }
  95130. #endif
  95131. #elif defined FLAC__CPU_PPC
  95132. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  95133. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  95134. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  95135. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  95136. }
  95137. #endif
  95138. }
  95139. #endif
  95140. /* from here on, errors are fatal */
  95141. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  95142. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95143. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95144. }
  95145. decoder->private_->read_callback = read_callback;
  95146. decoder->private_->seek_callback = seek_callback;
  95147. decoder->private_->tell_callback = tell_callback;
  95148. decoder->private_->length_callback = length_callback;
  95149. decoder->private_->eof_callback = eof_callback;
  95150. decoder->private_->write_callback = write_callback;
  95151. decoder->private_->metadata_callback = metadata_callback;
  95152. decoder->private_->error_callback = error_callback;
  95153. decoder->private_->client_data = client_data;
  95154. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95155. decoder->private_->samples_decoded = 0;
  95156. decoder->private_->has_stream_info = false;
  95157. decoder->private_->cached = false;
  95158. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95159. decoder->private_->is_seeking = false;
  95160. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95161. if(!FLAC__stream_decoder_reset(decoder)) {
  95162. /* above call sets the state for us */
  95163. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95164. }
  95165. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95166. }
  95167. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95168. FLAC__StreamDecoder *decoder,
  95169. FLAC__StreamDecoderReadCallback read_callback,
  95170. FLAC__StreamDecoderSeekCallback seek_callback,
  95171. FLAC__StreamDecoderTellCallback tell_callback,
  95172. FLAC__StreamDecoderLengthCallback length_callback,
  95173. FLAC__StreamDecoderEofCallback eof_callback,
  95174. FLAC__StreamDecoderWriteCallback write_callback,
  95175. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95176. FLAC__StreamDecoderErrorCallback error_callback,
  95177. void *client_data
  95178. )
  95179. {
  95180. return init_stream_internal_dec(
  95181. decoder,
  95182. read_callback,
  95183. seek_callback,
  95184. tell_callback,
  95185. length_callback,
  95186. eof_callback,
  95187. write_callback,
  95188. metadata_callback,
  95189. error_callback,
  95190. client_data,
  95191. /*is_ogg=*/false
  95192. );
  95193. }
  95194. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95195. FLAC__StreamDecoder *decoder,
  95196. FLAC__StreamDecoderReadCallback read_callback,
  95197. FLAC__StreamDecoderSeekCallback seek_callback,
  95198. FLAC__StreamDecoderTellCallback tell_callback,
  95199. FLAC__StreamDecoderLengthCallback length_callback,
  95200. FLAC__StreamDecoderEofCallback eof_callback,
  95201. FLAC__StreamDecoderWriteCallback write_callback,
  95202. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95203. FLAC__StreamDecoderErrorCallback error_callback,
  95204. void *client_data
  95205. )
  95206. {
  95207. return init_stream_internal_dec(
  95208. decoder,
  95209. read_callback,
  95210. seek_callback,
  95211. tell_callback,
  95212. length_callback,
  95213. eof_callback,
  95214. write_callback,
  95215. metadata_callback,
  95216. error_callback,
  95217. client_data,
  95218. /*is_ogg=*/true
  95219. );
  95220. }
  95221. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95222. FLAC__StreamDecoder *decoder,
  95223. FILE *file,
  95224. FLAC__StreamDecoderWriteCallback write_callback,
  95225. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95226. FLAC__StreamDecoderErrorCallback error_callback,
  95227. void *client_data,
  95228. FLAC__bool is_ogg
  95229. )
  95230. {
  95231. FLAC__ASSERT(0 != decoder);
  95232. FLAC__ASSERT(0 != file);
  95233. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95234. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95235. if(0 == write_callback || 0 == error_callback)
  95236. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95237. /*
  95238. * To make sure that our file does not go unclosed after an error, we
  95239. * must assign the FILE pointer before any further error can occur in
  95240. * this routine.
  95241. */
  95242. if(file == stdin)
  95243. file = get_binary_stdin_(); /* just to be safe */
  95244. decoder->private_->file = file;
  95245. return init_stream_internal_dec(
  95246. decoder,
  95247. file_read_callback_dec,
  95248. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  95249. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  95250. decoder->private_->file == stdin? 0: file_length_callback_,
  95251. file_eof_callback_,
  95252. write_callback,
  95253. metadata_callback,
  95254. error_callback,
  95255. client_data,
  95256. is_ogg
  95257. );
  95258. }
  95259. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  95260. FLAC__StreamDecoder *decoder,
  95261. FILE *file,
  95262. FLAC__StreamDecoderWriteCallback write_callback,
  95263. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95264. FLAC__StreamDecoderErrorCallback error_callback,
  95265. void *client_data
  95266. )
  95267. {
  95268. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95269. }
  95270. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  95271. FLAC__StreamDecoder *decoder,
  95272. FILE *file,
  95273. FLAC__StreamDecoderWriteCallback write_callback,
  95274. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95275. FLAC__StreamDecoderErrorCallback error_callback,
  95276. void *client_data
  95277. )
  95278. {
  95279. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95280. }
  95281. static FLAC__StreamDecoderInitStatus init_file_internal_(
  95282. FLAC__StreamDecoder *decoder,
  95283. const char *filename,
  95284. FLAC__StreamDecoderWriteCallback write_callback,
  95285. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95286. FLAC__StreamDecoderErrorCallback error_callback,
  95287. void *client_data,
  95288. FLAC__bool is_ogg
  95289. )
  95290. {
  95291. FILE *file;
  95292. FLAC__ASSERT(0 != decoder);
  95293. /*
  95294. * To make sure that our file does not go unclosed after an error, we
  95295. * have to do the same entrance checks here that are later performed
  95296. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  95297. */
  95298. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95299. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95300. if(0 == write_callback || 0 == error_callback)
  95301. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95302. file = filename? fopen(filename, "rb") : stdin;
  95303. if(0 == file)
  95304. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  95305. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  95306. }
  95307. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  95308. FLAC__StreamDecoder *decoder,
  95309. const char *filename,
  95310. FLAC__StreamDecoderWriteCallback write_callback,
  95311. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95312. FLAC__StreamDecoderErrorCallback error_callback,
  95313. void *client_data
  95314. )
  95315. {
  95316. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95317. }
  95318. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  95319. FLAC__StreamDecoder *decoder,
  95320. const char *filename,
  95321. FLAC__StreamDecoderWriteCallback write_callback,
  95322. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95323. FLAC__StreamDecoderErrorCallback error_callback,
  95324. void *client_data
  95325. )
  95326. {
  95327. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95328. }
  95329. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  95330. {
  95331. FLAC__bool md5_failed = false;
  95332. unsigned i;
  95333. FLAC__ASSERT(0 != decoder);
  95334. FLAC__ASSERT(0 != decoder->private_);
  95335. FLAC__ASSERT(0 != decoder->protected_);
  95336. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  95337. return true;
  95338. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  95339. * always call FLAC__MD5Final()
  95340. */
  95341. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  95342. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95343. free(decoder->private_->seek_table.data.seek_table.points);
  95344. decoder->private_->seek_table.data.seek_table.points = 0;
  95345. decoder->private_->has_seek_table = false;
  95346. }
  95347. FLAC__bitreader_free(decoder->private_->input);
  95348. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95349. /* WATCHOUT:
  95350. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95351. * output arrays have a buffer of up to 3 zeroes in front
  95352. * (at negative indices) for alignment purposes; we use 4
  95353. * to keep the data well-aligned.
  95354. */
  95355. if(0 != decoder->private_->output[i]) {
  95356. free(decoder->private_->output[i]-4);
  95357. decoder->private_->output[i] = 0;
  95358. }
  95359. if(0 != decoder->private_->residual_unaligned[i]) {
  95360. free(decoder->private_->residual_unaligned[i]);
  95361. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95362. }
  95363. }
  95364. decoder->private_->output_capacity = 0;
  95365. decoder->private_->output_channels = 0;
  95366. #if FLAC__HAS_OGG
  95367. if(decoder->private_->is_ogg)
  95368. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  95369. #endif
  95370. if(0 != decoder->private_->file) {
  95371. if(decoder->private_->file != stdin)
  95372. fclose(decoder->private_->file);
  95373. decoder->private_->file = 0;
  95374. }
  95375. if(decoder->private_->do_md5_checking) {
  95376. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  95377. md5_failed = true;
  95378. }
  95379. decoder->private_->is_seeking = false;
  95380. set_defaults_dec(decoder);
  95381. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95382. return !md5_failed;
  95383. }
  95384. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  95385. {
  95386. FLAC__ASSERT(0 != decoder);
  95387. FLAC__ASSERT(0 != decoder->private_);
  95388. FLAC__ASSERT(0 != decoder->protected_);
  95389. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95390. return false;
  95391. #if FLAC__HAS_OGG
  95392. /* can't check decoder->private_->is_ogg since that's not set until init time */
  95393. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  95394. return true;
  95395. #else
  95396. (void)value;
  95397. return false;
  95398. #endif
  95399. }
  95400. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  95401. {
  95402. FLAC__ASSERT(0 != decoder);
  95403. FLAC__ASSERT(0 != decoder->protected_);
  95404. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95405. return false;
  95406. decoder->protected_->md5_checking = value;
  95407. return true;
  95408. }
  95409. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95410. {
  95411. FLAC__ASSERT(0 != decoder);
  95412. FLAC__ASSERT(0 != decoder->private_);
  95413. FLAC__ASSERT(0 != decoder->protected_);
  95414. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95415. /* double protection */
  95416. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95417. return false;
  95418. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95419. return false;
  95420. decoder->private_->metadata_filter[type] = true;
  95421. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95422. decoder->private_->metadata_filter_ids_count = 0;
  95423. return true;
  95424. }
  95425. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95426. {
  95427. FLAC__ASSERT(0 != decoder);
  95428. FLAC__ASSERT(0 != decoder->private_);
  95429. FLAC__ASSERT(0 != decoder->protected_);
  95430. FLAC__ASSERT(0 != id);
  95431. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95432. return false;
  95433. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95434. return true;
  95435. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95436. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95437. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  95438. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95439. return false;
  95440. }
  95441. decoder->private_->metadata_filter_ids_capacity *= 2;
  95442. }
  95443. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  95444. decoder->private_->metadata_filter_ids_count++;
  95445. return true;
  95446. }
  95447. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  95448. {
  95449. unsigned i;
  95450. FLAC__ASSERT(0 != decoder);
  95451. FLAC__ASSERT(0 != decoder->private_);
  95452. FLAC__ASSERT(0 != decoder->protected_);
  95453. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95454. return false;
  95455. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  95456. decoder->private_->metadata_filter[i] = true;
  95457. decoder->private_->metadata_filter_ids_count = 0;
  95458. return true;
  95459. }
  95460. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95461. {
  95462. FLAC__ASSERT(0 != decoder);
  95463. FLAC__ASSERT(0 != decoder->private_);
  95464. FLAC__ASSERT(0 != decoder->protected_);
  95465. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95466. /* double protection */
  95467. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95468. return false;
  95469. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95470. return false;
  95471. decoder->private_->metadata_filter[type] = false;
  95472. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95473. decoder->private_->metadata_filter_ids_count = 0;
  95474. return true;
  95475. }
  95476. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95477. {
  95478. FLAC__ASSERT(0 != decoder);
  95479. FLAC__ASSERT(0 != decoder->private_);
  95480. FLAC__ASSERT(0 != decoder->protected_);
  95481. FLAC__ASSERT(0 != id);
  95482. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95483. return false;
  95484. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95485. return true;
  95486. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95487. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95488. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  95489. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95490. return false;
  95491. }
  95492. decoder->private_->metadata_filter_ids_capacity *= 2;
  95493. }
  95494. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  95495. decoder->private_->metadata_filter_ids_count++;
  95496. return true;
  95497. }
  95498. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  95499. {
  95500. FLAC__ASSERT(0 != decoder);
  95501. FLAC__ASSERT(0 != decoder->private_);
  95502. FLAC__ASSERT(0 != decoder->protected_);
  95503. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95504. return false;
  95505. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95506. decoder->private_->metadata_filter_ids_count = 0;
  95507. return true;
  95508. }
  95509. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  95510. {
  95511. FLAC__ASSERT(0 != decoder);
  95512. FLAC__ASSERT(0 != decoder->protected_);
  95513. return decoder->protected_->state;
  95514. }
  95515. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  95516. {
  95517. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  95518. }
  95519. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  95520. {
  95521. FLAC__ASSERT(0 != decoder);
  95522. FLAC__ASSERT(0 != decoder->protected_);
  95523. return decoder->protected_->md5_checking;
  95524. }
  95525. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  95526. {
  95527. FLAC__ASSERT(0 != decoder);
  95528. FLAC__ASSERT(0 != decoder->protected_);
  95529. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  95530. }
  95531. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  95532. {
  95533. FLAC__ASSERT(0 != decoder);
  95534. FLAC__ASSERT(0 != decoder->protected_);
  95535. return decoder->protected_->channels;
  95536. }
  95537. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  95538. {
  95539. FLAC__ASSERT(0 != decoder);
  95540. FLAC__ASSERT(0 != decoder->protected_);
  95541. return decoder->protected_->channel_assignment;
  95542. }
  95543. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  95544. {
  95545. FLAC__ASSERT(0 != decoder);
  95546. FLAC__ASSERT(0 != decoder->protected_);
  95547. return decoder->protected_->bits_per_sample;
  95548. }
  95549. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  95550. {
  95551. FLAC__ASSERT(0 != decoder);
  95552. FLAC__ASSERT(0 != decoder->protected_);
  95553. return decoder->protected_->sample_rate;
  95554. }
  95555. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  95556. {
  95557. FLAC__ASSERT(0 != decoder);
  95558. FLAC__ASSERT(0 != decoder->protected_);
  95559. return decoder->protected_->blocksize;
  95560. }
  95561. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  95562. {
  95563. FLAC__ASSERT(0 != decoder);
  95564. FLAC__ASSERT(0 != decoder->private_);
  95565. FLAC__ASSERT(0 != position);
  95566. #if FLAC__HAS_OGG
  95567. if(decoder->private_->is_ogg)
  95568. return false;
  95569. #endif
  95570. if(0 == decoder->private_->tell_callback)
  95571. return false;
  95572. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  95573. return false;
  95574. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  95575. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  95576. return false;
  95577. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  95578. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  95579. return true;
  95580. }
  95581. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  95582. {
  95583. FLAC__ASSERT(0 != decoder);
  95584. FLAC__ASSERT(0 != decoder->private_);
  95585. FLAC__ASSERT(0 != decoder->protected_);
  95586. decoder->private_->samples_decoded = 0;
  95587. decoder->private_->do_md5_checking = false;
  95588. #if FLAC__HAS_OGG
  95589. if(decoder->private_->is_ogg)
  95590. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  95591. #endif
  95592. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  95593. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95594. return false;
  95595. }
  95596. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95597. return true;
  95598. }
  95599. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  95600. {
  95601. FLAC__ASSERT(0 != decoder);
  95602. FLAC__ASSERT(0 != decoder->private_);
  95603. FLAC__ASSERT(0 != decoder->protected_);
  95604. if(!FLAC__stream_decoder_flush(decoder)) {
  95605. /* above call sets the state for us */
  95606. return false;
  95607. }
  95608. #if FLAC__HAS_OGG
  95609. /*@@@ could go in !internal_reset_hack block below */
  95610. if(decoder->private_->is_ogg)
  95611. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  95612. #endif
  95613. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  95614. * (internal_reset_hack) don't try to rewind since we are already at
  95615. * the beginning of the stream and don't want to fail if the input is
  95616. * not seekable.
  95617. */
  95618. if(!decoder->private_->internal_reset_hack) {
  95619. if(decoder->private_->file == stdin)
  95620. return false; /* can't rewind stdin, reset fails */
  95621. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  95622. return false; /* seekable and seek fails, reset fails */
  95623. }
  95624. else
  95625. decoder->private_->internal_reset_hack = false;
  95626. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  95627. decoder->private_->has_stream_info = false;
  95628. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95629. free(decoder->private_->seek_table.data.seek_table.points);
  95630. decoder->private_->seek_table.data.seek_table.points = 0;
  95631. decoder->private_->has_seek_table = false;
  95632. }
  95633. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95634. /*
  95635. * This goes in reset() and not flush() because according to the spec, a
  95636. * fixed-blocksize stream must stay that way through the whole stream.
  95637. */
  95638. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95639. /* We initialize the FLAC__MD5Context even though we may never use it. This
  95640. * is because md5 checking may be turned on to start and then turned off if
  95641. * a seek occurs. So we init the context here and finalize it in
  95642. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  95643. * properly.
  95644. */
  95645. FLAC__MD5Init(&decoder->private_->md5context);
  95646. decoder->private_->first_frame_offset = 0;
  95647. decoder->private_->unparseable_frame_count = 0;
  95648. return true;
  95649. }
  95650. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  95651. {
  95652. FLAC__bool got_a_frame;
  95653. FLAC__ASSERT(0 != decoder);
  95654. FLAC__ASSERT(0 != decoder->protected_);
  95655. while(1) {
  95656. switch(decoder->protected_->state) {
  95657. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95658. if(!find_metadata_(decoder))
  95659. return false; /* above function sets the status for us */
  95660. break;
  95661. case FLAC__STREAM_DECODER_READ_METADATA:
  95662. if(!read_metadata_(decoder))
  95663. return false; /* above function sets the status for us */
  95664. else
  95665. return true;
  95666. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95667. if(!frame_sync_(decoder))
  95668. return true; /* above function sets the status for us */
  95669. break;
  95670. case FLAC__STREAM_DECODER_READ_FRAME:
  95671. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  95672. return false; /* above function sets the status for us */
  95673. if(got_a_frame)
  95674. return true; /* above function sets the status for us */
  95675. break;
  95676. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95677. case FLAC__STREAM_DECODER_ABORTED:
  95678. return true;
  95679. default:
  95680. FLAC__ASSERT(0);
  95681. return false;
  95682. }
  95683. }
  95684. }
  95685. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  95686. {
  95687. FLAC__ASSERT(0 != decoder);
  95688. FLAC__ASSERT(0 != decoder->protected_);
  95689. while(1) {
  95690. switch(decoder->protected_->state) {
  95691. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95692. if(!find_metadata_(decoder))
  95693. return false; /* above function sets the status for us */
  95694. break;
  95695. case FLAC__STREAM_DECODER_READ_METADATA:
  95696. if(!read_metadata_(decoder))
  95697. return false; /* above function sets the status for us */
  95698. break;
  95699. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95700. case FLAC__STREAM_DECODER_READ_FRAME:
  95701. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95702. case FLAC__STREAM_DECODER_ABORTED:
  95703. return true;
  95704. default:
  95705. FLAC__ASSERT(0);
  95706. return false;
  95707. }
  95708. }
  95709. }
  95710. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  95711. {
  95712. FLAC__bool dummy;
  95713. FLAC__ASSERT(0 != decoder);
  95714. FLAC__ASSERT(0 != decoder->protected_);
  95715. while(1) {
  95716. switch(decoder->protected_->state) {
  95717. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95718. if(!find_metadata_(decoder))
  95719. return false; /* above function sets the status for us */
  95720. break;
  95721. case FLAC__STREAM_DECODER_READ_METADATA:
  95722. if(!read_metadata_(decoder))
  95723. return false; /* above function sets the status for us */
  95724. break;
  95725. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95726. if(!frame_sync_(decoder))
  95727. return true; /* above function sets the status for us */
  95728. break;
  95729. case FLAC__STREAM_DECODER_READ_FRAME:
  95730. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  95731. return false; /* above function sets the status for us */
  95732. break;
  95733. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95734. case FLAC__STREAM_DECODER_ABORTED:
  95735. return true;
  95736. default:
  95737. FLAC__ASSERT(0);
  95738. return false;
  95739. }
  95740. }
  95741. }
  95742. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  95743. {
  95744. FLAC__bool got_a_frame;
  95745. FLAC__ASSERT(0 != decoder);
  95746. FLAC__ASSERT(0 != decoder->protected_);
  95747. while(1) {
  95748. switch(decoder->protected_->state) {
  95749. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95750. case FLAC__STREAM_DECODER_READ_METADATA:
  95751. return false; /* above function sets the status for us */
  95752. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95753. if(!frame_sync_(decoder))
  95754. return true; /* above function sets the status for us */
  95755. break;
  95756. case FLAC__STREAM_DECODER_READ_FRAME:
  95757. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  95758. return false; /* above function sets the status for us */
  95759. if(got_a_frame)
  95760. return true; /* above function sets the status for us */
  95761. break;
  95762. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95763. case FLAC__STREAM_DECODER_ABORTED:
  95764. return true;
  95765. default:
  95766. FLAC__ASSERT(0);
  95767. return false;
  95768. }
  95769. }
  95770. }
  95771. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  95772. {
  95773. FLAC__uint64 length;
  95774. FLAC__ASSERT(0 != decoder);
  95775. if(
  95776. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  95777. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  95778. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  95779. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  95780. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  95781. )
  95782. return false;
  95783. if(0 == decoder->private_->seek_callback)
  95784. return false;
  95785. FLAC__ASSERT(decoder->private_->seek_callback);
  95786. FLAC__ASSERT(decoder->private_->tell_callback);
  95787. FLAC__ASSERT(decoder->private_->length_callback);
  95788. FLAC__ASSERT(decoder->private_->eof_callback);
  95789. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  95790. return false;
  95791. decoder->private_->is_seeking = true;
  95792. /* turn off md5 checking if a seek is attempted */
  95793. decoder->private_->do_md5_checking = false;
  95794. /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
  95795. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  95796. decoder->private_->is_seeking = false;
  95797. return false;
  95798. }
  95799. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  95800. if(
  95801. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  95802. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  95803. ) {
  95804. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  95805. /* above call sets the state for us */
  95806. decoder->private_->is_seeking = false;
  95807. return false;
  95808. }
  95809. /* check this again in case we didn't know total_samples the first time */
  95810. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95811. decoder->private_->is_seeking = false;
  95812. return false;
  95813. }
  95814. }
  95815. {
  95816. const FLAC__bool ok =
  95817. #if FLAC__HAS_OGG
  95818. decoder->private_->is_ogg?
  95819. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  95820. #endif
  95821. seek_to_absolute_sample_(decoder, length, sample)
  95822. ;
  95823. decoder->private_->is_seeking = false;
  95824. return ok;
  95825. }
  95826. }
  95827. /***********************************************************************
  95828. *
  95829. * Protected class methods
  95830. *
  95831. ***********************************************************************/
  95832. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  95833. {
  95834. FLAC__ASSERT(0 != decoder);
  95835. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95836. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  95837. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  95838. }
  95839. /***********************************************************************
  95840. *
  95841. * Private class methods
  95842. *
  95843. ***********************************************************************/
  95844. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  95845. {
  95846. #if FLAC__HAS_OGG
  95847. decoder->private_->is_ogg = false;
  95848. #endif
  95849. decoder->private_->read_callback = 0;
  95850. decoder->private_->seek_callback = 0;
  95851. decoder->private_->tell_callback = 0;
  95852. decoder->private_->length_callback = 0;
  95853. decoder->private_->eof_callback = 0;
  95854. decoder->private_->write_callback = 0;
  95855. decoder->private_->metadata_callback = 0;
  95856. decoder->private_->error_callback = 0;
  95857. decoder->private_->client_data = 0;
  95858. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95859. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  95860. decoder->private_->metadata_filter_ids_count = 0;
  95861. decoder->protected_->md5_checking = false;
  95862. #if FLAC__HAS_OGG
  95863. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  95864. #endif
  95865. }
  95866. /*
  95867. * This will forcibly set stdin to binary mode (for OSes that require it)
  95868. */
  95869. FILE *get_binary_stdin_(void)
  95870. {
  95871. /* if something breaks here it is probably due to the presence or
  95872. * absence of an underscore before the identifiers 'setmode',
  95873. * 'fileno', and/or 'O_BINARY'; check your system header files.
  95874. */
  95875. #if defined _MSC_VER || defined __MINGW32__
  95876. _setmode(_fileno(stdin), _O_BINARY);
  95877. #elif defined __CYGWIN__
  95878. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  95879. setmode(_fileno(stdin), _O_BINARY);
  95880. #elif defined __EMX__
  95881. setmode(fileno(stdin), O_BINARY);
  95882. #endif
  95883. return stdin;
  95884. }
  95885. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  95886. {
  95887. unsigned i;
  95888. FLAC__int32 *tmp;
  95889. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  95890. return true;
  95891. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  95892. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95893. if(0 != decoder->private_->output[i]) {
  95894. free(decoder->private_->output[i]-4);
  95895. decoder->private_->output[i] = 0;
  95896. }
  95897. if(0 != decoder->private_->residual_unaligned[i]) {
  95898. free(decoder->private_->residual_unaligned[i]);
  95899. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95900. }
  95901. }
  95902. for(i = 0; i < channels; i++) {
  95903. /* WATCHOUT:
  95904. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95905. * output arrays have a buffer of up to 3 zeroes in front
  95906. * (at negative indices) for alignment purposes; we use 4
  95907. * to keep the data well-aligned.
  95908. */
  95909. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  95910. if(tmp == 0) {
  95911. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95912. return false;
  95913. }
  95914. memset(tmp, 0, sizeof(FLAC__int32)*4);
  95915. decoder->private_->output[i] = tmp + 4;
  95916. /* WATCHOUT:
  95917. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  95918. */
  95919. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  95920. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95921. return false;
  95922. }
  95923. }
  95924. decoder->private_->output_capacity = size;
  95925. decoder->private_->output_channels = channels;
  95926. return true;
  95927. }
  95928. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  95929. {
  95930. size_t i;
  95931. FLAC__ASSERT(0 != decoder);
  95932. FLAC__ASSERT(0 != decoder->private_);
  95933. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  95934. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  95935. return true;
  95936. return false;
  95937. }
  95938. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  95939. {
  95940. FLAC__uint32 x;
  95941. unsigned i, id_;
  95942. FLAC__bool first = true;
  95943. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95944. for(i = id_ = 0; i < 4; ) {
  95945. if(decoder->private_->cached) {
  95946. x = (FLAC__uint32)decoder->private_->lookahead;
  95947. decoder->private_->cached = false;
  95948. }
  95949. else {
  95950. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95951. return false; /* read_callback_ sets the state for us */
  95952. }
  95953. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  95954. first = true;
  95955. i++;
  95956. id_ = 0;
  95957. continue;
  95958. }
  95959. if(x == ID3V2_TAG_[id_]) {
  95960. id_++;
  95961. i = 0;
  95962. if(id_ == 3) {
  95963. if(!skip_id3v2_tag_(decoder))
  95964. return false; /* skip_id3v2_tag_ sets the state for us */
  95965. }
  95966. continue;
  95967. }
  95968. id_ = 0;
  95969. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95970. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95971. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95972. return false; /* read_callback_ sets the state for us */
  95973. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  95974. /* else we have to check if the second byte is the end of a sync code */
  95975. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95976. decoder->private_->lookahead = (FLAC__byte)x;
  95977. decoder->private_->cached = true;
  95978. }
  95979. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95980. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95981. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95982. return true;
  95983. }
  95984. }
  95985. i = 0;
  95986. if(first) {
  95987. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95988. first = false;
  95989. }
  95990. }
  95991. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  95992. return true;
  95993. }
  95994. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  95995. {
  95996. FLAC__bool is_last;
  95997. FLAC__uint32 i, x, type, length;
  95998. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95999. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  96000. return false; /* read_callback_ sets the state for us */
  96001. is_last = x? true : false;
  96002. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  96003. return false; /* read_callback_ sets the state for us */
  96004. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  96005. return false; /* read_callback_ sets the state for us */
  96006. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  96007. if(!read_metadata_streaminfo_(decoder, is_last, length))
  96008. return false;
  96009. decoder->private_->has_stream_info = true;
  96010. if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
  96011. decoder->private_->do_md5_checking = false;
  96012. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  96013. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  96014. }
  96015. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96016. if(!read_metadata_seektable_(decoder, is_last, length))
  96017. return false;
  96018. decoder->private_->has_seek_table = true;
  96019. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  96020. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  96021. }
  96022. else {
  96023. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  96024. unsigned real_length = length;
  96025. FLAC__StreamMetadata block;
  96026. block.is_last = is_last;
  96027. block.type = (FLAC__MetadataType)type;
  96028. block.length = length;
  96029. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  96030. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  96031. return false; /* read_callback_ sets the state for us */
  96032. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  96033. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  96034. return false;
  96035. }
  96036. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  96037. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  96038. skip_it = !skip_it;
  96039. }
  96040. if(skip_it) {
  96041. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96042. return false; /* read_callback_ sets the state for us */
  96043. }
  96044. else {
  96045. switch(type) {
  96046. case FLAC__METADATA_TYPE_PADDING:
  96047. /* skip the padding bytes */
  96048. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96049. return false; /* read_callback_ sets the state for us */
  96050. break;
  96051. case FLAC__METADATA_TYPE_APPLICATION:
  96052. /* remember, we read the ID already */
  96053. if(real_length > 0) {
  96054. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  96055. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96056. return false;
  96057. }
  96058. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  96059. return false; /* read_callback_ sets the state for us */
  96060. }
  96061. else
  96062. block.data.application.data = 0;
  96063. break;
  96064. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96065. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  96066. return false;
  96067. break;
  96068. case FLAC__METADATA_TYPE_CUESHEET:
  96069. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  96070. return false;
  96071. break;
  96072. case FLAC__METADATA_TYPE_PICTURE:
  96073. if(!read_metadata_picture_(decoder, &block.data.picture))
  96074. return false;
  96075. break;
  96076. case FLAC__METADATA_TYPE_STREAMINFO:
  96077. case FLAC__METADATA_TYPE_SEEKTABLE:
  96078. FLAC__ASSERT(0);
  96079. break;
  96080. default:
  96081. if(real_length > 0) {
  96082. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  96083. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96084. return false;
  96085. }
  96086. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  96087. return false; /* read_callback_ sets the state for us */
  96088. }
  96089. else
  96090. block.data.unknown.data = 0;
  96091. break;
  96092. }
  96093. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  96094. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  96095. /* now we have to free any malloc()ed data in the block */
  96096. switch(type) {
  96097. case FLAC__METADATA_TYPE_PADDING:
  96098. break;
  96099. case FLAC__METADATA_TYPE_APPLICATION:
  96100. if(0 != block.data.application.data)
  96101. free(block.data.application.data);
  96102. break;
  96103. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96104. if(0 != block.data.vorbis_comment.vendor_string.entry)
  96105. free(block.data.vorbis_comment.vendor_string.entry);
  96106. if(block.data.vorbis_comment.num_comments > 0)
  96107. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  96108. if(0 != block.data.vorbis_comment.comments[i].entry)
  96109. free(block.data.vorbis_comment.comments[i].entry);
  96110. if(0 != block.data.vorbis_comment.comments)
  96111. free(block.data.vorbis_comment.comments);
  96112. break;
  96113. case FLAC__METADATA_TYPE_CUESHEET:
  96114. if(block.data.cue_sheet.num_tracks > 0)
  96115. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  96116. if(0 != block.data.cue_sheet.tracks[i].indices)
  96117. free(block.data.cue_sheet.tracks[i].indices);
  96118. if(0 != block.data.cue_sheet.tracks)
  96119. free(block.data.cue_sheet.tracks);
  96120. break;
  96121. case FLAC__METADATA_TYPE_PICTURE:
  96122. if(0 != block.data.picture.mime_type)
  96123. free(block.data.picture.mime_type);
  96124. if(0 != block.data.picture.description)
  96125. free(block.data.picture.description);
  96126. if(0 != block.data.picture.data)
  96127. free(block.data.picture.data);
  96128. break;
  96129. case FLAC__METADATA_TYPE_STREAMINFO:
  96130. case FLAC__METADATA_TYPE_SEEKTABLE:
  96131. FLAC__ASSERT(0);
  96132. default:
  96133. if(0 != block.data.unknown.data)
  96134. free(block.data.unknown.data);
  96135. break;
  96136. }
  96137. }
  96138. }
  96139. if(is_last) {
  96140. /* if this fails, it's OK, it's just a hint for the seek routine */
  96141. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  96142. decoder->private_->first_frame_offset = 0;
  96143. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96144. }
  96145. return true;
  96146. }
  96147. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96148. {
  96149. FLAC__uint32 x;
  96150. unsigned bits, used_bits = 0;
  96151. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96152. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96153. decoder->private_->stream_info.is_last = is_last;
  96154. decoder->private_->stream_info.length = length;
  96155. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96156. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96157. return false; /* read_callback_ sets the state for us */
  96158. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96159. used_bits += bits;
  96160. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96161. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96162. return false; /* read_callback_ sets the state for us */
  96163. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96164. used_bits += bits;
  96165. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96166. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96167. return false; /* read_callback_ sets the state for us */
  96168. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96169. used_bits += bits;
  96170. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96171. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96172. return false; /* read_callback_ sets the state for us */
  96173. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96174. used_bits += bits;
  96175. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96176. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96177. return false; /* read_callback_ sets the state for us */
  96178. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96179. used_bits += bits;
  96180. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96181. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96182. return false; /* read_callback_ sets the state for us */
  96183. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96184. used_bits += bits;
  96185. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96186. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96187. return false; /* read_callback_ sets the state for us */
  96188. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96189. used_bits += bits;
  96190. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96191. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  96192. return false; /* read_callback_ sets the state for us */
  96193. used_bits += bits;
  96194. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96195. return false; /* read_callback_ sets the state for us */
  96196. used_bits += 16*8;
  96197. /* skip the rest of the block */
  96198. FLAC__ASSERT(used_bits % 8 == 0);
  96199. length -= (used_bits / 8);
  96200. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96201. return false; /* read_callback_ sets the state for us */
  96202. return true;
  96203. }
  96204. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96205. {
  96206. FLAC__uint32 i, x;
  96207. FLAC__uint64 xx;
  96208. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96209. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96210. decoder->private_->seek_table.is_last = is_last;
  96211. decoder->private_->seek_table.length = length;
  96212. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96213. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96214. if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) {
  96215. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96216. return false;
  96217. }
  96218. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96219. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96220. return false; /* read_callback_ sets the state for us */
  96221. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96222. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96223. return false; /* read_callback_ sets the state for us */
  96224. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96225. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96226. return false; /* read_callback_ sets the state for us */
  96227. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96228. }
  96229. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96230. /* if there is a partial point left, skip over it */
  96231. if(length > 0) {
  96232. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96233. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96234. return false; /* read_callback_ sets the state for us */
  96235. }
  96236. return true;
  96237. }
  96238. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  96239. {
  96240. FLAC__uint32 i;
  96241. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96242. /* read vendor string */
  96243. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96244. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  96245. return false; /* read_callback_ sets the state for us */
  96246. if(obj->vendor_string.length > 0) {
  96247. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  96248. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96249. return false;
  96250. }
  96251. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  96252. return false; /* read_callback_ sets the state for us */
  96253. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  96254. }
  96255. else
  96256. obj->vendor_string.entry = 0;
  96257. /* read num comments */
  96258. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  96259. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  96260. return false; /* read_callback_ sets the state for us */
  96261. /* read comments */
  96262. if(obj->num_comments > 0) {
  96263. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  96264. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96265. return false;
  96266. }
  96267. for(i = 0; i < obj->num_comments; i++) {
  96268. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96269. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  96270. return false; /* read_callback_ sets the state for us */
  96271. if(obj->comments[i].length > 0) {
  96272. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  96273. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96274. return false;
  96275. }
  96276. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  96277. return false; /* read_callback_ sets the state for us */
  96278. obj->comments[i].entry[obj->comments[i].length] = '\0';
  96279. }
  96280. else
  96281. obj->comments[i].entry = 0;
  96282. }
  96283. }
  96284. else {
  96285. obj->comments = 0;
  96286. }
  96287. return true;
  96288. }
  96289. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  96290. {
  96291. FLAC__uint32 i, j, x;
  96292. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96293. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  96294. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  96295. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  96296. return false; /* read_callback_ sets the state for us */
  96297. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  96298. return false; /* read_callback_ sets the state for us */
  96299. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  96300. return false; /* read_callback_ sets the state for us */
  96301. obj->is_cd = x? true : false;
  96302. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  96303. return false; /* read_callback_ sets the state for us */
  96304. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  96305. return false; /* read_callback_ sets the state for us */
  96306. obj->num_tracks = x;
  96307. if(obj->num_tracks > 0) {
  96308. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  96309. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96310. return false;
  96311. }
  96312. for(i = 0; i < obj->num_tracks; i++) {
  96313. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  96314. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  96315. return false; /* read_callback_ sets the state for us */
  96316. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  96317. return false; /* read_callback_ sets the state for us */
  96318. track->number = (FLAC__byte)x;
  96319. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  96320. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  96321. return false; /* read_callback_ sets the state for us */
  96322. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  96323. return false; /* read_callback_ sets the state for us */
  96324. track->type = x;
  96325. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  96326. return false; /* read_callback_ sets the state for us */
  96327. track->pre_emphasis = x;
  96328. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  96329. return false; /* read_callback_ sets the state for us */
  96330. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  96331. return false; /* read_callback_ sets the state for us */
  96332. track->num_indices = (FLAC__byte)x;
  96333. if(track->num_indices > 0) {
  96334. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  96335. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96336. return false;
  96337. }
  96338. for(j = 0; j < track->num_indices; j++) {
  96339. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  96340. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  96341. return false; /* read_callback_ sets the state for us */
  96342. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  96343. return false; /* read_callback_ sets the state for us */
  96344. index->number = (FLAC__byte)x;
  96345. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  96346. return false; /* read_callback_ sets the state for us */
  96347. }
  96348. }
  96349. }
  96350. }
  96351. return true;
  96352. }
  96353. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  96354. {
  96355. FLAC__uint32 x;
  96356. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96357. /* read type */
  96358. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  96359. return false; /* read_callback_ sets the state for us */
  96360. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  96361. /* read MIME type */
  96362. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  96363. return false; /* read_callback_ sets the state for us */
  96364. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  96365. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96366. return false;
  96367. }
  96368. if(x > 0) {
  96369. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  96370. return false; /* read_callback_ sets the state for us */
  96371. }
  96372. obj->mime_type[x] = '\0';
  96373. /* read description */
  96374. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  96375. return false; /* read_callback_ sets the state for us */
  96376. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  96377. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96378. return false;
  96379. }
  96380. if(x > 0) {
  96381. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  96382. return false; /* read_callback_ sets the state for us */
  96383. }
  96384. obj->description[x] = '\0';
  96385. /* read width */
  96386. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  96387. return false; /* read_callback_ sets the state for us */
  96388. /* read height */
  96389. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  96390. return false; /* read_callback_ sets the state for us */
  96391. /* read depth */
  96392. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  96393. return false; /* read_callback_ sets the state for us */
  96394. /* read colors */
  96395. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  96396. return false; /* read_callback_ sets the state for us */
  96397. /* read data */
  96398. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  96399. return false; /* read_callback_ sets the state for us */
  96400. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  96401. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96402. return false;
  96403. }
  96404. if(obj->data_length > 0) {
  96405. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  96406. return false; /* read_callback_ sets the state for us */
  96407. }
  96408. return true;
  96409. }
  96410. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  96411. {
  96412. FLAC__uint32 x;
  96413. unsigned i, skip;
  96414. /* skip the version and flags bytes */
  96415. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  96416. return false; /* read_callback_ sets the state for us */
  96417. /* get the size (in bytes) to skip */
  96418. skip = 0;
  96419. for(i = 0; i < 4; i++) {
  96420. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96421. return false; /* read_callback_ sets the state for us */
  96422. skip <<= 7;
  96423. skip |= (x & 0x7f);
  96424. }
  96425. /* skip the rest of the tag */
  96426. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  96427. return false; /* read_callback_ sets the state for us */
  96428. return true;
  96429. }
  96430. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  96431. {
  96432. FLAC__uint32 x;
  96433. FLAC__bool first = true;
  96434. /* If we know the total number of samples in the stream, stop if we've read that many. */
  96435. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  96436. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  96437. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96438. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96439. return true;
  96440. }
  96441. }
  96442. /* make sure we're byte aligned */
  96443. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  96444. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  96445. return false; /* read_callback_ sets the state for us */
  96446. }
  96447. while(1) {
  96448. if(decoder->private_->cached) {
  96449. x = (FLAC__uint32)decoder->private_->lookahead;
  96450. decoder->private_->cached = false;
  96451. }
  96452. else {
  96453. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96454. return false; /* read_callback_ sets the state for us */
  96455. }
  96456. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96457. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96458. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96459. return false; /* read_callback_ sets the state for us */
  96460. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  96461. /* else we have to check if the second byte is the end of a sync code */
  96462. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96463. decoder->private_->lookahead = (FLAC__byte)x;
  96464. decoder->private_->cached = true;
  96465. }
  96466. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96467. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96468. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96469. return true;
  96470. }
  96471. }
  96472. if(first) {
  96473. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96474. first = false;
  96475. }
  96476. }
  96477. return true;
  96478. }
  96479. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  96480. {
  96481. unsigned channel;
  96482. unsigned i;
  96483. FLAC__int32 mid, side;
  96484. unsigned frame_crc; /* the one we calculate from the input stream */
  96485. FLAC__uint32 x;
  96486. *got_a_frame = false;
  96487. /* init the CRC */
  96488. frame_crc = 0;
  96489. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  96490. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  96491. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  96492. if(!read_frame_header_(decoder))
  96493. return false;
  96494. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  96495. return true;
  96496. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  96497. return false;
  96498. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96499. /*
  96500. * first figure the correct bits-per-sample of the subframe
  96501. */
  96502. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  96503. switch(decoder->private_->frame.header.channel_assignment) {
  96504. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96505. /* no adjustment needed */
  96506. break;
  96507. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96508. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96509. if(channel == 1)
  96510. bps++;
  96511. break;
  96512. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96513. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96514. if(channel == 0)
  96515. bps++;
  96516. break;
  96517. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96518. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96519. if(channel == 1)
  96520. bps++;
  96521. break;
  96522. default:
  96523. FLAC__ASSERT(0);
  96524. }
  96525. /*
  96526. * now read it
  96527. */
  96528. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  96529. return false;
  96530. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96531. return true;
  96532. }
  96533. if(!read_zero_padding_(decoder))
  96534. return false;
  96535. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
  96536. return true;
  96537. /*
  96538. * Read the frame CRC-16 from the footer and check
  96539. */
  96540. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  96541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  96542. return false; /* read_callback_ sets the state for us */
  96543. if(frame_crc == x) {
  96544. if(do_full_decode) {
  96545. /* Undo any special channel coding */
  96546. switch(decoder->private_->frame.header.channel_assignment) {
  96547. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96548. /* do nothing */
  96549. break;
  96550. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96551. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96552. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96553. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  96554. break;
  96555. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96556. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96557. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96558. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  96559. break;
  96560. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96561. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96562. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96563. #if 1
  96564. mid = decoder->private_->output[0][i];
  96565. side = decoder->private_->output[1][i];
  96566. mid <<= 1;
  96567. mid |= (side & 1); /* i.e. if 'side' is odd... */
  96568. decoder->private_->output[0][i] = (mid + side) >> 1;
  96569. decoder->private_->output[1][i] = (mid - side) >> 1;
  96570. #else
  96571. /* OPT: without 'side' temp variable */
  96572. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  96573. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  96574. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  96575. #endif
  96576. }
  96577. break;
  96578. default:
  96579. FLAC__ASSERT(0);
  96580. break;
  96581. }
  96582. }
  96583. }
  96584. else {
  96585. /* Bad frame, emit error and zero the output signal */
  96586. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  96587. if(do_full_decode) {
  96588. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96589. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96590. }
  96591. }
  96592. }
  96593. *got_a_frame = true;
  96594. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  96595. if(decoder->private_->next_fixed_block_size)
  96596. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  96597. /* put the latest values into the public section of the decoder instance */
  96598. decoder->protected_->channels = decoder->private_->frame.header.channels;
  96599. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  96600. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  96601. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  96602. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  96603. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96604. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  96605. /* write it */
  96606. if(do_full_decode) {
  96607. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  96608. return false;
  96609. }
  96610. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96611. return true;
  96612. }
  96613. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  96614. {
  96615. FLAC__uint32 x;
  96616. FLAC__uint64 xx;
  96617. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  96618. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  96619. unsigned raw_header_len;
  96620. FLAC__bool is_unparseable = false;
  96621. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96622. /* init the raw header with the saved bits from synchronization */
  96623. raw_header[0] = decoder->private_->header_warmup[0];
  96624. raw_header[1] = decoder->private_->header_warmup[1];
  96625. raw_header_len = 2;
  96626. /* check to make sure that reserved bit is 0 */
  96627. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  96628. is_unparseable = true;
  96629. /*
  96630. * Note that along the way as we read the header, we look for a sync
  96631. * code inside. If we find one it would indicate that our original
  96632. * sync was bad since there cannot be a sync code in a valid header.
  96633. *
  96634. * Three kinds of things can go wrong when reading the frame header:
  96635. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  96636. * If we don't find a sync code, it can end up looking like we read
  96637. * a valid but unparseable header, until getting to the frame header
  96638. * CRC. Even then we could get a false positive on the CRC.
  96639. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  96640. * future encoder).
  96641. * 3) We may be on a damaged frame which appears valid but unparseable.
  96642. *
  96643. * For all these reasons, we try and read a complete frame header as
  96644. * long as it seems valid, even if unparseable, up until the frame
  96645. * header CRC.
  96646. */
  96647. /*
  96648. * read in the raw header as bytes so we can CRC it, and parse it on the way
  96649. */
  96650. for(i = 0; i < 2; i++) {
  96651. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96652. return false; /* read_callback_ sets the state for us */
  96653. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96654. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  96655. decoder->private_->lookahead = (FLAC__byte)x;
  96656. decoder->private_->cached = true;
  96657. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96658. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96659. return true;
  96660. }
  96661. raw_header[raw_header_len++] = (FLAC__byte)x;
  96662. }
  96663. switch(x = raw_header[2] >> 4) {
  96664. case 0:
  96665. is_unparseable = true;
  96666. break;
  96667. case 1:
  96668. decoder->private_->frame.header.blocksize = 192;
  96669. break;
  96670. case 2:
  96671. case 3:
  96672. case 4:
  96673. case 5:
  96674. decoder->private_->frame.header.blocksize = 576 << (x-2);
  96675. break;
  96676. case 6:
  96677. case 7:
  96678. blocksize_hint = x;
  96679. break;
  96680. case 8:
  96681. case 9:
  96682. case 10:
  96683. case 11:
  96684. case 12:
  96685. case 13:
  96686. case 14:
  96687. case 15:
  96688. decoder->private_->frame.header.blocksize = 256 << (x-8);
  96689. break;
  96690. default:
  96691. FLAC__ASSERT(0);
  96692. break;
  96693. }
  96694. switch(x = raw_header[2] & 0x0f) {
  96695. case 0:
  96696. if(decoder->private_->has_stream_info)
  96697. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  96698. else
  96699. is_unparseable = true;
  96700. break;
  96701. case 1:
  96702. decoder->private_->frame.header.sample_rate = 88200;
  96703. break;
  96704. case 2:
  96705. decoder->private_->frame.header.sample_rate = 176400;
  96706. break;
  96707. case 3:
  96708. decoder->private_->frame.header.sample_rate = 192000;
  96709. break;
  96710. case 4:
  96711. decoder->private_->frame.header.sample_rate = 8000;
  96712. break;
  96713. case 5:
  96714. decoder->private_->frame.header.sample_rate = 16000;
  96715. break;
  96716. case 6:
  96717. decoder->private_->frame.header.sample_rate = 22050;
  96718. break;
  96719. case 7:
  96720. decoder->private_->frame.header.sample_rate = 24000;
  96721. break;
  96722. case 8:
  96723. decoder->private_->frame.header.sample_rate = 32000;
  96724. break;
  96725. case 9:
  96726. decoder->private_->frame.header.sample_rate = 44100;
  96727. break;
  96728. case 10:
  96729. decoder->private_->frame.header.sample_rate = 48000;
  96730. break;
  96731. case 11:
  96732. decoder->private_->frame.header.sample_rate = 96000;
  96733. break;
  96734. case 12:
  96735. case 13:
  96736. case 14:
  96737. sample_rate_hint = x;
  96738. break;
  96739. case 15:
  96740. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96741. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96742. return true;
  96743. default:
  96744. FLAC__ASSERT(0);
  96745. }
  96746. x = (unsigned)(raw_header[3] >> 4);
  96747. if(x & 8) {
  96748. decoder->private_->frame.header.channels = 2;
  96749. switch(x & 7) {
  96750. case 0:
  96751. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  96752. break;
  96753. case 1:
  96754. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  96755. break;
  96756. case 2:
  96757. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  96758. break;
  96759. default:
  96760. is_unparseable = true;
  96761. break;
  96762. }
  96763. }
  96764. else {
  96765. decoder->private_->frame.header.channels = (unsigned)x + 1;
  96766. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  96767. }
  96768. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  96769. case 0:
  96770. if(decoder->private_->has_stream_info)
  96771. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96772. else
  96773. is_unparseable = true;
  96774. break;
  96775. case 1:
  96776. decoder->private_->frame.header.bits_per_sample = 8;
  96777. break;
  96778. case 2:
  96779. decoder->private_->frame.header.bits_per_sample = 12;
  96780. break;
  96781. case 4:
  96782. decoder->private_->frame.header.bits_per_sample = 16;
  96783. break;
  96784. case 5:
  96785. decoder->private_->frame.header.bits_per_sample = 20;
  96786. break;
  96787. case 6:
  96788. decoder->private_->frame.header.bits_per_sample = 24;
  96789. break;
  96790. case 3:
  96791. case 7:
  96792. is_unparseable = true;
  96793. break;
  96794. default:
  96795. FLAC__ASSERT(0);
  96796. break;
  96797. }
  96798. /* check to make sure that reserved bit is 0 */
  96799. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  96800. is_unparseable = true;
  96801. /* read the frame's starting sample number (or frame number as the case may be) */
  96802. if(
  96803. raw_header[1] & 0x01 ||
  96804. /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
  96805. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  96806. ) { /* variable blocksize */
  96807. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  96808. return false; /* read_callback_ sets the state for us */
  96809. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  96810. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96811. decoder->private_->cached = true;
  96812. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96813. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96814. return true;
  96815. }
  96816. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96817. decoder->private_->frame.header.number.sample_number = xx;
  96818. }
  96819. else { /* fixed blocksize */
  96820. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  96821. return false; /* read_callback_ sets the state for us */
  96822. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  96823. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96824. decoder->private_->cached = true;
  96825. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96826. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96827. return true;
  96828. }
  96829. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  96830. decoder->private_->frame.header.number.frame_number = x;
  96831. }
  96832. if(blocksize_hint) {
  96833. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96834. return false; /* read_callback_ sets the state for us */
  96835. raw_header[raw_header_len++] = (FLAC__byte)x;
  96836. if(blocksize_hint == 7) {
  96837. FLAC__uint32 _x;
  96838. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96839. return false; /* read_callback_ sets the state for us */
  96840. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96841. x = (x << 8) | _x;
  96842. }
  96843. decoder->private_->frame.header.blocksize = x+1;
  96844. }
  96845. if(sample_rate_hint) {
  96846. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96847. return false; /* read_callback_ sets the state for us */
  96848. raw_header[raw_header_len++] = (FLAC__byte)x;
  96849. if(sample_rate_hint != 12) {
  96850. FLAC__uint32 _x;
  96851. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96852. return false; /* read_callback_ sets the state for us */
  96853. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96854. x = (x << 8) | _x;
  96855. }
  96856. if(sample_rate_hint == 12)
  96857. decoder->private_->frame.header.sample_rate = x*1000;
  96858. else if(sample_rate_hint == 13)
  96859. decoder->private_->frame.header.sample_rate = x;
  96860. else
  96861. decoder->private_->frame.header.sample_rate = x*10;
  96862. }
  96863. /* read the CRC-8 byte */
  96864. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96865. return false; /* read_callback_ sets the state for us */
  96866. crc8 = (FLAC__byte)x;
  96867. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  96868. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96869. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96870. return true;
  96871. }
  96872. /* calculate the sample number from the frame number if needed */
  96873. decoder->private_->next_fixed_block_size = 0;
  96874. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  96875. x = decoder->private_->frame.header.number.frame_number;
  96876. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96877. if(decoder->private_->fixed_block_size)
  96878. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  96879. else if(decoder->private_->has_stream_info) {
  96880. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  96881. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  96882. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96883. }
  96884. else
  96885. is_unparseable = true;
  96886. }
  96887. else if(x == 0) {
  96888. decoder->private_->frame.header.number.sample_number = 0;
  96889. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  96890. }
  96891. else {
  96892. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  96893. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  96894. }
  96895. }
  96896. if(is_unparseable) {
  96897. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96898. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96899. return true;
  96900. }
  96901. return true;
  96902. }
  96903. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96904. {
  96905. FLAC__uint32 x;
  96906. FLAC__bool wasted_bits;
  96907. unsigned i;
  96908. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  96909. return false; /* read_callback_ sets the state for us */
  96910. wasted_bits = (x & 1);
  96911. x &= 0xfe;
  96912. if(wasted_bits) {
  96913. unsigned u;
  96914. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  96915. return false; /* read_callback_ sets the state for us */
  96916. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  96917. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  96918. }
  96919. else
  96920. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  96921. /*
  96922. * Lots of magic numbers here
  96923. */
  96924. if(x & 0x80) {
  96925. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96926. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96927. return true;
  96928. }
  96929. else if(x == 0) {
  96930. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  96931. return false;
  96932. }
  96933. else if(x == 2) {
  96934. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  96935. return false;
  96936. }
  96937. else if(x < 16) {
  96938. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96939. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96940. return true;
  96941. }
  96942. else if(x <= 24) {
  96943. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  96944. return false;
  96945. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96946. return true;
  96947. }
  96948. else if(x < 64) {
  96949. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96950. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96951. return true;
  96952. }
  96953. else {
  96954. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  96955. return false;
  96956. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96957. return true;
  96958. }
  96959. if(wasted_bits && do_full_decode) {
  96960. x = decoder->private_->frame.subframes[channel].wasted_bits;
  96961. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96962. decoder->private_->output[channel][i] <<= x;
  96963. }
  96964. return true;
  96965. }
  96966. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96967. {
  96968. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  96969. FLAC__int32 x;
  96970. unsigned i;
  96971. FLAC__int32 *output = decoder->private_->output[channel];
  96972. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  96973. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96974. return false; /* read_callback_ sets the state for us */
  96975. subframe->value = x;
  96976. /* decode the subframe */
  96977. if(do_full_decode) {
  96978. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96979. output[i] = x;
  96980. }
  96981. return true;
  96982. }
  96983. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96984. {
  96985. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  96986. FLAC__int32 i32;
  96987. FLAC__uint32 u32;
  96988. unsigned u;
  96989. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  96990. subframe->residual = decoder->private_->residual[channel];
  96991. subframe->order = order;
  96992. /* read warm-up samples */
  96993. for(u = 0; u < order; u++) {
  96994. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96995. return false; /* read_callback_ sets the state for us */
  96996. subframe->warmup[u] = i32;
  96997. }
  96998. /* read entropy coding method info */
  96999. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97000. return false; /* read_callback_ sets the state for us */
  97001. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97002. switch(subframe->entropy_coding_method.type) {
  97003. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97004. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97005. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97006. return false; /* read_callback_ sets the state for us */
  97007. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97008. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97009. break;
  97010. default:
  97011. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97012. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97013. return true;
  97014. }
  97015. /* read residual */
  97016. switch(subframe->entropy_coding_method.type) {
  97017. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97018. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97019. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  97020. return false;
  97021. break;
  97022. default:
  97023. FLAC__ASSERT(0);
  97024. }
  97025. /* decode the subframe */
  97026. if(do_full_decode) {
  97027. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97028. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  97029. }
  97030. return true;
  97031. }
  97032. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97033. {
  97034. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  97035. FLAC__int32 i32;
  97036. FLAC__uint32 u32;
  97037. unsigned u;
  97038. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  97039. subframe->residual = decoder->private_->residual[channel];
  97040. subframe->order = order;
  97041. /* read warm-up samples */
  97042. for(u = 0; u < order; u++) {
  97043. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97044. return false; /* read_callback_ sets the state for us */
  97045. subframe->warmup[u] = i32;
  97046. }
  97047. /* read qlp coeff precision */
  97048. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  97049. return false; /* read_callback_ sets the state for us */
  97050. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  97051. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97052. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97053. return true;
  97054. }
  97055. subframe->qlp_coeff_precision = u32+1;
  97056. /* read qlp shift */
  97057. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  97058. return false; /* read_callback_ sets the state for us */
  97059. subframe->quantization_level = i32;
  97060. /* read quantized lp coefficiencts */
  97061. for(u = 0; u < order; u++) {
  97062. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  97063. return false; /* read_callback_ sets the state for us */
  97064. subframe->qlp_coeff[u] = i32;
  97065. }
  97066. /* read entropy coding method info */
  97067. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97068. return false; /* read_callback_ sets the state for us */
  97069. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97070. switch(subframe->entropy_coding_method.type) {
  97071. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97072. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97073. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97074. return false; /* read_callback_ sets the state for us */
  97075. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97076. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97077. break;
  97078. default:
  97079. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97080. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97081. return true;
  97082. }
  97083. /* read residual */
  97084. switch(subframe->entropy_coding_method.type) {
  97085. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97086. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97087. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  97088. return false;
  97089. break;
  97090. default:
  97091. FLAC__ASSERT(0);
  97092. }
  97093. /* decode the subframe */
  97094. if(do_full_decode) {
  97095. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97096. /*@@@@@@ technically not pessimistic enough, should be more like
  97097. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  97098. */
  97099. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  97100. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  97101. if(order <= 8)
  97102. decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  97103. else
  97104. decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  97105. }
  97106. else
  97107. decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  97108. else
  97109. decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  97110. }
  97111. return true;
  97112. }
  97113. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97114. {
  97115. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  97116. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  97117. unsigned i;
  97118. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  97119. subframe->data = residual;
  97120. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97121. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97122. return false; /* read_callback_ sets the state for us */
  97123. residual[i] = x;
  97124. }
  97125. /* decode the subframe */
  97126. if(do_full_decode)
  97127. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97128. return true;
  97129. }
  97130. FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
  97131. {
  97132. FLAC__uint32 rice_parameter;
  97133. int i;
  97134. unsigned partition, sample, u;
  97135. const unsigned partitions = 1u << partition_order;
  97136. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  97137. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  97138. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  97139. /* sanity checks */
  97140. if(partition_order == 0) {
  97141. if(decoder->private_->frame.header.blocksize < predictor_order) {
  97142. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97143. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97144. return true;
  97145. }
  97146. }
  97147. else {
  97148. if(partition_samples < predictor_order) {
  97149. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97150. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97151. return true;
  97152. }
  97153. }
  97154. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97155. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97156. return false;
  97157. }
  97158. sample = 0;
  97159. for(partition = 0; partition < partitions; partition++) {
  97160. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97161. return false; /* read_callback_ sets the state for us */
  97162. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97163. if(rice_parameter < pesc) {
  97164. partitioned_rice_contents->raw_bits[partition] = 0;
  97165. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97166. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97167. return false; /* read_callback_ sets the state for us */
  97168. sample += u;
  97169. }
  97170. else {
  97171. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97172. return false; /* read_callback_ sets the state for us */
  97173. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97174. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97175. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97176. return false; /* read_callback_ sets the state for us */
  97177. residual[sample] = i;
  97178. }
  97179. }
  97180. }
  97181. return true;
  97182. }
  97183. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97184. {
  97185. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97186. FLAC__uint32 zero = 0;
  97187. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97188. return false; /* read_callback_ sets the state for us */
  97189. if(zero != 0) {
  97190. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97191. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97192. }
  97193. }
  97194. return true;
  97195. }
  97196. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97197. {
  97198. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97199. if(
  97200. #if FLAC__HAS_OGG
  97201. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97202. !decoder->private_->is_ogg &&
  97203. #endif
  97204. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97205. ) {
  97206. *bytes = 0;
  97207. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97208. return false;
  97209. }
  97210. else if(*bytes > 0) {
  97211. /* While seeking, it is possible for our seek to land in the
  97212. * middle of audio data that looks exactly like a frame header
  97213. * from a future version of an encoder. When that happens, our
  97214. * error callback will get an
  97215. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97216. * unparseable_frame_count. But there is a remote possibility
  97217. * that it is properly synced at such a "future-codec frame",
  97218. * so to make sure, we wait to see many "unparseable" errors in
  97219. * a row before bailing out.
  97220. */
  97221. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97222. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97223. return false;
  97224. }
  97225. else {
  97226. const FLAC__StreamDecoderReadStatus status =
  97227. #if FLAC__HAS_OGG
  97228. decoder->private_->is_ogg?
  97229. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97230. #endif
  97231. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97232. ;
  97233. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97234. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97235. return false;
  97236. }
  97237. else if(*bytes == 0) {
  97238. if(
  97239. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  97240. (
  97241. #if FLAC__HAS_OGG
  97242. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97243. !decoder->private_->is_ogg &&
  97244. #endif
  97245. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97246. )
  97247. ) {
  97248. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97249. return false;
  97250. }
  97251. else
  97252. return true;
  97253. }
  97254. else
  97255. return true;
  97256. }
  97257. }
  97258. else {
  97259. /* abort to avoid a deadlock */
  97260. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97261. return false;
  97262. }
  97263. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  97264. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  97265. * and at the same time hit the end of the stream (for example, seeking
  97266. * to a point that is after the beginning of the last Ogg page). There
  97267. * is no way to report an Ogg sync loss through the callbacks (see note
  97268. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  97269. * So to keep the decoder from stopping at this point we gate the call
  97270. * to the eof_callback and let the Ogg decoder aspect set the
  97271. * end-of-stream state when it is needed.
  97272. */
  97273. }
  97274. #if FLAC__HAS_OGG
  97275. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  97276. {
  97277. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  97278. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  97279. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97280. /* we don't really have a way to handle lost sync via read
  97281. * callback so we'll let it pass and let the underlying
  97282. * FLAC decoder catch the error
  97283. */
  97284. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  97285. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97286. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  97287. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97288. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  97289. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  97290. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  97291. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  97292. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  97293. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97294. default:
  97295. FLAC__ASSERT(0);
  97296. /* double protection */
  97297. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97298. }
  97299. }
  97300. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97301. {
  97302. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  97303. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  97304. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  97305. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  97306. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  97307. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  97308. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  97309. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97310. default:
  97311. /* double protection: */
  97312. FLAC__ASSERT(0);
  97313. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97314. }
  97315. }
  97316. #endif
  97317. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  97318. {
  97319. if(decoder->private_->is_seeking) {
  97320. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  97321. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  97322. FLAC__uint64 target_sample = decoder->private_->target_sample;
  97323. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97324. #if FLAC__HAS_OGG
  97325. decoder->private_->got_a_frame = true;
  97326. #endif
  97327. decoder->private_->last_frame = *frame; /* save the frame */
  97328. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  97329. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  97330. /* kick out of seek mode */
  97331. decoder->private_->is_seeking = false;
  97332. /* shift out the samples before target_sample */
  97333. if(delta > 0) {
  97334. unsigned channel;
  97335. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  97336. for(channel = 0; channel < frame->header.channels; channel++)
  97337. newbuffer[channel] = buffer[channel] + delta;
  97338. decoder->private_->last_frame.header.blocksize -= delta;
  97339. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  97340. /* write the relevant samples */
  97341. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  97342. }
  97343. else {
  97344. /* write the relevant samples */
  97345. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97346. }
  97347. }
  97348. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  97349. }
  97350. /*
  97351. * If we never got STREAMINFO, turn off MD5 checking to save
  97352. * cycles since we don't have a sum to compare to anyway
  97353. */
  97354. if(!decoder->private_->has_stream_info)
  97355. decoder->private_->do_md5_checking = false;
  97356. if(decoder->private_->do_md5_checking) {
  97357. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  97358. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  97359. }
  97360. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97361. }
  97362. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  97363. {
  97364. if(!decoder->private_->is_seeking)
  97365. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  97366. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  97367. decoder->private_->unparseable_frame_count++;
  97368. }
  97369. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97370. {
  97371. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  97372. FLAC__int64 pos = -1;
  97373. int i;
  97374. unsigned approx_bytes_per_frame;
  97375. FLAC__bool first_seek = true;
  97376. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  97377. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  97378. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97379. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  97380. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  97381. /* take these from the current frame in case they've changed mid-stream */
  97382. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  97383. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  97384. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  97385. /* use values from stream info if we didn't decode a frame */
  97386. if(channels == 0)
  97387. channels = decoder->private_->stream_info.data.stream_info.channels;
  97388. if(bps == 0)
  97389. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97390. /* we are just guessing here */
  97391. if(max_framesize > 0)
  97392. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  97393. /*
  97394. * Check if it's a known fixed-blocksize stream. Note that though
  97395. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  97396. * never get a STREAMINFO block when decoding so the value of
  97397. * min_blocksize might be zero.
  97398. */
  97399. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  97400. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  97401. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  97402. }
  97403. else
  97404. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  97405. /*
  97406. * First, we set an upper and lower bound on where in the
  97407. * stream we will search. For now we assume the worst case
  97408. * scenario, which is our best guess at the beginning of
  97409. * the first frame and end of the stream.
  97410. */
  97411. lower_bound = first_frame_offset;
  97412. lower_bound_sample = 0;
  97413. upper_bound = stream_length;
  97414. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  97415. /*
  97416. * Now we refine the bounds if we have a seektable with
  97417. * suitable points. Note that according to the spec they
  97418. * must be ordered by ascending sample number.
  97419. *
  97420. * Note: to protect against invalid seek tables we will ignore points
  97421. * that have frame_samples==0 or sample_number>=total_samples
  97422. */
  97423. if(seek_table) {
  97424. FLAC__uint64 new_lower_bound = lower_bound;
  97425. FLAC__uint64 new_upper_bound = upper_bound;
  97426. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  97427. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  97428. /* find the closest seek point <= target_sample, if it exists */
  97429. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  97430. if(
  97431. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97432. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97433. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97434. seek_table->points[i].sample_number <= target_sample
  97435. )
  97436. break;
  97437. }
  97438. if(i >= 0) { /* i.e. we found a suitable seek point... */
  97439. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97440. new_lower_bound_sample = seek_table->points[i].sample_number;
  97441. }
  97442. /* find the closest seek point > target_sample, if it exists */
  97443. for(i = 0; i < (int)seek_table->num_points; i++) {
  97444. if(
  97445. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97446. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97447. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97448. seek_table->points[i].sample_number > target_sample
  97449. )
  97450. break;
  97451. }
  97452. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  97453. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97454. new_upper_bound_sample = seek_table->points[i].sample_number;
  97455. }
  97456. /* final protection against unsorted seek tables; keep original values if bogus */
  97457. if(new_upper_bound >= new_lower_bound) {
  97458. lower_bound = new_lower_bound;
  97459. upper_bound = new_upper_bound;
  97460. lower_bound_sample = new_lower_bound_sample;
  97461. upper_bound_sample = new_upper_bound_sample;
  97462. }
  97463. }
  97464. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  97465. /* there are 2 insidious ways that the following equality occurs, which
  97466. * we need to fix:
  97467. * 1) total_samples is 0 (unknown) and target_sample is 0
  97468. * 2) total_samples is 0 (unknown) and target_sample happens to be
  97469. * exactly equal to the last seek point in the seek table; this
  97470. * means there is no seek point above it, and upper_bound_samples
  97471. * remains equal to the estimate (of target_samples) we made above
  97472. * in either case it does not hurt to move upper_bound_sample up by 1
  97473. */
  97474. if(upper_bound_sample == lower_bound_sample)
  97475. upper_bound_sample++;
  97476. decoder->private_->target_sample = target_sample;
  97477. while(1) {
  97478. /* check if the bounds are still ok */
  97479. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  97480. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97481. return false;
  97482. }
  97483. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97484. #if defined _MSC_VER || defined __MINGW32__
  97485. /* with VC++ you have to spoon feed it the casting */
  97486. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  97487. #else
  97488. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  97489. #endif
  97490. #else
  97491. /* a little less accurate: */
  97492. if(upper_bound - lower_bound < 0xffffffff)
  97493. pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
  97494. else /* @@@ WATCHOUT, ~2TB limit */
  97495. pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
  97496. #endif
  97497. if(pos >= (FLAC__int64)upper_bound)
  97498. pos = (FLAC__int64)upper_bound - 1;
  97499. if(pos < (FLAC__int64)lower_bound)
  97500. pos = (FLAC__int64)lower_bound;
  97501. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97502. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97503. return false;
  97504. }
  97505. if(!FLAC__stream_decoder_flush(decoder)) {
  97506. /* above call sets the state for us */
  97507. return false;
  97508. }
  97509. /* Now we need to get a frame. First we need to reset our
  97510. * unparseable_frame_count; if we get too many unparseable
  97511. * frames in a row, the read callback will return
  97512. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  97513. * FLAC__stream_decoder_process_single() to return false.
  97514. */
  97515. decoder->private_->unparseable_frame_count = 0;
  97516. if(!FLAC__stream_decoder_process_single(decoder)) {
  97517. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97518. return false;
  97519. }
  97520. /* our write callback will change the state when it gets to the target frame */
  97521. /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
  97522. #if 0
  97523. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  97524. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  97525. break;
  97526. #endif
  97527. if(!decoder->private_->is_seeking)
  97528. break;
  97529. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97530. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97531. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  97532. if (pos == (FLAC__int64)lower_bound) {
  97533. /* can't move back any more than the first frame, something is fatally wrong */
  97534. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97535. return false;
  97536. }
  97537. /* our last move backwards wasn't big enough, try again */
  97538. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  97539. continue;
  97540. }
  97541. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  97542. first_seek = false;
  97543. /* make sure we are not seeking in corrupted stream */
  97544. if (this_frame_sample < lower_bound_sample) {
  97545. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97546. return false;
  97547. }
  97548. /* we need to narrow the search */
  97549. if(target_sample < this_frame_sample) {
  97550. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97551. /*@@@@@@ what will decode position be if at end of stream? */
  97552. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  97553. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97554. return false;
  97555. }
  97556. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  97557. }
  97558. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  97559. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97560. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  97561. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97562. return false;
  97563. }
  97564. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  97565. }
  97566. }
  97567. return true;
  97568. }
  97569. #if FLAC__HAS_OGG
  97570. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97571. {
  97572. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  97573. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  97574. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  97575. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  97576. FLAC__bool did_a_seek;
  97577. unsigned iteration = 0;
  97578. /* In the first iterations, we will calculate the target byte position
  97579. * by the distance from the target sample to left_sample and
  97580. * right_sample (let's call it "proportional search"). After that, we
  97581. * will switch to binary search.
  97582. */
  97583. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  97584. /* We will switch to a linear search once our current sample is less
  97585. * than this number of samples ahead of the target sample
  97586. */
  97587. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  97588. /* If the total number of samples is unknown, use a large value, and
  97589. * force binary search immediately.
  97590. */
  97591. if(right_sample == 0) {
  97592. right_sample = (FLAC__uint64)(-1);
  97593. BINARY_SEARCH_AFTER_ITERATION = 0;
  97594. }
  97595. decoder->private_->target_sample = target_sample;
  97596. for( ; ; iteration++) {
  97597. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  97598. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  97599. pos = (right_pos + left_pos) / 2;
  97600. }
  97601. else {
  97602. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97603. #if defined _MSC_VER || defined __MINGW32__
  97604. /* with MSVC you have to spoon feed it the casting */
  97605. pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos));
  97606. #else
  97607. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  97608. #endif
  97609. #else
  97610. /* a little less accurate: */
  97611. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  97612. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  97613. else /* @@@ WATCHOUT, ~2TB limit */
  97614. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  97615. #endif
  97616. /* @@@ TODO: might want to limit pos to some distance
  97617. * before EOF, to make sure we land before the last frame,
  97618. * thereby getting a this_frame_sample and so having a better
  97619. * estimate.
  97620. */
  97621. }
  97622. /* physical seek */
  97623. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97624. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97625. return false;
  97626. }
  97627. if(!FLAC__stream_decoder_flush(decoder)) {
  97628. /* above call sets the state for us */
  97629. return false;
  97630. }
  97631. did_a_seek = true;
  97632. }
  97633. else
  97634. did_a_seek = false;
  97635. decoder->private_->got_a_frame = false;
  97636. if(!FLAC__stream_decoder_process_single(decoder)) {
  97637. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97638. return false;
  97639. }
  97640. if(!decoder->private_->got_a_frame) {
  97641. if(did_a_seek) {
  97642. /* this can happen if we seek to a point after the last frame; we drop
  97643. * to binary search right away in this case to avoid any wasted
  97644. * iterations of proportional search.
  97645. */
  97646. right_pos = pos;
  97647. BINARY_SEARCH_AFTER_ITERATION = 0;
  97648. }
  97649. else {
  97650. /* this can probably only happen if total_samples is unknown and the
  97651. * target_sample is past the end of the stream
  97652. */
  97653. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97654. return false;
  97655. }
  97656. }
  97657. /* our write callback will change the state when it gets to the target frame */
  97658. else if(!decoder->private_->is_seeking) {
  97659. break;
  97660. }
  97661. else {
  97662. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97663. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97664. if (did_a_seek) {
  97665. if (this_frame_sample <= target_sample) {
  97666. /* The 'equal' case should not happen, since
  97667. * FLAC__stream_decoder_process_single()
  97668. * should recognize that it has hit the
  97669. * target sample and we would exit through
  97670. * the 'break' above.
  97671. */
  97672. FLAC__ASSERT(this_frame_sample != target_sample);
  97673. left_sample = this_frame_sample;
  97674. /* sanity check to avoid infinite loop */
  97675. if (left_pos == pos) {
  97676. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97677. return false;
  97678. }
  97679. left_pos = pos;
  97680. }
  97681. else if(this_frame_sample > target_sample) {
  97682. right_sample = this_frame_sample;
  97683. /* sanity check to avoid infinite loop */
  97684. if (right_pos == pos) {
  97685. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97686. return false;
  97687. }
  97688. right_pos = pos;
  97689. }
  97690. }
  97691. }
  97692. }
  97693. return true;
  97694. }
  97695. #endif
  97696. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97697. {
  97698. (void)client_data;
  97699. if(*bytes > 0) {
  97700. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  97701. if(ferror(decoder->private_->file))
  97702. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97703. else if(*bytes == 0)
  97704. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97705. else
  97706. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97707. }
  97708. else
  97709. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  97710. }
  97711. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  97712. {
  97713. (void)client_data;
  97714. if(decoder->private_->file == stdin)
  97715. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  97716. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  97717. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  97718. else
  97719. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  97720. }
  97721. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  97722. {
  97723. off_t pos;
  97724. (void)client_data;
  97725. if(decoder->private_->file == stdin)
  97726. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  97727. else if((pos = ftello(decoder->private_->file)) < 0)
  97728. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  97729. else {
  97730. *absolute_byte_offset = (FLAC__uint64)pos;
  97731. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  97732. }
  97733. }
  97734. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  97735. {
  97736. struct stat filestats;
  97737. (void)client_data;
  97738. if(decoder->private_->file == stdin)
  97739. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  97740. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  97741. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  97742. else {
  97743. *stream_length = (FLAC__uint64)filestats.st_size;
  97744. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  97745. }
  97746. }
  97747. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  97748. {
  97749. (void)client_data;
  97750. return feof(decoder->private_->file)? true : false;
  97751. }
  97752. #endif
  97753. /********* End of inlined file: stream_decoder.c *********/
  97754. /********* Start of inlined file: stream_encoder.c *********/
  97755. /********* Start of inlined file: juce_FlacHeader.h *********/
  97756. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97757. // tasks..
  97758. #define VERSION "1.2.1"
  97759. #define FLAC__NO_DLL 1
  97760. #if JUCE_MSVC
  97761. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97762. #endif
  97763. #if JUCE_MAC
  97764. #define FLAC__SYS_DARWIN 1
  97765. #endif
  97766. /********* End of inlined file: juce_FlacHeader.h *********/
  97767. #if JUCE_USE_FLAC
  97768. #if HAVE_CONFIG_H
  97769. # include <config.h>
  97770. #endif
  97771. #if defined _MSC_VER || defined __MINGW32__
  97772. #include <io.h> /* for _setmode() */
  97773. #include <fcntl.h> /* for _O_BINARY */
  97774. #endif
  97775. #if defined __CYGWIN__ || defined __EMX__
  97776. #include <io.h> /* for setmode(), O_BINARY */
  97777. #include <fcntl.h> /* for _O_BINARY */
  97778. #endif
  97779. #include <limits.h>
  97780. #include <stdio.h>
  97781. #include <stdlib.h> /* for malloc() */
  97782. #include <string.h> /* for memcpy() */
  97783. #include <sys/types.h> /* for off_t */
  97784. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  97785. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  97786. #define fseeko fseek
  97787. #define ftello ftell
  97788. #endif
  97789. #endif
  97790. /********* Start of inlined file: stream_encoder.h *********/
  97791. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  97792. #define FLAC__PROTECTED__STREAM_ENCODER_H
  97793. #if FLAC__HAS_OGG
  97794. #include "private/ogg_encoder_aspect.h"
  97795. #endif
  97796. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97797. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  97798. typedef enum {
  97799. FLAC__APODIZATION_BARTLETT,
  97800. FLAC__APODIZATION_BARTLETT_HANN,
  97801. FLAC__APODIZATION_BLACKMAN,
  97802. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  97803. FLAC__APODIZATION_CONNES,
  97804. FLAC__APODIZATION_FLATTOP,
  97805. FLAC__APODIZATION_GAUSS,
  97806. FLAC__APODIZATION_HAMMING,
  97807. FLAC__APODIZATION_HANN,
  97808. FLAC__APODIZATION_KAISER_BESSEL,
  97809. FLAC__APODIZATION_NUTTALL,
  97810. FLAC__APODIZATION_RECTANGLE,
  97811. FLAC__APODIZATION_TRIANGLE,
  97812. FLAC__APODIZATION_TUKEY,
  97813. FLAC__APODIZATION_WELCH
  97814. } FLAC__ApodizationFunction;
  97815. typedef struct {
  97816. FLAC__ApodizationFunction type;
  97817. union {
  97818. struct {
  97819. FLAC__real stddev;
  97820. } gauss;
  97821. struct {
  97822. FLAC__real p;
  97823. } tukey;
  97824. } parameters;
  97825. } FLAC__ApodizationSpecification;
  97826. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97827. typedef struct FLAC__StreamEncoderProtected {
  97828. FLAC__StreamEncoderState state;
  97829. FLAC__bool verify;
  97830. FLAC__bool streamable_subset;
  97831. FLAC__bool do_md5;
  97832. FLAC__bool do_mid_side_stereo;
  97833. FLAC__bool loose_mid_side_stereo;
  97834. unsigned channels;
  97835. unsigned bits_per_sample;
  97836. unsigned sample_rate;
  97837. unsigned blocksize;
  97838. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97839. unsigned num_apodizations;
  97840. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  97841. #endif
  97842. unsigned max_lpc_order;
  97843. unsigned qlp_coeff_precision;
  97844. FLAC__bool do_qlp_coeff_prec_search;
  97845. FLAC__bool do_exhaustive_model_search;
  97846. FLAC__bool do_escape_coding;
  97847. unsigned min_residual_partition_order;
  97848. unsigned max_residual_partition_order;
  97849. unsigned rice_parameter_search_dist;
  97850. FLAC__uint64 total_samples_estimate;
  97851. FLAC__StreamMetadata **metadata;
  97852. unsigned num_metadata_blocks;
  97853. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  97854. #if FLAC__HAS_OGG
  97855. FLAC__OggEncoderAspect ogg_encoder_aspect;
  97856. #endif
  97857. } FLAC__StreamEncoderProtected;
  97858. #endif
  97859. /********* End of inlined file: stream_encoder.h *********/
  97860. #if FLAC__HAS_OGG
  97861. #include "include/private/ogg_helper.h"
  97862. #include "include/private/ogg_mapping.h"
  97863. #endif
  97864. /********* Start of inlined file: stream_encoder_framing.h *********/
  97865. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97866. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97867. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  97868. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  97869. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97870. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97871. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97872. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97873. #endif
  97874. /********* End of inlined file: stream_encoder_framing.h *********/
  97875. /********* Start of inlined file: window.h *********/
  97876. #ifndef FLAC__PRIVATE__WINDOW_H
  97877. #define FLAC__PRIVATE__WINDOW_H
  97878. #ifdef HAVE_CONFIG_H
  97879. #include <config.h>
  97880. #endif
  97881. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97882. /*
  97883. * FLAC__window_*()
  97884. * --------------------------------------------------------------------
  97885. * Calculates window coefficients according to different apodization
  97886. * functions.
  97887. *
  97888. * OUT window[0,L-1]
  97889. * IN L (number of points in window)
  97890. */
  97891. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  97892. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  97893. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  97894. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  97895. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  97896. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  97897. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  97898. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  97899. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  97900. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  97901. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  97902. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  97903. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  97904. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  97905. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  97906. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97907. #endif
  97908. /********* End of inlined file: window.h *********/
  97909. #ifndef FLaC__INLINE
  97910. #define FLaC__INLINE
  97911. #endif
  97912. #ifdef min
  97913. #undef min
  97914. #endif
  97915. #define min(x,y) ((x)<(y)?(x):(y))
  97916. #ifdef max
  97917. #undef max
  97918. #endif
  97919. #define max(x,y) ((x)>(y)?(x):(y))
  97920. /* Exact Rice codeword length calculation is off by default. The simple
  97921. * (and fast) estimation (of how many bits a residual value will be
  97922. * encoded with) in this encoder is very good, almost always yielding
  97923. * compression within 0.1% of exact calculation.
  97924. */
  97925. #undef EXACT_RICE_BITS_CALCULATION
  97926. /* Rice parameter searching is off by default. The simple (and fast)
  97927. * parameter estimation in this encoder is very good, almost always
  97928. * yielding compression within 0.1% of the optimal parameters.
  97929. */
  97930. #undef ENABLE_RICE_PARAMETER_SEARCH
  97931. typedef struct {
  97932. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  97933. unsigned size; /* of each data[] in samples */
  97934. unsigned tail;
  97935. } verify_input_fifo;
  97936. typedef struct {
  97937. const FLAC__byte *data;
  97938. unsigned capacity;
  97939. unsigned bytes;
  97940. } verify_output;
  97941. typedef enum {
  97942. ENCODER_IN_MAGIC = 0,
  97943. ENCODER_IN_METADATA = 1,
  97944. ENCODER_IN_AUDIO = 2
  97945. } EncoderStateHint;
  97946. static struct CompressionLevels {
  97947. FLAC__bool do_mid_side_stereo;
  97948. FLAC__bool loose_mid_side_stereo;
  97949. unsigned max_lpc_order;
  97950. unsigned qlp_coeff_precision;
  97951. FLAC__bool do_qlp_coeff_prec_search;
  97952. FLAC__bool do_escape_coding;
  97953. FLAC__bool do_exhaustive_model_search;
  97954. unsigned min_residual_partition_order;
  97955. unsigned max_residual_partition_order;
  97956. unsigned rice_parameter_search_dist;
  97957. } compression_levels_[] = {
  97958. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  97959. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  97960. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  97961. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  97962. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  97963. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  97964. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  97965. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  97966. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  97967. };
  97968. /***********************************************************************
  97969. *
  97970. * Private class method prototypes
  97971. *
  97972. ***********************************************************************/
  97973. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  97974. static void free_(FLAC__StreamEncoder *encoder);
  97975. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  97976. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  97977. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  97978. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  97979. #if FLAC__HAS_OGG
  97980. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  97981. #endif
  97982. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  97983. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  97984. static FLAC__bool process_subframe_(
  97985. FLAC__StreamEncoder *encoder,
  97986. unsigned min_partition_order,
  97987. unsigned max_partition_order,
  97988. const FLAC__FrameHeader *frame_header,
  97989. unsigned subframe_bps,
  97990. const FLAC__int32 integer_signal[],
  97991. FLAC__Subframe *subframe[2],
  97992. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  97993. FLAC__int32 *residual[2],
  97994. unsigned *best_subframe,
  97995. unsigned *best_bits
  97996. );
  97997. static FLAC__bool add_subframe_(
  97998. FLAC__StreamEncoder *encoder,
  97999. unsigned blocksize,
  98000. unsigned subframe_bps,
  98001. const FLAC__Subframe *subframe,
  98002. FLAC__BitWriter *frame
  98003. );
  98004. static unsigned evaluate_constant_subframe_(
  98005. FLAC__StreamEncoder *encoder,
  98006. const FLAC__int32 signal,
  98007. unsigned blocksize,
  98008. unsigned subframe_bps,
  98009. FLAC__Subframe *subframe
  98010. );
  98011. static unsigned evaluate_fixed_subframe_(
  98012. FLAC__StreamEncoder *encoder,
  98013. const FLAC__int32 signal[],
  98014. FLAC__int32 residual[],
  98015. FLAC__uint64 abs_residual_partition_sums[],
  98016. unsigned raw_bits_per_partition[],
  98017. unsigned blocksize,
  98018. unsigned subframe_bps,
  98019. unsigned order,
  98020. unsigned rice_parameter,
  98021. unsigned rice_parameter_limit,
  98022. unsigned min_partition_order,
  98023. unsigned max_partition_order,
  98024. FLAC__bool do_escape_coding,
  98025. unsigned rice_parameter_search_dist,
  98026. FLAC__Subframe *subframe,
  98027. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98028. );
  98029. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98030. static unsigned evaluate_lpc_subframe_(
  98031. FLAC__StreamEncoder *encoder,
  98032. const FLAC__int32 signal[],
  98033. FLAC__int32 residual[],
  98034. FLAC__uint64 abs_residual_partition_sums[],
  98035. unsigned raw_bits_per_partition[],
  98036. const FLAC__real lp_coeff[],
  98037. unsigned blocksize,
  98038. unsigned subframe_bps,
  98039. unsigned order,
  98040. unsigned qlp_coeff_precision,
  98041. unsigned rice_parameter,
  98042. unsigned rice_parameter_limit,
  98043. unsigned min_partition_order,
  98044. unsigned max_partition_order,
  98045. FLAC__bool do_escape_coding,
  98046. unsigned rice_parameter_search_dist,
  98047. FLAC__Subframe *subframe,
  98048. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98049. );
  98050. #endif
  98051. static unsigned evaluate_verbatim_subframe_(
  98052. FLAC__StreamEncoder *encoder,
  98053. const FLAC__int32 signal[],
  98054. unsigned blocksize,
  98055. unsigned subframe_bps,
  98056. FLAC__Subframe *subframe
  98057. );
  98058. static unsigned find_best_partition_order_(
  98059. struct FLAC__StreamEncoderPrivate *private_,
  98060. const FLAC__int32 residual[],
  98061. FLAC__uint64 abs_residual_partition_sums[],
  98062. unsigned raw_bits_per_partition[],
  98063. unsigned residual_samples,
  98064. unsigned predictor_order,
  98065. unsigned rice_parameter,
  98066. unsigned rice_parameter_limit,
  98067. unsigned min_partition_order,
  98068. unsigned max_partition_order,
  98069. unsigned bps,
  98070. FLAC__bool do_escape_coding,
  98071. unsigned rice_parameter_search_dist,
  98072. FLAC__EntropyCodingMethod *best_ecm
  98073. );
  98074. static void precompute_partition_info_sums_(
  98075. const FLAC__int32 residual[],
  98076. FLAC__uint64 abs_residual_partition_sums[],
  98077. unsigned residual_samples,
  98078. unsigned predictor_order,
  98079. unsigned min_partition_order,
  98080. unsigned max_partition_order,
  98081. unsigned bps
  98082. );
  98083. static void precompute_partition_info_escapes_(
  98084. const FLAC__int32 residual[],
  98085. unsigned raw_bits_per_partition[],
  98086. unsigned residual_samples,
  98087. unsigned predictor_order,
  98088. unsigned min_partition_order,
  98089. unsigned max_partition_order
  98090. );
  98091. static FLAC__bool set_partitioned_rice_(
  98092. #ifdef EXACT_RICE_BITS_CALCULATION
  98093. const FLAC__int32 residual[],
  98094. #endif
  98095. const FLAC__uint64 abs_residual_partition_sums[],
  98096. const unsigned raw_bits_per_partition[],
  98097. const unsigned residual_samples,
  98098. const unsigned predictor_order,
  98099. const unsigned suggested_rice_parameter,
  98100. const unsigned rice_parameter_limit,
  98101. const unsigned rice_parameter_search_dist,
  98102. const unsigned partition_order,
  98103. const FLAC__bool search_for_escapes,
  98104. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  98105. unsigned *bits
  98106. );
  98107. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  98108. /* verify-related routines: */
  98109. static void append_to_verify_fifo_(
  98110. verify_input_fifo *fifo,
  98111. const FLAC__int32 * const input[],
  98112. unsigned input_offset,
  98113. unsigned channels,
  98114. unsigned wide_samples
  98115. );
  98116. static void append_to_verify_fifo_interleaved_(
  98117. verify_input_fifo *fifo,
  98118. const FLAC__int32 input[],
  98119. unsigned input_offset,
  98120. unsigned channels,
  98121. unsigned wide_samples
  98122. );
  98123. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98124. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  98125. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  98126. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  98127. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98128. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98129. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98130. static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  98131. static FILE *get_binary_stdout_(void);
  98132. /***********************************************************************
  98133. *
  98134. * Private class data
  98135. *
  98136. ***********************************************************************/
  98137. typedef struct FLAC__StreamEncoderPrivate {
  98138. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  98139. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  98140. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  98141. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98142. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  98143. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  98144. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  98145. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  98146. #endif
  98147. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  98148. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  98149. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98150. FLAC__int32 *residual_workspace_mid_side[2][2];
  98151. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  98152. FLAC__Subframe subframe_workspace_mid_side[2][2];
  98153. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98154. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  98155. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  98156. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  98157. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98158. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  98159. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  98160. unsigned best_subframe_mid_side[2];
  98161. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  98162. unsigned best_subframe_bits_mid_side[2];
  98163. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  98164. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  98165. FLAC__BitWriter *frame; /* the current frame being worked on */
  98166. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  98167. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  98168. FLAC__ChannelAssignment last_channel_assignment;
  98169. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  98170. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  98171. unsigned current_sample_number;
  98172. unsigned current_frame_number;
  98173. FLAC__MD5Context md5context;
  98174. FLAC__CPUInfo cpuinfo;
  98175. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98176. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98177. #else
  98178. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98179. #endif
  98180. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98181. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  98182. void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  98183. void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  98184. void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  98185. #endif
  98186. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  98187. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  98188. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  98189. FLAC__bool disable_constant_subframes;
  98190. FLAC__bool disable_fixed_subframes;
  98191. FLAC__bool disable_verbatim_subframes;
  98192. #if FLAC__HAS_OGG
  98193. FLAC__bool is_ogg;
  98194. #endif
  98195. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  98196. FLAC__StreamEncoderSeekCallback seek_callback;
  98197. FLAC__StreamEncoderTellCallback tell_callback;
  98198. FLAC__StreamEncoderWriteCallback write_callback;
  98199. FLAC__StreamEncoderMetadataCallback metadata_callback;
  98200. FLAC__StreamEncoderProgressCallback progress_callback;
  98201. void *client_data;
  98202. unsigned first_seekpoint_to_check;
  98203. FILE *file; /* only used when encoding to a file */
  98204. FLAC__uint64 bytes_written;
  98205. FLAC__uint64 samples_written;
  98206. unsigned frames_written;
  98207. unsigned total_frames_estimate;
  98208. /* unaligned (original) pointers to allocated data */
  98209. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  98210. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  98211. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98212. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  98213. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  98214. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  98215. FLAC__real *windowed_signal_unaligned;
  98216. #endif
  98217. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  98218. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  98219. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  98220. unsigned *raw_bits_per_partition_unaligned;
  98221. /*
  98222. * These fields have been moved here from private function local
  98223. * declarations merely to save stack space during encoding.
  98224. */
  98225. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98226. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  98227. #endif
  98228. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  98229. /*
  98230. * The data for the verify section
  98231. */
  98232. struct {
  98233. FLAC__StreamDecoder *decoder;
  98234. EncoderStateHint state_hint;
  98235. FLAC__bool needs_magic_hack;
  98236. verify_input_fifo input_fifo;
  98237. verify_output output;
  98238. struct {
  98239. FLAC__uint64 absolute_sample;
  98240. unsigned frame_number;
  98241. unsigned channel;
  98242. unsigned sample;
  98243. FLAC__int32 expected;
  98244. FLAC__int32 got;
  98245. } error_stats;
  98246. } verify;
  98247. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  98248. } FLAC__StreamEncoderPrivate;
  98249. /***********************************************************************
  98250. *
  98251. * Public static class data
  98252. *
  98253. ***********************************************************************/
  98254. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  98255. "FLAC__STREAM_ENCODER_OK",
  98256. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  98257. "FLAC__STREAM_ENCODER_OGG_ERROR",
  98258. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  98259. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  98260. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  98261. "FLAC__STREAM_ENCODER_IO_ERROR",
  98262. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  98263. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  98264. };
  98265. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  98266. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  98267. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  98268. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98269. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  98270. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  98271. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  98272. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  98273. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  98274. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  98275. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  98276. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  98277. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  98278. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  98279. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  98280. };
  98281. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  98282. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  98283. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  98284. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  98285. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  98286. };
  98287. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  98288. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  98289. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  98290. };
  98291. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  98292. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  98293. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  98294. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  98295. };
  98296. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  98297. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  98298. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  98299. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  98300. };
  98301. /* Number of samples that will be overread to watch for end of stream. By
  98302. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  98303. * always try to read blocksize+1 samples before encoding a block, so that
  98304. * even if the stream has a total sample count that is an integral multiple
  98305. * of the blocksize, we will still notice when we are encoding the last
  98306. * block. This is needed, for example, to correctly set the end-of-stream
  98307. * marker in Ogg FLAC.
  98308. *
  98309. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  98310. * not really any reason to change it.
  98311. */
  98312. static const unsigned OVERREAD_ = 1;
  98313. /***********************************************************************
  98314. *
  98315. * Class constructor/destructor
  98316. *
  98317. */
  98318. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  98319. {
  98320. FLAC__StreamEncoder *encoder;
  98321. unsigned i;
  98322. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98323. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  98324. if(encoder == 0) {
  98325. return 0;
  98326. }
  98327. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  98328. if(encoder->protected_ == 0) {
  98329. free(encoder);
  98330. return 0;
  98331. }
  98332. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  98333. if(encoder->private_ == 0) {
  98334. free(encoder->protected_);
  98335. free(encoder);
  98336. return 0;
  98337. }
  98338. encoder->private_->frame = FLAC__bitwriter_new();
  98339. if(encoder->private_->frame == 0) {
  98340. free(encoder->private_);
  98341. free(encoder->protected_);
  98342. free(encoder);
  98343. return 0;
  98344. }
  98345. encoder->private_->file = 0;
  98346. set_defaults_enc(encoder);
  98347. encoder->private_->is_being_deleted = false;
  98348. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98349. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  98350. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  98351. }
  98352. for(i = 0; i < 2; i++) {
  98353. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  98354. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  98355. }
  98356. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98357. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  98358. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  98359. }
  98360. for(i = 0; i < 2; i++) {
  98361. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  98362. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  98363. }
  98364. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98365. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98366. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98367. }
  98368. for(i = 0; i < 2; i++) {
  98369. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98370. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98371. }
  98372. for(i = 0; i < 2; i++)
  98373. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  98374. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98375. return encoder;
  98376. }
  98377. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  98378. {
  98379. unsigned i;
  98380. FLAC__ASSERT(0 != encoder);
  98381. FLAC__ASSERT(0 != encoder->protected_);
  98382. FLAC__ASSERT(0 != encoder->private_);
  98383. FLAC__ASSERT(0 != encoder->private_->frame);
  98384. encoder->private_->is_being_deleted = true;
  98385. (void)FLAC__stream_encoder_finish(encoder);
  98386. if(0 != encoder->private_->verify.decoder)
  98387. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  98388. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98389. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98390. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98391. }
  98392. for(i = 0; i < 2; i++) {
  98393. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98394. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98395. }
  98396. for(i = 0; i < 2; i++)
  98397. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  98398. FLAC__bitwriter_delete(encoder->private_->frame);
  98399. free(encoder->private_);
  98400. free(encoder->protected_);
  98401. free(encoder);
  98402. }
  98403. /***********************************************************************
  98404. *
  98405. * Public class methods
  98406. *
  98407. ***********************************************************************/
  98408. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  98409. FLAC__StreamEncoder *encoder,
  98410. FLAC__StreamEncoderReadCallback read_callback,
  98411. FLAC__StreamEncoderWriteCallback write_callback,
  98412. FLAC__StreamEncoderSeekCallback seek_callback,
  98413. FLAC__StreamEncoderTellCallback tell_callback,
  98414. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98415. void *client_data,
  98416. FLAC__bool is_ogg
  98417. )
  98418. {
  98419. unsigned i;
  98420. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  98421. FLAC__ASSERT(0 != encoder);
  98422. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98423. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98424. #if !FLAC__HAS_OGG
  98425. if(is_ogg)
  98426. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98427. #endif
  98428. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  98429. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  98430. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  98431. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  98432. if(encoder->protected_->channels != 2) {
  98433. encoder->protected_->do_mid_side_stereo = false;
  98434. encoder->protected_->loose_mid_side_stereo = false;
  98435. }
  98436. else if(!encoder->protected_->do_mid_side_stereo)
  98437. encoder->protected_->loose_mid_side_stereo = false;
  98438. if(encoder->protected_->bits_per_sample >= 32)
  98439. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  98440. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  98441. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  98442. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  98443. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  98444. if(encoder->protected_->blocksize == 0) {
  98445. if(encoder->protected_->max_lpc_order == 0)
  98446. encoder->protected_->blocksize = 1152;
  98447. else
  98448. encoder->protected_->blocksize = 4096;
  98449. }
  98450. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  98451. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  98452. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  98453. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  98454. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  98455. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  98456. if(encoder->protected_->qlp_coeff_precision == 0) {
  98457. if(encoder->protected_->bits_per_sample < 16) {
  98458. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  98459. /* @@@ until then we'll make a guess */
  98460. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  98461. }
  98462. else if(encoder->protected_->bits_per_sample == 16) {
  98463. if(encoder->protected_->blocksize <= 192)
  98464. encoder->protected_->qlp_coeff_precision = 7;
  98465. else if(encoder->protected_->blocksize <= 384)
  98466. encoder->protected_->qlp_coeff_precision = 8;
  98467. else if(encoder->protected_->blocksize <= 576)
  98468. encoder->protected_->qlp_coeff_precision = 9;
  98469. else if(encoder->protected_->blocksize <= 1152)
  98470. encoder->protected_->qlp_coeff_precision = 10;
  98471. else if(encoder->protected_->blocksize <= 2304)
  98472. encoder->protected_->qlp_coeff_precision = 11;
  98473. else if(encoder->protected_->blocksize <= 4608)
  98474. encoder->protected_->qlp_coeff_precision = 12;
  98475. else
  98476. encoder->protected_->qlp_coeff_precision = 13;
  98477. }
  98478. else {
  98479. if(encoder->protected_->blocksize <= 384)
  98480. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  98481. else if(encoder->protected_->blocksize <= 1152)
  98482. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  98483. else
  98484. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  98485. }
  98486. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  98487. }
  98488. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  98489. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  98490. if(encoder->protected_->streamable_subset) {
  98491. if(
  98492. encoder->protected_->blocksize != 192 &&
  98493. encoder->protected_->blocksize != 576 &&
  98494. encoder->protected_->blocksize != 1152 &&
  98495. encoder->protected_->blocksize != 2304 &&
  98496. encoder->protected_->blocksize != 4608 &&
  98497. encoder->protected_->blocksize != 256 &&
  98498. encoder->protected_->blocksize != 512 &&
  98499. encoder->protected_->blocksize != 1024 &&
  98500. encoder->protected_->blocksize != 2048 &&
  98501. encoder->protected_->blocksize != 4096 &&
  98502. encoder->protected_->blocksize != 8192 &&
  98503. encoder->protected_->blocksize != 16384
  98504. )
  98505. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98506. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  98507. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98508. if(
  98509. encoder->protected_->bits_per_sample != 8 &&
  98510. encoder->protected_->bits_per_sample != 12 &&
  98511. encoder->protected_->bits_per_sample != 16 &&
  98512. encoder->protected_->bits_per_sample != 20 &&
  98513. encoder->protected_->bits_per_sample != 24
  98514. )
  98515. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98516. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  98517. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98518. if(
  98519. encoder->protected_->sample_rate <= 48000 &&
  98520. (
  98521. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  98522. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  98523. )
  98524. ) {
  98525. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98526. }
  98527. }
  98528. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98529. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  98530. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  98531. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  98532. #if FLAC__HAS_OGG
  98533. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  98534. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  98535. unsigned i;
  98536. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  98537. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98538. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  98539. for( ; i > 0; i--)
  98540. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  98541. encoder->protected_->metadata[0] = vc;
  98542. break;
  98543. }
  98544. }
  98545. }
  98546. #endif
  98547. /* keep track of any SEEKTABLE block */
  98548. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  98549. unsigned i;
  98550. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98551. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98552. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  98553. break; /* take only the first one */
  98554. }
  98555. }
  98556. }
  98557. /* validate metadata */
  98558. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  98559. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98560. metadata_has_seektable = false;
  98561. metadata_has_vorbis_comment = false;
  98562. metadata_picture_has_type1 = false;
  98563. metadata_picture_has_type2 = false;
  98564. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98565. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  98566. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  98567. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98568. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98569. if(metadata_has_seektable) /* only one is allowed */
  98570. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98571. metadata_has_seektable = true;
  98572. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  98573. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98574. }
  98575. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98576. if(metadata_has_vorbis_comment) /* only one is allowed */
  98577. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98578. metadata_has_vorbis_comment = true;
  98579. }
  98580. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  98581. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  98582. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98583. }
  98584. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  98585. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  98586. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98587. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  98588. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  98589. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98590. metadata_picture_has_type1 = true;
  98591. /* standard icon must be 32x32 pixel PNG */
  98592. if(
  98593. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  98594. (
  98595. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  98596. m->data.picture.width != 32 ||
  98597. m->data.picture.height != 32
  98598. )
  98599. )
  98600. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98601. }
  98602. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  98603. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  98604. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98605. metadata_picture_has_type2 = true;
  98606. }
  98607. }
  98608. }
  98609. encoder->private_->input_capacity = 0;
  98610. for(i = 0; i < encoder->protected_->channels; i++) {
  98611. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  98612. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98613. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  98614. #endif
  98615. }
  98616. for(i = 0; i < 2; i++) {
  98617. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  98618. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98619. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  98620. #endif
  98621. }
  98622. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98623. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  98624. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  98625. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  98626. #endif
  98627. for(i = 0; i < encoder->protected_->channels; i++) {
  98628. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  98629. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  98630. encoder->private_->best_subframe[i] = 0;
  98631. }
  98632. for(i = 0; i < 2; i++) {
  98633. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  98634. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  98635. encoder->private_->best_subframe_mid_side[i] = 0;
  98636. }
  98637. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  98638. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  98639. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98640. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  98641. #else
  98642. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  98643. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  98644. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  98645. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  98646. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  98647. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  98648. encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
  98649. #endif
  98650. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  98651. encoder->private_->loose_mid_side_stereo_frames = 1;
  98652. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98653. encoder->private_->current_sample_number = 0;
  98654. encoder->private_->current_frame_number = 0;
  98655. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  98656. encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
  98657. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  98658. /*
  98659. * get the CPU info and set the function pointers
  98660. */
  98661. FLAC__cpu_info(&encoder->private_->cpuinfo);
  98662. /* first default to the non-asm routines */
  98663. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98664. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  98665. #endif
  98666. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  98667. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98668. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98669. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  98670. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98671. #endif
  98672. /* now override with asm where appropriate */
  98673. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98674. # ifndef FLAC__NO_ASM
  98675. if(encoder->private_->cpuinfo.use_asm) {
  98676. # ifdef FLAC__CPU_IA32
  98677. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98678. # ifdef FLAC__HAS_NASM
  98679. if(encoder->private_->cpuinfo.data.ia32.sse) {
  98680. if(encoder->protected_->max_lpc_order < 4)
  98681. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  98682. else if(encoder->protected_->max_lpc_order < 8)
  98683. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  98684. else if(encoder->protected_->max_lpc_order < 12)
  98685. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  98686. else
  98687. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98688. }
  98689. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  98690. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  98691. else
  98692. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98693. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  98694. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98695. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  98696. }
  98697. else {
  98698. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98699. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98700. }
  98701. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  98702. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  98703. # endif /* FLAC__HAS_NASM */
  98704. # endif /* FLAC__CPU_IA32 */
  98705. }
  98706. # endif /* !FLAC__NO_ASM */
  98707. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  98708. /* finally override based on wide-ness if necessary */
  98709. if(encoder->private_->use_wide_by_block) {
  98710. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  98711. }
  98712. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  98713. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  98714. #if FLAC__HAS_OGG
  98715. encoder->private_->is_ogg = is_ogg;
  98716. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  98717. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98718. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98719. }
  98720. #endif
  98721. encoder->private_->read_callback = read_callback;
  98722. encoder->private_->write_callback = write_callback;
  98723. encoder->private_->seek_callback = seek_callback;
  98724. encoder->private_->tell_callback = tell_callback;
  98725. encoder->private_->metadata_callback = metadata_callback;
  98726. encoder->private_->client_data = client_data;
  98727. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  98728. /* the above function sets the state for us in case of an error */
  98729. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98730. }
  98731. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  98732. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98733. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98734. }
  98735. /*
  98736. * Set up the verify stuff if necessary
  98737. */
  98738. if(encoder->protected_->verify) {
  98739. /*
  98740. * First, set up the fifo which will hold the
  98741. * original signal to compare against
  98742. */
  98743. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  98744. for(i = 0; i < encoder->protected_->channels; i++) {
  98745. if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
  98746. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98747. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98748. }
  98749. }
  98750. encoder->private_->verify.input_fifo.tail = 0;
  98751. /*
  98752. * Now set up a stream decoder for verification
  98753. */
  98754. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  98755. if(0 == encoder->private_->verify.decoder) {
  98756. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98757. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98758. }
  98759. if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
  98760. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98761. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98762. }
  98763. }
  98764. encoder->private_->verify.error_stats.absolute_sample = 0;
  98765. encoder->private_->verify.error_stats.frame_number = 0;
  98766. encoder->private_->verify.error_stats.channel = 0;
  98767. encoder->private_->verify.error_stats.sample = 0;
  98768. encoder->private_->verify.error_stats.expected = 0;
  98769. encoder->private_->verify.error_stats.got = 0;
  98770. /*
  98771. * These must be done before we write any metadata, because that
  98772. * calls the write_callback, which uses these values.
  98773. */
  98774. encoder->private_->first_seekpoint_to_check = 0;
  98775. encoder->private_->samples_written = 0;
  98776. encoder->protected_->streaminfo_offset = 0;
  98777. encoder->protected_->seektable_offset = 0;
  98778. encoder->protected_->audio_offset = 0;
  98779. /*
  98780. * write the stream header
  98781. */
  98782. if(encoder->protected_->verify)
  98783. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  98784. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  98785. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98786. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98787. }
  98788. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98789. /* the above function sets the state for us in case of an error */
  98790. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98791. }
  98792. /*
  98793. * write the STREAMINFO metadata block
  98794. */
  98795. if(encoder->protected_->verify)
  98796. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  98797. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  98798. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  98799. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  98800. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  98801. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  98802. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  98803. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  98804. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  98805. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  98806. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  98807. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  98808. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  98809. if(encoder->protected_->do_md5)
  98810. FLAC__MD5Init(&encoder->private_->md5context);
  98811. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  98812. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98813. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98814. }
  98815. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98816. /* the above function sets the state for us in case of an error */
  98817. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98818. }
  98819. /*
  98820. * Now that the STREAMINFO block is written, we can init this to an
  98821. * absurdly-high value...
  98822. */
  98823. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  98824. /* ... and clear this to 0 */
  98825. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  98826. /*
  98827. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  98828. * if not, we will write an empty one (FLAC__add_metadata_block()
  98829. * automatically supplies the vendor string).
  98830. *
  98831. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  98832. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  98833. * true it will have already insured that the metadata list is properly
  98834. * ordered.)
  98835. */
  98836. if(!metadata_has_vorbis_comment) {
  98837. FLAC__StreamMetadata vorbis_comment;
  98838. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  98839. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  98840. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  98841. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  98842. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  98843. vorbis_comment.data.vorbis_comment.num_comments = 0;
  98844. vorbis_comment.data.vorbis_comment.comments = 0;
  98845. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  98846. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98847. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98848. }
  98849. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98850. /* the above function sets the state for us in case of an error */
  98851. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98852. }
  98853. }
  98854. /*
  98855. * write the user's metadata blocks
  98856. */
  98857. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98858. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  98859. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  98860. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98861. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98862. }
  98863. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98864. /* the above function sets the state for us in case of an error */
  98865. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98866. }
  98867. }
  98868. /* now that all the metadata is written, we save the stream offset */
  98869. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  98870. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98871. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98872. }
  98873. if(encoder->protected_->verify)
  98874. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  98875. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  98876. }
  98877. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  98878. FLAC__StreamEncoder *encoder,
  98879. FLAC__StreamEncoderWriteCallback write_callback,
  98880. FLAC__StreamEncoderSeekCallback seek_callback,
  98881. FLAC__StreamEncoderTellCallback tell_callback,
  98882. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98883. void *client_data
  98884. )
  98885. {
  98886. return init_stream_internal_enc(
  98887. encoder,
  98888. /*read_callback=*/0,
  98889. write_callback,
  98890. seek_callback,
  98891. tell_callback,
  98892. metadata_callback,
  98893. client_data,
  98894. /*is_ogg=*/false
  98895. );
  98896. }
  98897. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  98898. FLAC__StreamEncoder *encoder,
  98899. FLAC__StreamEncoderReadCallback read_callback,
  98900. FLAC__StreamEncoderWriteCallback write_callback,
  98901. FLAC__StreamEncoderSeekCallback seek_callback,
  98902. FLAC__StreamEncoderTellCallback tell_callback,
  98903. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98904. void *client_data
  98905. )
  98906. {
  98907. return init_stream_internal_enc(
  98908. encoder,
  98909. read_callback,
  98910. write_callback,
  98911. seek_callback,
  98912. tell_callback,
  98913. metadata_callback,
  98914. client_data,
  98915. /*is_ogg=*/true
  98916. );
  98917. }
  98918. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  98919. FLAC__StreamEncoder *encoder,
  98920. FILE *file,
  98921. FLAC__StreamEncoderProgressCallback progress_callback,
  98922. void *client_data,
  98923. FLAC__bool is_ogg
  98924. )
  98925. {
  98926. FLAC__StreamEncoderInitStatus init_status;
  98927. FLAC__ASSERT(0 != encoder);
  98928. FLAC__ASSERT(0 != file);
  98929. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98930. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98931. /* double protection */
  98932. if(file == 0) {
  98933. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98934. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98935. }
  98936. /*
  98937. * To make sure that our file does not go unclosed after an error, we
  98938. * must assign the FILE pointer before any further error can occur in
  98939. * this routine.
  98940. */
  98941. if(file == stdout)
  98942. file = get_binary_stdout_(); /* just to be safe */
  98943. encoder->private_->file = file;
  98944. encoder->private_->progress_callback = progress_callback;
  98945. encoder->private_->bytes_written = 0;
  98946. encoder->private_->samples_written = 0;
  98947. encoder->private_->frames_written = 0;
  98948. init_status = init_stream_internal_enc(
  98949. encoder,
  98950. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  98951. file_write_callback_,
  98952. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  98953. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  98954. /*metadata_callback=*/0,
  98955. client_data,
  98956. is_ogg
  98957. );
  98958. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  98959. /* the above function sets the state for us in case of an error */
  98960. return init_status;
  98961. }
  98962. {
  98963. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98964. FLAC__ASSERT(blocksize != 0);
  98965. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  98966. }
  98967. return init_status;
  98968. }
  98969. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  98970. FLAC__StreamEncoder *encoder,
  98971. FILE *file,
  98972. FLAC__StreamEncoderProgressCallback progress_callback,
  98973. void *client_data
  98974. )
  98975. {
  98976. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  98977. }
  98978. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  98979. FLAC__StreamEncoder *encoder,
  98980. FILE *file,
  98981. FLAC__StreamEncoderProgressCallback progress_callback,
  98982. void *client_data
  98983. )
  98984. {
  98985. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  98986. }
  98987. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  98988. FLAC__StreamEncoder *encoder,
  98989. const char *filename,
  98990. FLAC__StreamEncoderProgressCallback progress_callback,
  98991. void *client_data,
  98992. FLAC__bool is_ogg
  98993. )
  98994. {
  98995. FILE *file;
  98996. FLAC__ASSERT(0 != encoder);
  98997. /*
  98998. * To make sure that our file does not go unclosed after an error, we
  98999. * have to do the same entrance checks here that are later performed
  99000. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  99001. */
  99002. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99003. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99004. file = filename? fopen(filename, "w+b") : stdout;
  99005. if(file == 0) {
  99006. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99007. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99008. }
  99009. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  99010. }
  99011. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  99012. FLAC__StreamEncoder *encoder,
  99013. const char *filename,
  99014. FLAC__StreamEncoderProgressCallback progress_callback,
  99015. void *client_data
  99016. )
  99017. {
  99018. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  99019. }
  99020. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  99021. FLAC__StreamEncoder *encoder,
  99022. const char *filename,
  99023. FLAC__StreamEncoderProgressCallback progress_callback,
  99024. void *client_data
  99025. )
  99026. {
  99027. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  99028. }
  99029. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  99030. {
  99031. FLAC__bool error = false;
  99032. FLAC__ASSERT(0 != encoder);
  99033. FLAC__ASSERT(0 != encoder->private_);
  99034. FLAC__ASSERT(0 != encoder->protected_);
  99035. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  99036. return true;
  99037. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  99038. if(encoder->private_->current_sample_number != 0) {
  99039. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  99040. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  99041. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  99042. error = true;
  99043. }
  99044. }
  99045. if(encoder->protected_->do_md5)
  99046. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  99047. if(!encoder->private_->is_being_deleted) {
  99048. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  99049. if(encoder->private_->seek_callback) {
  99050. #if FLAC__HAS_OGG
  99051. if(encoder->private_->is_ogg)
  99052. update_ogg_metadata_(encoder);
  99053. else
  99054. #endif
  99055. update_metadata_(encoder);
  99056. /* check if an error occurred while updating metadata */
  99057. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  99058. error = true;
  99059. }
  99060. if(encoder->private_->metadata_callback)
  99061. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  99062. }
  99063. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  99064. if(!error)
  99065. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99066. error = true;
  99067. }
  99068. }
  99069. if(0 != encoder->private_->file) {
  99070. if(encoder->private_->file != stdout)
  99071. fclose(encoder->private_->file);
  99072. encoder->private_->file = 0;
  99073. }
  99074. #if FLAC__HAS_OGG
  99075. if(encoder->private_->is_ogg)
  99076. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  99077. #endif
  99078. free_(encoder);
  99079. set_defaults_enc(encoder);
  99080. if(!error)
  99081. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99082. return !error;
  99083. }
  99084. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  99085. {
  99086. FLAC__ASSERT(0 != encoder);
  99087. FLAC__ASSERT(0 != encoder->private_);
  99088. FLAC__ASSERT(0 != encoder->protected_);
  99089. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99090. return false;
  99091. #if FLAC__HAS_OGG
  99092. /* can't check encoder->private_->is_ogg since that's not set until init time */
  99093. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  99094. return true;
  99095. #else
  99096. (void)value;
  99097. return false;
  99098. #endif
  99099. }
  99100. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99101. {
  99102. FLAC__ASSERT(0 != encoder);
  99103. FLAC__ASSERT(0 != encoder->private_);
  99104. FLAC__ASSERT(0 != encoder->protected_);
  99105. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99106. return false;
  99107. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99108. encoder->protected_->verify = value;
  99109. #endif
  99110. return true;
  99111. }
  99112. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99113. {
  99114. FLAC__ASSERT(0 != encoder);
  99115. FLAC__ASSERT(0 != encoder->private_);
  99116. FLAC__ASSERT(0 != encoder->protected_);
  99117. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99118. return false;
  99119. encoder->protected_->streamable_subset = value;
  99120. return true;
  99121. }
  99122. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99123. {
  99124. FLAC__ASSERT(0 != encoder);
  99125. FLAC__ASSERT(0 != encoder->private_);
  99126. FLAC__ASSERT(0 != encoder->protected_);
  99127. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99128. return false;
  99129. encoder->protected_->do_md5 = value;
  99130. return true;
  99131. }
  99132. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  99133. {
  99134. FLAC__ASSERT(0 != encoder);
  99135. FLAC__ASSERT(0 != encoder->private_);
  99136. FLAC__ASSERT(0 != encoder->protected_);
  99137. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99138. return false;
  99139. encoder->protected_->channels = value;
  99140. return true;
  99141. }
  99142. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  99143. {
  99144. FLAC__ASSERT(0 != encoder);
  99145. FLAC__ASSERT(0 != encoder->private_);
  99146. FLAC__ASSERT(0 != encoder->protected_);
  99147. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99148. return false;
  99149. encoder->protected_->bits_per_sample = value;
  99150. return true;
  99151. }
  99152. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  99153. {
  99154. FLAC__ASSERT(0 != encoder);
  99155. FLAC__ASSERT(0 != encoder->private_);
  99156. FLAC__ASSERT(0 != encoder->protected_);
  99157. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99158. return false;
  99159. encoder->protected_->sample_rate = value;
  99160. return true;
  99161. }
  99162. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  99163. {
  99164. FLAC__bool ok = true;
  99165. FLAC__ASSERT(0 != encoder);
  99166. FLAC__ASSERT(0 != encoder->private_);
  99167. FLAC__ASSERT(0 != encoder->protected_);
  99168. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99169. return false;
  99170. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  99171. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  99172. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  99173. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  99174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99175. #if 0
  99176. /* was: */
  99177. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  99178. /* but it's too hard to specify the string in a locale-specific way */
  99179. #else
  99180. encoder->protected_->num_apodizations = 1;
  99181. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99182. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99183. #endif
  99184. #endif
  99185. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  99186. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  99187. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  99188. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  99189. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  99190. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  99191. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  99192. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  99193. return ok;
  99194. }
  99195. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  99196. {
  99197. FLAC__ASSERT(0 != encoder);
  99198. FLAC__ASSERT(0 != encoder->private_);
  99199. FLAC__ASSERT(0 != encoder->protected_);
  99200. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99201. return false;
  99202. encoder->protected_->blocksize = value;
  99203. return true;
  99204. }
  99205. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99206. {
  99207. FLAC__ASSERT(0 != encoder);
  99208. FLAC__ASSERT(0 != encoder->private_);
  99209. FLAC__ASSERT(0 != encoder->protected_);
  99210. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99211. return false;
  99212. encoder->protected_->do_mid_side_stereo = value;
  99213. return true;
  99214. }
  99215. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99216. {
  99217. FLAC__ASSERT(0 != encoder);
  99218. FLAC__ASSERT(0 != encoder->private_);
  99219. FLAC__ASSERT(0 != encoder->protected_);
  99220. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99221. return false;
  99222. encoder->protected_->loose_mid_side_stereo = value;
  99223. return true;
  99224. }
  99225. /*@@@@add to tests*/
  99226. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  99227. {
  99228. FLAC__ASSERT(0 != encoder);
  99229. FLAC__ASSERT(0 != encoder->private_);
  99230. FLAC__ASSERT(0 != encoder->protected_);
  99231. FLAC__ASSERT(0 != specification);
  99232. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99233. return false;
  99234. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  99235. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  99236. #else
  99237. encoder->protected_->num_apodizations = 0;
  99238. while(1) {
  99239. const char *s = strchr(specification, ';');
  99240. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  99241. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  99242. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  99243. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  99244. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  99245. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  99246. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  99247. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  99248. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  99249. else if(n==6 && 0 == strncmp("connes" , specification, n))
  99250. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  99251. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  99252. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  99253. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  99254. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  99255. if (stddev > 0.0 && stddev <= 0.5) {
  99256. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  99257. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  99258. }
  99259. }
  99260. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  99261. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  99262. else if(n==4 && 0 == strncmp("hann" , specification, n))
  99263. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  99264. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  99265. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  99266. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  99267. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  99268. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  99269. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  99270. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  99271. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  99272. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  99273. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  99274. if (p >= 0.0 && p <= 1.0) {
  99275. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  99276. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  99277. }
  99278. }
  99279. else if(n==5 && 0 == strncmp("welch" , specification, n))
  99280. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  99281. if (encoder->protected_->num_apodizations == 32)
  99282. break;
  99283. if (s)
  99284. specification = s+1;
  99285. else
  99286. break;
  99287. }
  99288. if(encoder->protected_->num_apodizations == 0) {
  99289. encoder->protected_->num_apodizations = 1;
  99290. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99291. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99292. }
  99293. #endif
  99294. return true;
  99295. }
  99296. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  99297. {
  99298. FLAC__ASSERT(0 != encoder);
  99299. FLAC__ASSERT(0 != encoder->private_);
  99300. FLAC__ASSERT(0 != encoder->protected_);
  99301. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99302. return false;
  99303. encoder->protected_->max_lpc_order = value;
  99304. return true;
  99305. }
  99306. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  99307. {
  99308. FLAC__ASSERT(0 != encoder);
  99309. FLAC__ASSERT(0 != encoder->private_);
  99310. FLAC__ASSERT(0 != encoder->protected_);
  99311. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99312. return false;
  99313. encoder->protected_->qlp_coeff_precision = value;
  99314. return true;
  99315. }
  99316. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99317. {
  99318. FLAC__ASSERT(0 != encoder);
  99319. FLAC__ASSERT(0 != encoder->private_);
  99320. FLAC__ASSERT(0 != encoder->protected_);
  99321. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99322. return false;
  99323. encoder->protected_->do_qlp_coeff_prec_search = value;
  99324. return true;
  99325. }
  99326. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99327. {
  99328. FLAC__ASSERT(0 != encoder);
  99329. FLAC__ASSERT(0 != encoder->private_);
  99330. FLAC__ASSERT(0 != encoder->protected_);
  99331. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99332. return false;
  99333. #if 0
  99334. /*@@@ deprecated: */
  99335. encoder->protected_->do_escape_coding = value;
  99336. #else
  99337. (void)value;
  99338. #endif
  99339. return true;
  99340. }
  99341. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99342. {
  99343. FLAC__ASSERT(0 != encoder);
  99344. FLAC__ASSERT(0 != encoder->private_);
  99345. FLAC__ASSERT(0 != encoder->protected_);
  99346. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99347. return false;
  99348. encoder->protected_->do_exhaustive_model_search = value;
  99349. return true;
  99350. }
  99351. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99352. {
  99353. FLAC__ASSERT(0 != encoder);
  99354. FLAC__ASSERT(0 != encoder->private_);
  99355. FLAC__ASSERT(0 != encoder->protected_);
  99356. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99357. return false;
  99358. encoder->protected_->min_residual_partition_order = value;
  99359. return true;
  99360. }
  99361. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99362. {
  99363. FLAC__ASSERT(0 != encoder);
  99364. FLAC__ASSERT(0 != encoder->private_);
  99365. FLAC__ASSERT(0 != encoder->protected_);
  99366. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99367. return false;
  99368. encoder->protected_->max_residual_partition_order = value;
  99369. return true;
  99370. }
  99371. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  99372. {
  99373. FLAC__ASSERT(0 != encoder);
  99374. FLAC__ASSERT(0 != encoder->private_);
  99375. FLAC__ASSERT(0 != encoder->protected_);
  99376. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99377. return false;
  99378. #if 0
  99379. /*@@@ deprecated: */
  99380. encoder->protected_->rice_parameter_search_dist = value;
  99381. #else
  99382. (void)value;
  99383. #endif
  99384. return true;
  99385. }
  99386. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  99387. {
  99388. FLAC__ASSERT(0 != encoder);
  99389. FLAC__ASSERT(0 != encoder->private_);
  99390. FLAC__ASSERT(0 != encoder->protected_);
  99391. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99392. return false;
  99393. encoder->protected_->total_samples_estimate = value;
  99394. return true;
  99395. }
  99396. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  99397. {
  99398. FLAC__ASSERT(0 != encoder);
  99399. FLAC__ASSERT(0 != encoder->private_);
  99400. FLAC__ASSERT(0 != encoder->protected_);
  99401. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99402. return false;
  99403. if(0 == metadata)
  99404. num_blocks = 0;
  99405. if(0 == num_blocks)
  99406. metadata = 0;
  99407. /* realloc() does not do exactly what we want so... */
  99408. if(encoder->protected_->metadata) {
  99409. free(encoder->protected_->metadata);
  99410. encoder->protected_->metadata = 0;
  99411. encoder->protected_->num_metadata_blocks = 0;
  99412. }
  99413. if(num_blocks) {
  99414. FLAC__StreamMetadata **m;
  99415. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  99416. return false;
  99417. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  99418. encoder->protected_->metadata = m;
  99419. encoder->protected_->num_metadata_blocks = num_blocks;
  99420. }
  99421. #if FLAC__HAS_OGG
  99422. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  99423. return false;
  99424. #endif
  99425. return true;
  99426. }
  99427. /*
  99428. * These three functions are not static, but not publically exposed in
  99429. * include/FLAC/ either. They are used by the test suite.
  99430. */
  99431. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99432. {
  99433. FLAC__ASSERT(0 != encoder);
  99434. FLAC__ASSERT(0 != encoder->private_);
  99435. FLAC__ASSERT(0 != encoder->protected_);
  99436. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99437. return false;
  99438. encoder->private_->disable_constant_subframes = value;
  99439. return true;
  99440. }
  99441. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99442. {
  99443. FLAC__ASSERT(0 != encoder);
  99444. FLAC__ASSERT(0 != encoder->private_);
  99445. FLAC__ASSERT(0 != encoder->protected_);
  99446. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99447. return false;
  99448. encoder->private_->disable_fixed_subframes = value;
  99449. return true;
  99450. }
  99451. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99452. {
  99453. FLAC__ASSERT(0 != encoder);
  99454. FLAC__ASSERT(0 != encoder->private_);
  99455. FLAC__ASSERT(0 != encoder->protected_);
  99456. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99457. return false;
  99458. encoder->private_->disable_verbatim_subframes = value;
  99459. return true;
  99460. }
  99461. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  99462. {
  99463. FLAC__ASSERT(0 != encoder);
  99464. FLAC__ASSERT(0 != encoder->private_);
  99465. FLAC__ASSERT(0 != encoder->protected_);
  99466. return encoder->protected_->state;
  99467. }
  99468. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  99469. {
  99470. FLAC__ASSERT(0 != encoder);
  99471. FLAC__ASSERT(0 != encoder->private_);
  99472. FLAC__ASSERT(0 != encoder->protected_);
  99473. if(encoder->protected_->verify)
  99474. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  99475. else
  99476. return FLAC__STREAM_DECODER_UNINITIALIZED;
  99477. }
  99478. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  99479. {
  99480. FLAC__ASSERT(0 != encoder);
  99481. FLAC__ASSERT(0 != encoder->private_);
  99482. FLAC__ASSERT(0 != encoder->protected_);
  99483. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  99484. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  99485. else
  99486. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  99487. }
  99488. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
  99489. {
  99490. FLAC__ASSERT(0 != encoder);
  99491. FLAC__ASSERT(0 != encoder->private_);
  99492. FLAC__ASSERT(0 != encoder->protected_);
  99493. if(0 != absolute_sample)
  99494. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  99495. if(0 != frame_number)
  99496. *frame_number = encoder->private_->verify.error_stats.frame_number;
  99497. if(0 != channel)
  99498. *channel = encoder->private_->verify.error_stats.channel;
  99499. if(0 != sample)
  99500. *sample = encoder->private_->verify.error_stats.sample;
  99501. if(0 != expected)
  99502. *expected = encoder->private_->verify.error_stats.expected;
  99503. if(0 != got)
  99504. *got = encoder->private_->verify.error_stats.got;
  99505. }
  99506. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  99507. {
  99508. FLAC__ASSERT(0 != encoder);
  99509. FLAC__ASSERT(0 != encoder->private_);
  99510. FLAC__ASSERT(0 != encoder->protected_);
  99511. return encoder->protected_->verify;
  99512. }
  99513. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  99514. {
  99515. FLAC__ASSERT(0 != encoder);
  99516. FLAC__ASSERT(0 != encoder->private_);
  99517. FLAC__ASSERT(0 != encoder->protected_);
  99518. return encoder->protected_->streamable_subset;
  99519. }
  99520. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  99521. {
  99522. FLAC__ASSERT(0 != encoder);
  99523. FLAC__ASSERT(0 != encoder->private_);
  99524. FLAC__ASSERT(0 != encoder->protected_);
  99525. return encoder->protected_->do_md5;
  99526. }
  99527. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  99528. {
  99529. FLAC__ASSERT(0 != encoder);
  99530. FLAC__ASSERT(0 != encoder->private_);
  99531. FLAC__ASSERT(0 != encoder->protected_);
  99532. return encoder->protected_->channels;
  99533. }
  99534. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  99535. {
  99536. FLAC__ASSERT(0 != encoder);
  99537. FLAC__ASSERT(0 != encoder->private_);
  99538. FLAC__ASSERT(0 != encoder->protected_);
  99539. return encoder->protected_->bits_per_sample;
  99540. }
  99541. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  99542. {
  99543. FLAC__ASSERT(0 != encoder);
  99544. FLAC__ASSERT(0 != encoder->private_);
  99545. FLAC__ASSERT(0 != encoder->protected_);
  99546. return encoder->protected_->sample_rate;
  99547. }
  99548. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  99549. {
  99550. FLAC__ASSERT(0 != encoder);
  99551. FLAC__ASSERT(0 != encoder->private_);
  99552. FLAC__ASSERT(0 != encoder->protected_);
  99553. return encoder->protected_->blocksize;
  99554. }
  99555. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  99556. {
  99557. FLAC__ASSERT(0 != encoder);
  99558. FLAC__ASSERT(0 != encoder->private_);
  99559. FLAC__ASSERT(0 != encoder->protected_);
  99560. return encoder->protected_->do_mid_side_stereo;
  99561. }
  99562. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  99563. {
  99564. FLAC__ASSERT(0 != encoder);
  99565. FLAC__ASSERT(0 != encoder->private_);
  99566. FLAC__ASSERT(0 != encoder->protected_);
  99567. return encoder->protected_->loose_mid_side_stereo;
  99568. }
  99569. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  99570. {
  99571. FLAC__ASSERT(0 != encoder);
  99572. FLAC__ASSERT(0 != encoder->private_);
  99573. FLAC__ASSERT(0 != encoder->protected_);
  99574. return encoder->protected_->max_lpc_order;
  99575. }
  99576. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  99577. {
  99578. FLAC__ASSERT(0 != encoder);
  99579. FLAC__ASSERT(0 != encoder->private_);
  99580. FLAC__ASSERT(0 != encoder->protected_);
  99581. return encoder->protected_->qlp_coeff_precision;
  99582. }
  99583. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  99584. {
  99585. FLAC__ASSERT(0 != encoder);
  99586. FLAC__ASSERT(0 != encoder->private_);
  99587. FLAC__ASSERT(0 != encoder->protected_);
  99588. return encoder->protected_->do_qlp_coeff_prec_search;
  99589. }
  99590. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  99591. {
  99592. FLAC__ASSERT(0 != encoder);
  99593. FLAC__ASSERT(0 != encoder->private_);
  99594. FLAC__ASSERT(0 != encoder->protected_);
  99595. return encoder->protected_->do_escape_coding;
  99596. }
  99597. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  99598. {
  99599. FLAC__ASSERT(0 != encoder);
  99600. FLAC__ASSERT(0 != encoder->private_);
  99601. FLAC__ASSERT(0 != encoder->protected_);
  99602. return encoder->protected_->do_exhaustive_model_search;
  99603. }
  99604. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99605. {
  99606. FLAC__ASSERT(0 != encoder);
  99607. FLAC__ASSERT(0 != encoder->private_);
  99608. FLAC__ASSERT(0 != encoder->protected_);
  99609. return encoder->protected_->min_residual_partition_order;
  99610. }
  99611. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99612. {
  99613. FLAC__ASSERT(0 != encoder);
  99614. FLAC__ASSERT(0 != encoder->private_);
  99615. FLAC__ASSERT(0 != encoder->protected_);
  99616. return encoder->protected_->max_residual_partition_order;
  99617. }
  99618. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  99619. {
  99620. FLAC__ASSERT(0 != encoder);
  99621. FLAC__ASSERT(0 != encoder->private_);
  99622. FLAC__ASSERT(0 != encoder->protected_);
  99623. return encoder->protected_->rice_parameter_search_dist;
  99624. }
  99625. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  99626. {
  99627. FLAC__ASSERT(0 != encoder);
  99628. FLAC__ASSERT(0 != encoder->private_);
  99629. FLAC__ASSERT(0 != encoder->protected_);
  99630. return encoder->protected_->total_samples_estimate;
  99631. }
  99632. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  99633. {
  99634. unsigned i, j = 0, channel;
  99635. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99636. FLAC__ASSERT(0 != encoder);
  99637. FLAC__ASSERT(0 != encoder->private_);
  99638. FLAC__ASSERT(0 != encoder->protected_);
  99639. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99640. do {
  99641. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  99642. if(encoder->protected_->verify)
  99643. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  99644. for(channel = 0; channel < channels; channel++)
  99645. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  99646. if(encoder->protected_->do_mid_side_stereo) {
  99647. FLAC__ASSERT(channels == 2);
  99648. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99649. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99650. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  99651. encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
  99652. }
  99653. }
  99654. else
  99655. j += n;
  99656. encoder->private_->current_sample_number += n;
  99657. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99658. if(encoder->private_->current_sample_number > blocksize) {
  99659. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  99660. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99661. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99662. return false;
  99663. /* move unprocessed overread samples to beginnings of arrays */
  99664. for(channel = 0; channel < channels; channel++)
  99665. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99666. if(encoder->protected_->do_mid_side_stereo) {
  99667. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99668. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99669. }
  99670. encoder->private_->current_sample_number = 1;
  99671. }
  99672. } while(j < samples);
  99673. return true;
  99674. }
  99675. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  99676. {
  99677. unsigned i, j, k, channel;
  99678. FLAC__int32 x, mid, side;
  99679. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99680. FLAC__ASSERT(0 != encoder);
  99681. FLAC__ASSERT(0 != encoder->private_);
  99682. FLAC__ASSERT(0 != encoder->protected_);
  99683. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99684. j = k = 0;
  99685. /*
  99686. * we have several flavors of the same basic loop, optimized for
  99687. * different conditions:
  99688. */
  99689. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  99690. /*
  99691. * stereo coding: unroll channel loop
  99692. */
  99693. do {
  99694. if(encoder->protected_->verify)
  99695. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99696. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99697. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99698. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  99699. x = buffer[k++];
  99700. encoder->private_->integer_signal[1][i] = x;
  99701. mid += x;
  99702. side -= x;
  99703. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  99704. encoder->private_->integer_signal_mid_side[1][i] = side;
  99705. encoder->private_->integer_signal_mid_side[0][i] = mid;
  99706. }
  99707. encoder->private_->current_sample_number = i;
  99708. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99709. if(i > blocksize) {
  99710. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99711. return false;
  99712. /* move unprocessed overread samples to beginnings of arrays */
  99713. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99714. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99715. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  99716. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  99717. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99718. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99719. encoder->private_->current_sample_number = 1;
  99720. }
  99721. } while(j < samples);
  99722. }
  99723. else {
  99724. /*
  99725. * independent channel coding: buffer each channel in inner loop
  99726. */
  99727. do {
  99728. if(encoder->protected_->verify)
  99729. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99730. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99731. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99732. for(channel = 0; channel < channels; channel++)
  99733. encoder->private_->integer_signal[channel][i] = buffer[k++];
  99734. }
  99735. encoder->private_->current_sample_number = i;
  99736. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99737. if(i > blocksize) {
  99738. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99739. return false;
  99740. /* move unprocessed overread samples to beginnings of arrays */
  99741. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99742. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99743. for(channel = 0; channel < channels; channel++)
  99744. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99745. encoder->private_->current_sample_number = 1;
  99746. }
  99747. } while(j < samples);
  99748. }
  99749. return true;
  99750. }
  99751. /***********************************************************************
  99752. *
  99753. * Private class methods
  99754. *
  99755. ***********************************************************************/
  99756. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  99757. {
  99758. FLAC__ASSERT(0 != encoder);
  99759. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99760. encoder->protected_->verify = true;
  99761. #else
  99762. encoder->protected_->verify = false;
  99763. #endif
  99764. encoder->protected_->streamable_subset = true;
  99765. encoder->protected_->do_md5 = true;
  99766. encoder->protected_->do_mid_side_stereo = false;
  99767. encoder->protected_->loose_mid_side_stereo = false;
  99768. encoder->protected_->channels = 2;
  99769. encoder->protected_->bits_per_sample = 16;
  99770. encoder->protected_->sample_rate = 44100;
  99771. encoder->protected_->blocksize = 0;
  99772. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99773. encoder->protected_->num_apodizations = 1;
  99774. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99775. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99776. #endif
  99777. encoder->protected_->max_lpc_order = 0;
  99778. encoder->protected_->qlp_coeff_precision = 0;
  99779. encoder->protected_->do_qlp_coeff_prec_search = false;
  99780. encoder->protected_->do_exhaustive_model_search = false;
  99781. encoder->protected_->do_escape_coding = false;
  99782. encoder->protected_->min_residual_partition_order = 0;
  99783. encoder->protected_->max_residual_partition_order = 0;
  99784. encoder->protected_->rice_parameter_search_dist = 0;
  99785. encoder->protected_->total_samples_estimate = 0;
  99786. encoder->protected_->metadata = 0;
  99787. encoder->protected_->num_metadata_blocks = 0;
  99788. encoder->private_->seek_table = 0;
  99789. encoder->private_->disable_constant_subframes = false;
  99790. encoder->private_->disable_fixed_subframes = false;
  99791. encoder->private_->disable_verbatim_subframes = false;
  99792. #if FLAC__HAS_OGG
  99793. encoder->private_->is_ogg = false;
  99794. #endif
  99795. encoder->private_->read_callback = 0;
  99796. encoder->private_->write_callback = 0;
  99797. encoder->private_->seek_callback = 0;
  99798. encoder->private_->tell_callback = 0;
  99799. encoder->private_->metadata_callback = 0;
  99800. encoder->private_->progress_callback = 0;
  99801. encoder->private_->client_data = 0;
  99802. #if FLAC__HAS_OGG
  99803. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  99804. #endif
  99805. }
  99806. void free_(FLAC__StreamEncoder *encoder)
  99807. {
  99808. unsigned i, channel;
  99809. FLAC__ASSERT(0 != encoder);
  99810. if(encoder->protected_->metadata) {
  99811. free(encoder->protected_->metadata);
  99812. encoder->protected_->metadata = 0;
  99813. encoder->protected_->num_metadata_blocks = 0;
  99814. }
  99815. for(i = 0; i < encoder->protected_->channels; i++) {
  99816. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  99817. free(encoder->private_->integer_signal_unaligned[i]);
  99818. encoder->private_->integer_signal_unaligned[i] = 0;
  99819. }
  99820. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99821. if(0 != encoder->private_->real_signal_unaligned[i]) {
  99822. free(encoder->private_->real_signal_unaligned[i]);
  99823. encoder->private_->real_signal_unaligned[i] = 0;
  99824. }
  99825. #endif
  99826. }
  99827. for(i = 0; i < 2; i++) {
  99828. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  99829. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  99830. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  99831. }
  99832. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99833. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  99834. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  99835. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  99836. }
  99837. #endif
  99838. }
  99839. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99840. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  99841. if(0 != encoder->private_->window_unaligned[i]) {
  99842. free(encoder->private_->window_unaligned[i]);
  99843. encoder->private_->window_unaligned[i] = 0;
  99844. }
  99845. }
  99846. if(0 != encoder->private_->windowed_signal_unaligned) {
  99847. free(encoder->private_->windowed_signal_unaligned);
  99848. encoder->private_->windowed_signal_unaligned = 0;
  99849. }
  99850. #endif
  99851. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99852. for(i = 0; i < 2; i++) {
  99853. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  99854. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  99855. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  99856. }
  99857. }
  99858. }
  99859. for(channel = 0; channel < 2; channel++) {
  99860. for(i = 0; i < 2; i++) {
  99861. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  99862. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  99863. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  99864. }
  99865. }
  99866. }
  99867. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  99868. free(encoder->private_->abs_residual_partition_sums_unaligned);
  99869. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  99870. }
  99871. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  99872. free(encoder->private_->raw_bits_per_partition_unaligned);
  99873. encoder->private_->raw_bits_per_partition_unaligned = 0;
  99874. }
  99875. if(encoder->protected_->verify) {
  99876. for(i = 0; i < encoder->protected_->channels; i++) {
  99877. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  99878. free(encoder->private_->verify.input_fifo.data[i]);
  99879. encoder->private_->verify.input_fifo.data[i] = 0;
  99880. }
  99881. }
  99882. }
  99883. FLAC__bitwriter_free(encoder->private_->frame);
  99884. }
  99885. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  99886. {
  99887. FLAC__bool ok;
  99888. unsigned i, channel;
  99889. FLAC__ASSERT(new_blocksize > 0);
  99890. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99891. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  99892. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  99893. if(new_blocksize <= encoder->private_->input_capacity)
  99894. return true;
  99895. ok = true;
  99896. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  99897. * requires that the input arrays (in our case the integer signals)
  99898. * have a buffer of up to 3 zeroes in front (at negative indices) for
  99899. * alignment purposes; we use 4 in front to keep the data well-aligned.
  99900. */
  99901. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  99902. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  99903. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  99904. encoder->private_->integer_signal[i] += 4;
  99905. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99906. #if 0 /* @@@ currently unused */
  99907. if(encoder->protected_->max_lpc_order > 0)
  99908. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  99909. #endif
  99910. #endif
  99911. }
  99912. for(i = 0; ok && i < 2; i++) {
  99913. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
  99914. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  99915. encoder->private_->integer_signal_mid_side[i] += 4;
  99916. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99917. #if 0 /* @@@ currently unused */
  99918. if(encoder->protected_->max_lpc_order > 0)
  99919. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  99920. #endif
  99921. #endif
  99922. }
  99923. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99924. if(ok && encoder->protected_->max_lpc_order > 0) {
  99925. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  99926. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  99927. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  99928. }
  99929. #endif
  99930. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  99931. for(i = 0; ok && i < 2; i++) {
  99932. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  99933. }
  99934. }
  99935. for(channel = 0; ok && channel < 2; channel++) {
  99936. for(i = 0; ok && i < 2; i++) {
  99937. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
  99938. }
  99939. }
  99940. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  99941. /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
  99942. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  99943. if(encoder->protected_->do_escape_coding)
  99944. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  99945. /* now adjust the windows if the blocksize has changed */
  99946. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99947. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  99948. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  99949. switch(encoder->protected_->apodizations[i].type) {
  99950. case FLAC__APODIZATION_BARTLETT:
  99951. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  99952. break;
  99953. case FLAC__APODIZATION_BARTLETT_HANN:
  99954. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  99955. break;
  99956. case FLAC__APODIZATION_BLACKMAN:
  99957. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  99958. break;
  99959. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  99960. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  99961. break;
  99962. case FLAC__APODIZATION_CONNES:
  99963. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  99964. break;
  99965. case FLAC__APODIZATION_FLATTOP:
  99966. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  99967. break;
  99968. case FLAC__APODIZATION_GAUSS:
  99969. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  99970. break;
  99971. case FLAC__APODIZATION_HAMMING:
  99972. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  99973. break;
  99974. case FLAC__APODIZATION_HANN:
  99975. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99976. break;
  99977. case FLAC__APODIZATION_KAISER_BESSEL:
  99978. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  99979. break;
  99980. case FLAC__APODIZATION_NUTTALL:
  99981. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  99982. break;
  99983. case FLAC__APODIZATION_RECTANGLE:
  99984. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  99985. break;
  99986. case FLAC__APODIZATION_TRIANGLE:
  99987. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  99988. break;
  99989. case FLAC__APODIZATION_TUKEY:
  99990. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  99991. break;
  99992. case FLAC__APODIZATION_WELCH:
  99993. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  99994. break;
  99995. default:
  99996. FLAC__ASSERT(0);
  99997. /* double protection */
  99998. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99999. break;
  100000. }
  100001. }
  100002. }
  100003. #endif
  100004. if(ok)
  100005. encoder->private_->input_capacity = new_blocksize;
  100006. else
  100007. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100008. return ok;
  100009. }
  100010. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  100011. {
  100012. const FLAC__byte *buffer;
  100013. size_t bytes;
  100014. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100015. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  100016. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100017. return false;
  100018. }
  100019. if(encoder->protected_->verify) {
  100020. encoder->private_->verify.output.data = buffer;
  100021. encoder->private_->verify.output.bytes = bytes;
  100022. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  100023. encoder->private_->verify.needs_magic_hack = true;
  100024. }
  100025. else {
  100026. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  100027. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100028. FLAC__bitwriter_clear(encoder->private_->frame);
  100029. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  100030. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100031. return false;
  100032. }
  100033. }
  100034. }
  100035. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100036. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100037. FLAC__bitwriter_clear(encoder->private_->frame);
  100038. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100039. return false;
  100040. }
  100041. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100042. FLAC__bitwriter_clear(encoder->private_->frame);
  100043. if(samples > 0) {
  100044. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  100045. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  100046. }
  100047. return true;
  100048. }
  100049. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  100050. {
  100051. FLAC__StreamEncoderWriteStatus status;
  100052. FLAC__uint64 output_position = 0;
  100053. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  100054. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  100055. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100056. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100057. }
  100058. /*
  100059. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  100060. */
  100061. if(samples == 0) {
  100062. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  100063. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  100064. encoder->protected_->streaminfo_offset = output_position;
  100065. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  100066. encoder->protected_->seektable_offset = output_position;
  100067. }
  100068. /*
  100069. * Mark the current seek point if hit (if audio_offset == 0 that
  100070. * means we're still writing metadata and haven't hit the first
  100071. * frame yet)
  100072. */
  100073. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  100074. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100075. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  100076. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  100077. FLAC__uint64 test_sample;
  100078. unsigned i;
  100079. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  100080. test_sample = encoder->private_->seek_table->points[i].sample_number;
  100081. if(test_sample > frame_last_sample) {
  100082. break;
  100083. }
  100084. else if(test_sample >= frame_first_sample) {
  100085. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  100086. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  100087. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  100088. encoder->private_->first_seekpoint_to_check++;
  100089. /* DO NOT: "break;" and here's why:
  100090. * The seektable template may contain more than one target
  100091. * sample for any given frame; we will keep looping, generating
  100092. * duplicate seekpoints for them, and we'll clean it up later,
  100093. * just before writing the seektable back to the metadata.
  100094. */
  100095. }
  100096. else {
  100097. encoder->private_->first_seekpoint_to_check++;
  100098. }
  100099. }
  100100. }
  100101. #if FLAC__HAS_OGG
  100102. if(encoder->private_->is_ogg) {
  100103. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  100104. &encoder->protected_->ogg_encoder_aspect,
  100105. buffer,
  100106. bytes,
  100107. samples,
  100108. encoder->private_->current_frame_number,
  100109. is_last_block,
  100110. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  100111. encoder,
  100112. encoder->private_->client_data
  100113. );
  100114. }
  100115. else
  100116. #endif
  100117. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  100118. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100119. encoder->private_->bytes_written += bytes;
  100120. encoder->private_->samples_written += samples;
  100121. /* we keep a high watermark on the number of frames written because
  100122. * when the encoder goes back to write metadata, 'current_frame'
  100123. * will drop back to 0.
  100124. */
  100125. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  100126. }
  100127. else
  100128. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100129. return status;
  100130. }
  100131. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100132. void update_metadata_(const FLAC__StreamEncoder *encoder)
  100133. {
  100134. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100135. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100136. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100137. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100138. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100139. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  100140. FLAC__StreamEncoderSeekStatus seek_status;
  100141. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100142. /* All this is based on intimate knowledge of the stream header
  100143. * layout, but a change to the header format that would break this
  100144. * would also break all streams encoded in the previous format.
  100145. */
  100146. /*
  100147. * Write MD5 signature
  100148. */
  100149. {
  100150. const unsigned md5_offset =
  100151. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100152. (
  100153. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100154. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100155. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100156. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100157. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100158. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100159. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100160. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100161. ) / 8;
  100162. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100163. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100164. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100165. return;
  100166. }
  100167. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100168. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100169. return;
  100170. }
  100171. }
  100172. /*
  100173. * Write total samples
  100174. */
  100175. {
  100176. const unsigned total_samples_byte_offset =
  100177. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100178. (
  100179. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100180. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100181. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100182. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100183. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100184. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100185. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100186. - 4
  100187. ) / 8;
  100188. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  100189. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100190. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100191. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100192. b[4] = (FLAC__byte)(samples & 0xFF);
  100193. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100194. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100195. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100196. return;
  100197. }
  100198. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100199. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100200. return;
  100201. }
  100202. }
  100203. /*
  100204. * Write min/max framesize
  100205. */
  100206. {
  100207. const unsigned min_framesize_offset =
  100208. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100209. (
  100210. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100211. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100212. ) / 8;
  100213. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100214. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100215. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100216. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100217. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100218. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100219. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100220. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100221. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100222. return;
  100223. }
  100224. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100225. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100226. return;
  100227. }
  100228. }
  100229. /*
  100230. * Write seektable
  100231. */
  100232. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100233. unsigned i;
  100234. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100235. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100236. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100237. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100238. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100239. return;
  100240. }
  100241. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  100242. FLAC__uint64 xx;
  100243. unsigned x;
  100244. xx = encoder->private_->seek_table->points[i].sample_number;
  100245. b[7] = (FLAC__byte)xx; xx >>= 8;
  100246. b[6] = (FLAC__byte)xx; xx >>= 8;
  100247. b[5] = (FLAC__byte)xx; xx >>= 8;
  100248. b[4] = (FLAC__byte)xx; xx >>= 8;
  100249. b[3] = (FLAC__byte)xx; xx >>= 8;
  100250. b[2] = (FLAC__byte)xx; xx >>= 8;
  100251. b[1] = (FLAC__byte)xx; xx >>= 8;
  100252. b[0] = (FLAC__byte)xx; xx >>= 8;
  100253. xx = encoder->private_->seek_table->points[i].stream_offset;
  100254. b[15] = (FLAC__byte)xx; xx >>= 8;
  100255. b[14] = (FLAC__byte)xx; xx >>= 8;
  100256. b[13] = (FLAC__byte)xx; xx >>= 8;
  100257. b[12] = (FLAC__byte)xx; xx >>= 8;
  100258. b[11] = (FLAC__byte)xx; xx >>= 8;
  100259. b[10] = (FLAC__byte)xx; xx >>= 8;
  100260. b[9] = (FLAC__byte)xx; xx >>= 8;
  100261. b[8] = (FLAC__byte)xx; xx >>= 8;
  100262. x = encoder->private_->seek_table->points[i].frame_samples;
  100263. b[17] = (FLAC__byte)x; x >>= 8;
  100264. b[16] = (FLAC__byte)x; x >>= 8;
  100265. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100266. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100267. return;
  100268. }
  100269. }
  100270. }
  100271. }
  100272. #if FLAC__HAS_OGG
  100273. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100274. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  100275. {
  100276. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  100277. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  100278. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  100279. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  100280. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  100281. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  100282. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  100283. FLAC__STREAM_SYNC_LENGTH
  100284. ;
  100285. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100286. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100287. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100288. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100289. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100290. ogg_page page;
  100291. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100292. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  100293. /* Pre-check that client supports seeking, since we don't want the
  100294. * ogg_helper code to ever have to deal with this condition.
  100295. */
  100296. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  100297. return;
  100298. /* All this is based on intimate knowledge of the stream header
  100299. * layout, but a change to the header format that would break this
  100300. * would also break all streams encoded in the previous format.
  100301. */
  100302. /**
  100303. ** Write STREAMINFO stats
  100304. **/
  100305. simple_ogg_page__init(&page);
  100306. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100307. simple_ogg_page__clear(&page);
  100308. return; /* state already set */
  100309. }
  100310. /*
  100311. * Write MD5 signature
  100312. */
  100313. {
  100314. const unsigned md5_offset =
  100315. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100316. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100317. (
  100318. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100319. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100320. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100321. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100322. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100323. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100324. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100325. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100326. ) / 8;
  100327. if(md5_offset + 16 > (unsigned)page.body_len) {
  100328. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100329. simple_ogg_page__clear(&page);
  100330. return;
  100331. }
  100332. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  100333. }
  100334. /*
  100335. * Write total samples
  100336. */
  100337. {
  100338. const unsigned total_samples_byte_offset =
  100339. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100340. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100341. (
  100342. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100343. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100344. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100345. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100346. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100347. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100348. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100349. - 4
  100350. ) / 8;
  100351. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  100352. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100353. simple_ogg_page__clear(&page);
  100354. return;
  100355. }
  100356. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  100357. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  100358. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100359. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100360. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100361. b[4] = (FLAC__byte)(samples & 0xFF);
  100362. memcpy(page.body + total_samples_byte_offset, b, 5);
  100363. }
  100364. /*
  100365. * Write min/max framesize
  100366. */
  100367. {
  100368. const unsigned min_framesize_offset =
  100369. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100370. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100371. (
  100372. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100373. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100374. ) / 8;
  100375. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  100376. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100377. simple_ogg_page__clear(&page);
  100378. return;
  100379. }
  100380. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100381. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100382. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100383. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100384. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100385. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100386. memcpy(page.body + min_framesize_offset, b, 6);
  100387. }
  100388. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100389. simple_ogg_page__clear(&page);
  100390. return; /* state already set */
  100391. }
  100392. simple_ogg_page__clear(&page);
  100393. /*
  100394. * Write seektable
  100395. */
  100396. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100397. unsigned i;
  100398. FLAC__byte *p;
  100399. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100400. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100401. simple_ogg_page__init(&page);
  100402. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100403. simple_ogg_page__clear(&page);
  100404. return; /* state already set */
  100405. }
  100406. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  100407. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100408. simple_ogg_page__clear(&page);
  100409. return;
  100410. }
  100411. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  100412. FLAC__uint64 xx;
  100413. unsigned x;
  100414. xx = encoder->private_->seek_table->points[i].sample_number;
  100415. b[7] = (FLAC__byte)xx; xx >>= 8;
  100416. b[6] = (FLAC__byte)xx; xx >>= 8;
  100417. b[5] = (FLAC__byte)xx; xx >>= 8;
  100418. b[4] = (FLAC__byte)xx; xx >>= 8;
  100419. b[3] = (FLAC__byte)xx; xx >>= 8;
  100420. b[2] = (FLAC__byte)xx; xx >>= 8;
  100421. b[1] = (FLAC__byte)xx; xx >>= 8;
  100422. b[0] = (FLAC__byte)xx; xx >>= 8;
  100423. xx = encoder->private_->seek_table->points[i].stream_offset;
  100424. b[15] = (FLAC__byte)xx; xx >>= 8;
  100425. b[14] = (FLAC__byte)xx; xx >>= 8;
  100426. b[13] = (FLAC__byte)xx; xx >>= 8;
  100427. b[12] = (FLAC__byte)xx; xx >>= 8;
  100428. b[11] = (FLAC__byte)xx; xx >>= 8;
  100429. b[10] = (FLAC__byte)xx; xx >>= 8;
  100430. b[9] = (FLAC__byte)xx; xx >>= 8;
  100431. b[8] = (FLAC__byte)xx; xx >>= 8;
  100432. x = encoder->private_->seek_table->points[i].frame_samples;
  100433. b[17] = (FLAC__byte)x; x >>= 8;
  100434. b[16] = (FLAC__byte)x; x >>= 8;
  100435. memcpy(p, b, 18);
  100436. }
  100437. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100438. simple_ogg_page__clear(&page);
  100439. return; /* state already set */
  100440. }
  100441. simple_ogg_page__clear(&page);
  100442. }
  100443. }
  100444. #endif
  100445. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  100446. {
  100447. FLAC__uint16 crc;
  100448. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100449. /*
  100450. * Accumulate raw signal to the MD5 signature
  100451. */
  100452. if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
  100453. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100454. return false;
  100455. }
  100456. /*
  100457. * Process the frame header and subframes into the frame bitbuffer
  100458. */
  100459. if(!process_subframes_(encoder, is_fractional_block)) {
  100460. /* the above function sets the state for us in case of an error */
  100461. return false;
  100462. }
  100463. /*
  100464. * Zero-pad the frame to a byte_boundary
  100465. */
  100466. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  100467. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100468. return false;
  100469. }
  100470. /*
  100471. * CRC-16 the whole thing
  100472. */
  100473. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100474. if(
  100475. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  100476. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  100477. ) {
  100478. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100479. return false;
  100480. }
  100481. /*
  100482. * Write it
  100483. */
  100484. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  100485. /* the above function sets the state for us in case of an error */
  100486. return false;
  100487. }
  100488. /*
  100489. * Get ready for the next frame
  100490. */
  100491. encoder->private_->current_sample_number = 0;
  100492. encoder->private_->current_frame_number++;
  100493. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  100494. return true;
  100495. }
  100496. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  100497. {
  100498. FLAC__FrameHeader frame_header;
  100499. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  100500. FLAC__bool do_independent, do_mid_side;
  100501. /*
  100502. * Calculate the min,max Rice partition orders
  100503. */
  100504. if(is_fractional_block) {
  100505. max_partition_order = 0;
  100506. }
  100507. else {
  100508. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  100509. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  100510. }
  100511. min_partition_order = min(min_partition_order, max_partition_order);
  100512. /*
  100513. * Setup the frame
  100514. */
  100515. frame_header.blocksize = encoder->protected_->blocksize;
  100516. frame_header.sample_rate = encoder->protected_->sample_rate;
  100517. frame_header.channels = encoder->protected_->channels;
  100518. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  100519. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  100520. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100521. frame_header.number.frame_number = encoder->private_->current_frame_number;
  100522. /*
  100523. * Figure out what channel assignments to try
  100524. */
  100525. if(encoder->protected_->do_mid_side_stereo) {
  100526. if(encoder->protected_->loose_mid_side_stereo) {
  100527. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  100528. do_independent = true;
  100529. do_mid_side = true;
  100530. }
  100531. else {
  100532. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  100533. do_mid_side = !do_independent;
  100534. }
  100535. }
  100536. else {
  100537. do_independent = true;
  100538. do_mid_side = true;
  100539. }
  100540. }
  100541. else {
  100542. do_independent = true;
  100543. do_mid_side = false;
  100544. }
  100545. FLAC__ASSERT(do_independent || do_mid_side);
  100546. /*
  100547. * Check for wasted bits; set effective bps for each subframe
  100548. */
  100549. if(do_independent) {
  100550. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100551. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  100552. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  100553. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  100554. }
  100555. }
  100556. if(do_mid_side) {
  100557. FLAC__ASSERT(encoder->protected_->channels == 2);
  100558. for(channel = 0; channel < 2; channel++) {
  100559. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  100560. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  100561. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  100562. }
  100563. }
  100564. /*
  100565. * First do a normal encoding pass of each independent channel
  100566. */
  100567. if(do_independent) {
  100568. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100569. if(!
  100570. process_subframe_(
  100571. encoder,
  100572. min_partition_order,
  100573. max_partition_order,
  100574. &frame_header,
  100575. encoder->private_->subframe_bps[channel],
  100576. encoder->private_->integer_signal[channel],
  100577. encoder->private_->subframe_workspace_ptr[channel],
  100578. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  100579. encoder->private_->residual_workspace[channel],
  100580. encoder->private_->best_subframe+channel,
  100581. encoder->private_->best_subframe_bits+channel
  100582. )
  100583. )
  100584. return false;
  100585. }
  100586. }
  100587. /*
  100588. * Now do mid and side channels if requested
  100589. */
  100590. if(do_mid_side) {
  100591. FLAC__ASSERT(encoder->protected_->channels == 2);
  100592. for(channel = 0; channel < 2; channel++) {
  100593. if(!
  100594. process_subframe_(
  100595. encoder,
  100596. min_partition_order,
  100597. max_partition_order,
  100598. &frame_header,
  100599. encoder->private_->subframe_bps_mid_side[channel],
  100600. encoder->private_->integer_signal_mid_side[channel],
  100601. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  100602. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  100603. encoder->private_->residual_workspace_mid_side[channel],
  100604. encoder->private_->best_subframe_mid_side+channel,
  100605. encoder->private_->best_subframe_bits_mid_side+channel
  100606. )
  100607. )
  100608. return false;
  100609. }
  100610. }
  100611. /*
  100612. * Compose the frame bitbuffer
  100613. */
  100614. if(do_mid_side) {
  100615. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  100616. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  100617. FLAC__ChannelAssignment channel_assignment;
  100618. FLAC__ASSERT(encoder->protected_->channels == 2);
  100619. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  100620. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  100621. }
  100622. else {
  100623. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  100624. unsigned min_bits;
  100625. int ca;
  100626. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  100627. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  100628. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  100629. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  100630. FLAC__ASSERT(do_independent && do_mid_side);
  100631. /* We have to figure out which channel assignent results in the smallest frame */
  100632. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  100633. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  100634. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  100635. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  100636. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100637. min_bits = bits[channel_assignment];
  100638. for(ca = 1; ca <= 3; ca++) {
  100639. if(bits[ca] < min_bits) {
  100640. min_bits = bits[ca];
  100641. channel_assignment = (FLAC__ChannelAssignment)ca;
  100642. }
  100643. }
  100644. }
  100645. frame_header.channel_assignment = channel_assignment;
  100646. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100647. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100648. return false;
  100649. }
  100650. switch(channel_assignment) {
  100651. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100652. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100653. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100654. break;
  100655. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100656. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100657. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100658. break;
  100659. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100660. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100661. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100662. break;
  100663. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100664. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  100665. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100666. break;
  100667. default:
  100668. FLAC__ASSERT(0);
  100669. }
  100670. switch(channel_assignment) {
  100671. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100672. left_bps = encoder->private_->subframe_bps [0];
  100673. right_bps = encoder->private_->subframe_bps [1];
  100674. break;
  100675. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100676. left_bps = encoder->private_->subframe_bps [0];
  100677. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100678. break;
  100679. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100680. left_bps = encoder->private_->subframe_bps_mid_side[1];
  100681. right_bps = encoder->private_->subframe_bps [1];
  100682. break;
  100683. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100684. left_bps = encoder->private_->subframe_bps_mid_side[0];
  100685. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100686. break;
  100687. default:
  100688. FLAC__ASSERT(0);
  100689. }
  100690. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  100691. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  100692. return false;
  100693. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  100694. return false;
  100695. }
  100696. else {
  100697. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100698. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100699. return false;
  100700. }
  100701. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100702. if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
  100703. /* the above function sets the state for us in case of an error */
  100704. return false;
  100705. }
  100706. }
  100707. }
  100708. if(encoder->protected_->loose_mid_side_stereo) {
  100709. encoder->private_->loose_mid_side_stereo_frame_count++;
  100710. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  100711. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  100712. }
  100713. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  100714. return true;
  100715. }
  100716. FLAC__bool process_subframe_(
  100717. FLAC__StreamEncoder *encoder,
  100718. unsigned min_partition_order,
  100719. unsigned max_partition_order,
  100720. const FLAC__FrameHeader *frame_header,
  100721. unsigned subframe_bps,
  100722. const FLAC__int32 integer_signal[],
  100723. FLAC__Subframe *subframe[2],
  100724. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  100725. FLAC__int32 *residual[2],
  100726. unsigned *best_subframe,
  100727. unsigned *best_bits
  100728. )
  100729. {
  100730. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100731. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100732. #else
  100733. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100734. #endif
  100735. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100736. FLAC__double lpc_residual_bits_per_sample;
  100737. FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
  100738. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  100739. unsigned min_lpc_order, max_lpc_order, lpc_order;
  100740. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  100741. #endif
  100742. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  100743. unsigned rice_parameter;
  100744. unsigned _candidate_bits, _best_bits;
  100745. unsigned _best_subframe;
  100746. /* only use RICE2 partitions if stream bps > 16 */
  100747. const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100748. FLAC__ASSERT(frame_header->blocksize > 0);
  100749. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  100750. _best_subframe = 0;
  100751. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  100752. _best_bits = UINT_MAX;
  100753. else
  100754. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100755. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  100756. unsigned signal_is_constant = false;
  100757. guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
  100758. /* check for constant subframe */
  100759. if(
  100760. !encoder->private_->disable_constant_subframes &&
  100761. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100762. fixed_residual_bits_per_sample[1] == 0.0
  100763. #else
  100764. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  100765. #endif
  100766. ) {
  100767. /* the above means it's possible all samples are the same value; now double-check it: */
  100768. unsigned i;
  100769. signal_is_constant = true;
  100770. for(i = 1; i < frame_header->blocksize; i++) {
  100771. if(integer_signal[0] != integer_signal[i]) {
  100772. signal_is_constant = false;
  100773. break;
  100774. }
  100775. }
  100776. }
  100777. if(signal_is_constant) {
  100778. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  100779. if(_candidate_bits < _best_bits) {
  100780. _best_subframe = !_best_subframe;
  100781. _best_bits = _candidate_bits;
  100782. }
  100783. }
  100784. else {
  100785. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  100786. /* encode fixed */
  100787. if(encoder->protected_->do_exhaustive_model_search) {
  100788. min_fixed_order = 0;
  100789. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  100790. }
  100791. else {
  100792. min_fixed_order = max_fixed_order = guess_fixed_order;
  100793. }
  100794. if(max_fixed_order >= frame_header->blocksize)
  100795. max_fixed_order = frame_header->blocksize - 1;
  100796. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  100797. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100798. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  100799. continue; /* don't even try */
  100800. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
  100801. #else
  100802. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  100803. continue; /* don't even try */
  100804. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
  100805. #endif
  100806. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100807. if(rice_parameter >= rice_parameter_limit) {
  100808. #ifdef DEBUG_VERBOSE
  100809. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  100810. #endif
  100811. rice_parameter = rice_parameter_limit - 1;
  100812. }
  100813. _candidate_bits =
  100814. evaluate_fixed_subframe_(
  100815. encoder,
  100816. integer_signal,
  100817. residual[!_best_subframe],
  100818. encoder->private_->abs_residual_partition_sums,
  100819. encoder->private_->raw_bits_per_partition,
  100820. frame_header->blocksize,
  100821. subframe_bps,
  100822. fixed_order,
  100823. rice_parameter,
  100824. rice_parameter_limit,
  100825. min_partition_order,
  100826. max_partition_order,
  100827. encoder->protected_->do_escape_coding,
  100828. encoder->protected_->rice_parameter_search_dist,
  100829. subframe[!_best_subframe],
  100830. partitioned_rice_contents[!_best_subframe]
  100831. );
  100832. if(_candidate_bits < _best_bits) {
  100833. _best_subframe = !_best_subframe;
  100834. _best_bits = _candidate_bits;
  100835. }
  100836. }
  100837. }
  100838. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100839. /* encode lpc */
  100840. if(encoder->protected_->max_lpc_order > 0) {
  100841. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  100842. max_lpc_order = frame_header->blocksize-1;
  100843. else
  100844. max_lpc_order = encoder->protected_->max_lpc_order;
  100845. if(max_lpc_order > 0) {
  100846. unsigned a;
  100847. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  100848. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  100849. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  100850. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  100851. if(autoc[0] != 0.0) {
  100852. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  100853. if(encoder->protected_->do_exhaustive_model_search) {
  100854. min_lpc_order = 1;
  100855. }
  100856. else {
  100857. const unsigned guess_lpc_order =
  100858. FLAC__lpc_compute_best_order(
  100859. lpc_error,
  100860. max_lpc_order,
  100861. frame_header->blocksize,
  100862. subframe_bps + (
  100863. encoder->protected_->do_qlp_coeff_prec_search?
  100864. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  100865. encoder->protected_->qlp_coeff_precision
  100866. )
  100867. );
  100868. min_lpc_order = max_lpc_order = guess_lpc_order;
  100869. }
  100870. if(max_lpc_order >= frame_header->blocksize)
  100871. max_lpc_order = frame_header->blocksize - 1;
  100872. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  100873. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  100874. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  100875. continue; /* don't even try */
  100876. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  100877. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100878. if(rice_parameter >= rice_parameter_limit) {
  100879. #ifdef DEBUG_VERBOSE
  100880. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  100881. #endif
  100882. rice_parameter = rice_parameter_limit - 1;
  100883. }
  100884. if(encoder->protected_->do_qlp_coeff_prec_search) {
  100885. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  100886. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  100887. if(subframe_bps <= 17) {
  100888. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  100889. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  100890. }
  100891. else
  100892. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  100893. }
  100894. else {
  100895. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  100896. }
  100897. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  100898. _candidate_bits =
  100899. evaluate_lpc_subframe_(
  100900. encoder,
  100901. integer_signal,
  100902. residual[!_best_subframe],
  100903. encoder->private_->abs_residual_partition_sums,
  100904. encoder->private_->raw_bits_per_partition,
  100905. encoder->private_->lp_coeff[lpc_order-1],
  100906. frame_header->blocksize,
  100907. subframe_bps,
  100908. lpc_order,
  100909. qlp_coeff_precision,
  100910. rice_parameter,
  100911. rice_parameter_limit,
  100912. min_partition_order,
  100913. max_partition_order,
  100914. encoder->protected_->do_escape_coding,
  100915. encoder->protected_->rice_parameter_search_dist,
  100916. subframe[!_best_subframe],
  100917. partitioned_rice_contents[!_best_subframe]
  100918. );
  100919. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  100920. if(_candidate_bits < _best_bits) {
  100921. _best_subframe = !_best_subframe;
  100922. _best_bits = _candidate_bits;
  100923. }
  100924. }
  100925. }
  100926. }
  100927. }
  100928. }
  100929. }
  100930. }
  100931. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100932. }
  100933. }
  100934. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  100935. if(_best_bits == UINT_MAX) {
  100936. FLAC__ASSERT(_best_subframe == 0);
  100937. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100938. }
  100939. *best_subframe = _best_subframe;
  100940. *best_bits = _best_bits;
  100941. return true;
  100942. }
  100943. FLAC__bool add_subframe_(
  100944. FLAC__StreamEncoder *encoder,
  100945. unsigned blocksize,
  100946. unsigned subframe_bps,
  100947. const FLAC__Subframe *subframe,
  100948. FLAC__BitWriter *frame
  100949. )
  100950. {
  100951. switch(subframe->type) {
  100952. case FLAC__SUBFRAME_TYPE_CONSTANT:
  100953. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  100954. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100955. return false;
  100956. }
  100957. break;
  100958. case FLAC__SUBFRAME_TYPE_FIXED:
  100959. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  100960. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100961. return false;
  100962. }
  100963. break;
  100964. case FLAC__SUBFRAME_TYPE_LPC:
  100965. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  100966. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100967. return false;
  100968. }
  100969. break;
  100970. case FLAC__SUBFRAME_TYPE_VERBATIM:
  100971. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  100972. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100973. return false;
  100974. }
  100975. break;
  100976. default:
  100977. FLAC__ASSERT(0);
  100978. }
  100979. return true;
  100980. }
  100981. #define SPOTCHECK_ESTIMATE 0
  100982. #if SPOTCHECK_ESTIMATE
  100983. static void spotcheck_subframe_estimate_(
  100984. FLAC__StreamEncoder *encoder,
  100985. unsigned blocksize,
  100986. unsigned subframe_bps,
  100987. const FLAC__Subframe *subframe,
  100988. unsigned estimate
  100989. )
  100990. {
  100991. FLAC__bool ret;
  100992. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  100993. if(frame == 0) {
  100994. fprintf(stderr, "EST: can't allocate frame\n");
  100995. return;
  100996. }
  100997. if(!FLAC__bitwriter_init(frame)) {
  100998. fprintf(stderr, "EST: can't init frame\n");
  100999. return;
  101000. }
  101001. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  101002. FLAC__ASSERT(ret);
  101003. {
  101004. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  101005. if(estimate != actual)
  101006. fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
  101007. }
  101008. FLAC__bitwriter_delete(frame);
  101009. }
  101010. #endif
  101011. unsigned evaluate_constant_subframe_(
  101012. FLAC__StreamEncoder *encoder,
  101013. const FLAC__int32 signal,
  101014. unsigned blocksize,
  101015. unsigned subframe_bps,
  101016. FLAC__Subframe *subframe
  101017. )
  101018. {
  101019. unsigned estimate;
  101020. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101021. subframe->data.constant.value = signal;
  101022. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  101023. #if SPOTCHECK_ESTIMATE
  101024. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101025. #else
  101026. (void)encoder, (void)blocksize;
  101027. #endif
  101028. return estimate;
  101029. }
  101030. unsigned evaluate_fixed_subframe_(
  101031. FLAC__StreamEncoder *encoder,
  101032. const FLAC__int32 signal[],
  101033. FLAC__int32 residual[],
  101034. FLAC__uint64 abs_residual_partition_sums[],
  101035. unsigned raw_bits_per_partition[],
  101036. unsigned blocksize,
  101037. unsigned subframe_bps,
  101038. unsigned order,
  101039. unsigned rice_parameter,
  101040. unsigned rice_parameter_limit,
  101041. unsigned min_partition_order,
  101042. unsigned max_partition_order,
  101043. FLAC__bool do_escape_coding,
  101044. unsigned rice_parameter_search_dist,
  101045. FLAC__Subframe *subframe,
  101046. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101047. )
  101048. {
  101049. unsigned i, residual_bits, estimate;
  101050. const unsigned residual_samples = blocksize - order;
  101051. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  101052. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  101053. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101054. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101055. subframe->data.fixed.residual = residual;
  101056. residual_bits =
  101057. find_best_partition_order_(
  101058. encoder->private_,
  101059. residual,
  101060. abs_residual_partition_sums,
  101061. raw_bits_per_partition,
  101062. residual_samples,
  101063. order,
  101064. rice_parameter,
  101065. rice_parameter_limit,
  101066. min_partition_order,
  101067. max_partition_order,
  101068. subframe_bps,
  101069. do_escape_coding,
  101070. rice_parameter_search_dist,
  101071. &subframe->data.fixed.entropy_coding_method
  101072. );
  101073. subframe->data.fixed.order = order;
  101074. for(i = 0; i < order; i++)
  101075. subframe->data.fixed.warmup[i] = signal[i];
  101076. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  101077. #if SPOTCHECK_ESTIMATE
  101078. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101079. #endif
  101080. return estimate;
  101081. }
  101082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101083. unsigned evaluate_lpc_subframe_(
  101084. FLAC__StreamEncoder *encoder,
  101085. const FLAC__int32 signal[],
  101086. FLAC__int32 residual[],
  101087. FLAC__uint64 abs_residual_partition_sums[],
  101088. unsigned raw_bits_per_partition[],
  101089. const FLAC__real lp_coeff[],
  101090. unsigned blocksize,
  101091. unsigned subframe_bps,
  101092. unsigned order,
  101093. unsigned qlp_coeff_precision,
  101094. unsigned rice_parameter,
  101095. unsigned rice_parameter_limit,
  101096. unsigned min_partition_order,
  101097. unsigned max_partition_order,
  101098. FLAC__bool do_escape_coding,
  101099. unsigned rice_parameter_search_dist,
  101100. FLAC__Subframe *subframe,
  101101. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101102. )
  101103. {
  101104. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  101105. unsigned i, residual_bits, estimate;
  101106. int quantization, ret;
  101107. const unsigned residual_samples = blocksize - order;
  101108. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  101109. if(subframe_bps <= 16) {
  101110. FLAC__ASSERT(order > 0);
  101111. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  101112. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  101113. }
  101114. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  101115. if(ret != 0)
  101116. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  101117. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101118. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  101119. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101120. else
  101121. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101122. else
  101123. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101124. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  101125. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101126. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101127. subframe->data.lpc.residual = residual;
  101128. residual_bits =
  101129. find_best_partition_order_(
  101130. encoder->private_,
  101131. residual,
  101132. abs_residual_partition_sums,
  101133. raw_bits_per_partition,
  101134. residual_samples,
  101135. order,
  101136. rice_parameter,
  101137. rice_parameter_limit,
  101138. min_partition_order,
  101139. max_partition_order,
  101140. subframe_bps,
  101141. do_escape_coding,
  101142. rice_parameter_search_dist,
  101143. &subframe->data.lpc.entropy_coding_method
  101144. );
  101145. subframe->data.lpc.order = order;
  101146. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  101147. subframe->data.lpc.quantization_level = quantization;
  101148. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  101149. for(i = 0; i < order; i++)
  101150. subframe->data.lpc.warmup[i] = signal[i];
  101151. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
  101152. #if SPOTCHECK_ESTIMATE
  101153. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101154. #endif
  101155. return estimate;
  101156. }
  101157. #endif
  101158. unsigned evaluate_verbatim_subframe_(
  101159. FLAC__StreamEncoder *encoder,
  101160. const FLAC__int32 signal[],
  101161. unsigned blocksize,
  101162. unsigned subframe_bps,
  101163. FLAC__Subframe *subframe
  101164. )
  101165. {
  101166. unsigned estimate;
  101167. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101168. subframe->data.verbatim.data = signal;
  101169. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  101170. #if SPOTCHECK_ESTIMATE
  101171. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101172. #else
  101173. (void)encoder;
  101174. #endif
  101175. return estimate;
  101176. }
  101177. unsigned find_best_partition_order_(
  101178. FLAC__StreamEncoderPrivate *private_,
  101179. const FLAC__int32 residual[],
  101180. FLAC__uint64 abs_residual_partition_sums[],
  101181. unsigned raw_bits_per_partition[],
  101182. unsigned residual_samples,
  101183. unsigned predictor_order,
  101184. unsigned rice_parameter,
  101185. unsigned rice_parameter_limit,
  101186. unsigned min_partition_order,
  101187. unsigned max_partition_order,
  101188. unsigned bps,
  101189. FLAC__bool do_escape_coding,
  101190. unsigned rice_parameter_search_dist,
  101191. FLAC__EntropyCodingMethod *best_ecm
  101192. )
  101193. {
  101194. unsigned residual_bits, best_residual_bits = 0;
  101195. unsigned best_parameters_index = 0;
  101196. unsigned best_partition_order = 0;
  101197. const unsigned blocksize = residual_samples + predictor_order;
  101198. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  101199. min_partition_order = min(min_partition_order, max_partition_order);
  101200. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  101201. if(do_escape_coding)
  101202. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  101203. {
  101204. int partition_order;
  101205. unsigned sum;
  101206. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  101207. if(!
  101208. set_partitioned_rice_(
  101209. #ifdef EXACT_RICE_BITS_CALCULATION
  101210. residual,
  101211. #endif
  101212. abs_residual_partition_sums+sum,
  101213. raw_bits_per_partition+sum,
  101214. residual_samples,
  101215. predictor_order,
  101216. rice_parameter,
  101217. rice_parameter_limit,
  101218. rice_parameter_search_dist,
  101219. (unsigned)partition_order,
  101220. do_escape_coding,
  101221. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  101222. &residual_bits
  101223. )
  101224. )
  101225. {
  101226. FLAC__ASSERT(best_residual_bits != 0);
  101227. break;
  101228. }
  101229. sum += 1u << partition_order;
  101230. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  101231. best_residual_bits = residual_bits;
  101232. best_parameters_index = !best_parameters_index;
  101233. best_partition_order = partition_order;
  101234. }
  101235. }
  101236. }
  101237. best_ecm->data.partitioned_rice.order = best_partition_order;
  101238. {
  101239. /*
  101240. * We are allowed to de-const the pointer based on our special
  101241. * knowledge; it is const to the outside world.
  101242. */
  101243. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  101244. unsigned partition;
  101245. /* save best parameters and raw_bits */
  101246. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  101247. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  101248. if(do_escape_coding)
  101249. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  101250. /*
  101251. * Now need to check if the type should be changed to
  101252. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  101253. * size of the rice parameters.
  101254. */
  101255. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  101256. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  101257. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  101258. break;
  101259. }
  101260. }
  101261. }
  101262. return best_residual_bits;
  101263. }
  101264. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101265. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  101266. const FLAC__int32 residual[],
  101267. FLAC__uint64 abs_residual_partition_sums[],
  101268. unsigned blocksize,
  101269. unsigned predictor_order,
  101270. unsigned min_partition_order,
  101271. unsigned max_partition_order
  101272. );
  101273. #endif
  101274. void precompute_partition_info_sums_(
  101275. const FLAC__int32 residual[],
  101276. FLAC__uint64 abs_residual_partition_sums[],
  101277. unsigned residual_samples,
  101278. unsigned predictor_order,
  101279. unsigned min_partition_order,
  101280. unsigned max_partition_order,
  101281. unsigned bps
  101282. )
  101283. {
  101284. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  101285. unsigned partitions = 1u << max_partition_order;
  101286. FLAC__ASSERT(default_partition_samples > predictor_order);
  101287. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101288. /* slightly pessimistic but still catches all common cases */
  101289. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101290. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101291. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  101292. return;
  101293. }
  101294. #endif
  101295. /* first do max_partition_order */
  101296. {
  101297. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  101298. /* slightly pessimistic but still catches all common cases */
  101299. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101300. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101301. FLAC__uint32 abs_residual_partition_sum;
  101302. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101303. end += default_partition_samples;
  101304. abs_residual_partition_sum = 0;
  101305. for( ; residual_sample < end; residual_sample++)
  101306. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101307. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101308. }
  101309. }
  101310. else { /* have to pessimistically use 64 bits for accumulator */
  101311. FLAC__uint64 abs_residual_partition_sum;
  101312. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101313. end += default_partition_samples;
  101314. abs_residual_partition_sum = 0;
  101315. for( ; residual_sample < end; residual_sample++)
  101316. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101317. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101318. }
  101319. }
  101320. }
  101321. /* now merge partitions for lower orders */
  101322. {
  101323. unsigned from_partition = 0, to_partition = partitions;
  101324. int partition_order;
  101325. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  101326. unsigned i;
  101327. partitions >>= 1;
  101328. for(i = 0; i < partitions; i++) {
  101329. abs_residual_partition_sums[to_partition++] =
  101330. abs_residual_partition_sums[from_partition ] +
  101331. abs_residual_partition_sums[from_partition+1];
  101332. from_partition += 2;
  101333. }
  101334. }
  101335. }
  101336. }
  101337. void precompute_partition_info_escapes_(
  101338. const FLAC__int32 residual[],
  101339. unsigned raw_bits_per_partition[],
  101340. unsigned residual_samples,
  101341. unsigned predictor_order,
  101342. unsigned min_partition_order,
  101343. unsigned max_partition_order
  101344. )
  101345. {
  101346. int partition_order;
  101347. unsigned from_partition, to_partition = 0;
  101348. const unsigned blocksize = residual_samples + predictor_order;
  101349. /* first do max_partition_order */
  101350. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  101351. FLAC__int32 r;
  101352. FLAC__uint32 rmax;
  101353. unsigned partition, partition_sample, partition_samples, residual_sample;
  101354. const unsigned partitions = 1u << partition_order;
  101355. const unsigned default_partition_samples = blocksize >> partition_order;
  101356. FLAC__ASSERT(default_partition_samples > predictor_order);
  101357. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101358. partition_samples = default_partition_samples;
  101359. if(partition == 0)
  101360. partition_samples -= predictor_order;
  101361. rmax = 0;
  101362. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  101363. r = residual[residual_sample++];
  101364. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  101365. if(r < 0)
  101366. rmax |= ~r;
  101367. else
  101368. rmax |= r;
  101369. }
  101370. /* now we know all residual values are in the range [-rmax-1,rmax] */
  101371. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  101372. }
  101373. to_partition = partitions;
  101374. break; /*@@@ yuck, should remove the 'for' loop instead */
  101375. }
  101376. /* now merge partitions for lower orders */
  101377. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  101378. unsigned m;
  101379. unsigned i;
  101380. const unsigned partitions = 1u << partition_order;
  101381. for(i = 0; i < partitions; i++) {
  101382. m = raw_bits_per_partition[from_partition];
  101383. from_partition++;
  101384. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  101385. from_partition++;
  101386. to_partition++;
  101387. }
  101388. }
  101389. }
  101390. #ifdef EXACT_RICE_BITS_CALCULATION
  101391. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101392. const unsigned rice_parameter,
  101393. const unsigned partition_samples,
  101394. const FLAC__int32 *residual
  101395. )
  101396. {
  101397. unsigned i, partition_bits =
  101398. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  101399. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  101400. ;
  101401. for(i = 0; i < partition_samples; i++)
  101402. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  101403. return partition_bits;
  101404. }
  101405. #else
  101406. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101407. const unsigned rice_parameter,
  101408. const unsigned partition_samples,
  101409. const FLAC__uint64 abs_residual_partition_sum
  101410. )
  101411. {
  101412. return
  101413. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  101414. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  101415. (
  101416. rice_parameter?
  101417. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  101418. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  101419. )
  101420. - (partition_samples >> 1)
  101421. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  101422. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  101423. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  101424. * So the subtraction term tries to guess how many extra bits were contributed.
  101425. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  101426. */
  101427. ;
  101428. }
  101429. #endif
  101430. FLAC__bool set_partitioned_rice_(
  101431. #ifdef EXACT_RICE_BITS_CALCULATION
  101432. const FLAC__int32 residual[],
  101433. #endif
  101434. const FLAC__uint64 abs_residual_partition_sums[],
  101435. const unsigned raw_bits_per_partition[],
  101436. const unsigned residual_samples,
  101437. const unsigned predictor_order,
  101438. const unsigned suggested_rice_parameter,
  101439. const unsigned rice_parameter_limit,
  101440. const unsigned rice_parameter_search_dist,
  101441. const unsigned partition_order,
  101442. const FLAC__bool search_for_escapes,
  101443. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101444. unsigned *bits
  101445. )
  101446. {
  101447. unsigned rice_parameter, partition_bits;
  101448. unsigned best_partition_bits, best_rice_parameter = 0;
  101449. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  101450. unsigned *parameters, *raw_bits;
  101451. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101452. unsigned min_rice_parameter, max_rice_parameter;
  101453. #else
  101454. (void)rice_parameter_search_dist;
  101455. #endif
  101456. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101457. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101458. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  101459. parameters = partitioned_rice_contents->parameters;
  101460. raw_bits = partitioned_rice_contents->raw_bits;
  101461. if(partition_order == 0) {
  101462. best_partition_bits = (unsigned)(-1);
  101463. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101464. if(rice_parameter_search_dist) {
  101465. if(suggested_rice_parameter < rice_parameter_search_dist)
  101466. min_rice_parameter = 0;
  101467. else
  101468. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  101469. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  101470. if(max_rice_parameter >= rice_parameter_limit) {
  101471. #ifdef DEBUG_VERBOSE
  101472. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  101473. #endif
  101474. max_rice_parameter = rice_parameter_limit - 1;
  101475. }
  101476. }
  101477. else
  101478. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  101479. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101480. #else
  101481. rice_parameter = suggested_rice_parameter;
  101482. #endif
  101483. #ifdef EXACT_RICE_BITS_CALCULATION
  101484. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  101485. #else
  101486. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  101487. #endif
  101488. if(partition_bits < best_partition_bits) {
  101489. best_rice_parameter = rice_parameter;
  101490. best_partition_bits = partition_bits;
  101491. }
  101492. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101493. }
  101494. #endif
  101495. if(search_for_escapes) {
  101496. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
  101497. if(partition_bits <= best_partition_bits) {
  101498. raw_bits[0] = raw_bits_per_partition[0];
  101499. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101500. best_partition_bits = partition_bits;
  101501. }
  101502. else
  101503. raw_bits[0] = 0;
  101504. }
  101505. parameters[0] = best_rice_parameter;
  101506. bits_ += best_partition_bits;
  101507. }
  101508. else {
  101509. unsigned partition, residual_sample;
  101510. unsigned partition_samples;
  101511. FLAC__uint64 mean, k;
  101512. const unsigned partitions = 1u << partition_order;
  101513. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101514. partition_samples = (residual_samples+predictor_order) >> partition_order;
  101515. if(partition == 0) {
  101516. if(partition_samples <= predictor_order)
  101517. return false;
  101518. else
  101519. partition_samples -= predictor_order;
  101520. }
  101521. mean = abs_residual_partition_sums[partition];
  101522. /* we are basically calculating the size in bits of the
  101523. * average residual magnitude in the partition:
  101524. * rice_parameter = floor(log2(mean/partition_samples))
  101525. * 'mean' is not a good name for the variable, it is
  101526. * actually the sum of magnitudes of all residual values
  101527. * in the partition, so the actual mean is
  101528. * mean/partition_samples
  101529. */
  101530. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  101531. ;
  101532. if(rice_parameter >= rice_parameter_limit) {
  101533. #ifdef DEBUG_VERBOSE
  101534. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  101535. #endif
  101536. rice_parameter = rice_parameter_limit - 1;
  101537. }
  101538. best_partition_bits = (unsigned)(-1);
  101539. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101540. if(rice_parameter_search_dist) {
  101541. if(rice_parameter < rice_parameter_search_dist)
  101542. min_rice_parameter = 0;
  101543. else
  101544. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  101545. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  101546. if(max_rice_parameter >= rice_parameter_limit) {
  101547. #ifdef DEBUG_VERBOSE
  101548. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  101549. #endif
  101550. max_rice_parameter = rice_parameter_limit - 1;
  101551. }
  101552. }
  101553. else
  101554. min_rice_parameter = max_rice_parameter = rice_parameter;
  101555. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101556. #endif
  101557. #ifdef EXACT_RICE_BITS_CALCULATION
  101558. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  101559. #else
  101560. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  101561. #endif
  101562. if(partition_bits < best_partition_bits) {
  101563. best_rice_parameter = rice_parameter;
  101564. best_partition_bits = partition_bits;
  101565. }
  101566. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101567. }
  101568. #endif
  101569. if(search_for_escapes) {
  101570. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
  101571. if(partition_bits <= best_partition_bits) {
  101572. raw_bits[partition] = raw_bits_per_partition[partition];
  101573. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101574. best_partition_bits = partition_bits;
  101575. }
  101576. else
  101577. raw_bits[partition] = 0;
  101578. }
  101579. parameters[partition] = best_rice_parameter;
  101580. bits_ += best_partition_bits;
  101581. residual_sample += partition_samples;
  101582. }
  101583. }
  101584. *bits = bits_;
  101585. return true;
  101586. }
  101587. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  101588. {
  101589. unsigned i, shift;
  101590. FLAC__int32 x = 0;
  101591. for(i = 0; i < samples && !(x&1); i++)
  101592. x |= signal[i];
  101593. if(x == 0) {
  101594. shift = 0;
  101595. }
  101596. else {
  101597. for(shift = 0; !(x&1); shift++)
  101598. x >>= 1;
  101599. }
  101600. if(shift > 0) {
  101601. for(i = 0; i < samples; i++)
  101602. signal[i] >>= shift;
  101603. }
  101604. return shift;
  101605. }
  101606. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101607. {
  101608. unsigned channel;
  101609. for(channel = 0; channel < channels; channel++)
  101610. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  101611. fifo->tail += wide_samples;
  101612. FLAC__ASSERT(fifo->tail <= fifo->size);
  101613. }
  101614. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101615. {
  101616. unsigned channel;
  101617. unsigned sample, wide_sample;
  101618. unsigned tail = fifo->tail;
  101619. sample = input_offset * channels;
  101620. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  101621. for(channel = 0; channel < channels; channel++)
  101622. fifo->data[channel][tail] = input[sample++];
  101623. tail++;
  101624. }
  101625. fifo->tail = tail;
  101626. FLAC__ASSERT(fifo->tail <= fifo->size);
  101627. }
  101628. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101629. {
  101630. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101631. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  101632. (void)decoder;
  101633. if(encoder->private_->verify.needs_magic_hack) {
  101634. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  101635. *bytes = FLAC__STREAM_SYNC_LENGTH;
  101636. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  101637. encoder->private_->verify.needs_magic_hack = false;
  101638. }
  101639. else {
  101640. if(encoded_bytes == 0) {
  101641. /*
  101642. * If we get here, a FIFO underflow has occurred,
  101643. * which means there is a bug somewhere.
  101644. */
  101645. FLAC__ASSERT(0);
  101646. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101647. }
  101648. else if(encoded_bytes < *bytes)
  101649. *bytes = encoded_bytes;
  101650. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  101651. encoder->private_->verify.output.data += *bytes;
  101652. encoder->private_->verify.output.bytes -= *bytes;
  101653. }
  101654. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101655. }
  101656. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  101657. {
  101658. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  101659. unsigned channel;
  101660. const unsigned channels = frame->header.channels;
  101661. const unsigned blocksize = frame->header.blocksize;
  101662. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  101663. (void)decoder;
  101664. for(channel = 0; channel < channels; channel++) {
  101665. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  101666. unsigned i, sample = 0;
  101667. FLAC__int32 expect = 0, got = 0;
  101668. for(i = 0; i < blocksize; i++) {
  101669. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  101670. sample = i;
  101671. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  101672. got = (FLAC__int32)buffer[channel][i];
  101673. break;
  101674. }
  101675. }
  101676. FLAC__ASSERT(i < blocksize);
  101677. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101678. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  101679. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  101680. encoder->private_->verify.error_stats.channel = channel;
  101681. encoder->private_->verify.error_stats.sample = sample;
  101682. encoder->private_->verify.error_stats.expected = expect;
  101683. encoder->private_->verify.error_stats.got = got;
  101684. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  101685. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101686. }
  101687. }
  101688. /* dequeue the frame from the fifo */
  101689. encoder->private_->verify.input_fifo.tail -= blocksize;
  101690. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  101691. for(channel = 0; channel < channels; channel++)
  101692. memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
  101693. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101694. }
  101695. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  101696. {
  101697. (void)decoder, (void)metadata, (void)client_data;
  101698. }
  101699. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  101700. {
  101701. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101702. (void)decoder, (void)status;
  101703. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101704. }
  101705. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101706. {
  101707. (void)client_data;
  101708. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  101709. if (*bytes == 0) {
  101710. if (feof(encoder->private_->file))
  101711. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  101712. else if (ferror(encoder->private_->file))
  101713. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  101714. }
  101715. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  101716. }
  101717. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101718. {
  101719. (void)client_data;
  101720. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101721. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  101722. else
  101723. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  101724. }
  101725. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101726. {
  101727. off_t offset;
  101728. (void)client_data;
  101729. offset = ftello(encoder->private_->file);
  101730. if(offset < 0) {
  101731. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  101732. }
  101733. else {
  101734. *absolute_byte_offset = (FLAC__uint64)offset;
  101735. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  101736. }
  101737. }
  101738. #ifdef FLAC__VALGRIND_TESTING
  101739. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  101740. {
  101741. size_t ret = fwrite(ptr, size, nmemb, stream);
  101742. if(!ferror(stream))
  101743. fflush(stream);
  101744. return ret;
  101745. }
  101746. #else
  101747. #define local__fwrite fwrite
  101748. #endif
  101749. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  101750. {
  101751. (void)client_data, (void)current_frame;
  101752. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  101753. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  101754. #if FLAC__HAS_OGG
  101755. /* We would like to be able to use 'samples > 0' in the
  101756. * clause here but currently because of the nature of our
  101757. * Ogg writing implementation, 'samples' is always 0 (see
  101758. * ogg_encoder_aspect.c). The downside is extra progress
  101759. * callbacks.
  101760. */
  101761. encoder->private_->is_ogg? true :
  101762. #endif
  101763. samples > 0
  101764. );
  101765. if(call_it) {
  101766. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  101767. * because at this point in the callback chain, the stats
  101768. * have not been updated. Only after we return and control
  101769. * gets back to write_frame_() are the stats updated
  101770. */
  101771. encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
  101772. }
  101773. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  101774. }
  101775. else
  101776. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101777. }
  101778. /*
  101779. * This will forcibly set stdout to binary mode (for OSes that require it)
  101780. */
  101781. FILE *get_binary_stdout_(void)
  101782. {
  101783. /* if something breaks here it is probably due to the presence or
  101784. * absence of an underscore before the identifiers 'setmode',
  101785. * 'fileno', and/or 'O_BINARY'; check your system header files.
  101786. */
  101787. #if defined _MSC_VER || defined __MINGW32__
  101788. _setmode(_fileno(stdout), _O_BINARY);
  101789. #elif defined __CYGWIN__
  101790. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  101791. setmode(_fileno(stdout), _O_BINARY);
  101792. #elif defined __EMX__
  101793. setmode(fileno(stdout), O_BINARY);
  101794. #endif
  101795. return stdout;
  101796. }
  101797. #endif
  101798. /********* End of inlined file: stream_encoder.c *********/
  101799. /********* Start of inlined file: stream_encoder_framing.c *********/
  101800. /********* Start of inlined file: juce_FlacHeader.h *********/
  101801. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101802. // tasks..
  101803. #define VERSION "1.2.1"
  101804. #define FLAC__NO_DLL 1
  101805. #if JUCE_MSVC
  101806. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101807. #endif
  101808. #if JUCE_MAC
  101809. #define FLAC__SYS_DARWIN 1
  101810. #endif
  101811. /********* End of inlined file: juce_FlacHeader.h *********/
  101812. #if JUCE_USE_FLAC
  101813. #if HAVE_CONFIG_H
  101814. # include <config.h>
  101815. #endif
  101816. #include <stdio.h>
  101817. #include <string.h> /* for strlen() */
  101818. #ifdef max
  101819. #undef max
  101820. #endif
  101821. #define max(x,y) ((x)>(y)?(x):(y))
  101822. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  101823. static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended);
  101824. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  101825. {
  101826. unsigned i, j;
  101827. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  101828. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  101829. return false;
  101830. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  101831. return false;
  101832. /*
  101833. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  101834. */
  101835. i = metadata->length;
  101836. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101837. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  101838. i -= metadata->data.vorbis_comment.vendor_string.length;
  101839. i += vendor_string_length;
  101840. }
  101841. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  101842. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  101843. return false;
  101844. switch(metadata->type) {
  101845. case FLAC__METADATA_TYPE_STREAMINFO:
  101846. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  101847. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  101848. return false;
  101849. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  101850. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  101851. return false;
  101852. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  101853. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  101854. return false;
  101855. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  101856. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  101857. return false;
  101858. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  101859. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  101860. return false;
  101861. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  101862. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  101863. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  101864. return false;
  101865. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  101866. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101867. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  101868. return false;
  101869. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  101870. return false;
  101871. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  101872. return false;
  101873. break;
  101874. case FLAC__METADATA_TYPE_PADDING:
  101875. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  101876. return false;
  101877. break;
  101878. case FLAC__METADATA_TYPE_APPLICATION:
  101879. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  101880. return false;
  101881. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  101882. return false;
  101883. break;
  101884. case FLAC__METADATA_TYPE_SEEKTABLE:
  101885. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  101886. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  101887. return false;
  101888. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  101889. return false;
  101890. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  101891. return false;
  101892. }
  101893. break;
  101894. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  101895. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  101896. return false;
  101897. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  101898. return false;
  101899. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  101900. return false;
  101901. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  101902. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  101903. return false;
  101904. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  101905. return false;
  101906. }
  101907. break;
  101908. case FLAC__METADATA_TYPE_CUESHEET:
  101909. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  101910. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  101911. return false;
  101912. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  101913. return false;
  101914. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  101915. return false;
  101916. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  101917. return false;
  101918. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  101919. return false;
  101920. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  101921. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  101922. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  101923. return false;
  101924. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  101925. return false;
  101926. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  101927. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  101928. return false;
  101929. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  101930. return false;
  101931. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  101932. return false;
  101933. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  101934. return false;
  101935. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  101936. return false;
  101937. for(j = 0; j < track->num_indices; j++) {
  101938. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  101939. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  101940. return false;
  101941. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  101942. return false;
  101943. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  101944. return false;
  101945. }
  101946. }
  101947. break;
  101948. case FLAC__METADATA_TYPE_PICTURE:
  101949. {
  101950. size_t len;
  101951. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  101952. return false;
  101953. len = strlen(metadata->data.picture.mime_type);
  101954. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  101955. return false;
  101956. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  101957. return false;
  101958. len = strlen((const char *)metadata->data.picture.description);
  101959. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  101960. return false;
  101961. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  101962. return false;
  101963. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  101964. return false;
  101965. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  101966. return false;
  101967. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  101968. return false;
  101969. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  101970. return false;
  101971. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  101972. return false;
  101973. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  101974. return false;
  101975. }
  101976. break;
  101977. default:
  101978. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  101979. return false;
  101980. break;
  101981. }
  101982. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101983. return true;
  101984. }
  101985. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  101986. {
  101987. unsigned u, blocksize_hint, sample_rate_hint;
  101988. FLAC__byte crc;
  101989. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101990. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  101991. return false;
  101992. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  101993. return false;
  101994. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  101995. return false;
  101996. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  101997. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  101998. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  101999. blocksize_hint = 0;
  102000. switch(header->blocksize) {
  102001. case 192: u = 1; break;
  102002. case 576: u = 2; break;
  102003. case 1152: u = 3; break;
  102004. case 2304: u = 4; break;
  102005. case 4608: u = 5; break;
  102006. case 256: u = 8; break;
  102007. case 512: u = 9; break;
  102008. case 1024: u = 10; break;
  102009. case 2048: u = 11; break;
  102010. case 4096: u = 12; break;
  102011. case 8192: u = 13; break;
  102012. case 16384: u = 14; break;
  102013. case 32768: u = 15; break;
  102014. default:
  102015. if(header->blocksize <= 0x100)
  102016. blocksize_hint = u = 6;
  102017. else
  102018. blocksize_hint = u = 7;
  102019. break;
  102020. }
  102021. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  102022. return false;
  102023. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  102024. sample_rate_hint = 0;
  102025. switch(header->sample_rate) {
  102026. case 88200: u = 1; break;
  102027. case 176400: u = 2; break;
  102028. case 192000: u = 3; break;
  102029. case 8000: u = 4; break;
  102030. case 16000: u = 5; break;
  102031. case 22050: u = 6; break;
  102032. case 24000: u = 7; break;
  102033. case 32000: u = 8; break;
  102034. case 44100: u = 9; break;
  102035. case 48000: u = 10; break;
  102036. case 96000: u = 11; break;
  102037. default:
  102038. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  102039. sample_rate_hint = u = 12;
  102040. else if(header->sample_rate % 10 == 0)
  102041. sample_rate_hint = u = 14;
  102042. else if(header->sample_rate <= 0xffff)
  102043. sample_rate_hint = u = 13;
  102044. else
  102045. u = 0;
  102046. break;
  102047. }
  102048. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  102049. return false;
  102050. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  102051. switch(header->channel_assignment) {
  102052. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  102053. u = header->channels - 1;
  102054. break;
  102055. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  102056. FLAC__ASSERT(header->channels == 2);
  102057. u = 8;
  102058. break;
  102059. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  102060. FLAC__ASSERT(header->channels == 2);
  102061. u = 9;
  102062. break;
  102063. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  102064. FLAC__ASSERT(header->channels == 2);
  102065. u = 10;
  102066. break;
  102067. default:
  102068. FLAC__ASSERT(0);
  102069. }
  102070. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  102071. return false;
  102072. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102073. switch(header->bits_per_sample) {
  102074. case 8 : u = 1; break;
  102075. case 12: u = 2; break;
  102076. case 16: u = 4; break;
  102077. case 20: u = 5; break;
  102078. case 24: u = 6; break;
  102079. default: u = 0; break;
  102080. }
  102081. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  102082. return false;
  102083. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  102084. return false;
  102085. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  102086. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  102087. return false;
  102088. }
  102089. else {
  102090. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  102091. return false;
  102092. }
  102093. if(blocksize_hint)
  102094. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  102095. return false;
  102096. switch(sample_rate_hint) {
  102097. case 12:
  102098. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  102099. return false;
  102100. break;
  102101. case 13:
  102102. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  102103. return false;
  102104. break;
  102105. case 14:
  102106. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  102107. return false;
  102108. break;
  102109. }
  102110. /* write the CRC */
  102111. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  102112. return false;
  102113. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  102114. return false;
  102115. return true;
  102116. }
  102117. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102118. {
  102119. FLAC__bool ok;
  102120. ok =
  102121. FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) &&
  102122. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  102123. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  102124. ;
  102125. return ok;
  102126. }
  102127. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102128. {
  102129. unsigned i;
  102130. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  102131. return false;
  102132. if(wasted_bits)
  102133. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102134. return false;
  102135. for(i = 0; i < subframe->order; i++)
  102136. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102137. return false;
  102138. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102139. return false;
  102140. switch(subframe->entropy_coding_method.type) {
  102141. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102142. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102143. if(!add_residual_partitioned_rice_(
  102144. bw,
  102145. subframe->residual,
  102146. residual_samples,
  102147. subframe->order,
  102148. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102149. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102150. subframe->entropy_coding_method.data.partitioned_rice.order,
  102151. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102152. ))
  102153. return false;
  102154. break;
  102155. default:
  102156. FLAC__ASSERT(0);
  102157. }
  102158. return true;
  102159. }
  102160. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102161. {
  102162. unsigned i;
  102163. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  102164. return false;
  102165. if(wasted_bits)
  102166. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102167. return false;
  102168. for(i = 0; i < subframe->order; i++)
  102169. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102170. return false;
  102171. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  102172. return false;
  102173. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  102174. return false;
  102175. for(i = 0; i < subframe->order; i++)
  102176. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  102177. return false;
  102178. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102179. return false;
  102180. switch(subframe->entropy_coding_method.type) {
  102181. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102182. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102183. if(!add_residual_partitioned_rice_(
  102184. bw,
  102185. subframe->residual,
  102186. residual_samples,
  102187. subframe->order,
  102188. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102189. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102190. subframe->entropy_coding_method.data.partitioned_rice.order,
  102191. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102192. ))
  102193. return false;
  102194. break;
  102195. default:
  102196. FLAC__ASSERT(0);
  102197. }
  102198. return true;
  102199. }
  102200. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102201. {
  102202. unsigned i;
  102203. const FLAC__int32 *signal = subframe->data;
  102204. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  102205. return false;
  102206. if(wasted_bits)
  102207. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102208. return false;
  102209. for(i = 0; i < samples; i++)
  102210. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  102211. return false;
  102212. return true;
  102213. }
  102214. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  102215. {
  102216. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  102217. return false;
  102218. switch(method->type) {
  102219. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102220. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102221. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102222. return false;
  102223. break;
  102224. default:
  102225. FLAC__ASSERT(0);
  102226. }
  102227. return true;
  102228. }
  102229. FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended)
  102230. {
  102231. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  102232. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  102233. if(partition_order == 0) {
  102234. unsigned i;
  102235. if(raw_bits[0] == 0) {
  102236. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  102237. return false;
  102238. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  102239. return false;
  102240. }
  102241. else {
  102242. FLAC__ASSERT(rice_parameters[0] == 0);
  102243. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102244. return false;
  102245. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102246. return false;
  102247. for(i = 0; i < residual_samples; i++) {
  102248. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  102249. return false;
  102250. }
  102251. }
  102252. return true;
  102253. }
  102254. else {
  102255. unsigned i, j, k = 0, k_last = 0;
  102256. unsigned partition_samples;
  102257. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  102258. for(i = 0; i < (1u<<partition_order); i++) {
  102259. partition_samples = default_partition_samples;
  102260. if(i == 0)
  102261. partition_samples -= predictor_order;
  102262. k += partition_samples;
  102263. if(raw_bits[i] == 0) {
  102264. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  102265. return false;
  102266. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  102267. return false;
  102268. }
  102269. else {
  102270. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102271. return false;
  102272. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102273. return false;
  102274. for(j = k_last; j < k; j++) {
  102275. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  102276. return false;
  102277. }
  102278. }
  102279. k_last = k;
  102280. }
  102281. return true;
  102282. }
  102283. }
  102284. #endif
  102285. /********* End of inlined file: stream_encoder_framing.c *********/
  102286. /********* Start of inlined file: window_flac.c *********/
  102287. /********* Start of inlined file: juce_FlacHeader.h *********/
  102288. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102289. // tasks..
  102290. #define VERSION "1.2.1"
  102291. #define FLAC__NO_DLL 1
  102292. #if JUCE_MSVC
  102293. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102294. #endif
  102295. #if JUCE_MAC
  102296. #define FLAC__SYS_DARWIN 1
  102297. #endif
  102298. /********* End of inlined file: juce_FlacHeader.h *********/
  102299. #if JUCE_USE_FLAC
  102300. #if HAVE_CONFIG_H
  102301. # include <config.h>
  102302. #endif
  102303. #include <math.h>
  102304. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102305. #ifndef M_PI
  102306. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  102307. #define M_PI 3.14159265358979323846
  102308. #endif
  102309. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  102310. {
  102311. const FLAC__int32 N = L - 1;
  102312. FLAC__int32 n;
  102313. if (L & 1) {
  102314. for (n = 0; n <= N/2; n++)
  102315. window[n] = 2.0f * n / (float)N;
  102316. for (; n <= N; n++)
  102317. window[n] = 2.0f - 2.0f * n / (float)N;
  102318. }
  102319. else {
  102320. for (n = 0; n <= L/2-1; n++)
  102321. window[n] = 2.0f * n / (float)N;
  102322. for (; n <= N; n++)
  102323. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  102324. }
  102325. }
  102326. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  102327. {
  102328. const FLAC__int32 N = L - 1;
  102329. FLAC__int32 n;
  102330. for (n = 0; n < L; n++)
  102331. window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f)));
  102332. }
  102333. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  102334. {
  102335. const FLAC__int32 N = L - 1;
  102336. FLAC__int32 n;
  102337. for (n = 0; n < L; n++)
  102338. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  102339. }
  102340. /* 4-term -92dB side-lobe */
  102341. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  102342. {
  102343. const FLAC__int32 N = L - 1;
  102344. FLAC__int32 n;
  102345. for (n = 0; n <= N; n++)
  102346. window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N));
  102347. }
  102348. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  102349. {
  102350. const FLAC__int32 N = L - 1;
  102351. const double N2 = (double)N / 2.;
  102352. FLAC__int32 n;
  102353. for (n = 0; n <= N; n++) {
  102354. double k = ((double)n - N2) / N2;
  102355. k = 1.0f - k * k;
  102356. window[n] = (FLAC__real)(k * k);
  102357. }
  102358. }
  102359. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  102360. {
  102361. const FLAC__int32 N = L - 1;
  102362. FLAC__int32 n;
  102363. for (n = 0; n < L; n++)
  102364. window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N));
  102365. }
  102366. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  102367. {
  102368. const FLAC__int32 N = L - 1;
  102369. const double N2 = (double)N / 2.;
  102370. FLAC__int32 n;
  102371. for (n = 0; n <= N; n++) {
  102372. const double k = ((double)n - N2) / (stddev * N2);
  102373. window[n] = (FLAC__real)exp(-0.5f * k * k);
  102374. }
  102375. }
  102376. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  102377. {
  102378. const FLAC__int32 N = L - 1;
  102379. FLAC__int32 n;
  102380. for (n = 0; n < L; n++)
  102381. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  102382. }
  102383. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  102384. {
  102385. const FLAC__int32 N = L - 1;
  102386. FLAC__int32 n;
  102387. for (n = 0; n < L; n++)
  102388. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  102389. }
  102390. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  102391. {
  102392. const FLAC__int32 N = L - 1;
  102393. FLAC__int32 n;
  102394. for (n = 0; n < L; n++)
  102395. window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N));
  102396. }
  102397. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  102398. {
  102399. const FLAC__int32 N = L - 1;
  102400. FLAC__int32 n;
  102401. for (n = 0; n < L; n++)
  102402. window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N));
  102403. }
  102404. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  102405. {
  102406. FLAC__int32 n;
  102407. for (n = 0; n < L; n++)
  102408. window[n] = 1.0f;
  102409. }
  102410. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  102411. {
  102412. FLAC__int32 n;
  102413. if (L & 1) {
  102414. for (n = 1; n <= L+1/2; n++)
  102415. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  102416. for (; n <= L; n++)
  102417. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  102418. }
  102419. else {
  102420. for (n = 1; n <= L/2; n++)
  102421. window[n-1] = 2.0f * n / (float)L;
  102422. for (; n <= L; n++)
  102423. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  102424. }
  102425. }
  102426. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  102427. {
  102428. if (p <= 0.0)
  102429. FLAC__window_rectangle(window, L);
  102430. else if (p >= 1.0)
  102431. FLAC__window_hann(window, L);
  102432. else {
  102433. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  102434. FLAC__int32 n;
  102435. /* start with rectangle... */
  102436. FLAC__window_rectangle(window, L);
  102437. /* ...replace ends with hann */
  102438. if (Np > 0) {
  102439. for (n = 0; n <= Np; n++) {
  102440. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  102441. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  102442. }
  102443. }
  102444. }
  102445. }
  102446. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  102447. {
  102448. const FLAC__int32 N = L - 1;
  102449. const double N2 = (double)N / 2.;
  102450. FLAC__int32 n;
  102451. for (n = 0; n <= N; n++) {
  102452. const double k = ((double)n - N2) / N2;
  102453. window[n] = (FLAC__real)(1.0f - k * k);
  102454. }
  102455. }
  102456. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102457. #endif
  102458. /********* End of inlined file: window_flac.c *********/
  102459. #else
  102460. #include <FLAC/all.h>
  102461. #endif
  102462. }
  102463. #ifdef _MSC_VER
  102464. #pragma warning (pop)
  102465. #endif
  102466. BEGIN_JUCE_NAMESPACE
  102467. using namespace FlacNamespace;
  102468. #define flacFormatName TRANS("FLAC file")
  102469. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  102470. class FlacReader : public AudioFormatReader
  102471. {
  102472. FLAC__StreamDecoder* decoder;
  102473. AudioSampleBuffer reservoir;
  102474. int reservoirStart, samplesInReservoir;
  102475. bool ok, scanningForLength;
  102476. public:
  102477. FlacReader (InputStream* const in)
  102478. : AudioFormatReader (in, flacFormatName),
  102479. reservoir (2, 0),
  102480. reservoirStart (0),
  102481. samplesInReservoir (0),
  102482. scanningForLength (false)
  102483. {
  102484. using namespace FlacNamespace;
  102485. lengthInSamples = 0;
  102486. decoder = FLAC__stream_decoder_new();
  102487. ok = FLAC__stream_decoder_init_stream (decoder,
  102488. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  102489. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  102490. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  102491. if (ok)
  102492. {
  102493. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102494. if (lengthInSamples == 0 && sampleRate > 0)
  102495. {
  102496. // the length hasn't been stored in the metadata, so we'll need to
  102497. // work it out the length the hard way, by scanning the whole file..
  102498. scanningForLength = true;
  102499. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  102500. scanningForLength = false;
  102501. const int64 tempLength = lengthInSamples;
  102502. FLAC__stream_decoder_reset (decoder);
  102503. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102504. lengthInSamples = tempLength;
  102505. }
  102506. }
  102507. }
  102508. ~FlacReader()
  102509. {
  102510. FLAC__stream_decoder_delete (decoder);
  102511. }
  102512. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  102513. {
  102514. sampleRate = info.sample_rate;
  102515. bitsPerSample = info.bits_per_sample;
  102516. lengthInSamples = (unsigned int) info.total_samples;
  102517. numChannels = info.channels;
  102518. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  102519. }
  102520. // returns the number of samples read
  102521. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  102522. int64 startSampleInFile, int numSamples)
  102523. {
  102524. using namespace FlacNamespace;
  102525. if (! ok)
  102526. return false;
  102527. while (numSamples > 0)
  102528. {
  102529. if (startSampleInFile >= reservoirStart
  102530. && startSampleInFile < reservoirStart + samplesInReservoir)
  102531. {
  102532. const int num = (int) jmin ((int64) numSamples,
  102533. reservoirStart + samplesInReservoir - startSampleInFile);
  102534. jassert (num > 0);
  102535. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  102536. if (destSamples[i] != 0)
  102537. memcpy (destSamples[i] + startOffsetInDestBuffer,
  102538. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  102539. sizeof (int) * num);
  102540. startOffsetInDestBuffer += num;
  102541. startSampleInFile += num;
  102542. numSamples -= num;
  102543. }
  102544. else
  102545. {
  102546. if (startSampleInFile >= (int) lengthInSamples)
  102547. {
  102548. samplesInReservoir = 0;
  102549. }
  102550. else if (startSampleInFile < reservoirStart
  102551. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  102552. {
  102553. // had some problems with flac crashing if the read pos is aligned more
  102554. // accurately than this. Probably fixed in newer versions of the library, though.
  102555. reservoirStart = (int) (startSampleInFile & ~511);
  102556. samplesInReservoir = 0;
  102557. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  102558. }
  102559. else
  102560. {
  102561. reservoirStart += samplesInReservoir;
  102562. samplesInReservoir = 0;
  102563. FLAC__stream_decoder_process_single (decoder);
  102564. }
  102565. if (samplesInReservoir == 0)
  102566. break;
  102567. }
  102568. }
  102569. if (numSamples > 0)
  102570. {
  102571. for (int i = numDestChannels; --i >= 0;)
  102572. if (destSamples[i] != 0)
  102573. zeromem (destSamples[i] + startOffsetInDestBuffer,
  102574. sizeof (int) * numSamples);
  102575. }
  102576. return true;
  102577. }
  102578. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  102579. {
  102580. if (scanningForLength)
  102581. {
  102582. lengthInSamples += numSamples;
  102583. }
  102584. else
  102585. {
  102586. if (numSamples > reservoir.getNumSamples())
  102587. reservoir.setSize (numChannels, numSamples, false, false, true);
  102588. const int bitsToShift = 32 - bitsPerSample;
  102589. for (int i = 0; i < (int) numChannels; ++i)
  102590. {
  102591. const FLAC__int32* src = buffer[i];
  102592. int n = i;
  102593. while (src == 0 && n > 0)
  102594. src = buffer [--n];
  102595. if (src != 0)
  102596. {
  102597. int* dest = (int*) reservoir.getSampleData(i);
  102598. for (int j = 0; j < numSamples; ++j)
  102599. dest[j] = src[j] << bitsToShift;
  102600. }
  102601. }
  102602. samplesInReservoir = numSamples;
  102603. }
  102604. }
  102605. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  102606. {
  102607. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  102608. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102609. }
  102610. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  102611. {
  102612. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  102613. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102614. }
  102615. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  102616. {
  102617. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  102618. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102619. }
  102620. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  102621. {
  102622. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  102623. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102624. }
  102625. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  102626. {
  102627. return ((const FlacReader*) client_data)->input->isExhausted();
  102628. }
  102629. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  102630. const FLAC__Frame* frame,
  102631. const FLAC__int32* const buffer[],
  102632. void* client_data)
  102633. {
  102634. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  102635. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102636. }
  102637. static void metadataCallback_ (const FLAC__StreamDecoder*,
  102638. const FLAC__StreamMetadata* metadata,
  102639. void* client_data)
  102640. {
  102641. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  102642. }
  102643. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  102644. {
  102645. }
  102646. juce_UseDebuggingNewOperator
  102647. };
  102648. class FlacWriter : public AudioFormatWriter
  102649. {
  102650. FLAC__StreamEncoder* encoder;
  102651. MemoryBlock temp;
  102652. public:
  102653. bool ok;
  102654. FlacWriter (OutputStream* const out,
  102655. const double sampleRate,
  102656. const int numChannels,
  102657. const int bitsPerSample_)
  102658. : AudioFormatWriter (out, flacFormatName,
  102659. sampleRate,
  102660. numChannels,
  102661. bitsPerSample_)
  102662. {
  102663. using namespace FlacNamespace;
  102664. encoder = FLAC__stream_encoder_new();
  102665. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  102666. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  102667. FLAC__stream_encoder_set_channels (encoder, numChannels);
  102668. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  102669. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  102670. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  102671. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  102672. ok = FLAC__stream_encoder_init_stream (encoder,
  102673. encodeWriteCallback, encodeSeekCallback,
  102674. encodeTellCallback, encodeMetadataCallback,
  102675. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102676. }
  102677. ~FlacWriter()
  102678. {
  102679. if (ok)
  102680. {
  102681. FLAC__stream_encoder_finish (encoder);
  102682. output->flush();
  102683. }
  102684. else
  102685. {
  102686. output = 0; // to stop the base class deleting this, as it needs to be returned
  102687. // to the caller of createWriter()
  102688. }
  102689. FLAC__stream_encoder_delete (encoder);
  102690. }
  102691. bool write (const int** samplesToWrite, int numSamples)
  102692. {
  102693. if (! ok)
  102694. return false;
  102695. int* buf[3];
  102696. const int bitsToShift = 32 - bitsPerSample;
  102697. if (bitsToShift > 0)
  102698. {
  102699. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  102700. temp.setSize (sizeof (int) * numSamples * numChannels);
  102701. buf[0] = (int*) temp.getData();
  102702. buf[1] = buf[0] + numSamples;
  102703. buf[2] = 0;
  102704. for (int i = numChannels; --i >= 0;)
  102705. {
  102706. if (samplesToWrite[i] != 0)
  102707. {
  102708. for (int j = 0; j < numSamples; ++j)
  102709. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  102710. }
  102711. }
  102712. samplesToWrite = (const int**) buf;
  102713. }
  102714. return FLAC__stream_encoder_process (encoder,
  102715. (const FLAC__int32**) samplesToWrite,
  102716. numSamples) != 0;
  102717. }
  102718. bool writeData (const void* const data, const int size) const
  102719. {
  102720. return output->write (data, size);
  102721. }
  102722. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  102723. {
  102724. b += bytes;
  102725. for (int i = 0; i < bytes; ++i)
  102726. {
  102727. *(--b) = (FLAC__byte) (val & 0xff);
  102728. val >>= 8;
  102729. }
  102730. }
  102731. void writeMetaData (const FLAC__StreamMetadata* metadata)
  102732. {
  102733. using namespace FlacNamespace;
  102734. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  102735. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  102736. const unsigned int channelsMinus1 = info.channels - 1;
  102737. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  102738. packUint32 (info.min_blocksize, buffer, 2);
  102739. packUint32 (info.max_blocksize, buffer + 2, 2);
  102740. packUint32 (info.min_framesize, buffer + 4, 3);
  102741. packUint32 (info.max_framesize, buffer + 7, 3);
  102742. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  102743. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  102744. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  102745. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  102746. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  102747. memcpy (buffer + 18, info.md5sum, 16);
  102748. const bool ok = output->setPosition (4);
  102749. (void) ok;
  102750. // if this fails, you've given it an output stream that can't seek! It needs
  102751. // to be able to seek back to write the header
  102752. jassert (ok);
  102753. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102754. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102755. }
  102756. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  102757. const FLAC__byte buffer[],
  102758. size_t bytes,
  102759. unsigned int /*samples*/,
  102760. unsigned int /*current_frame*/,
  102761. void* client_data)
  102762. {
  102763. using namespace FlacNamespace;
  102764. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  102765. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  102766. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102767. }
  102768. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  102769. {
  102770. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  102771. }
  102772. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  102773. {
  102774. if (client_data == 0)
  102775. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  102776. *absolute_byte_offset = (FLAC__uint64) ((FlacWriter*) client_data)->output->getPosition();
  102777. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  102778. }
  102779. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  102780. const FLAC__StreamMetadata* metadata,
  102781. void* client_data)
  102782. {
  102783. ((FlacWriter*) client_data)->writeMetaData (metadata);
  102784. }
  102785. juce_UseDebuggingNewOperator
  102786. };
  102787. FlacAudioFormat::FlacAudioFormat()
  102788. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  102789. {
  102790. }
  102791. FlacAudioFormat::~FlacAudioFormat()
  102792. {
  102793. }
  102794. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  102795. {
  102796. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  102797. return Array <int> (rates);
  102798. }
  102799. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  102800. {
  102801. const int depths[] = { 16, 24, 0 };
  102802. return Array <int> (depths);
  102803. }
  102804. bool FlacAudioFormat::canDoStereo()
  102805. {
  102806. return true;
  102807. }
  102808. bool FlacAudioFormat::canDoMono()
  102809. {
  102810. return true;
  102811. }
  102812. bool FlacAudioFormat::isCompressed()
  102813. {
  102814. return true;
  102815. }
  102816. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  102817. const bool deleteStreamIfOpeningFails)
  102818. {
  102819. FlacReader* r = new FlacReader (in);
  102820. if (r->sampleRate == 0)
  102821. {
  102822. if (! deleteStreamIfOpeningFails)
  102823. r->input = 0;
  102824. deleteAndZero (r);
  102825. }
  102826. return r;
  102827. }
  102828. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  102829. double sampleRate,
  102830. unsigned int numberOfChannels,
  102831. int bitsPerSample,
  102832. const StringPairArray& /*metadataValues*/,
  102833. int /*qualityOptionIndex*/)
  102834. {
  102835. if (getPossibleBitDepths().contains (bitsPerSample))
  102836. {
  102837. FlacWriter* w = new FlacWriter (out,
  102838. sampleRate,
  102839. numberOfChannels,
  102840. bitsPerSample);
  102841. if (! w->ok)
  102842. deleteAndZero (w);
  102843. return w;
  102844. }
  102845. return 0;
  102846. }
  102847. END_JUCE_NAMESPACE
  102848. #endif
  102849. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  102850. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  102851. #if JUCE_USE_OGGVORBIS
  102852. #if JUCE_MAC
  102853. #define __MACOSX__ 1
  102854. #endif
  102855. namespace OggVorbisNamespace
  102856. {
  102857. #if JUCE_INCLUDE_OGGVORBIS_CODE
  102858. /********* Start of inlined file: vorbisenc.h *********/
  102859. #ifndef _OV_ENC_H_
  102860. #define _OV_ENC_H_
  102861. #ifdef __cplusplus
  102862. extern "C"
  102863. {
  102864. #endif /* __cplusplus */
  102865. /********* Start of inlined file: codec.h *********/
  102866. #ifndef _vorbis_codec_h_
  102867. #define _vorbis_codec_h_
  102868. #ifdef __cplusplus
  102869. extern "C"
  102870. {
  102871. #endif /* __cplusplus */
  102872. /********* Start of inlined file: ogg.h *********/
  102873. #ifndef _OGG_H
  102874. #define _OGG_H
  102875. #ifdef __cplusplus
  102876. extern "C" {
  102877. #endif
  102878. /********* Start of inlined file: os_types.h *********/
  102879. #ifndef _OS_TYPES_H
  102880. #define _OS_TYPES_H
  102881. /* make it easy on the folks that want to compile the libs with a
  102882. different malloc than stdlib */
  102883. #define _ogg_malloc malloc
  102884. #define _ogg_calloc calloc
  102885. #define _ogg_realloc realloc
  102886. #define _ogg_free free
  102887. #if defined(_WIN32)
  102888. # if defined(__CYGWIN__)
  102889. # include <_G_config.h>
  102890. typedef _G_int64_t ogg_int64_t;
  102891. typedef _G_int32_t ogg_int32_t;
  102892. typedef _G_uint32_t ogg_uint32_t;
  102893. typedef _G_int16_t ogg_int16_t;
  102894. typedef _G_uint16_t ogg_uint16_t;
  102895. # elif defined(__MINGW32__)
  102896. typedef short ogg_int16_t;
  102897. typedef unsigned short ogg_uint16_t;
  102898. typedef int ogg_int32_t;
  102899. typedef unsigned int ogg_uint32_t;
  102900. typedef long long ogg_int64_t;
  102901. typedef unsigned long long ogg_uint64_t;
  102902. # elif defined(__MWERKS__)
  102903. typedef long long ogg_int64_t;
  102904. typedef int ogg_int32_t;
  102905. typedef unsigned int ogg_uint32_t;
  102906. typedef short ogg_int16_t;
  102907. typedef unsigned short ogg_uint16_t;
  102908. # else
  102909. /* MSVC/Borland */
  102910. typedef __int64 ogg_int64_t;
  102911. typedef __int32 ogg_int32_t;
  102912. typedef unsigned __int32 ogg_uint32_t;
  102913. typedef __int16 ogg_int16_t;
  102914. typedef unsigned __int16 ogg_uint16_t;
  102915. # endif
  102916. #elif defined(__MACOS__)
  102917. # include <sys/types.h>
  102918. typedef SInt16 ogg_int16_t;
  102919. typedef UInt16 ogg_uint16_t;
  102920. typedef SInt32 ogg_int32_t;
  102921. typedef UInt32 ogg_uint32_t;
  102922. typedef SInt64 ogg_int64_t;
  102923. #elif defined(__MACOSX__) /* MacOS X Framework build */
  102924. # include <sys/types.h>
  102925. typedef int16_t ogg_int16_t;
  102926. typedef u_int16_t ogg_uint16_t;
  102927. typedef int32_t ogg_int32_t;
  102928. typedef u_int32_t ogg_uint32_t;
  102929. typedef int64_t ogg_int64_t;
  102930. #elif defined(__BEOS__)
  102931. /* Be */
  102932. # include <inttypes.h>
  102933. typedef int16_t ogg_int16_t;
  102934. typedef u_int16_t ogg_uint16_t;
  102935. typedef int32_t ogg_int32_t;
  102936. typedef u_int32_t ogg_uint32_t;
  102937. typedef int64_t ogg_int64_t;
  102938. #elif defined (__EMX__)
  102939. /* OS/2 GCC */
  102940. typedef short ogg_int16_t;
  102941. typedef unsigned short ogg_uint16_t;
  102942. typedef int ogg_int32_t;
  102943. typedef unsigned int ogg_uint32_t;
  102944. typedef long long ogg_int64_t;
  102945. #elif defined (DJGPP)
  102946. /* DJGPP */
  102947. typedef short ogg_int16_t;
  102948. typedef int ogg_int32_t;
  102949. typedef unsigned int ogg_uint32_t;
  102950. typedef long long ogg_int64_t;
  102951. #elif defined(R5900)
  102952. /* PS2 EE */
  102953. typedef long ogg_int64_t;
  102954. typedef int ogg_int32_t;
  102955. typedef unsigned ogg_uint32_t;
  102956. typedef short ogg_int16_t;
  102957. #elif defined(__SYMBIAN32__)
  102958. /* Symbian GCC */
  102959. typedef signed short ogg_int16_t;
  102960. typedef unsigned short ogg_uint16_t;
  102961. typedef signed int ogg_int32_t;
  102962. typedef unsigned int ogg_uint32_t;
  102963. typedef long long int ogg_int64_t;
  102964. #else
  102965. # include <sys/types.h>
  102966. /********* Start of inlined file: config_types.h *********/
  102967. #ifndef __CONFIG_TYPES_H__
  102968. #define __CONFIG_TYPES_H__
  102969. typedef int16_t ogg_int16_t;
  102970. typedef unsigned short ogg_uint16_t;
  102971. typedef int32_t ogg_int32_t;
  102972. typedef unsigned int ogg_uint32_t;
  102973. typedef int64_t ogg_int64_t;
  102974. #endif
  102975. /********* End of inlined file: config_types.h *********/
  102976. #endif
  102977. #endif /* _OS_TYPES_H */
  102978. /********* End of inlined file: os_types.h *********/
  102979. typedef struct {
  102980. long endbyte;
  102981. int endbit;
  102982. unsigned char *buffer;
  102983. unsigned char *ptr;
  102984. long storage;
  102985. } oggpack_buffer;
  102986. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  102987. typedef struct {
  102988. unsigned char *header;
  102989. long header_len;
  102990. unsigned char *body;
  102991. long body_len;
  102992. } ogg_page;
  102993. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  102994. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  102995. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  102996. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  102997. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  102998. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  102999. }
  103000. /* ogg_stream_state contains the current encode/decode state of a logical
  103001. Ogg bitstream **********************************************************/
  103002. typedef struct {
  103003. unsigned char *body_data; /* bytes from packet bodies */
  103004. long body_storage; /* storage elements allocated */
  103005. long body_fill; /* elements stored; fill mark */
  103006. long body_returned; /* elements of fill returned */
  103007. int *lacing_vals; /* The values that will go to the segment table */
  103008. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  103009. this way, but it is simple coupled to the
  103010. lacing fifo */
  103011. long lacing_storage;
  103012. long lacing_fill;
  103013. long lacing_packet;
  103014. long lacing_returned;
  103015. unsigned char header[282]; /* working space for header encode */
  103016. int header_fill;
  103017. int e_o_s; /* set when we have buffered the last packet in the
  103018. logical bitstream */
  103019. int b_o_s; /* set after we've written the initial page
  103020. of a logical bitstream */
  103021. long serialno;
  103022. long pageno;
  103023. ogg_int64_t packetno; /* sequence number for decode; the framing
  103024. knows where there's a hole in the data,
  103025. but we need coupling so that the codec
  103026. (which is in a seperate abstraction
  103027. layer) also knows about the gap */
  103028. ogg_int64_t granulepos;
  103029. } ogg_stream_state;
  103030. /* ogg_packet is used to encapsulate the data and metadata belonging
  103031. to a single raw Ogg/Vorbis packet *************************************/
  103032. typedef struct {
  103033. unsigned char *packet;
  103034. long bytes;
  103035. long b_o_s;
  103036. long e_o_s;
  103037. ogg_int64_t granulepos;
  103038. ogg_int64_t packetno; /* sequence number for decode; the framing
  103039. knows where there's a hole in the data,
  103040. but we need coupling so that the codec
  103041. (which is in a seperate abstraction
  103042. layer) also knows about the gap */
  103043. } ogg_packet;
  103044. typedef struct {
  103045. unsigned char *data;
  103046. int storage;
  103047. int fill;
  103048. int returned;
  103049. int unsynced;
  103050. int headerbytes;
  103051. int bodybytes;
  103052. } ogg_sync_state;
  103053. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  103054. extern void oggpack_writeinit(oggpack_buffer *b);
  103055. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  103056. extern void oggpack_writealign(oggpack_buffer *b);
  103057. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  103058. extern void oggpack_reset(oggpack_buffer *b);
  103059. extern void oggpack_writeclear(oggpack_buffer *b);
  103060. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103061. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  103062. extern long oggpack_look(oggpack_buffer *b,int bits);
  103063. extern long oggpack_look1(oggpack_buffer *b);
  103064. extern void oggpack_adv(oggpack_buffer *b,int bits);
  103065. extern void oggpack_adv1(oggpack_buffer *b);
  103066. extern long oggpack_read(oggpack_buffer *b,int bits);
  103067. extern long oggpack_read1(oggpack_buffer *b);
  103068. extern long oggpack_bytes(oggpack_buffer *b);
  103069. extern long oggpack_bits(oggpack_buffer *b);
  103070. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  103071. extern void oggpackB_writeinit(oggpack_buffer *b);
  103072. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  103073. extern void oggpackB_writealign(oggpack_buffer *b);
  103074. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  103075. extern void oggpackB_reset(oggpack_buffer *b);
  103076. extern void oggpackB_writeclear(oggpack_buffer *b);
  103077. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103078. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  103079. extern long oggpackB_look(oggpack_buffer *b,int bits);
  103080. extern long oggpackB_look1(oggpack_buffer *b);
  103081. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  103082. extern void oggpackB_adv1(oggpack_buffer *b);
  103083. extern long oggpackB_read(oggpack_buffer *b,int bits);
  103084. extern long oggpackB_read1(oggpack_buffer *b);
  103085. extern long oggpackB_bytes(oggpack_buffer *b);
  103086. extern long oggpackB_bits(oggpack_buffer *b);
  103087. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  103088. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  103089. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  103090. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  103091. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  103092. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  103093. extern int ogg_sync_init(ogg_sync_state *oy);
  103094. extern int ogg_sync_clear(ogg_sync_state *oy);
  103095. extern int ogg_sync_reset(ogg_sync_state *oy);
  103096. extern int ogg_sync_destroy(ogg_sync_state *oy);
  103097. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  103098. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  103099. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  103100. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  103101. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  103102. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  103103. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  103104. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  103105. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  103106. extern int ogg_stream_clear(ogg_stream_state *os);
  103107. extern int ogg_stream_reset(ogg_stream_state *os);
  103108. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  103109. extern int ogg_stream_destroy(ogg_stream_state *os);
  103110. extern int ogg_stream_eos(ogg_stream_state *os);
  103111. extern void ogg_page_checksum_set(ogg_page *og);
  103112. extern int ogg_page_version(ogg_page *og);
  103113. extern int ogg_page_continued(ogg_page *og);
  103114. extern int ogg_page_bos(ogg_page *og);
  103115. extern int ogg_page_eos(ogg_page *og);
  103116. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  103117. extern int ogg_page_serialno(ogg_page *og);
  103118. extern long ogg_page_pageno(ogg_page *og);
  103119. extern int ogg_page_packets(ogg_page *og);
  103120. extern void ogg_packet_clear(ogg_packet *op);
  103121. #ifdef __cplusplus
  103122. }
  103123. #endif
  103124. #endif /* _OGG_H */
  103125. /********* End of inlined file: ogg.h *********/
  103126. typedef struct vorbis_info{
  103127. int version;
  103128. int channels;
  103129. long rate;
  103130. /* The below bitrate declarations are *hints*.
  103131. Combinations of the three values carry the following implications:
  103132. all three set to the same value:
  103133. implies a fixed rate bitstream
  103134. only nominal set:
  103135. implies a VBR stream that averages the nominal bitrate. No hard
  103136. upper/lower limit
  103137. upper and or lower set:
  103138. implies a VBR bitstream that obeys the bitrate limits. nominal
  103139. may also be set to give a nominal rate.
  103140. none set:
  103141. the coder does not care to speculate.
  103142. */
  103143. long bitrate_upper;
  103144. long bitrate_nominal;
  103145. long bitrate_lower;
  103146. long bitrate_window;
  103147. void *codec_setup;
  103148. } vorbis_info;
  103149. /* vorbis_dsp_state buffers the current vorbis audio
  103150. analysis/synthesis state. The DSP state belongs to a specific
  103151. logical bitstream ****************************************************/
  103152. typedef struct vorbis_dsp_state{
  103153. int analysisp;
  103154. vorbis_info *vi;
  103155. float **pcm;
  103156. float **pcmret;
  103157. int pcm_storage;
  103158. int pcm_current;
  103159. int pcm_returned;
  103160. int preextrapolate;
  103161. int eofflag;
  103162. long lW;
  103163. long W;
  103164. long nW;
  103165. long centerW;
  103166. ogg_int64_t granulepos;
  103167. ogg_int64_t sequence;
  103168. ogg_int64_t glue_bits;
  103169. ogg_int64_t time_bits;
  103170. ogg_int64_t floor_bits;
  103171. ogg_int64_t res_bits;
  103172. void *backend_state;
  103173. } vorbis_dsp_state;
  103174. typedef struct vorbis_block{
  103175. /* necessary stream state for linking to the framing abstraction */
  103176. float **pcm; /* this is a pointer into local storage */
  103177. oggpack_buffer opb;
  103178. long lW;
  103179. long W;
  103180. long nW;
  103181. int pcmend;
  103182. int mode;
  103183. int eofflag;
  103184. ogg_int64_t granulepos;
  103185. ogg_int64_t sequence;
  103186. vorbis_dsp_state *vd; /* For read-only access of configuration */
  103187. /* local storage to avoid remallocing; it's up to the mapping to
  103188. structure it */
  103189. void *localstore;
  103190. long localtop;
  103191. long localalloc;
  103192. long totaluse;
  103193. struct alloc_chain *reap;
  103194. /* bitmetrics for the frame */
  103195. long glue_bits;
  103196. long time_bits;
  103197. long floor_bits;
  103198. long res_bits;
  103199. void *internal;
  103200. } vorbis_block;
  103201. /* vorbis_block is a single block of data to be processed as part of
  103202. the analysis/synthesis stream; it belongs to a specific logical
  103203. bitstream, but is independant from other vorbis_blocks belonging to
  103204. that logical bitstream. *************************************************/
  103205. struct alloc_chain{
  103206. void *ptr;
  103207. struct alloc_chain *next;
  103208. };
  103209. /* vorbis_info contains all the setup information specific to the
  103210. specific compression/decompression mode in progress (eg,
  103211. psychoacoustic settings, channel setup, options, codebook
  103212. etc). vorbis_info and substructures are in backends.h.
  103213. *********************************************************************/
  103214. /* the comments are not part of vorbis_info so that vorbis_info can be
  103215. static storage */
  103216. typedef struct vorbis_comment{
  103217. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  103218. whatever vendor is set to in encode */
  103219. char **user_comments;
  103220. int *comment_lengths;
  103221. int comments;
  103222. char *vendor;
  103223. } vorbis_comment;
  103224. /* libvorbis encodes in two abstraction layers; first we perform DSP
  103225. and produce a packet (see docs/analysis.txt). The packet is then
  103226. coded into a framed OggSquish bitstream by the second layer (see
  103227. docs/framing.txt). Decode is the reverse process; we sync/frame
  103228. the bitstream and extract individual packets, then decode the
  103229. packet back into PCM audio.
  103230. The extra framing/packetizing is used in streaming formats, such as
  103231. files. Over the net (such as with UDP), the framing and
  103232. packetization aren't necessary as they're provided by the transport
  103233. and the streaming layer is not used */
  103234. /* Vorbis PRIMITIVES: general ***************************************/
  103235. extern void vorbis_info_init(vorbis_info *vi);
  103236. extern void vorbis_info_clear(vorbis_info *vi);
  103237. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  103238. extern void vorbis_comment_init(vorbis_comment *vc);
  103239. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  103240. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  103241. const char *tag, char *contents);
  103242. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  103243. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  103244. extern void vorbis_comment_clear(vorbis_comment *vc);
  103245. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  103246. extern int vorbis_block_clear(vorbis_block *vb);
  103247. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  103248. extern double vorbis_granule_time(vorbis_dsp_state *v,
  103249. ogg_int64_t granulepos);
  103250. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  103251. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103252. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  103253. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  103254. vorbis_comment *vc,
  103255. ogg_packet *op,
  103256. ogg_packet *op_comm,
  103257. ogg_packet *op_code);
  103258. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  103259. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  103260. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  103261. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  103262. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  103263. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  103264. ogg_packet *op);
  103265. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  103266. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  103267. ogg_packet *op);
  103268. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103269. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  103270. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  103271. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  103272. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  103273. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  103274. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  103275. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  103276. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  103277. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  103278. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  103279. /* Vorbis ERRORS and return codes ***********************************/
  103280. #define OV_FALSE -1
  103281. #define OV_EOF -2
  103282. #define OV_HOLE -3
  103283. #define OV_EREAD -128
  103284. #define OV_EFAULT -129
  103285. #define OV_EIMPL -130
  103286. #define OV_EINVAL -131
  103287. #define OV_ENOTVORBIS -132
  103288. #define OV_EBADHEADER -133
  103289. #define OV_EVERSION -134
  103290. #define OV_ENOTAUDIO -135
  103291. #define OV_EBADPACKET -136
  103292. #define OV_EBADLINK -137
  103293. #define OV_ENOSEEK -138
  103294. #ifdef __cplusplus
  103295. }
  103296. #endif /* __cplusplus */
  103297. #endif
  103298. /********* End of inlined file: codec.h *********/
  103299. extern int vorbis_encode_init(vorbis_info *vi,
  103300. long channels,
  103301. long rate,
  103302. long max_bitrate,
  103303. long nominal_bitrate,
  103304. long min_bitrate);
  103305. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  103306. long channels,
  103307. long rate,
  103308. long max_bitrate,
  103309. long nominal_bitrate,
  103310. long min_bitrate);
  103311. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  103312. long channels,
  103313. long rate,
  103314. float quality /* quality level from 0. (lo) to 1. (hi) */
  103315. );
  103316. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  103317. long channels,
  103318. long rate,
  103319. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  103320. );
  103321. extern int vorbis_encode_setup_init(vorbis_info *vi);
  103322. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  103323. /* deprecated rate management supported only for compatability */
  103324. #define OV_ECTL_RATEMANAGE_GET 0x10
  103325. #define OV_ECTL_RATEMANAGE_SET 0x11
  103326. #define OV_ECTL_RATEMANAGE_AVG 0x12
  103327. #define OV_ECTL_RATEMANAGE_HARD 0x13
  103328. struct ovectl_ratemanage_arg {
  103329. int management_active;
  103330. long bitrate_hard_min;
  103331. long bitrate_hard_max;
  103332. double bitrate_hard_window;
  103333. long bitrate_av_lo;
  103334. long bitrate_av_hi;
  103335. double bitrate_av_window;
  103336. double bitrate_av_window_center;
  103337. };
  103338. /* new rate setup */
  103339. #define OV_ECTL_RATEMANAGE2_GET 0x14
  103340. #define OV_ECTL_RATEMANAGE2_SET 0x15
  103341. struct ovectl_ratemanage2_arg {
  103342. int management_active;
  103343. long bitrate_limit_min_kbps;
  103344. long bitrate_limit_max_kbps;
  103345. long bitrate_limit_reservoir_bits;
  103346. double bitrate_limit_reservoir_bias;
  103347. long bitrate_average_kbps;
  103348. double bitrate_average_damping;
  103349. };
  103350. #define OV_ECTL_LOWPASS_GET 0x20
  103351. #define OV_ECTL_LOWPASS_SET 0x21
  103352. #define OV_ECTL_IBLOCK_GET 0x30
  103353. #define OV_ECTL_IBLOCK_SET 0x31
  103354. #ifdef __cplusplus
  103355. }
  103356. #endif /* __cplusplus */
  103357. #endif
  103358. /********* End of inlined file: vorbisenc.h *********/
  103359. /********* Start of inlined file: vorbisfile.h *********/
  103360. #ifndef _OV_FILE_H_
  103361. #define _OV_FILE_H_
  103362. #ifdef __cplusplus
  103363. extern "C"
  103364. {
  103365. #endif /* __cplusplus */
  103366. #include <stdio.h>
  103367. /* The function prototypes for the callbacks are basically the same as for
  103368. * the stdio functions fread, fseek, fclose, ftell.
  103369. * The one difference is that the FILE * arguments have been replaced with
  103370. * a void * - this is to be used as a pointer to whatever internal data these
  103371. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  103372. *
  103373. * If you use other functions, check the docs for these functions and return
  103374. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  103375. * unseekable
  103376. */
  103377. typedef struct {
  103378. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  103379. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  103380. int (*close_func) (void *datasource);
  103381. long (*tell_func) (void *datasource);
  103382. } ov_callbacks;
  103383. #define NOTOPEN 0
  103384. #define PARTOPEN 1
  103385. #define OPENED 2
  103386. #define STREAMSET 3
  103387. #define INITSET 4
  103388. typedef struct OggVorbis_File {
  103389. void *datasource; /* Pointer to a FILE *, etc. */
  103390. int seekable;
  103391. ogg_int64_t offset;
  103392. ogg_int64_t end;
  103393. ogg_sync_state oy;
  103394. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  103395. stream appears */
  103396. int links;
  103397. ogg_int64_t *offsets;
  103398. ogg_int64_t *dataoffsets;
  103399. long *serialnos;
  103400. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  103401. compatability; x2 size, stores both
  103402. beginning and end values */
  103403. vorbis_info *vi;
  103404. vorbis_comment *vc;
  103405. /* Decoding working state local storage */
  103406. ogg_int64_t pcm_offset;
  103407. int ready_state;
  103408. long current_serialno;
  103409. int current_link;
  103410. double bittrack;
  103411. double samptrack;
  103412. ogg_stream_state os; /* take physical pages, weld into a logical
  103413. stream of packets */
  103414. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  103415. vorbis_block vb; /* local working space for packet->PCM decode */
  103416. ov_callbacks callbacks;
  103417. } OggVorbis_File;
  103418. extern int ov_clear(OggVorbis_File *vf);
  103419. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103420. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  103421. char *initial, long ibytes, ov_callbacks callbacks);
  103422. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103423. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  103424. char *initial, long ibytes, ov_callbacks callbacks);
  103425. extern int ov_test_open(OggVorbis_File *vf);
  103426. extern long ov_bitrate(OggVorbis_File *vf,int i);
  103427. extern long ov_bitrate_instant(OggVorbis_File *vf);
  103428. extern long ov_streams(OggVorbis_File *vf);
  103429. extern long ov_seekable(OggVorbis_File *vf);
  103430. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  103431. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  103432. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  103433. extern double ov_time_total(OggVorbis_File *vf,int i);
  103434. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103435. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103436. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  103437. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  103438. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  103439. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103440. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103441. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103442. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  103443. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  103444. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  103445. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  103446. extern double ov_time_tell(OggVorbis_File *vf);
  103447. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  103448. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  103449. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  103450. int *bitstream);
  103451. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  103452. int bigendianp,int word,int sgned,int *bitstream);
  103453. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  103454. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  103455. extern int ov_halfrate_p(OggVorbis_File *vf);
  103456. #ifdef __cplusplus
  103457. }
  103458. #endif /* __cplusplus */
  103459. #endif
  103460. /********* End of inlined file: vorbisfile.h *********/
  103461. /********* Start of inlined file: bitwise.c *********/
  103462. /* We're 'LSb' endian; if we write a word but read individual bits,
  103463. then we'll read the lsb first */
  103464. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103465. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103466. // tasks..
  103467. #if JUCE_MSVC
  103468. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103469. #endif
  103470. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103471. #if JUCE_USE_OGGVORBIS
  103472. #include <string.h>
  103473. #include <stdlib.h>
  103474. #define BUFFER_INCREMENT 256
  103475. static const unsigned long mask[]=
  103476. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  103477. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  103478. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  103479. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  103480. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  103481. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  103482. 0x3fffffff,0x7fffffff,0xffffffff };
  103483. static const unsigned int mask8B[]=
  103484. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  103485. void oggpack_writeinit(oggpack_buffer *b){
  103486. memset(b,0,sizeof(*b));
  103487. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  103488. b->buffer[0]='\0';
  103489. b->storage=BUFFER_INCREMENT;
  103490. }
  103491. void oggpackB_writeinit(oggpack_buffer *b){
  103492. oggpack_writeinit(b);
  103493. }
  103494. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  103495. long bytes=bits>>3;
  103496. bits-=bytes*8;
  103497. b->ptr=b->buffer+bytes;
  103498. b->endbit=bits;
  103499. b->endbyte=bytes;
  103500. *b->ptr&=mask[bits];
  103501. }
  103502. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  103503. long bytes=bits>>3;
  103504. bits-=bytes*8;
  103505. b->ptr=b->buffer+bytes;
  103506. b->endbit=bits;
  103507. b->endbyte=bytes;
  103508. *b->ptr&=mask8B[bits];
  103509. }
  103510. /* Takes only up to 32 bits. */
  103511. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  103512. if(b->endbyte+4>=b->storage){
  103513. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103514. b->storage+=BUFFER_INCREMENT;
  103515. b->ptr=b->buffer+b->endbyte;
  103516. }
  103517. value&=mask[bits];
  103518. bits+=b->endbit;
  103519. b->ptr[0]|=value<<b->endbit;
  103520. if(bits>=8){
  103521. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  103522. if(bits>=16){
  103523. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  103524. if(bits>=24){
  103525. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  103526. if(bits>=32){
  103527. if(b->endbit)
  103528. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  103529. else
  103530. b->ptr[4]=0;
  103531. }
  103532. }
  103533. }
  103534. }
  103535. b->endbyte+=bits/8;
  103536. b->ptr+=bits/8;
  103537. b->endbit=bits&7;
  103538. }
  103539. /* Takes only up to 32 bits. */
  103540. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  103541. if(b->endbyte+4>=b->storage){
  103542. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103543. b->storage+=BUFFER_INCREMENT;
  103544. b->ptr=b->buffer+b->endbyte;
  103545. }
  103546. value=(value&mask[bits])<<(32-bits);
  103547. bits+=b->endbit;
  103548. b->ptr[0]|=value>>(24+b->endbit);
  103549. if(bits>=8){
  103550. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  103551. if(bits>=16){
  103552. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  103553. if(bits>=24){
  103554. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  103555. if(bits>=32){
  103556. if(b->endbit)
  103557. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  103558. else
  103559. b->ptr[4]=0;
  103560. }
  103561. }
  103562. }
  103563. }
  103564. b->endbyte+=bits/8;
  103565. b->ptr+=bits/8;
  103566. b->endbit=bits&7;
  103567. }
  103568. void oggpack_writealign(oggpack_buffer *b){
  103569. int bits=8-b->endbit;
  103570. if(bits<8)
  103571. oggpack_write(b,0,bits);
  103572. }
  103573. void oggpackB_writealign(oggpack_buffer *b){
  103574. int bits=8-b->endbit;
  103575. if(bits<8)
  103576. oggpackB_write(b,0,bits);
  103577. }
  103578. static void oggpack_writecopy_helper(oggpack_buffer *b,
  103579. void *source,
  103580. long bits,
  103581. void (*w)(oggpack_buffer *,
  103582. unsigned long,
  103583. int),
  103584. int msb){
  103585. unsigned char *ptr=(unsigned char *)source;
  103586. long bytes=bits/8;
  103587. bits-=bytes*8;
  103588. if(b->endbit){
  103589. int i;
  103590. /* unaligned copy. Do it the hard way. */
  103591. for(i=0;i<bytes;i++)
  103592. w(b,(unsigned long)(ptr[i]),8);
  103593. }else{
  103594. /* aligned block copy */
  103595. if(b->endbyte+bytes+1>=b->storage){
  103596. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  103597. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  103598. b->ptr=b->buffer+b->endbyte;
  103599. }
  103600. memmove(b->ptr,source,bytes);
  103601. b->ptr+=bytes;
  103602. b->endbyte+=bytes;
  103603. *b->ptr=0;
  103604. }
  103605. if(bits){
  103606. if(msb)
  103607. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  103608. else
  103609. w(b,(unsigned long)(ptr[bytes]),bits);
  103610. }
  103611. }
  103612. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  103613. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  103614. }
  103615. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  103616. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  103617. }
  103618. void oggpack_reset(oggpack_buffer *b){
  103619. b->ptr=b->buffer;
  103620. b->buffer[0]=0;
  103621. b->endbit=b->endbyte=0;
  103622. }
  103623. void oggpackB_reset(oggpack_buffer *b){
  103624. oggpack_reset(b);
  103625. }
  103626. void oggpack_writeclear(oggpack_buffer *b){
  103627. _ogg_free(b->buffer);
  103628. memset(b,0,sizeof(*b));
  103629. }
  103630. void oggpackB_writeclear(oggpack_buffer *b){
  103631. oggpack_writeclear(b);
  103632. }
  103633. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103634. memset(b,0,sizeof(*b));
  103635. b->buffer=b->ptr=buf;
  103636. b->storage=bytes;
  103637. }
  103638. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103639. oggpack_readinit(b,buf,bytes);
  103640. }
  103641. /* Read in bits without advancing the bitptr; bits <= 32 */
  103642. long oggpack_look(oggpack_buffer *b,int bits){
  103643. unsigned long ret;
  103644. unsigned long m=mask[bits];
  103645. bits+=b->endbit;
  103646. if(b->endbyte+4>=b->storage){
  103647. /* not the main path */
  103648. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103649. }
  103650. ret=b->ptr[0]>>b->endbit;
  103651. if(bits>8){
  103652. ret|=b->ptr[1]<<(8-b->endbit);
  103653. if(bits>16){
  103654. ret|=b->ptr[2]<<(16-b->endbit);
  103655. if(bits>24){
  103656. ret|=b->ptr[3]<<(24-b->endbit);
  103657. if(bits>32 && b->endbit)
  103658. ret|=b->ptr[4]<<(32-b->endbit);
  103659. }
  103660. }
  103661. }
  103662. return(m&ret);
  103663. }
  103664. /* Read in bits without advancing the bitptr; bits <= 32 */
  103665. long oggpackB_look(oggpack_buffer *b,int bits){
  103666. unsigned long ret;
  103667. int m=32-bits;
  103668. bits+=b->endbit;
  103669. if(b->endbyte+4>=b->storage){
  103670. /* not the main path */
  103671. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103672. }
  103673. ret=b->ptr[0]<<(24+b->endbit);
  103674. if(bits>8){
  103675. ret|=b->ptr[1]<<(16+b->endbit);
  103676. if(bits>16){
  103677. ret|=b->ptr[2]<<(8+b->endbit);
  103678. if(bits>24){
  103679. ret|=b->ptr[3]<<(b->endbit);
  103680. if(bits>32 && b->endbit)
  103681. ret|=b->ptr[4]>>(8-b->endbit);
  103682. }
  103683. }
  103684. }
  103685. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  103686. }
  103687. long oggpack_look1(oggpack_buffer *b){
  103688. if(b->endbyte>=b->storage)return(-1);
  103689. return((b->ptr[0]>>b->endbit)&1);
  103690. }
  103691. long oggpackB_look1(oggpack_buffer *b){
  103692. if(b->endbyte>=b->storage)return(-1);
  103693. return((b->ptr[0]>>(7-b->endbit))&1);
  103694. }
  103695. void oggpack_adv(oggpack_buffer *b,int bits){
  103696. bits+=b->endbit;
  103697. b->ptr+=bits/8;
  103698. b->endbyte+=bits/8;
  103699. b->endbit=bits&7;
  103700. }
  103701. void oggpackB_adv(oggpack_buffer *b,int bits){
  103702. oggpack_adv(b,bits);
  103703. }
  103704. void oggpack_adv1(oggpack_buffer *b){
  103705. if(++(b->endbit)>7){
  103706. b->endbit=0;
  103707. b->ptr++;
  103708. b->endbyte++;
  103709. }
  103710. }
  103711. void oggpackB_adv1(oggpack_buffer *b){
  103712. oggpack_adv1(b);
  103713. }
  103714. /* bits <= 32 */
  103715. long oggpack_read(oggpack_buffer *b,int bits){
  103716. long ret;
  103717. unsigned long m=mask[bits];
  103718. bits+=b->endbit;
  103719. if(b->endbyte+4>=b->storage){
  103720. /* not the main path */
  103721. ret=-1L;
  103722. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103723. }
  103724. ret=b->ptr[0]>>b->endbit;
  103725. if(bits>8){
  103726. ret|=b->ptr[1]<<(8-b->endbit);
  103727. if(bits>16){
  103728. ret|=b->ptr[2]<<(16-b->endbit);
  103729. if(bits>24){
  103730. ret|=b->ptr[3]<<(24-b->endbit);
  103731. if(bits>32 && b->endbit){
  103732. ret|=b->ptr[4]<<(32-b->endbit);
  103733. }
  103734. }
  103735. }
  103736. }
  103737. ret&=m;
  103738. overflow:
  103739. b->ptr+=bits/8;
  103740. b->endbyte+=bits/8;
  103741. b->endbit=bits&7;
  103742. return(ret);
  103743. }
  103744. /* bits <= 32 */
  103745. long oggpackB_read(oggpack_buffer *b,int bits){
  103746. long ret;
  103747. long m=32-bits;
  103748. bits+=b->endbit;
  103749. if(b->endbyte+4>=b->storage){
  103750. /* not the main path */
  103751. ret=-1L;
  103752. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103753. }
  103754. ret=b->ptr[0]<<(24+b->endbit);
  103755. if(bits>8){
  103756. ret|=b->ptr[1]<<(16+b->endbit);
  103757. if(bits>16){
  103758. ret|=b->ptr[2]<<(8+b->endbit);
  103759. if(bits>24){
  103760. ret|=b->ptr[3]<<(b->endbit);
  103761. if(bits>32 && b->endbit)
  103762. ret|=b->ptr[4]>>(8-b->endbit);
  103763. }
  103764. }
  103765. }
  103766. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  103767. overflow:
  103768. b->ptr+=bits/8;
  103769. b->endbyte+=bits/8;
  103770. b->endbit=bits&7;
  103771. return(ret);
  103772. }
  103773. long oggpack_read1(oggpack_buffer *b){
  103774. long ret;
  103775. if(b->endbyte>=b->storage){
  103776. /* not the main path */
  103777. ret=-1L;
  103778. goto overflow;
  103779. }
  103780. ret=(b->ptr[0]>>b->endbit)&1;
  103781. overflow:
  103782. b->endbit++;
  103783. if(b->endbit>7){
  103784. b->endbit=0;
  103785. b->ptr++;
  103786. b->endbyte++;
  103787. }
  103788. return(ret);
  103789. }
  103790. long oggpackB_read1(oggpack_buffer *b){
  103791. long ret;
  103792. if(b->endbyte>=b->storage){
  103793. /* not the main path */
  103794. ret=-1L;
  103795. goto overflow;
  103796. }
  103797. ret=(b->ptr[0]>>(7-b->endbit))&1;
  103798. overflow:
  103799. b->endbit++;
  103800. if(b->endbit>7){
  103801. b->endbit=0;
  103802. b->ptr++;
  103803. b->endbyte++;
  103804. }
  103805. return(ret);
  103806. }
  103807. long oggpack_bytes(oggpack_buffer *b){
  103808. return(b->endbyte+(b->endbit+7)/8);
  103809. }
  103810. long oggpack_bits(oggpack_buffer *b){
  103811. return(b->endbyte*8+b->endbit);
  103812. }
  103813. long oggpackB_bytes(oggpack_buffer *b){
  103814. return oggpack_bytes(b);
  103815. }
  103816. long oggpackB_bits(oggpack_buffer *b){
  103817. return oggpack_bits(b);
  103818. }
  103819. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  103820. return(b->buffer);
  103821. }
  103822. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  103823. return oggpack_get_buffer(b);
  103824. }
  103825. /* Self test of the bitwise routines; everything else is based on
  103826. them, so they damned well better be solid. */
  103827. #ifdef _V_SELFTEST
  103828. #include <stdio.h>
  103829. static int ilog(unsigned int v){
  103830. int ret=0;
  103831. while(v){
  103832. ret++;
  103833. v>>=1;
  103834. }
  103835. return(ret);
  103836. }
  103837. oggpack_buffer o;
  103838. oggpack_buffer r;
  103839. void report(char *in){
  103840. fprintf(stderr,"%s",in);
  103841. exit(1);
  103842. }
  103843. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103844. long bytes,i;
  103845. unsigned char *buffer;
  103846. oggpack_reset(&o);
  103847. for(i=0;i<vals;i++)
  103848. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  103849. buffer=oggpack_get_buffer(&o);
  103850. bytes=oggpack_bytes(&o);
  103851. if(bytes!=compsize)report("wrong number of bytes!\n");
  103852. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103853. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103854. report("wrote incorrect value!\n");
  103855. }
  103856. oggpack_readinit(&r,buffer,bytes);
  103857. for(i=0;i<vals;i++){
  103858. int tbit=bits?bits:ilog(b[i]);
  103859. if(oggpack_look(&r,tbit)==-1)
  103860. report("out of data!\n");
  103861. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  103862. report("looked at incorrect value!\n");
  103863. if(tbit==1)
  103864. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  103865. report("looked at single bit incorrect value!\n");
  103866. if(tbit==1){
  103867. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  103868. report("read incorrect single bit value!\n");
  103869. }else{
  103870. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  103871. report("read incorrect value!\n");
  103872. }
  103873. }
  103874. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103875. }
  103876. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103877. long bytes,i;
  103878. unsigned char *buffer;
  103879. oggpackB_reset(&o);
  103880. for(i=0;i<vals;i++)
  103881. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  103882. buffer=oggpackB_get_buffer(&o);
  103883. bytes=oggpackB_bytes(&o);
  103884. if(bytes!=compsize)report("wrong number of bytes!\n");
  103885. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103886. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103887. report("wrote incorrect value!\n");
  103888. }
  103889. oggpackB_readinit(&r,buffer,bytes);
  103890. for(i=0;i<vals;i++){
  103891. int tbit=bits?bits:ilog(b[i]);
  103892. if(oggpackB_look(&r,tbit)==-1)
  103893. report("out of data!\n");
  103894. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  103895. report("looked at incorrect value!\n");
  103896. if(tbit==1)
  103897. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  103898. report("looked at single bit incorrect value!\n");
  103899. if(tbit==1){
  103900. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  103901. report("read incorrect single bit value!\n");
  103902. }else{
  103903. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  103904. report("read incorrect value!\n");
  103905. }
  103906. }
  103907. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103908. }
  103909. int main(void){
  103910. unsigned char *buffer;
  103911. long bytes,i;
  103912. static unsigned long testbuffer1[]=
  103913. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  103914. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  103915. int test1size=43;
  103916. static unsigned long testbuffer2[]=
  103917. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  103918. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  103919. 85525151,0,12321,1,349528352};
  103920. int test2size=21;
  103921. static unsigned long testbuffer3[]=
  103922. {1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
  103923. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  103924. int test3size=56;
  103925. static unsigned long large[]=
  103926. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  103927. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  103928. 85525151,0,12321,1,2146528352};
  103929. int onesize=33;
  103930. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  103931. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  103932. 223,4};
  103933. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  103934. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  103935. 245,251,128};
  103936. int twosize=6;
  103937. static int two[6]={61,255,255,251,231,29};
  103938. static int twoB[6]={247,63,255,253,249,120};
  103939. int threesize=54;
  103940. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  103941. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  103942. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  103943. 100,52,4,14,18,86,77,1};
  103944. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  103945. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  103946. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  103947. 200,20,254,4,58,106,176,144,0};
  103948. int foursize=38;
  103949. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  103950. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  103951. 28,2,133,0,1};
  103952. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  103953. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  103954. 129,10,4,32};
  103955. int fivesize=45;
  103956. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  103957. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  103958. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  103959. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  103960. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  103961. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  103962. int sixsize=7;
  103963. static int six[7]={17,177,170,242,169,19,148};
  103964. static int sixB[7]={136,141,85,79,149,200,41};
  103965. /* Test read/write together */
  103966. /* Later we test against pregenerated bitstreams */
  103967. oggpack_writeinit(&o);
  103968. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  103969. cliptest(testbuffer1,test1size,0,one,onesize);
  103970. fprintf(stderr,"ok.");
  103971. fprintf(stderr,"\nNull bit call (LSb): ");
  103972. cliptest(testbuffer3,test3size,0,two,twosize);
  103973. fprintf(stderr,"ok.");
  103974. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  103975. cliptest(testbuffer2,test2size,0,three,threesize);
  103976. fprintf(stderr,"ok.");
  103977. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  103978. oggpack_reset(&o);
  103979. for(i=0;i<test2size;i++)
  103980. oggpack_write(&o,large[i],32);
  103981. buffer=oggpack_get_buffer(&o);
  103982. bytes=oggpack_bytes(&o);
  103983. oggpack_readinit(&r,buffer,bytes);
  103984. for(i=0;i<test2size;i++){
  103985. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  103986. if(oggpack_look(&r,32)!=large[i]){
  103987. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  103988. oggpack_look(&r,32),large[i]);
  103989. report("read incorrect value!\n");
  103990. }
  103991. oggpack_adv(&r,32);
  103992. }
  103993. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103994. fprintf(stderr,"ok.");
  103995. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  103996. cliptest(testbuffer1,test1size,7,four,foursize);
  103997. fprintf(stderr,"ok.");
  103998. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  103999. cliptest(testbuffer2,test2size,17,five,fivesize);
  104000. fprintf(stderr,"ok.");
  104001. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  104002. cliptest(testbuffer3,test3size,1,six,sixsize);
  104003. fprintf(stderr,"ok.");
  104004. fprintf(stderr,"\nTesting read past end (LSb): ");
  104005. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104006. for(i=0;i<64;i++){
  104007. if(oggpack_read(&r,1)!=0){
  104008. fprintf(stderr,"failed; got -1 prematurely.\n");
  104009. exit(1);
  104010. }
  104011. }
  104012. if(oggpack_look(&r,1)!=-1 ||
  104013. oggpack_read(&r,1)!=-1){
  104014. fprintf(stderr,"failed; read past end without -1.\n");
  104015. exit(1);
  104016. }
  104017. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104018. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  104019. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104020. exit(1);
  104021. }
  104022. if(oggpack_look(&r,18)!=0 ||
  104023. oggpack_look(&r,18)!=0){
  104024. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104025. exit(1);
  104026. }
  104027. if(oggpack_look(&r,19)!=-1 ||
  104028. oggpack_look(&r,19)!=-1){
  104029. fprintf(stderr,"failed; read past end without -1.\n");
  104030. exit(1);
  104031. }
  104032. if(oggpack_look(&r,32)!=-1 ||
  104033. oggpack_look(&r,32)!=-1){
  104034. fprintf(stderr,"failed; read past end without -1.\n");
  104035. exit(1);
  104036. }
  104037. oggpack_writeclear(&o);
  104038. fprintf(stderr,"ok.\n");
  104039. /********** lazy, cut-n-paste retest with MSb packing ***********/
  104040. /* Test read/write together */
  104041. /* Later we test against pregenerated bitstreams */
  104042. oggpackB_writeinit(&o);
  104043. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  104044. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  104045. fprintf(stderr,"ok.");
  104046. fprintf(stderr,"\nNull bit call (MSb): ");
  104047. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  104048. fprintf(stderr,"ok.");
  104049. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  104050. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  104051. fprintf(stderr,"ok.");
  104052. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  104053. oggpackB_reset(&o);
  104054. for(i=0;i<test2size;i++)
  104055. oggpackB_write(&o,large[i],32);
  104056. buffer=oggpackB_get_buffer(&o);
  104057. bytes=oggpackB_bytes(&o);
  104058. oggpackB_readinit(&r,buffer,bytes);
  104059. for(i=0;i<test2size;i++){
  104060. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  104061. if(oggpackB_look(&r,32)!=large[i]){
  104062. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  104063. oggpackB_look(&r,32),large[i]);
  104064. report("read incorrect value!\n");
  104065. }
  104066. oggpackB_adv(&r,32);
  104067. }
  104068. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104069. fprintf(stderr,"ok.");
  104070. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  104071. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  104072. fprintf(stderr,"ok.");
  104073. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  104074. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  104075. fprintf(stderr,"ok.");
  104076. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  104077. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  104078. fprintf(stderr,"ok.");
  104079. fprintf(stderr,"\nTesting read past end (MSb): ");
  104080. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104081. for(i=0;i<64;i++){
  104082. if(oggpackB_read(&r,1)!=0){
  104083. fprintf(stderr,"failed; got -1 prematurely.\n");
  104084. exit(1);
  104085. }
  104086. }
  104087. if(oggpackB_look(&r,1)!=-1 ||
  104088. oggpackB_read(&r,1)!=-1){
  104089. fprintf(stderr,"failed; read past end without -1.\n");
  104090. exit(1);
  104091. }
  104092. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104093. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  104094. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104095. exit(1);
  104096. }
  104097. if(oggpackB_look(&r,18)!=0 ||
  104098. oggpackB_look(&r,18)!=0){
  104099. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104100. exit(1);
  104101. }
  104102. if(oggpackB_look(&r,19)!=-1 ||
  104103. oggpackB_look(&r,19)!=-1){
  104104. fprintf(stderr,"failed; read past end without -1.\n");
  104105. exit(1);
  104106. }
  104107. if(oggpackB_look(&r,32)!=-1 ||
  104108. oggpackB_look(&r,32)!=-1){
  104109. fprintf(stderr,"failed; read past end without -1.\n");
  104110. exit(1);
  104111. }
  104112. oggpackB_writeclear(&o);
  104113. fprintf(stderr,"ok.\n\n");
  104114. return(0);
  104115. }
  104116. #endif /* _V_SELFTEST */
  104117. #undef BUFFER_INCREMENT
  104118. #endif
  104119. /********* End of inlined file: bitwise.c *********/
  104120. /********* Start of inlined file: framing.c *********/
  104121. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104122. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104123. // tasks..
  104124. #if JUCE_MSVC
  104125. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104126. #endif
  104127. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104128. #if JUCE_USE_OGGVORBIS
  104129. #include <stdlib.h>
  104130. #include <string.h>
  104131. /* A complete description of Ogg framing exists in docs/framing.html */
  104132. int ogg_page_version(ogg_page *og){
  104133. return((int)(og->header[4]));
  104134. }
  104135. int ogg_page_continued(ogg_page *og){
  104136. return((int)(og->header[5]&0x01));
  104137. }
  104138. int ogg_page_bos(ogg_page *og){
  104139. return((int)(og->header[5]&0x02));
  104140. }
  104141. int ogg_page_eos(ogg_page *og){
  104142. return((int)(og->header[5]&0x04));
  104143. }
  104144. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  104145. unsigned char *page=og->header;
  104146. ogg_int64_t granulepos=page[13]&(0xff);
  104147. granulepos= (granulepos<<8)|(page[12]&0xff);
  104148. granulepos= (granulepos<<8)|(page[11]&0xff);
  104149. granulepos= (granulepos<<8)|(page[10]&0xff);
  104150. granulepos= (granulepos<<8)|(page[9]&0xff);
  104151. granulepos= (granulepos<<8)|(page[8]&0xff);
  104152. granulepos= (granulepos<<8)|(page[7]&0xff);
  104153. granulepos= (granulepos<<8)|(page[6]&0xff);
  104154. return(granulepos);
  104155. }
  104156. int ogg_page_serialno(ogg_page *og){
  104157. return(og->header[14] |
  104158. (og->header[15]<<8) |
  104159. (og->header[16]<<16) |
  104160. (og->header[17]<<24));
  104161. }
  104162. long ogg_page_pageno(ogg_page *og){
  104163. return(og->header[18] |
  104164. (og->header[19]<<8) |
  104165. (og->header[20]<<16) |
  104166. (og->header[21]<<24));
  104167. }
  104168. /* returns the number of packets that are completed on this page (if
  104169. the leading packet is begun on a previous page, but ends on this
  104170. page, it's counted */
  104171. /* NOTE:
  104172. If a page consists of a packet begun on a previous page, and a new
  104173. packet begun (but not completed) on this page, the return will be:
  104174. ogg_page_packets(page) ==1,
  104175. ogg_page_continued(page) !=0
  104176. If a page happens to be a single packet that was begun on a
  104177. previous page, and spans to the next page (in the case of a three or
  104178. more page packet), the return will be:
  104179. ogg_page_packets(page) ==0,
  104180. ogg_page_continued(page) !=0
  104181. */
  104182. int ogg_page_packets(ogg_page *og){
  104183. int i,n=og->header[26],count=0;
  104184. for(i=0;i<n;i++)
  104185. if(og->header[27+i]<255)count++;
  104186. return(count);
  104187. }
  104188. #if 0
  104189. /* helper to initialize lookup for direct-table CRC (illustrative; we
  104190. use the static init below) */
  104191. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  104192. int i;
  104193. unsigned long r;
  104194. r = index << 24;
  104195. for (i=0; i<8; i++)
  104196. if (r & 0x80000000UL)
  104197. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  104198. polynomial, although we use an
  104199. unreflected alg and an init/final
  104200. of 0, not 0xffffffff */
  104201. else
  104202. r<<=1;
  104203. return (r & 0xffffffffUL);
  104204. }
  104205. #endif
  104206. static const ogg_uint32_t crc_lookup[256]={
  104207. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  104208. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  104209. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  104210. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  104211. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  104212. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  104213. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  104214. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  104215. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  104216. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  104217. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  104218. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  104219. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  104220. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  104221. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  104222. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  104223. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  104224. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  104225. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  104226. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  104227. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  104228. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  104229. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  104230. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  104231. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  104232. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  104233. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  104234. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  104235. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  104236. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  104237. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  104238. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  104239. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  104240. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  104241. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  104242. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  104243. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  104244. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  104245. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  104246. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  104247. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  104248. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  104249. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  104250. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  104251. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  104252. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  104253. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  104254. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  104255. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  104256. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  104257. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  104258. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  104259. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  104260. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  104261. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  104262. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  104263. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  104264. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  104265. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  104266. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  104267. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  104268. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  104269. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  104270. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  104271. /* init the encode/decode logical stream state */
  104272. int ogg_stream_init(ogg_stream_state *os,int serialno){
  104273. if(os){
  104274. memset(os,0,sizeof(*os));
  104275. os->body_storage=16*1024;
  104276. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  104277. os->lacing_storage=1024;
  104278. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  104279. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  104280. os->serialno=serialno;
  104281. return(0);
  104282. }
  104283. return(-1);
  104284. }
  104285. /* _clear does not free os, only the non-flat storage within */
  104286. int ogg_stream_clear(ogg_stream_state *os){
  104287. if(os){
  104288. if(os->body_data)_ogg_free(os->body_data);
  104289. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  104290. if(os->granule_vals)_ogg_free(os->granule_vals);
  104291. memset(os,0,sizeof(*os));
  104292. }
  104293. return(0);
  104294. }
  104295. int ogg_stream_destroy(ogg_stream_state *os){
  104296. if(os){
  104297. ogg_stream_clear(os);
  104298. _ogg_free(os);
  104299. }
  104300. return(0);
  104301. }
  104302. /* Helpers for ogg_stream_encode; this keeps the structure and
  104303. what's happening fairly clear */
  104304. static void _os_body_expand(ogg_stream_state *os,int needed){
  104305. if(os->body_storage<=os->body_fill+needed){
  104306. os->body_storage+=(needed+1024);
  104307. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  104308. }
  104309. }
  104310. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  104311. if(os->lacing_storage<=os->lacing_fill+needed){
  104312. os->lacing_storage+=(needed+32);
  104313. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  104314. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  104315. }
  104316. }
  104317. /* checksum the page */
  104318. /* Direct table CRC; note that this will be faster in the future if we
  104319. perform the checksum silmultaneously with other copies */
  104320. void ogg_page_checksum_set(ogg_page *og){
  104321. if(og){
  104322. ogg_uint32_t crc_reg=0;
  104323. int i;
  104324. /* safety; needed for API behavior, but not framing code */
  104325. og->header[22]=0;
  104326. og->header[23]=0;
  104327. og->header[24]=0;
  104328. og->header[25]=0;
  104329. for(i=0;i<og->header_len;i++)
  104330. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  104331. for(i=0;i<og->body_len;i++)
  104332. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  104333. og->header[22]=(unsigned char)(crc_reg&0xff);
  104334. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  104335. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  104336. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  104337. }
  104338. }
  104339. /* submit data to the internal buffer of the framing engine */
  104340. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  104341. int lacing_vals=op->bytes/255+1,i;
  104342. if(os->body_returned){
  104343. /* advance packet data according to the body_returned pointer. We
  104344. had to keep it around to return a pointer into the buffer last
  104345. call */
  104346. os->body_fill-=os->body_returned;
  104347. if(os->body_fill)
  104348. memmove(os->body_data,os->body_data+os->body_returned,
  104349. os->body_fill);
  104350. os->body_returned=0;
  104351. }
  104352. /* make sure we have the buffer storage */
  104353. _os_body_expand(os,op->bytes);
  104354. _os_lacing_expand(os,lacing_vals);
  104355. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  104356. the liability of overly clean abstraction for the time being. It
  104357. will actually be fairly easy to eliminate the extra copy in the
  104358. future */
  104359. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  104360. os->body_fill+=op->bytes;
  104361. /* Store lacing vals for this packet */
  104362. for(i=0;i<lacing_vals-1;i++){
  104363. os->lacing_vals[os->lacing_fill+i]=255;
  104364. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  104365. }
  104366. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  104367. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  104368. /* flag the first segment as the beginning of the packet */
  104369. os->lacing_vals[os->lacing_fill]|= 0x100;
  104370. os->lacing_fill+=lacing_vals;
  104371. /* for the sake of completeness */
  104372. os->packetno++;
  104373. if(op->e_o_s)os->e_o_s=1;
  104374. return(0);
  104375. }
  104376. /* This will flush remaining packets into a page (returning nonzero),
  104377. even if there is not enough data to trigger a flush normally
  104378. (undersized page). If there are no packets or partial packets to
  104379. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  104380. try to flush a normal sized page like ogg_stream_pageout; a call to
  104381. ogg_stream_flush does not guarantee that all packets have flushed.
  104382. Only a return value of 0 from ogg_stream_flush indicates all packet
  104383. data is flushed into pages.
  104384. since ogg_stream_flush will flush the last page in a stream even if
  104385. it's undersized, you almost certainly want to use ogg_stream_pageout
  104386. (and *not* ogg_stream_flush) unless you specifically need to flush
  104387. an page regardless of size in the middle of a stream. */
  104388. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  104389. int i;
  104390. int vals=0;
  104391. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  104392. int bytes=0;
  104393. long acc=0;
  104394. ogg_int64_t granule_pos=-1;
  104395. if(maxvals==0)return(0);
  104396. /* construct a page */
  104397. /* decide how many segments to include */
  104398. /* If this is the initial header case, the first page must only include
  104399. the initial header packet */
  104400. if(os->b_o_s==0){ /* 'initial header page' case */
  104401. granule_pos=0;
  104402. for(vals=0;vals<maxvals;vals++){
  104403. if((os->lacing_vals[vals]&0x0ff)<255){
  104404. vals++;
  104405. break;
  104406. }
  104407. }
  104408. }else{
  104409. for(vals=0;vals<maxvals;vals++){
  104410. if(acc>4096)break;
  104411. acc+=os->lacing_vals[vals]&0x0ff;
  104412. if((os->lacing_vals[vals]&0xff)<255)
  104413. granule_pos=os->granule_vals[vals];
  104414. }
  104415. }
  104416. /* construct the header in temp storage */
  104417. memcpy(os->header,"OggS",4);
  104418. /* stream structure version */
  104419. os->header[4]=0x00;
  104420. /* continued packet flag? */
  104421. os->header[5]=0x00;
  104422. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  104423. /* first page flag? */
  104424. if(os->b_o_s==0)os->header[5]|=0x02;
  104425. /* last page flag? */
  104426. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  104427. os->b_o_s=1;
  104428. /* 64 bits of PCM position */
  104429. for(i=6;i<14;i++){
  104430. os->header[i]=(unsigned char)(granule_pos&0xff);
  104431. granule_pos>>=8;
  104432. }
  104433. /* 32 bits of stream serial number */
  104434. {
  104435. long serialno=os->serialno;
  104436. for(i=14;i<18;i++){
  104437. os->header[i]=(unsigned char)(serialno&0xff);
  104438. serialno>>=8;
  104439. }
  104440. }
  104441. /* 32 bits of page counter (we have both counter and page header
  104442. because this val can roll over) */
  104443. if(os->pageno==-1)os->pageno=0; /* because someone called
  104444. stream_reset; this would be a
  104445. strange thing to do in an
  104446. encode stream, but it has
  104447. plausible uses */
  104448. {
  104449. long pageno=os->pageno++;
  104450. for(i=18;i<22;i++){
  104451. os->header[i]=(unsigned char)(pageno&0xff);
  104452. pageno>>=8;
  104453. }
  104454. }
  104455. /* zero for computation; filled in later */
  104456. os->header[22]=0;
  104457. os->header[23]=0;
  104458. os->header[24]=0;
  104459. os->header[25]=0;
  104460. /* segment table */
  104461. os->header[26]=(unsigned char)(vals&0xff);
  104462. for(i=0;i<vals;i++)
  104463. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  104464. /* set pointers in the ogg_page struct */
  104465. og->header=os->header;
  104466. og->header_len=os->header_fill=vals+27;
  104467. og->body=os->body_data+os->body_returned;
  104468. og->body_len=bytes;
  104469. /* advance the lacing data and set the body_returned pointer */
  104470. os->lacing_fill-=vals;
  104471. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  104472. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  104473. os->body_returned+=bytes;
  104474. /* calculate the checksum */
  104475. ogg_page_checksum_set(og);
  104476. /* done */
  104477. return(1);
  104478. }
  104479. /* This constructs pages from buffered packet segments. The pointers
  104480. returned are to static buffers; do not free. The returned buffers are
  104481. good only until the next call (using the same ogg_stream_state) */
  104482. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  104483. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  104484. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  104485. os->lacing_fill>=255 || /* 'segment table full' case */
  104486. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  104487. return(ogg_stream_flush(os,og));
  104488. }
  104489. /* not enough data to construct a page and not end of stream */
  104490. return(0);
  104491. }
  104492. int ogg_stream_eos(ogg_stream_state *os){
  104493. return os->e_o_s;
  104494. }
  104495. /* DECODING PRIMITIVES: packet streaming layer **********************/
  104496. /* This has two layers to place more of the multi-serialno and paging
  104497. control in the application's hands. First, we expose a data buffer
  104498. using ogg_sync_buffer(). The app either copies into the
  104499. buffer, or passes it directly to read(), etc. We then call
  104500. ogg_sync_wrote() to tell how many bytes we just added.
  104501. Pages are returned (pointers into the buffer in ogg_sync_state)
  104502. by ogg_sync_pageout(). The page is then submitted to
  104503. ogg_stream_pagein() along with the appropriate
  104504. ogg_stream_state* (ie, matching serialno). We then get raw
  104505. packets out calling ogg_stream_packetout() with a
  104506. ogg_stream_state. */
  104507. /* initialize the struct to a known state */
  104508. int ogg_sync_init(ogg_sync_state *oy){
  104509. if(oy){
  104510. memset(oy,0,sizeof(*oy));
  104511. }
  104512. return(0);
  104513. }
  104514. /* clear non-flat storage within */
  104515. int ogg_sync_clear(ogg_sync_state *oy){
  104516. if(oy){
  104517. if(oy->data)_ogg_free(oy->data);
  104518. ogg_sync_init(oy);
  104519. }
  104520. return(0);
  104521. }
  104522. int ogg_sync_destroy(ogg_sync_state *oy){
  104523. if(oy){
  104524. ogg_sync_clear(oy);
  104525. _ogg_free(oy);
  104526. }
  104527. return(0);
  104528. }
  104529. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  104530. /* first, clear out any space that has been previously returned */
  104531. if(oy->returned){
  104532. oy->fill-=oy->returned;
  104533. if(oy->fill>0)
  104534. memmove(oy->data,oy->data+oy->returned,oy->fill);
  104535. oy->returned=0;
  104536. }
  104537. if(size>oy->storage-oy->fill){
  104538. /* We need to extend the internal buffer */
  104539. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  104540. if(oy->data)
  104541. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  104542. else
  104543. oy->data=(unsigned char*) _ogg_malloc(newsize);
  104544. oy->storage=newsize;
  104545. }
  104546. /* expose a segment at least as large as requested at the fill mark */
  104547. return((char *)oy->data+oy->fill);
  104548. }
  104549. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  104550. if(oy->fill+bytes>oy->storage)return(-1);
  104551. oy->fill+=bytes;
  104552. return(0);
  104553. }
  104554. /* sync the stream. This is meant to be useful for finding page
  104555. boundaries.
  104556. return values for this:
  104557. -n) skipped n bytes
  104558. 0) page not ready; more data (no bytes skipped)
  104559. n) page synced at current location; page length n bytes
  104560. */
  104561. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  104562. unsigned char *page=oy->data+oy->returned;
  104563. unsigned char *next;
  104564. long bytes=oy->fill-oy->returned;
  104565. if(oy->headerbytes==0){
  104566. int headerbytes,i;
  104567. if(bytes<27)return(0); /* not enough for a header */
  104568. /* verify capture pattern */
  104569. if(memcmp(page,"OggS",4))goto sync_fail;
  104570. headerbytes=page[26]+27;
  104571. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  104572. /* count up body length in the segment table */
  104573. for(i=0;i<page[26];i++)
  104574. oy->bodybytes+=page[27+i];
  104575. oy->headerbytes=headerbytes;
  104576. }
  104577. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  104578. /* The whole test page is buffered. Verify the checksum */
  104579. {
  104580. /* Grab the checksum bytes, set the header field to zero */
  104581. char chksum[4];
  104582. ogg_page log;
  104583. memcpy(chksum,page+22,4);
  104584. memset(page+22,0,4);
  104585. /* set up a temp page struct and recompute the checksum */
  104586. log.header=page;
  104587. log.header_len=oy->headerbytes;
  104588. log.body=page+oy->headerbytes;
  104589. log.body_len=oy->bodybytes;
  104590. ogg_page_checksum_set(&log);
  104591. /* Compare */
  104592. if(memcmp(chksum,page+22,4)){
  104593. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  104594. at all) */
  104595. /* replace the computed checksum with the one actually read in */
  104596. memcpy(page+22,chksum,4);
  104597. /* Bad checksum. Lose sync */
  104598. goto sync_fail;
  104599. }
  104600. }
  104601. /* yes, have a whole page all ready to go */
  104602. {
  104603. unsigned char *page=oy->data+oy->returned;
  104604. long bytes;
  104605. if(og){
  104606. og->header=page;
  104607. og->header_len=oy->headerbytes;
  104608. og->body=page+oy->headerbytes;
  104609. og->body_len=oy->bodybytes;
  104610. }
  104611. oy->unsynced=0;
  104612. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  104613. oy->headerbytes=0;
  104614. oy->bodybytes=0;
  104615. return(bytes);
  104616. }
  104617. sync_fail:
  104618. oy->headerbytes=0;
  104619. oy->bodybytes=0;
  104620. /* search for possible capture */
  104621. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  104622. if(!next)
  104623. next=oy->data+oy->fill;
  104624. oy->returned=next-oy->data;
  104625. return(-(next-page));
  104626. }
  104627. /* sync the stream and get a page. Keep trying until we find a page.
  104628. Supress 'sync errors' after reporting the first.
  104629. return values:
  104630. -1) recapture (hole in data)
  104631. 0) need more data
  104632. 1) page returned
  104633. Returns pointers into buffered data; invalidated by next call to
  104634. _stream, _clear, _init, or _buffer */
  104635. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  104636. /* all we need to do is verify a page at the head of the stream
  104637. buffer. If it doesn't verify, we look for the next potential
  104638. frame */
  104639. for(;;){
  104640. long ret=ogg_sync_pageseek(oy,og);
  104641. if(ret>0){
  104642. /* have a page */
  104643. return(1);
  104644. }
  104645. if(ret==0){
  104646. /* need more data */
  104647. return(0);
  104648. }
  104649. /* head did not start a synced page... skipped some bytes */
  104650. if(!oy->unsynced){
  104651. oy->unsynced=1;
  104652. return(-1);
  104653. }
  104654. /* loop. keep looking */
  104655. }
  104656. }
  104657. /* add the incoming page to the stream state; we decompose the page
  104658. into packet segments here as well. */
  104659. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  104660. unsigned char *header=og->header;
  104661. unsigned char *body=og->body;
  104662. long bodysize=og->body_len;
  104663. int segptr=0;
  104664. int version=ogg_page_version(og);
  104665. int continued=ogg_page_continued(og);
  104666. int bos=ogg_page_bos(og);
  104667. int eos=ogg_page_eos(og);
  104668. ogg_int64_t granulepos=ogg_page_granulepos(og);
  104669. int serialno=ogg_page_serialno(og);
  104670. long pageno=ogg_page_pageno(og);
  104671. int segments=header[26];
  104672. /* clean up 'returned data' */
  104673. {
  104674. long lr=os->lacing_returned;
  104675. long br=os->body_returned;
  104676. /* body data */
  104677. if(br){
  104678. os->body_fill-=br;
  104679. if(os->body_fill)
  104680. memmove(os->body_data,os->body_data+br,os->body_fill);
  104681. os->body_returned=0;
  104682. }
  104683. if(lr){
  104684. /* segment table */
  104685. if(os->lacing_fill-lr){
  104686. memmove(os->lacing_vals,os->lacing_vals+lr,
  104687. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  104688. memmove(os->granule_vals,os->granule_vals+lr,
  104689. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  104690. }
  104691. os->lacing_fill-=lr;
  104692. os->lacing_packet-=lr;
  104693. os->lacing_returned=0;
  104694. }
  104695. }
  104696. /* check the serial number */
  104697. if(serialno!=os->serialno)return(-1);
  104698. if(version>0)return(-1);
  104699. _os_lacing_expand(os,segments+1);
  104700. /* are we in sequence? */
  104701. if(pageno!=os->pageno){
  104702. int i;
  104703. /* unroll previous partial packet (if any) */
  104704. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  104705. os->body_fill-=os->lacing_vals[i]&0xff;
  104706. os->lacing_fill=os->lacing_packet;
  104707. /* make a note of dropped data in segment table */
  104708. if(os->pageno!=-1){
  104709. os->lacing_vals[os->lacing_fill++]=0x400;
  104710. os->lacing_packet++;
  104711. }
  104712. }
  104713. /* are we a 'continued packet' page? If so, we may need to skip
  104714. some segments */
  104715. if(continued){
  104716. if(os->lacing_fill<1 ||
  104717. os->lacing_vals[os->lacing_fill-1]==0x400){
  104718. bos=0;
  104719. for(;segptr<segments;segptr++){
  104720. int val=header[27+segptr];
  104721. body+=val;
  104722. bodysize-=val;
  104723. if(val<255){
  104724. segptr++;
  104725. break;
  104726. }
  104727. }
  104728. }
  104729. }
  104730. if(bodysize){
  104731. _os_body_expand(os,bodysize);
  104732. memcpy(os->body_data+os->body_fill,body,bodysize);
  104733. os->body_fill+=bodysize;
  104734. }
  104735. {
  104736. int saved=-1;
  104737. while(segptr<segments){
  104738. int val=header[27+segptr];
  104739. os->lacing_vals[os->lacing_fill]=val;
  104740. os->granule_vals[os->lacing_fill]=-1;
  104741. if(bos){
  104742. os->lacing_vals[os->lacing_fill]|=0x100;
  104743. bos=0;
  104744. }
  104745. if(val<255)saved=os->lacing_fill;
  104746. os->lacing_fill++;
  104747. segptr++;
  104748. if(val<255)os->lacing_packet=os->lacing_fill;
  104749. }
  104750. /* set the granulepos on the last granuleval of the last full packet */
  104751. if(saved!=-1){
  104752. os->granule_vals[saved]=granulepos;
  104753. }
  104754. }
  104755. if(eos){
  104756. os->e_o_s=1;
  104757. if(os->lacing_fill>0)
  104758. os->lacing_vals[os->lacing_fill-1]|=0x200;
  104759. }
  104760. os->pageno=pageno+1;
  104761. return(0);
  104762. }
  104763. /* clear things to an initial state. Good to call, eg, before seeking */
  104764. int ogg_sync_reset(ogg_sync_state *oy){
  104765. oy->fill=0;
  104766. oy->returned=0;
  104767. oy->unsynced=0;
  104768. oy->headerbytes=0;
  104769. oy->bodybytes=0;
  104770. return(0);
  104771. }
  104772. int ogg_stream_reset(ogg_stream_state *os){
  104773. os->body_fill=0;
  104774. os->body_returned=0;
  104775. os->lacing_fill=0;
  104776. os->lacing_packet=0;
  104777. os->lacing_returned=0;
  104778. os->header_fill=0;
  104779. os->e_o_s=0;
  104780. os->b_o_s=0;
  104781. os->pageno=-1;
  104782. os->packetno=0;
  104783. os->granulepos=0;
  104784. return(0);
  104785. }
  104786. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  104787. ogg_stream_reset(os);
  104788. os->serialno=serialno;
  104789. return(0);
  104790. }
  104791. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  104792. /* The last part of decode. We have the stream broken into packet
  104793. segments. Now we need to group them into packets (or return the
  104794. out of sync markers) */
  104795. int ptr=os->lacing_returned;
  104796. if(os->lacing_packet<=ptr)return(0);
  104797. if(os->lacing_vals[ptr]&0x400){
  104798. /* we need to tell the codec there's a gap; it might need to
  104799. handle previous packet dependencies. */
  104800. os->lacing_returned++;
  104801. os->packetno++;
  104802. return(-1);
  104803. }
  104804. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  104805. to ask if there's a whole packet
  104806. waiting */
  104807. /* Gather the whole packet. We'll have no holes or a partial packet */
  104808. {
  104809. int size=os->lacing_vals[ptr]&0xff;
  104810. int bytes=size;
  104811. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  104812. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  104813. while(size==255){
  104814. int val=os->lacing_vals[++ptr];
  104815. size=val&0xff;
  104816. if(val&0x200)eos=0x200;
  104817. bytes+=size;
  104818. }
  104819. if(op){
  104820. op->e_o_s=eos;
  104821. op->b_o_s=bos;
  104822. op->packet=os->body_data+os->body_returned;
  104823. op->packetno=os->packetno;
  104824. op->granulepos=os->granule_vals[ptr];
  104825. op->bytes=bytes;
  104826. }
  104827. if(adv){
  104828. os->body_returned+=bytes;
  104829. os->lacing_returned=ptr+1;
  104830. os->packetno++;
  104831. }
  104832. }
  104833. return(1);
  104834. }
  104835. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  104836. return _packetout(os,op,1);
  104837. }
  104838. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  104839. return _packetout(os,op,0);
  104840. }
  104841. void ogg_packet_clear(ogg_packet *op) {
  104842. _ogg_free(op->packet);
  104843. memset(op, 0, sizeof(*op));
  104844. }
  104845. #ifdef _V_SELFTEST
  104846. #include <stdio.h>
  104847. ogg_stream_state os_en, os_de;
  104848. ogg_sync_state oy;
  104849. void checkpacket(ogg_packet *op,int len, int no, int pos){
  104850. long j;
  104851. static int sequence=0;
  104852. static int lastno=0;
  104853. if(op->bytes!=len){
  104854. fprintf(stderr,"incorrect packet length!\n");
  104855. exit(1);
  104856. }
  104857. if(op->granulepos!=pos){
  104858. fprintf(stderr,"incorrect packet position!\n");
  104859. exit(1);
  104860. }
  104861. /* packet number just follows sequence/gap; adjust the input number
  104862. for that */
  104863. if(no==0){
  104864. sequence=0;
  104865. }else{
  104866. sequence++;
  104867. if(no>lastno+1)
  104868. sequence++;
  104869. }
  104870. lastno=no;
  104871. if(op->packetno!=sequence){
  104872. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  104873. (long)(op->packetno),sequence);
  104874. exit(1);
  104875. }
  104876. /* Test data */
  104877. for(j=0;j<op->bytes;j++)
  104878. if(op->packet[j]!=((j+no)&0xff)){
  104879. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  104880. j,op->packet[j],(j+no)&0xff);
  104881. exit(1);
  104882. }
  104883. }
  104884. void check_page(unsigned char *data,const int *header,ogg_page *og){
  104885. long j;
  104886. /* Test data */
  104887. for(j=0;j<og->body_len;j++)
  104888. if(og->body[j]!=data[j]){
  104889. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  104890. j,data[j],og->body[j]);
  104891. exit(1);
  104892. }
  104893. /* Test header */
  104894. for(j=0;j<og->header_len;j++){
  104895. if(og->header[j]!=header[j]){
  104896. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  104897. for(j=0;j<header[26]+27;j++)
  104898. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  104899. fprintf(stderr,"\n");
  104900. exit(1);
  104901. }
  104902. }
  104903. if(og->header_len!=header[26]+27){
  104904. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  104905. og->header_len,header[26]+27);
  104906. exit(1);
  104907. }
  104908. }
  104909. void print_header(ogg_page *og){
  104910. int j;
  104911. fprintf(stderr,"\nHEADER:\n");
  104912. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  104913. og->header[0],og->header[1],og->header[2],og->header[3],
  104914. (int)og->header[4],(int)og->header[5]);
  104915. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  104916. (og->header[9]<<24)|(og->header[8]<<16)|
  104917. (og->header[7]<<8)|og->header[6],
  104918. (og->header[17]<<24)|(og->header[16]<<16)|
  104919. (og->header[15]<<8)|og->header[14],
  104920. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  104921. (og->header[19]<<8)|og->header[18]);
  104922. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  104923. (int)og->header[22],(int)og->header[23],
  104924. (int)og->header[24],(int)og->header[25],
  104925. (int)og->header[26]);
  104926. for(j=27;j<og->header_len;j++)
  104927. fprintf(stderr,"%d ",(int)og->header[j]);
  104928. fprintf(stderr,")\n\n");
  104929. }
  104930. void copy_page(ogg_page *og){
  104931. unsigned char *temp=_ogg_malloc(og->header_len);
  104932. memcpy(temp,og->header,og->header_len);
  104933. og->header=temp;
  104934. temp=_ogg_malloc(og->body_len);
  104935. memcpy(temp,og->body,og->body_len);
  104936. og->body=temp;
  104937. }
  104938. void free_page(ogg_page *og){
  104939. _ogg_free (og->header);
  104940. _ogg_free (og->body);
  104941. }
  104942. void error(void){
  104943. fprintf(stderr,"error!\n");
  104944. exit(1);
  104945. }
  104946. /* 17 only */
  104947. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  104948. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104949. 0x01,0x02,0x03,0x04,0,0,0,0,
  104950. 0x15,0xed,0xec,0x91,
  104951. 1,
  104952. 17};
  104953. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104954. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104955. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104956. 0x01,0x02,0x03,0x04,0,0,0,0,
  104957. 0x59,0x10,0x6c,0x2c,
  104958. 1,
  104959. 17};
  104960. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104961. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  104962. 0x01,0x02,0x03,0x04,1,0,0,0,
  104963. 0x89,0x33,0x85,0xce,
  104964. 13,
  104965. 254,255,0,255,1,255,245,255,255,0,
  104966. 255,255,90};
  104967. /* nil packets; beginning,middle,end */
  104968. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104969. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104970. 0x01,0x02,0x03,0x04,0,0,0,0,
  104971. 0xff,0x7b,0x23,0x17,
  104972. 1,
  104973. 0};
  104974. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104975. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  104976. 0x01,0x02,0x03,0x04,1,0,0,0,
  104977. 0x5c,0x3f,0x66,0xcb,
  104978. 17,
  104979. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  104980. 255,255,90,0};
  104981. /* large initial packet */
  104982. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104983. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104984. 0x01,0x02,0x03,0x04,0,0,0,0,
  104985. 0x01,0x27,0x31,0xaa,
  104986. 18,
  104987. 255,255,255,255,255,255,255,255,
  104988. 255,255,255,255,255,255,255,255,255,10};
  104989. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104990. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104991. 0x01,0x02,0x03,0x04,1,0,0,0,
  104992. 0x7f,0x4e,0x8a,0xd2,
  104993. 4,
  104994. 255,4,255,0};
  104995. /* continuing packet test */
  104996. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104997. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104998. 0x01,0x02,0x03,0x04,0,0,0,0,
  104999. 0xff,0x7b,0x23,0x17,
  105000. 1,
  105001. 0};
  105002. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105003. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105004. 0x01,0x02,0x03,0x04,1,0,0,0,
  105005. 0x54,0x05,0x51,0xc8,
  105006. 17,
  105007. 255,255,255,255,255,255,255,255,
  105008. 255,255,255,255,255,255,255,255,255};
  105009. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105010. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  105011. 0x01,0x02,0x03,0x04,2,0,0,0,
  105012. 0xc8,0xc3,0xcb,0xed,
  105013. 5,
  105014. 10,255,4,255,0};
  105015. /* page with the 255 segment limit */
  105016. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105017. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105018. 0x01,0x02,0x03,0x04,0,0,0,0,
  105019. 0xff,0x7b,0x23,0x17,
  105020. 1,
  105021. 0};
  105022. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105023. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  105024. 0x01,0x02,0x03,0x04,1,0,0,0,
  105025. 0xed,0x2a,0x2e,0xa7,
  105026. 255,
  105027. 10,10,10,10,10,10,10,10,
  105028. 10,10,10,10,10,10,10,10,
  105029. 10,10,10,10,10,10,10,10,
  105030. 10,10,10,10,10,10,10,10,
  105031. 10,10,10,10,10,10,10,10,
  105032. 10,10,10,10,10,10,10,10,
  105033. 10,10,10,10,10,10,10,10,
  105034. 10,10,10,10,10,10,10,10,
  105035. 10,10,10,10,10,10,10,10,
  105036. 10,10,10,10,10,10,10,10,
  105037. 10,10,10,10,10,10,10,10,
  105038. 10,10,10,10,10,10,10,10,
  105039. 10,10,10,10,10,10,10,10,
  105040. 10,10,10,10,10,10,10,10,
  105041. 10,10,10,10,10,10,10,10,
  105042. 10,10,10,10,10,10,10,10,
  105043. 10,10,10,10,10,10,10,10,
  105044. 10,10,10,10,10,10,10,10,
  105045. 10,10,10,10,10,10,10,10,
  105046. 10,10,10,10,10,10,10,10,
  105047. 10,10,10,10,10,10,10,10,
  105048. 10,10,10,10,10,10,10,10,
  105049. 10,10,10,10,10,10,10,10,
  105050. 10,10,10,10,10,10,10,10,
  105051. 10,10,10,10,10,10,10,10,
  105052. 10,10,10,10,10,10,10,10,
  105053. 10,10,10,10,10,10,10,10,
  105054. 10,10,10,10,10,10,10,10,
  105055. 10,10,10,10,10,10,10,10,
  105056. 10,10,10,10,10,10,10,10,
  105057. 10,10,10,10,10,10,10,10,
  105058. 10,10,10,10,10,10,10};
  105059. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105060. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  105061. 0x01,0x02,0x03,0x04,2,0,0,0,
  105062. 0x6c,0x3b,0x82,0x3d,
  105063. 1,
  105064. 50};
  105065. /* packet that overspans over an entire page */
  105066. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105067. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105068. 0x01,0x02,0x03,0x04,0,0,0,0,
  105069. 0xff,0x7b,0x23,0x17,
  105070. 1,
  105071. 0};
  105072. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105073. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105074. 0x01,0x02,0x03,0x04,1,0,0,0,
  105075. 0x3c,0xd9,0x4d,0x3f,
  105076. 17,
  105077. 100,255,255,255,255,255,255,255,255,
  105078. 255,255,255,255,255,255,255,255};
  105079. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  105080. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105081. 0x01,0x02,0x03,0x04,2,0,0,0,
  105082. 0x01,0xd2,0xe5,0xe5,
  105083. 17,
  105084. 255,255,255,255,255,255,255,255,
  105085. 255,255,255,255,255,255,255,255,255};
  105086. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105087. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  105088. 0x01,0x02,0x03,0x04,3,0,0,0,
  105089. 0xef,0xdd,0x88,0xde,
  105090. 7,
  105091. 255,255,75,255,4,255,0};
  105092. /* packet that overspans over an entire page */
  105093. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105094. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105095. 0x01,0x02,0x03,0x04,0,0,0,0,
  105096. 0xff,0x7b,0x23,0x17,
  105097. 1,
  105098. 0};
  105099. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105100. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105101. 0x01,0x02,0x03,0x04,1,0,0,0,
  105102. 0x3c,0xd9,0x4d,0x3f,
  105103. 17,
  105104. 100,255,255,255,255,255,255,255,255,
  105105. 255,255,255,255,255,255,255,255};
  105106. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105107. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105108. 0x01,0x02,0x03,0x04,2,0,0,0,
  105109. 0xd4,0xe0,0x60,0xe5,
  105110. 1,0};
  105111. void test_pack(const int *pl, const int **headers, int byteskip,
  105112. int pageskip, int packetskip){
  105113. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  105114. long inptr=0;
  105115. long outptr=0;
  105116. long deptr=0;
  105117. long depacket=0;
  105118. long granule_pos=7,pageno=0;
  105119. int i,j,packets,pageout=pageskip;
  105120. int eosflag=0;
  105121. int bosflag=0;
  105122. int byteskipcount=0;
  105123. ogg_stream_reset(&os_en);
  105124. ogg_stream_reset(&os_de);
  105125. ogg_sync_reset(&oy);
  105126. for(packets=0;packets<packetskip;packets++)
  105127. depacket+=pl[packets];
  105128. for(packets=0;;packets++)if(pl[packets]==-1)break;
  105129. for(i=0;i<packets;i++){
  105130. /* construct a test packet */
  105131. ogg_packet op;
  105132. int len=pl[i];
  105133. op.packet=data+inptr;
  105134. op.bytes=len;
  105135. op.e_o_s=(pl[i+1]<0?1:0);
  105136. op.granulepos=granule_pos;
  105137. granule_pos+=1024;
  105138. for(j=0;j<len;j++)data[inptr++]=i+j;
  105139. /* submit the test packet */
  105140. ogg_stream_packetin(&os_en,&op);
  105141. /* retrieve any finished pages */
  105142. {
  105143. ogg_page og;
  105144. while(ogg_stream_pageout(&os_en,&og)){
  105145. /* We have a page. Check it carefully */
  105146. fprintf(stderr,"%ld, ",pageno);
  105147. if(headers[pageno]==NULL){
  105148. fprintf(stderr,"coded too many pages!\n");
  105149. exit(1);
  105150. }
  105151. check_page(data+outptr,headers[pageno],&og);
  105152. outptr+=og.body_len;
  105153. pageno++;
  105154. if(pageskip){
  105155. bosflag=1;
  105156. pageskip--;
  105157. deptr+=og.body_len;
  105158. }
  105159. /* have a complete page; submit it to sync/decode */
  105160. {
  105161. ogg_page og_de;
  105162. ogg_packet op_de,op_de2;
  105163. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  105164. char *next=buf;
  105165. byteskipcount+=og.header_len;
  105166. if(byteskipcount>byteskip){
  105167. memcpy(next,og.header,byteskipcount-byteskip);
  105168. next+=byteskipcount-byteskip;
  105169. byteskipcount=byteskip;
  105170. }
  105171. byteskipcount+=og.body_len;
  105172. if(byteskipcount>byteskip){
  105173. memcpy(next,og.body,byteskipcount-byteskip);
  105174. next+=byteskipcount-byteskip;
  105175. byteskipcount=byteskip;
  105176. }
  105177. ogg_sync_wrote(&oy,next-buf);
  105178. while(1){
  105179. int ret=ogg_sync_pageout(&oy,&og_de);
  105180. if(ret==0)break;
  105181. if(ret<0)continue;
  105182. /* got a page. Happy happy. Verify that it's good. */
  105183. fprintf(stderr,"(%ld), ",pageout);
  105184. check_page(data+deptr,headers[pageout],&og_de);
  105185. deptr+=og_de.body_len;
  105186. pageout++;
  105187. /* submit it to deconstitution */
  105188. ogg_stream_pagein(&os_de,&og_de);
  105189. /* packets out? */
  105190. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  105191. ogg_stream_packetpeek(&os_de,NULL);
  105192. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  105193. /* verify peek and out match */
  105194. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  105195. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  105196. depacket);
  105197. exit(1);
  105198. }
  105199. /* verify the packet! */
  105200. /* check data */
  105201. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  105202. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  105203. depacket);
  105204. exit(1);
  105205. }
  105206. /* check bos flag */
  105207. if(bosflag==0 && op_de.b_o_s==0){
  105208. fprintf(stderr,"b_o_s flag not set on packet!\n");
  105209. exit(1);
  105210. }
  105211. if(bosflag && op_de.b_o_s){
  105212. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  105213. exit(1);
  105214. }
  105215. bosflag=1;
  105216. depacket+=op_de.bytes;
  105217. /* check eos flag */
  105218. if(eosflag){
  105219. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  105220. exit(1);
  105221. }
  105222. if(op_de.e_o_s)eosflag=1;
  105223. /* check granulepos flag */
  105224. if(op_de.granulepos!=-1){
  105225. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  105226. }
  105227. }
  105228. }
  105229. }
  105230. }
  105231. }
  105232. }
  105233. _ogg_free(data);
  105234. if(headers[pageno]!=NULL){
  105235. fprintf(stderr,"did not write last page!\n");
  105236. exit(1);
  105237. }
  105238. if(headers[pageout]!=NULL){
  105239. fprintf(stderr,"did not decode last page!\n");
  105240. exit(1);
  105241. }
  105242. if(inptr!=outptr){
  105243. fprintf(stderr,"encoded page data incomplete!\n");
  105244. exit(1);
  105245. }
  105246. if(inptr!=deptr){
  105247. fprintf(stderr,"decoded page data incomplete!\n");
  105248. exit(1);
  105249. }
  105250. if(inptr!=depacket){
  105251. fprintf(stderr,"decoded packet data incomplete!\n");
  105252. exit(1);
  105253. }
  105254. if(!eosflag){
  105255. fprintf(stderr,"Never got a packet with EOS set!\n");
  105256. exit(1);
  105257. }
  105258. fprintf(stderr,"ok.\n");
  105259. }
  105260. int main(void){
  105261. ogg_stream_init(&os_en,0x04030201);
  105262. ogg_stream_init(&os_de,0x04030201);
  105263. ogg_sync_init(&oy);
  105264. /* Exercise each code path in the framing code. Also verify that
  105265. the checksums are working. */
  105266. {
  105267. /* 17 only */
  105268. const int packets[]={17, -1};
  105269. const int *headret[]={head1_0,NULL};
  105270. fprintf(stderr,"testing single page encoding... ");
  105271. test_pack(packets,headret,0,0,0);
  105272. }
  105273. {
  105274. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  105275. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  105276. const int *headret[]={head1_1,head2_1,NULL};
  105277. fprintf(stderr,"testing basic page encoding... ");
  105278. test_pack(packets,headret,0,0,0);
  105279. }
  105280. {
  105281. /* nil packets; beginning,middle,end */
  105282. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  105283. const int *headret[]={head1_2,head2_2,NULL};
  105284. fprintf(stderr,"testing basic nil packets... ");
  105285. test_pack(packets,headret,0,0,0);
  105286. }
  105287. {
  105288. /* large initial packet */
  105289. const int packets[]={4345,259,255,-1};
  105290. const int *headret[]={head1_3,head2_3,NULL};
  105291. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  105292. test_pack(packets,headret,0,0,0);
  105293. }
  105294. {
  105295. /* continuing packet test */
  105296. const int packets[]={0,4345,259,255,-1};
  105297. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  105298. fprintf(stderr,"testing single packet page span... ");
  105299. test_pack(packets,headret,0,0,0);
  105300. }
  105301. /* page with the 255 segment limit */
  105302. {
  105303. const int packets[]={0,10,10,10,10,10,10,10,10,
  105304. 10,10,10,10,10,10,10,10,
  105305. 10,10,10,10,10,10,10,10,
  105306. 10,10,10,10,10,10,10,10,
  105307. 10,10,10,10,10,10,10,10,
  105308. 10,10,10,10,10,10,10,10,
  105309. 10,10,10,10,10,10,10,10,
  105310. 10,10,10,10,10,10,10,10,
  105311. 10,10,10,10,10,10,10,10,
  105312. 10,10,10,10,10,10,10,10,
  105313. 10,10,10,10,10,10,10,10,
  105314. 10,10,10,10,10,10,10,10,
  105315. 10,10,10,10,10,10,10,10,
  105316. 10,10,10,10,10,10,10,10,
  105317. 10,10,10,10,10,10,10,10,
  105318. 10,10,10,10,10,10,10,10,
  105319. 10,10,10,10,10,10,10,10,
  105320. 10,10,10,10,10,10,10,10,
  105321. 10,10,10,10,10,10,10,10,
  105322. 10,10,10,10,10,10,10,10,
  105323. 10,10,10,10,10,10,10,10,
  105324. 10,10,10,10,10,10,10,10,
  105325. 10,10,10,10,10,10,10,10,
  105326. 10,10,10,10,10,10,10,10,
  105327. 10,10,10,10,10,10,10,10,
  105328. 10,10,10,10,10,10,10,10,
  105329. 10,10,10,10,10,10,10,10,
  105330. 10,10,10,10,10,10,10,10,
  105331. 10,10,10,10,10,10,10,10,
  105332. 10,10,10,10,10,10,10,10,
  105333. 10,10,10,10,10,10,10,10,
  105334. 10,10,10,10,10,10,10,50,-1};
  105335. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  105336. fprintf(stderr,"testing max packet segments... ");
  105337. test_pack(packets,headret,0,0,0);
  105338. }
  105339. {
  105340. /* packet that overspans over an entire page */
  105341. const int packets[]={0,100,9000,259,255,-1};
  105342. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105343. fprintf(stderr,"testing very large packets... ");
  105344. test_pack(packets,headret,0,0,0);
  105345. }
  105346. {
  105347. /* test for the libogg 1.1.1 resync in large continuation bug
  105348. found by Josh Coalson) */
  105349. const int packets[]={0,100,9000,259,255,-1};
  105350. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105351. fprintf(stderr,"testing continuation resync in very large packets... ");
  105352. test_pack(packets,headret,100,2,3);
  105353. }
  105354. {
  105355. /* term only page. why not? */
  105356. const int packets[]={0,100,4080,-1};
  105357. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  105358. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  105359. test_pack(packets,headret,0,0,0);
  105360. }
  105361. {
  105362. /* build a bunch of pages for testing */
  105363. unsigned char *data=_ogg_malloc(1024*1024);
  105364. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  105365. int inptr=0,i,j;
  105366. ogg_page og[5];
  105367. ogg_stream_reset(&os_en);
  105368. for(i=0;pl[i]!=-1;i++){
  105369. ogg_packet op;
  105370. int len=pl[i];
  105371. op.packet=data+inptr;
  105372. op.bytes=len;
  105373. op.e_o_s=(pl[i+1]<0?1:0);
  105374. op.granulepos=(i+1)*1000;
  105375. for(j=0;j<len;j++)data[inptr++]=i+j;
  105376. ogg_stream_packetin(&os_en,&op);
  105377. }
  105378. _ogg_free(data);
  105379. /* retrieve finished pages */
  105380. for(i=0;i<5;i++){
  105381. if(ogg_stream_pageout(&os_en,&og[i])==0){
  105382. fprintf(stderr,"Too few pages output building sync tests!\n");
  105383. exit(1);
  105384. }
  105385. copy_page(&og[i]);
  105386. }
  105387. /* Test lost pages on pagein/packetout: no rollback */
  105388. {
  105389. ogg_page temp;
  105390. ogg_packet test;
  105391. fprintf(stderr,"Testing loss of pages... ");
  105392. ogg_sync_reset(&oy);
  105393. ogg_stream_reset(&os_de);
  105394. for(i=0;i<5;i++){
  105395. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105396. og[i].header_len);
  105397. ogg_sync_wrote(&oy,og[i].header_len);
  105398. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105399. ogg_sync_wrote(&oy,og[i].body_len);
  105400. }
  105401. ogg_sync_pageout(&oy,&temp);
  105402. ogg_stream_pagein(&os_de,&temp);
  105403. ogg_sync_pageout(&oy,&temp);
  105404. ogg_stream_pagein(&os_de,&temp);
  105405. ogg_sync_pageout(&oy,&temp);
  105406. /* skip */
  105407. ogg_sync_pageout(&oy,&temp);
  105408. ogg_stream_pagein(&os_de,&temp);
  105409. /* do we get the expected results/packets? */
  105410. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105411. checkpacket(&test,0,0,0);
  105412. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105413. checkpacket(&test,100,1,-1);
  105414. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105415. checkpacket(&test,4079,2,3000);
  105416. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105417. fprintf(stderr,"Error: loss of page did not return error\n");
  105418. exit(1);
  105419. }
  105420. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105421. checkpacket(&test,76,5,-1);
  105422. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105423. checkpacket(&test,34,6,-1);
  105424. fprintf(stderr,"ok.\n");
  105425. }
  105426. /* Test lost pages on pagein/packetout: rollback with continuation */
  105427. {
  105428. ogg_page temp;
  105429. ogg_packet test;
  105430. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  105431. ogg_sync_reset(&oy);
  105432. ogg_stream_reset(&os_de);
  105433. for(i=0;i<5;i++){
  105434. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105435. og[i].header_len);
  105436. ogg_sync_wrote(&oy,og[i].header_len);
  105437. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105438. ogg_sync_wrote(&oy,og[i].body_len);
  105439. }
  105440. ogg_sync_pageout(&oy,&temp);
  105441. ogg_stream_pagein(&os_de,&temp);
  105442. ogg_sync_pageout(&oy,&temp);
  105443. ogg_stream_pagein(&os_de,&temp);
  105444. ogg_sync_pageout(&oy,&temp);
  105445. ogg_stream_pagein(&os_de,&temp);
  105446. ogg_sync_pageout(&oy,&temp);
  105447. /* skip */
  105448. ogg_sync_pageout(&oy,&temp);
  105449. ogg_stream_pagein(&os_de,&temp);
  105450. /* do we get the expected results/packets? */
  105451. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105452. checkpacket(&test,0,0,0);
  105453. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105454. checkpacket(&test,100,1,-1);
  105455. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105456. checkpacket(&test,4079,2,3000);
  105457. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105458. checkpacket(&test,2956,3,4000);
  105459. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105460. fprintf(stderr,"Error: loss of page did not return error\n");
  105461. exit(1);
  105462. }
  105463. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105464. checkpacket(&test,300,13,14000);
  105465. fprintf(stderr,"ok.\n");
  105466. }
  105467. /* the rest only test sync */
  105468. {
  105469. ogg_page og_de;
  105470. /* Test fractional page inputs: incomplete capture */
  105471. fprintf(stderr,"Testing sync on partial inputs... ");
  105472. ogg_sync_reset(&oy);
  105473. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105474. 3);
  105475. ogg_sync_wrote(&oy,3);
  105476. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105477. /* Test fractional page inputs: incomplete fixed header */
  105478. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  105479. 20);
  105480. ogg_sync_wrote(&oy,20);
  105481. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105482. /* Test fractional page inputs: incomplete header */
  105483. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  105484. 5);
  105485. ogg_sync_wrote(&oy,5);
  105486. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105487. /* Test fractional page inputs: incomplete body */
  105488. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  105489. og[1].header_len-28);
  105490. ogg_sync_wrote(&oy,og[1].header_len-28);
  105491. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105492. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  105493. ogg_sync_wrote(&oy,1000);
  105494. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105495. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  105496. og[1].body_len-1000);
  105497. ogg_sync_wrote(&oy,og[1].body_len-1000);
  105498. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105499. fprintf(stderr,"ok.\n");
  105500. }
  105501. /* Test fractional page inputs: page + incomplete capture */
  105502. {
  105503. ogg_page og_de;
  105504. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  105505. ogg_sync_reset(&oy);
  105506. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105507. og[1].header_len);
  105508. ogg_sync_wrote(&oy,og[1].header_len);
  105509. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105510. og[1].body_len);
  105511. ogg_sync_wrote(&oy,og[1].body_len);
  105512. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105513. 20);
  105514. ogg_sync_wrote(&oy,20);
  105515. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105516. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105517. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  105518. og[1].header_len-20);
  105519. ogg_sync_wrote(&oy,og[1].header_len-20);
  105520. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105521. og[1].body_len);
  105522. ogg_sync_wrote(&oy,og[1].body_len);
  105523. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105524. fprintf(stderr,"ok.\n");
  105525. }
  105526. /* Test recapture: garbage + page */
  105527. {
  105528. ogg_page og_de;
  105529. fprintf(stderr,"Testing search for capture... ");
  105530. ogg_sync_reset(&oy);
  105531. /* 'garbage' */
  105532. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105533. og[1].body_len);
  105534. ogg_sync_wrote(&oy,og[1].body_len);
  105535. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105536. og[1].header_len);
  105537. ogg_sync_wrote(&oy,og[1].header_len);
  105538. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105539. og[1].body_len);
  105540. ogg_sync_wrote(&oy,og[1].body_len);
  105541. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105542. 20);
  105543. ogg_sync_wrote(&oy,20);
  105544. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105545. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105546. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105547. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  105548. og[2].header_len-20);
  105549. ogg_sync_wrote(&oy,og[2].header_len-20);
  105550. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105551. og[2].body_len);
  105552. ogg_sync_wrote(&oy,og[2].body_len);
  105553. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105554. fprintf(stderr,"ok.\n");
  105555. }
  105556. /* Test recapture: page + garbage + page */
  105557. {
  105558. ogg_page og_de;
  105559. fprintf(stderr,"Testing recapture... ");
  105560. ogg_sync_reset(&oy);
  105561. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105562. og[1].header_len);
  105563. ogg_sync_wrote(&oy,og[1].header_len);
  105564. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105565. og[1].body_len);
  105566. ogg_sync_wrote(&oy,og[1].body_len);
  105567. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105568. og[2].header_len);
  105569. ogg_sync_wrote(&oy,og[2].header_len);
  105570. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105571. og[2].header_len);
  105572. ogg_sync_wrote(&oy,og[2].header_len);
  105573. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105574. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105575. og[2].body_len-5);
  105576. ogg_sync_wrote(&oy,og[2].body_len-5);
  105577. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  105578. og[3].header_len);
  105579. ogg_sync_wrote(&oy,og[3].header_len);
  105580. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  105581. og[3].body_len);
  105582. ogg_sync_wrote(&oy,og[3].body_len);
  105583. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105584. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105585. fprintf(stderr,"ok.\n");
  105586. }
  105587. /* Free page data that was previously copied */
  105588. {
  105589. for(i=0;i<5;i++){
  105590. free_page(&og[i]);
  105591. }
  105592. }
  105593. }
  105594. return(0);
  105595. }
  105596. #endif
  105597. #endif
  105598. /********* End of inlined file: framing.c *********/
  105599. /********* Start of inlined file: analysis.c *********/
  105600. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105601. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105602. // tasks..
  105603. #if JUCE_MSVC
  105604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105605. #endif
  105606. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105607. #if JUCE_USE_OGGVORBIS
  105608. #include <stdio.h>
  105609. #include <string.h>
  105610. #include <math.h>
  105611. /********* Start of inlined file: codec_internal.h *********/
  105612. #ifndef _V_CODECI_H_
  105613. #define _V_CODECI_H_
  105614. /********* Start of inlined file: envelope.h *********/
  105615. #ifndef _V_ENVELOPE_
  105616. #define _V_ENVELOPE_
  105617. /********* Start of inlined file: mdct.h *********/
  105618. #ifndef _OGG_mdct_H_
  105619. #define _OGG_mdct_H_
  105620. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  105621. #ifdef MDCT_INTEGERIZED
  105622. #define DATA_TYPE int
  105623. #define REG_TYPE register int
  105624. #define TRIGBITS 14
  105625. #define cPI3_8 6270
  105626. #define cPI2_8 11585
  105627. #define cPI1_8 15137
  105628. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  105629. #define MULT_NORM(x) ((x)>>TRIGBITS)
  105630. #define HALVE(x) ((x)>>1)
  105631. #else
  105632. #define DATA_TYPE float
  105633. #define REG_TYPE float
  105634. #define cPI3_8 .38268343236508977175F
  105635. #define cPI2_8 .70710678118654752441F
  105636. #define cPI1_8 .92387953251128675613F
  105637. #define FLOAT_CONV(x) (x)
  105638. #define MULT_NORM(x) (x)
  105639. #define HALVE(x) ((x)*.5f)
  105640. #endif
  105641. typedef struct {
  105642. int n;
  105643. int log2n;
  105644. DATA_TYPE *trig;
  105645. int *bitrev;
  105646. DATA_TYPE scale;
  105647. } mdct_lookup;
  105648. extern void mdct_init(mdct_lookup *lookup,int n);
  105649. extern void mdct_clear(mdct_lookup *l);
  105650. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105651. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105652. #endif
  105653. /********* End of inlined file: mdct.h *********/
  105654. #define VE_PRE 16
  105655. #define VE_WIN 4
  105656. #define VE_POST 2
  105657. #define VE_AMP (VE_PRE+VE_POST-1)
  105658. #define VE_BANDS 7
  105659. #define VE_NEARDC 15
  105660. #define VE_MINSTRETCH 2 /* a bit less than short block */
  105661. #define VE_MAXSTRETCH 12 /* one-third full block */
  105662. typedef struct {
  105663. float ampbuf[VE_AMP];
  105664. int ampptr;
  105665. float nearDC[VE_NEARDC];
  105666. float nearDC_acc;
  105667. float nearDC_partialacc;
  105668. int nearptr;
  105669. } envelope_filter_state;
  105670. typedef struct {
  105671. int begin;
  105672. int end;
  105673. float *window;
  105674. float total;
  105675. } envelope_band;
  105676. typedef struct {
  105677. int ch;
  105678. int winlength;
  105679. int searchstep;
  105680. float minenergy;
  105681. mdct_lookup mdct;
  105682. float *mdct_win;
  105683. envelope_band band[VE_BANDS];
  105684. envelope_filter_state *filter;
  105685. int stretch;
  105686. int *mark;
  105687. long storage;
  105688. long current;
  105689. long curmark;
  105690. long cursor;
  105691. } envelope_lookup;
  105692. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  105693. extern void _ve_envelope_clear(envelope_lookup *e);
  105694. extern long _ve_envelope_search(vorbis_dsp_state *v);
  105695. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  105696. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  105697. #endif
  105698. /********* End of inlined file: envelope.h *********/
  105699. /********* Start of inlined file: codebook.h *********/
  105700. #ifndef _V_CODEBOOK_H_
  105701. #define _V_CODEBOOK_H_
  105702. /* This structure encapsulates huffman and VQ style encoding books; it
  105703. doesn't do anything specific to either.
  105704. valuelist/quantlist are nonNULL (and q_* significant) only if
  105705. there's entry->value mapping to be done.
  105706. If encode-side mapping must be done (and thus the entry needs to be
  105707. hunted), the auxiliary encode pointer will point to a decision
  105708. tree. This is true of both VQ and huffman, but is mostly useful
  105709. with VQ.
  105710. */
  105711. typedef struct static_codebook{
  105712. long dim; /* codebook dimensions (elements per vector) */
  105713. long entries; /* codebook entries */
  105714. long *lengthlist; /* codeword lengths in bits */
  105715. /* mapping ***************************************************************/
  105716. int maptype; /* 0=none
  105717. 1=implicitly populated values from map column
  105718. 2=listed arbitrary values */
  105719. /* The below does a linear, single monotonic sequence mapping. */
  105720. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  105721. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  105722. int q_quant; /* bits: 0 < quant <= 16 */
  105723. int q_sequencep; /* bitflag */
  105724. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  105725. map == 2: list of dim*entries quantized entry vals
  105726. */
  105727. /* encode helpers ********************************************************/
  105728. struct encode_aux_nearestmatch *nearest_tree;
  105729. struct encode_aux_threshmatch *thresh_tree;
  105730. struct encode_aux_pigeonhole *pigeon_tree;
  105731. int allocedp;
  105732. } static_codebook;
  105733. /* this structures an arbitrary trained book to quickly find the
  105734. nearest cell match */
  105735. typedef struct encode_aux_nearestmatch{
  105736. /* pre-calculated partitioning tree */
  105737. long *ptr0;
  105738. long *ptr1;
  105739. long *p; /* decision points (each is an entry) */
  105740. long *q; /* decision points (each is an entry) */
  105741. long aux; /* number of tree entries */
  105742. long alloc;
  105743. } encode_aux_nearestmatch;
  105744. /* assumes a maptype of 1; encode side only, so that's OK */
  105745. typedef struct encode_aux_threshmatch{
  105746. float *quantthresh;
  105747. long *quantmap;
  105748. int quantvals;
  105749. int threshvals;
  105750. } encode_aux_threshmatch;
  105751. typedef struct encode_aux_pigeonhole{
  105752. float min;
  105753. float del;
  105754. int mapentries;
  105755. int quantvals;
  105756. long *pigeonmap;
  105757. long fittotal;
  105758. long *fitlist;
  105759. long *fitmap;
  105760. long *fitlength;
  105761. } encode_aux_pigeonhole;
  105762. typedef struct codebook{
  105763. long dim; /* codebook dimensions (elements per vector) */
  105764. long entries; /* codebook entries */
  105765. long used_entries; /* populated codebook entries */
  105766. const static_codebook *c;
  105767. /* for encode, the below are entry-ordered, fully populated */
  105768. /* for decode, the below are ordered by bitreversed codeword and only
  105769. used entries are populated */
  105770. float *valuelist; /* list of dim*entries actual entry values */
  105771. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  105772. int *dec_index; /* only used if sparseness collapsed */
  105773. char *dec_codelengths;
  105774. ogg_uint32_t *dec_firsttable;
  105775. int dec_firsttablen;
  105776. int dec_maxlength;
  105777. } codebook;
  105778. extern void vorbis_staticbook_clear(static_codebook *b);
  105779. extern void vorbis_staticbook_destroy(static_codebook *b);
  105780. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  105781. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  105782. extern void vorbis_book_clear(codebook *b);
  105783. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  105784. extern float *_book_logdist(const static_codebook *b,float *vals);
  105785. extern float _float32_unpack(long val);
  105786. extern long _float32_pack(float val);
  105787. extern int _best(codebook *book, float *a, int step);
  105788. extern int _ilog(unsigned int v);
  105789. extern long _book_maptype1_quantvals(const static_codebook *b);
  105790. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  105791. extern long vorbis_book_codeword(codebook *book,int entry);
  105792. extern long vorbis_book_codelen(codebook *book,int entry);
  105793. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  105794. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  105795. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  105796. extern int vorbis_book_errorv(codebook *book, float *a);
  105797. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  105798. oggpack_buffer *b);
  105799. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  105800. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  105801. oggpack_buffer *b,int n);
  105802. extern long vorbis_book_decodev_set(codebook *book, float *a,
  105803. oggpack_buffer *b,int n);
  105804. extern long vorbis_book_decodev_add(codebook *book, float *a,
  105805. oggpack_buffer *b,int n);
  105806. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  105807. long off,int ch,
  105808. oggpack_buffer *b,int n);
  105809. #endif
  105810. /********* End of inlined file: codebook.h *********/
  105811. #define BLOCKTYPE_IMPULSE 0
  105812. #define BLOCKTYPE_PADDING 1
  105813. #define BLOCKTYPE_TRANSITION 0
  105814. #define BLOCKTYPE_LONG 1
  105815. #define PACKETBLOBS 15
  105816. typedef struct vorbis_block_internal{
  105817. float **pcmdelay; /* this is a pointer into local storage */
  105818. float ampmax;
  105819. int blocktype;
  105820. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  105821. blob [PACKETBLOBS/2] points to
  105822. the oggpack_buffer in the
  105823. main vorbis_block */
  105824. } vorbis_block_internal;
  105825. typedef void vorbis_look_floor;
  105826. typedef void vorbis_look_residue;
  105827. typedef void vorbis_look_transform;
  105828. /* mode ************************************************************/
  105829. typedef struct {
  105830. int blockflag;
  105831. int windowtype;
  105832. int transformtype;
  105833. int mapping;
  105834. } vorbis_info_mode;
  105835. typedef void vorbis_info_floor;
  105836. typedef void vorbis_info_residue;
  105837. typedef void vorbis_info_mapping;
  105838. /********* Start of inlined file: psy.h *********/
  105839. #ifndef _V_PSY_H_
  105840. #define _V_PSY_H_
  105841. /********* Start of inlined file: smallft.h *********/
  105842. #ifndef _V_SMFT_H_
  105843. #define _V_SMFT_H_
  105844. typedef struct {
  105845. int n;
  105846. float *trigcache;
  105847. int *splitcache;
  105848. } drft_lookup;
  105849. extern void drft_forward(drft_lookup *l,float *data);
  105850. extern void drft_backward(drft_lookup *l,float *data);
  105851. extern void drft_init(drft_lookup *l,int n);
  105852. extern void drft_clear(drft_lookup *l);
  105853. #endif
  105854. /********* End of inlined file: smallft.h *********/
  105855. /********* Start of inlined file: backends.h *********/
  105856. /* this is exposed up here because we need it for static modes.
  105857. Lookups for each backend aren't exposed because there's no reason
  105858. to do so */
  105859. #ifndef _vorbis_backend_h_
  105860. #define _vorbis_backend_h_
  105861. /* this would all be simpler/shorter with templates, but.... */
  105862. /* Floor backend generic *****************************************/
  105863. typedef struct{
  105864. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  105865. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  105866. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  105867. void (*free_info) (vorbis_info_floor *);
  105868. void (*free_look) (vorbis_look_floor *);
  105869. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  105870. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  105871. void *buffer,float *);
  105872. } vorbis_func_floor;
  105873. typedef struct{
  105874. int order;
  105875. long rate;
  105876. long barkmap;
  105877. int ampbits;
  105878. int ampdB;
  105879. int numbooks; /* <= 16 */
  105880. int books[16];
  105881. float lessthan; /* encode-only config setting hacks for libvorbis */
  105882. float greaterthan; /* encode-only config setting hacks for libvorbis */
  105883. } vorbis_info_floor0;
  105884. #define VIF_POSIT 63
  105885. #define VIF_CLASS 16
  105886. #define VIF_PARTS 31
  105887. typedef struct{
  105888. int partitions; /* 0 to 31 */
  105889. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  105890. int class_dim[VIF_CLASS]; /* 1 to 8 */
  105891. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  105892. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  105893. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  105894. int mult; /* 1 2 3 or 4 */
  105895. int postlist[VIF_POSIT+2]; /* first two implicit */
  105896. /* encode side analysis parameters */
  105897. float maxover;
  105898. float maxunder;
  105899. float maxerr;
  105900. float twofitweight;
  105901. float twofitatten;
  105902. int n;
  105903. } vorbis_info_floor1;
  105904. /* Residue backend generic *****************************************/
  105905. typedef struct{
  105906. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  105907. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  105908. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  105909. vorbis_info_residue *);
  105910. void (*free_info) (vorbis_info_residue *);
  105911. void (*free_look) (vorbis_look_residue *);
  105912. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  105913. float **,int *,int);
  105914. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  105915. vorbis_look_residue *,
  105916. float **,float **,int *,int,long **);
  105917. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  105918. float **,int *,int);
  105919. } vorbis_func_residue;
  105920. typedef struct vorbis_info_residue0{
  105921. /* block-partitioned VQ coded straight residue */
  105922. long begin;
  105923. long end;
  105924. /* first stage (lossless partitioning) */
  105925. int grouping; /* group n vectors per partition */
  105926. int partitions; /* possible codebooks for a partition */
  105927. int groupbook; /* huffbook for partitioning */
  105928. int secondstages[64]; /* expanded out to pointers in lookup */
  105929. int booklist[256]; /* list of second stage books */
  105930. float classmetric1[64];
  105931. float classmetric2[64];
  105932. } vorbis_info_residue0;
  105933. /* Mapping backend generic *****************************************/
  105934. typedef struct{
  105935. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  105936. oggpack_buffer *);
  105937. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  105938. void (*free_info) (vorbis_info_mapping *);
  105939. int (*forward) (struct vorbis_block *vb);
  105940. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  105941. } vorbis_func_mapping;
  105942. typedef struct vorbis_info_mapping0{
  105943. int submaps; /* <= 16 */
  105944. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  105945. int floorsubmap[16]; /* [mux] submap to floors */
  105946. int residuesubmap[16]; /* [mux] submap to residue */
  105947. int coupling_steps;
  105948. int coupling_mag[256];
  105949. int coupling_ang[256];
  105950. } vorbis_info_mapping0;
  105951. #endif
  105952. /********* End of inlined file: backends.h *********/
  105953. #ifndef EHMER_MAX
  105954. #define EHMER_MAX 56
  105955. #endif
  105956. /* psychoacoustic setup ********************************************/
  105957. #define P_BANDS 17 /* 62Hz to 16kHz */
  105958. #define P_LEVELS 8 /* 30dB to 100dB */
  105959. #define P_LEVEL_0 30. /* 30 dB */
  105960. #define P_NOISECURVES 3
  105961. #define NOISE_COMPAND_LEVELS 40
  105962. typedef struct vorbis_info_psy{
  105963. int blockflag;
  105964. float ath_adjatt;
  105965. float ath_maxatt;
  105966. float tone_masteratt[P_NOISECURVES];
  105967. float tone_centerboost;
  105968. float tone_decay;
  105969. float tone_abs_limit;
  105970. float toneatt[P_BANDS];
  105971. int noisemaskp;
  105972. float noisemaxsupp;
  105973. float noisewindowlo;
  105974. float noisewindowhi;
  105975. int noisewindowlomin;
  105976. int noisewindowhimin;
  105977. int noisewindowfixed;
  105978. float noiseoff[P_NOISECURVES][P_BANDS];
  105979. float noisecompand[NOISE_COMPAND_LEVELS];
  105980. float max_curve_dB;
  105981. int normal_channel_p;
  105982. int normal_point_p;
  105983. int normal_start;
  105984. int normal_partition;
  105985. double normal_thresh;
  105986. } vorbis_info_psy;
  105987. typedef struct{
  105988. int eighth_octave_lines;
  105989. /* for block long/short tuning; encode only */
  105990. float preecho_thresh[VE_BANDS];
  105991. float postecho_thresh[VE_BANDS];
  105992. float stretch_penalty;
  105993. float preecho_minenergy;
  105994. float ampmax_att_per_sec;
  105995. /* channel coupling config */
  105996. int coupling_pkHz[PACKETBLOBS];
  105997. int coupling_pointlimit[2][PACKETBLOBS];
  105998. int coupling_prepointamp[PACKETBLOBS];
  105999. int coupling_postpointamp[PACKETBLOBS];
  106000. int sliding_lowpass[2][PACKETBLOBS];
  106001. } vorbis_info_psy_global;
  106002. typedef struct {
  106003. float ampmax;
  106004. int channels;
  106005. vorbis_info_psy_global *gi;
  106006. int coupling_pointlimit[2][P_NOISECURVES];
  106007. } vorbis_look_psy_global;
  106008. typedef struct {
  106009. int n;
  106010. struct vorbis_info_psy *vi;
  106011. float ***tonecurves;
  106012. float **noiseoffset;
  106013. float *ath;
  106014. long *octave; /* in n.ocshift format */
  106015. long *bark;
  106016. long firstoc;
  106017. long shiftoc;
  106018. int eighth_octave_lines; /* power of two, please */
  106019. int total_octave_lines;
  106020. long rate; /* cache it */
  106021. float m_val; /* Masking compensation value */
  106022. } vorbis_look_psy;
  106023. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  106024. vorbis_info_psy_global *gi,int n,long rate);
  106025. extern void _vp_psy_clear(vorbis_look_psy *p);
  106026. extern void *_vi_psy_dup(void *source);
  106027. extern void _vi_psy_free(vorbis_info_psy *i);
  106028. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  106029. extern void _vp_remove_floor(vorbis_look_psy *p,
  106030. float *mdct,
  106031. int *icodedflr,
  106032. float *residue,
  106033. int sliding_lowpass);
  106034. extern void _vp_noisemask(vorbis_look_psy *p,
  106035. float *logmdct,
  106036. float *logmask);
  106037. extern void _vp_tonemask(vorbis_look_psy *p,
  106038. float *logfft,
  106039. float *logmask,
  106040. float global_specmax,
  106041. float local_specmax);
  106042. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  106043. float *noise,
  106044. float *tone,
  106045. int offset_select,
  106046. float *logmask,
  106047. float *mdct,
  106048. float *logmdct);
  106049. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  106050. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  106051. vorbis_info_psy_global *g,
  106052. vorbis_look_psy *p,
  106053. vorbis_info_mapping0 *vi,
  106054. float **mdct);
  106055. extern void _vp_couple(int blobno,
  106056. vorbis_info_psy_global *g,
  106057. vorbis_look_psy *p,
  106058. vorbis_info_mapping0 *vi,
  106059. float **res,
  106060. float **mag_memo,
  106061. int **mag_sort,
  106062. int **ifloor,
  106063. int *nonzero,
  106064. int sliding_lowpass);
  106065. extern void _vp_noise_normalize(vorbis_look_psy *p,
  106066. float *in,float *out,int *sortedindex);
  106067. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  106068. float *magnitudes,int *sortedindex);
  106069. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  106070. vorbis_look_psy *p,
  106071. vorbis_info_mapping0 *vi,
  106072. float **mags);
  106073. extern void hf_reduction(vorbis_info_psy_global *g,
  106074. vorbis_look_psy *p,
  106075. vorbis_info_mapping0 *vi,
  106076. float **mdct);
  106077. #endif
  106078. /********* End of inlined file: psy.h *********/
  106079. /********* Start of inlined file: bitrate.h *********/
  106080. #ifndef _V_BITRATE_H_
  106081. #define _V_BITRATE_H_
  106082. /********* Start of inlined file: os.h *********/
  106083. #ifndef _OS_H
  106084. #define _OS_H
  106085. /********************************************************************
  106086. * *
  106087. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  106088. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  106089. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  106090. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  106091. * *
  106092. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  106093. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  106094. * *
  106095. ********************************************************************
  106096. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  106097. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  106098. ********************************************************************/
  106099. #ifdef HAVE_CONFIG_H
  106100. #include "config.h"
  106101. #endif
  106102. #include <math.h>
  106103. /********* Start of inlined file: misc.h *********/
  106104. #ifndef _V_RANDOM_H_
  106105. #define _V_RANDOM_H_
  106106. extern int analysis_noisy;
  106107. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  106108. extern void _vorbis_block_ripcord(vorbis_block *vb);
  106109. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106110. ogg_int64_t off);
  106111. #ifdef DEBUG_MALLOC
  106112. #define _VDBG_GRAPHFILE "malloc.m"
  106113. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  106114. extern void _VDBG_free(void *ptr,char *file,long line);
  106115. #ifndef MISC_C
  106116. #undef _ogg_malloc
  106117. #undef _ogg_calloc
  106118. #undef _ogg_realloc
  106119. #undef _ogg_free
  106120. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  106121. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  106122. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  106123. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  106124. #endif
  106125. #endif
  106126. #endif
  106127. /********* End of inlined file: misc.h *********/
  106128. #ifndef _V_IFDEFJAIL_H_
  106129. # define _V_IFDEFJAIL_H_
  106130. # ifdef __GNUC__
  106131. # define STIN static __inline__
  106132. # elif _WIN32
  106133. # define STIN static __inline
  106134. # else
  106135. # define STIN static
  106136. # endif
  106137. #ifdef DJGPP
  106138. # define rint(x) (floor((x)+0.5f))
  106139. #endif
  106140. #ifndef M_PI
  106141. # define M_PI (3.1415926536f)
  106142. #endif
  106143. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  106144. # include <malloc.h>
  106145. # define rint(x) (floor((x)+0.5f))
  106146. # define NO_FLOAT_MATH_LIB
  106147. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  106148. #endif
  106149. #if defined(__SYMBIAN32__) && defined(__WINS__)
  106150. void *_alloca(size_t size);
  106151. # define alloca _alloca
  106152. #endif
  106153. #ifndef FAST_HYPOT
  106154. # define FAST_HYPOT hypot
  106155. #endif
  106156. #endif
  106157. #ifdef HAVE_ALLOCA_H
  106158. # include <alloca.h>
  106159. #endif
  106160. #ifdef USE_MEMORY_H
  106161. # include <memory.h>
  106162. #endif
  106163. #ifndef min
  106164. # define min(x,y) ((x)>(y)?(y):(x))
  106165. #endif
  106166. #ifndef max
  106167. # define max(x,y) ((x)<(y)?(y):(x))
  106168. #endif
  106169. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  106170. # define VORBIS_FPU_CONTROL
  106171. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  106172. Because of encapsulation constraints (GCC can't see inside the asm
  106173. block and so we end up doing stupid things like a store/load that
  106174. is collectively a noop), we do it this way */
  106175. /* we must set up the fpu before this works!! */
  106176. typedef ogg_int16_t vorbis_fpu_control;
  106177. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106178. ogg_int16_t ret;
  106179. ogg_int16_t temp;
  106180. __asm__ __volatile__("fnstcw %0\n\t"
  106181. "movw %0,%%dx\n\t"
  106182. "orw $62463,%%dx\n\t"
  106183. "movw %%dx,%1\n\t"
  106184. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  106185. *fpu=ret;
  106186. }
  106187. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106188. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  106189. }
  106190. /* assumes the FPU is in round mode! */
  106191. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  106192. we get extra fst/fld to
  106193. truncate precision */
  106194. int i;
  106195. __asm__("fistl %0": "=m"(i) : "t"(f));
  106196. return(i);
  106197. }
  106198. #endif
  106199. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  106200. # define VORBIS_FPU_CONTROL
  106201. typedef ogg_int16_t vorbis_fpu_control;
  106202. static __inline int vorbis_ftoi(double f){
  106203. int i;
  106204. __asm{
  106205. fld f
  106206. fistp i
  106207. }
  106208. return i;
  106209. }
  106210. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106211. }
  106212. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106213. }
  106214. #endif
  106215. #ifndef VORBIS_FPU_CONTROL
  106216. typedef int vorbis_fpu_control;
  106217. static int vorbis_ftoi(double f){
  106218. return (int)(f+.5);
  106219. }
  106220. /* We don't have special code for this compiler/arch, so do it the slow way */
  106221. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  106222. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  106223. #endif
  106224. #endif /* _OS_H */
  106225. /********* End of inlined file: os.h *********/
  106226. /* encode side bitrate tracking */
  106227. typedef struct bitrate_manager_state {
  106228. int managed;
  106229. long avg_reservoir;
  106230. long minmax_reservoir;
  106231. long avg_bitsper;
  106232. long min_bitsper;
  106233. long max_bitsper;
  106234. long short_per_long;
  106235. double avgfloat;
  106236. vorbis_block *vb;
  106237. int choice;
  106238. } bitrate_manager_state;
  106239. typedef struct bitrate_manager_info{
  106240. long avg_rate;
  106241. long min_rate;
  106242. long max_rate;
  106243. long reservoir_bits;
  106244. double reservoir_bias;
  106245. double slew_damp;
  106246. } bitrate_manager_info;
  106247. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  106248. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  106249. extern int vorbis_bitrate_managed(vorbis_block *vb);
  106250. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106251. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  106252. #endif
  106253. /********* End of inlined file: bitrate.h *********/
  106254. static int ilog(unsigned int v){
  106255. int ret=0;
  106256. while(v){
  106257. ret++;
  106258. v>>=1;
  106259. }
  106260. return(ret);
  106261. }
  106262. static int ilog2(unsigned int v){
  106263. int ret=0;
  106264. if(v)--v;
  106265. while(v){
  106266. ret++;
  106267. v>>=1;
  106268. }
  106269. return(ret);
  106270. }
  106271. typedef struct private_state {
  106272. /* local lookup storage */
  106273. envelope_lookup *ve; /* envelope lookup */
  106274. int window[2];
  106275. vorbis_look_transform **transform[2]; /* block, type */
  106276. drft_lookup fft_look[2];
  106277. int modebits;
  106278. vorbis_look_floor **flr;
  106279. vorbis_look_residue **residue;
  106280. vorbis_look_psy *psy;
  106281. vorbis_look_psy_global *psy_g_look;
  106282. /* local storage, only used on the encoding side. This way the
  106283. application does not need to worry about freeing some packets'
  106284. memory and not others'; packet storage is always tracked.
  106285. Cleared next call to a _dsp_ function */
  106286. unsigned char *header;
  106287. unsigned char *header1;
  106288. unsigned char *header2;
  106289. bitrate_manager_state bms;
  106290. ogg_int64_t sample_count;
  106291. } private_state;
  106292. /* codec_setup_info contains all the setup information specific to the
  106293. specific compression/decompression mode in progress (eg,
  106294. psychoacoustic settings, channel setup, options, codebook
  106295. etc).
  106296. *********************************************************************/
  106297. /********* Start of inlined file: highlevel.h *********/
  106298. typedef struct highlevel_byblocktype {
  106299. double tone_mask_setting;
  106300. double tone_peaklimit_setting;
  106301. double noise_bias_setting;
  106302. double noise_compand_setting;
  106303. } highlevel_byblocktype;
  106304. typedef struct highlevel_encode_setup {
  106305. void *setup;
  106306. int set_in_stone;
  106307. double base_setting;
  106308. double long_setting;
  106309. double short_setting;
  106310. double impulse_noisetune;
  106311. int managed;
  106312. long bitrate_min;
  106313. long bitrate_av;
  106314. double bitrate_av_damp;
  106315. long bitrate_max;
  106316. long bitrate_reservoir;
  106317. double bitrate_reservoir_bias;
  106318. int impulse_block_p;
  106319. int noise_normalize_p;
  106320. double stereo_point_setting;
  106321. double lowpass_kHz;
  106322. double ath_floating_dB;
  106323. double ath_absolute_dB;
  106324. double amplitude_track_dBpersec;
  106325. double trigger_setting;
  106326. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  106327. } highlevel_encode_setup;
  106328. /********* End of inlined file: highlevel.h *********/
  106329. typedef struct codec_setup_info {
  106330. /* Vorbis supports only short and long blocks, but allows the
  106331. encoder to choose the sizes */
  106332. long blocksizes[2];
  106333. /* modes are the primary means of supporting on-the-fly different
  106334. blocksizes, different channel mappings (LR or M/A),
  106335. different residue backends, etc. Each mode consists of a
  106336. blocksize flag and a mapping (along with the mapping setup */
  106337. int modes;
  106338. int maps;
  106339. int floors;
  106340. int residues;
  106341. int books;
  106342. int psys; /* encode only */
  106343. vorbis_info_mode *mode_param[64];
  106344. int map_type[64];
  106345. vorbis_info_mapping *map_param[64];
  106346. int floor_type[64];
  106347. vorbis_info_floor *floor_param[64];
  106348. int residue_type[64];
  106349. vorbis_info_residue *residue_param[64];
  106350. static_codebook *book_param[256];
  106351. codebook *fullbooks;
  106352. vorbis_info_psy *psy_param[4]; /* encode only */
  106353. vorbis_info_psy_global psy_g_param;
  106354. bitrate_manager_info bi;
  106355. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  106356. highly redundant structure, but
  106357. improves clarity of program flow. */
  106358. int halfrate_flag; /* painless downsample for decode */
  106359. } codec_setup_info;
  106360. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  106361. extern void _vp_global_free(vorbis_look_psy_global *look);
  106362. #endif
  106363. /********* End of inlined file: codec_internal.h *********/
  106364. /********* Start of inlined file: registry.h *********/
  106365. #ifndef _V_REG_H_
  106366. #define _V_REG_H_
  106367. #define VI_TRANSFORMB 1
  106368. #define VI_WINDOWB 1
  106369. #define VI_TIMEB 1
  106370. #define VI_FLOORB 2
  106371. #define VI_RESB 3
  106372. #define VI_MAPB 1
  106373. extern vorbis_func_floor *_floor_P[];
  106374. extern vorbis_func_residue *_residue_P[];
  106375. extern vorbis_func_mapping *_mapping_P[];
  106376. #endif
  106377. /********* End of inlined file: registry.h *********/
  106378. /********* Start of inlined file: scales.h *********/
  106379. #ifndef _V_SCALES_H_
  106380. #define _V_SCALES_H_
  106381. #include <math.h>
  106382. /* 20log10(x) */
  106383. #define VORBIS_IEEE_FLOAT32 1
  106384. #ifdef VORBIS_IEEE_FLOAT32
  106385. static float unitnorm(float x){
  106386. union {
  106387. ogg_uint32_t i;
  106388. float f;
  106389. } ix;
  106390. ix.f = x;
  106391. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  106392. return ix.f;
  106393. }
  106394. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  106395. static float todB(const float *x){
  106396. union {
  106397. ogg_uint32_t i;
  106398. float f;
  106399. } ix;
  106400. ix.f = *x;
  106401. ix.i = ix.i&0x7fffffff;
  106402. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  106403. }
  106404. #define todB_nn(x) todB(x)
  106405. #else
  106406. static float unitnorm(float x){
  106407. if(x<0)return(-1.f);
  106408. return(1.f);
  106409. }
  106410. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  106411. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  106412. #endif
  106413. #define fromdB(x) (exp((x)*.11512925f))
  106414. /* The bark scale equations are approximations, since the original
  106415. table was somewhat hand rolled. The below are chosen to have the
  106416. best possible fit to the rolled tables, thus their somewhat odd
  106417. appearance (these are more accurate and over a longer range than
  106418. the oft-quoted bark equations found in the texts I have). The
  106419. approximations are valid from 0 - 30kHz (nyquist) or so.
  106420. all f in Hz, z in Bark */
  106421. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  106422. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  106423. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  106424. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  106425. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  106426. 0.0 */
  106427. #define toOC(n) (log(n)*1.442695f-5.965784f)
  106428. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  106429. #endif
  106430. /********* End of inlined file: scales.h *********/
  106431. int analysis_noisy=1;
  106432. /* decides between modes, dispatches to the appropriate mapping. */
  106433. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  106434. int ret,i;
  106435. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106436. vb->glue_bits=0;
  106437. vb->time_bits=0;
  106438. vb->floor_bits=0;
  106439. vb->res_bits=0;
  106440. /* first things first. Make sure encode is ready */
  106441. for(i=0;i<PACKETBLOBS;i++)
  106442. oggpack_reset(vbi->packetblob[i]);
  106443. /* we only have one mapping type (0), and we let the mapping code
  106444. itself figure out what soft mode to use. This allows easier
  106445. bitrate management */
  106446. if((ret=_mapping_P[0]->forward(vb)))
  106447. return(ret);
  106448. if(op){
  106449. if(vorbis_bitrate_managed(vb))
  106450. /* The app is using a bitmanaged mode... but not using the
  106451. bitrate management interface. */
  106452. return(OV_EINVAL);
  106453. op->packet=oggpack_get_buffer(&vb->opb);
  106454. op->bytes=oggpack_bytes(&vb->opb);
  106455. op->b_o_s=0;
  106456. op->e_o_s=vb->eofflag;
  106457. op->granulepos=vb->granulepos;
  106458. op->packetno=vb->sequence; /* for sake of completeness */
  106459. }
  106460. return(0);
  106461. }
  106462. /* there was no great place to put this.... */
  106463. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  106464. int j;
  106465. FILE *of;
  106466. char buffer[80];
  106467. /* if(i==5870){*/
  106468. sprintf(buffer,"%s_%d.m",base,i);
  106469. of=fopen(buffer,"w");
  106470. if(!of)perror("failed to open data dump file");
  106471. for(j=0;j<n;j++){
  106472. if(bark){
  106473. float b=toBARK((4000.f*j/n)+.25);
  106474. fprintf(of,"%f ",b);
  106475. }else
  106476. if(off!=0)
  106477. fprintf(of,"%f ",(double)(j+off)/8000.);
  106478. else
  106479. fprintf(of,"%f ",(double)j);
  106480. if(dB){
  106481. float val;
  106482. if(v[j]==0.)
  106483. val=-140.;
  106484. else
  106485. val=todB(v+j);
  106486. fprintf(of,"%f\n",val);
  106487. }else{
  106488. fprintf(of,"%f\n",v[j]);
  106489. }
  106490. }
  106491. fclose(of);
  106492. /* } */
  106493. }
  106494. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106495. ogg_int64_t off){
  106496. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  106497. }
  106498. #endif
  106499. /********* End of inlined file: analysis.c *********/
  106500. /********* Start of inlined file: bitrate.c *********/
  106501. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106502. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106503. // tasks..
  106504. #if JUCE_MSVC
  106505. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106506. #endif
  106507. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106508. #if JUCE_USE_OGGVORBIS
  106509. #include <stdlib.h>
  106510. #include <string.h>
  106511. #include <math.h>
  106512. /* compute bitrate tracking setup */
  106513. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  106514. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106515. bitrate_manager_info *bi=&ci->bi;
  106516. memset(bm,0,sizeof(*bm));
  106517. if(bi && (bi->reservoir_bits>0)){
  106518. long ratesamples=vi->rate;
  106519. int halfsamples=ci->blocksizes[0]>>1;
  106520. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  106521. bm->managed=1;
  106522. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  106523. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  106524. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  106525. bm->avgfloat=PACKETBLOBS/2;
  106526. /* not a necessary fix, but one that leads to a more balanced
  106527. typical initialization */
  106528. {
  106529. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106530. bm->minmax_reservoir=desired_fill;
  106531. bm->avg_reservoir=desired_fill;
  106532. }
  106533. }
  106534. }
  106535. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  106536. memset(bm,0,sizeof(*bm));
  106537. return;
  106538. }
  106539. int vorbis_bitrate_managed(vorbis_block *vb){
  106540. vorbis_dsp_state *vd=vb->vd;
  106541. private_state *b=(private_state*)vd->backend_state;
  106542. bitrate_manager_state *bm=&b->bms;
  106543. if(bm && bm->managed)return(1);
  106544. return(0);
  106545. }
  106546. /* finish taking in the block we just processed */
  106547. int vorbis_bitrate_addblock(vorbis_block *vb){
  106548. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106549. vorbis_dsp_state *vd=vb->vd;
  106550. private_state *b=(private_state*)vd->backend_state;
  106551. bitrate_manager_state *bm=&b->bms;
  106552. vorbis_info *vi=vd->vi;
  106553. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106554. bitrate_manager_info *bi=&ci->bi;
  106555. int choice=rint(bm->avgfloat);
  106556. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106557. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  106558. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  106559. int samples=ci->blocksizes[vb->W]>>1;
  106560. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106561. if(!bm->managed){
  106562. /* not a bitrate managed stream, but for API simplicity, we'll
  106563. buffer the packet to keep the code path clean */
  106564. if(bm->vb)return(-1); /* one has been submitted without
  106565. being claimed */
  106566. bm->vb=vb;
  106567. return(0);
  106568. }
  106569. bm->vb=vb;
  106570. /* look ahead for avg floater */
  106571. if(bm->avg_bitsper>0){
  106572. double slew=0.;
  106573. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106574. double slewlimit= 15./bi->slew_damp;
  106575. /* choosing a new floater:
  106576. if we're over target, we slew down
  106577. if we're under target, we slew up
  106578. choose slew as follows: look through packetblobs of this frame
  106579. and set slew as the first in the appropriate direction that
  106580. gives us the slew we want. This may mean no slew if delta is
  106581. already favorable.
  106582. Then limit slew to slew max */
  106583. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106584. while(choice>0 && this_bits>avg_target_bits &&
  106585. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106586. choice--;
  106587. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106588. }
  106589. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106590. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  106591. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106592. choice++;
  106593. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106594. }
  106595. }
  106596. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  106597. if(slew<-slewlimit)slew=-slewlimit;
  106598. if(slew>slewlimit)slew=slewlimit;
  106599. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  106600. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106601. }
  106602. /* enforce min(if used) on the current floater (if used) */
  106603. if(bm->min_bitsper>0){
  106604. /* do we need to force the bitrate up? */
  106605. if(this_bits<min_target_bits){
  106606. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  106607. choice++;
  106608. if(choice>=PACKETBLOBS)break;
  106609. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106610. }
  106611. }
  106612. }
  106613. /* enforce max (if used) on the current floater (if used) */
  106614. if(bm->max_bitsper>0){
  106615. /* do we need to force the bitrate down? */
  106616. if(this_bits>max_target_bits){
  106617. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  106618. choice--;
  106619. if(choice<0)break;
  106620. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106621. }
  106622. }
  106623. }
  106624. /* Choice of packetblobs now made based on floater, and min/max
  106625. requirements. Now boundary check extreme choices */
  106626. if(choice<0){
  106627. /* choosing a smaller packetblob is insufficient to trim bitrate.
  106628. frame will need to be truncated */
  106629. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  106630. bm->choice=choice=0;
  106631. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  106632. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  106633. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106634. }
  106635. }else{
  106636. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  106637. if(choice>=PACKETBLOBS)
  106638. choice=PACKETBLOBS-1;
  106639. bm->choice=choice;
  106640. /* prop up bitrate according to demand. pad this frame out with zeroes */
  106641. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  106642. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  106643. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106644. }
  106645. /* now we have the final packet and the final packet size. Update statistics */
  106646. /* min and max reservoir */
  106647. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  106648. if(max_target_bits>0 && this_bits>max_target_bits){
  106649. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106650. }else if(min_target_bits>0 && this_bits<min_target_bits){
  106651. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106652. }else{
  106653. /* inbetween; we want to take reservoir toward but not past desired_fill */
  106654. if(bm->minmax_reservoir>desired_fill){
  106655. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  106656. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106657. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  106658. }else{
  106659. bm->minmax_reservoir=desired_fill;
  106660. }
  106661. }else{
  106662. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  106663. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106664. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  106665. }else{
  106666. bm->minmax_reservoir=desired_fill;
  106667. }
  106668. }
  106669. }
  106670. }
  106671. /* avg reservoir */
  106672. if(bm->avg_bitsper>0){
  106673. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106674. bm->avg_reservoir+=this_bits-avg_target_bits;
  106675. }
  106676. return(0);
  106677. }
  106678. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  106679. private_state *b=(private_state*)vd->backend_state;
  106680. bitrate_manager_state *bm=&b->bms;
  106681. vorbis_block *vb=bm->vb;
  106682. int choice=PACKETBLOBS/2;
  106683. if(!vb)return 0;
  106684. if(op){
  106685. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106686. if(vorbis_bitrate_managed(vb))
  106687. choice=bm->choice;
  106688. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  106689. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  106690. op->b_o_s=0;
  106691. op->e_o_s=vb->eofflag;
  106692. op->granulepos=vb->granulepos;
  106693. op->packetno=vb->sequence; /* for sake of completeness */
  106694. }
  106695. bm->vb=0;
  106696. return(1);
  106697. }
  106698. #endif
  106699. /********* End of inlined file: bitrate.c *********/
  106700. /********* Start of inlined file: block.c *********/
  106701. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106702. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106703. // tasks..
  106704. #if JUCE_MSVC
  106705. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106706. #endif
  106707. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106708. #if JUCE_USE_OGGVORBIS
  106709. #include <stdio.h>
  106710. #include <stdlib.h>
  106711. #include <string.h>
  106712. /********* Start of inlined file: window.h *********/
  106713. #ifndef _V_WINDOW_
  106714. #define _V_WINDOW_
  106715. extern float *_vorbis_window_get(int n);
  106716. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  106717. int lW,int W,int nW);
  106718. #endif
  106719. /********* End of inlined file: window.h *********/
  106720. /********* Start of inlined file: lpc.h *********/
  106721. #ifndef _V_LPC_H_
  106722. #define _V_LPC_H_
  106723. /* simple linear scale LPC code */
  106724. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  106725. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  106726. float *data,long n);
  106727. #endif
  106728. /********* End of inlined file: lpc.h *********/
  106729. /* pcm accumulator examples (not exhaustive):
  106730. <-------------- lW ---------------->
  106731. <--------------- W ---------------->
  106732. : .....|..... _______________ |
  106733. : .''' | '''_--- | |\ |
  106734. :.....''' |_____--- '''......| | \_______|
  106735. :.................|__________________|_______|__|______|
  106736. |<------ Sl ------>| > Sr < |endW
  106737. |beginSl |endSl | |endSr
  106738. |beginW |endlW |beginSr
  106739. |< lW >|
  106740. <--------------- W ---------------->
  106741. | | .. ______________ |
  106742. | | ' `/ | ---_ |
  106743. |___.'___/`. | ---_____|
  106744. |_______|__|_______|_________________|
  106745. | >|Sl|< |<------ Sr ----->|endW
  106746. | | |endSl |beginSr |endSr
  106747. |beginW | |endlW
  106748. mult[0] |beginSl mult[n]
  106749. <-------------- lW ----------------->
  106750. |<--W-->|
  106751. : .............. ___ | |
  106752. : .''' |`/ \ | |
  106753. :.....''' |/`....\|...|
  106754. :.........................|___|___|___|
  106755. |Sl |Sr |endW
  106756. | | |endSr
  106757. | |beginSr
  106758. | |endSl
  106759. |beginSl
  106760. |beginW
  106761. */
  106762. /* block abstraction setup *********************************************/
  106763. #ifndef WORD_ALIGN
  106764. #define WORD_ALIGN 8
  106765. #endif
  106766. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  106767. int i;
  106768. memset(vb,0,sizeof(*vb));
  106769. vb->vd=v;
  106770. vb->localalloc=0;
  106771. vb->localstore=NULL;
  106772. if(v->analysisp){
  106773. vorbis_block_internal *vbi=(vorbis_block_internal*)
  106774. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  106775. vbi->ampmax=-9999;
  106776. for(i=0;i<PACKETBLOBS;i++){
  106777. if(i==PACKETBLOBS/2){
  106778. vbi->packetblob[i]=&vb->opb;
  106779. }else{
  106780. vbi->packetblob[i]=
  106781. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  106782. }
  106783. oggpack_writeinit(vbi->packetblob[i]);
  106784. }
  106785. }
  106786. return(0);
  106787. }
  106788. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  106789. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  106790. if(bytes+vb->localtop>vb->localalloc){
  106791. /* can't just _ogg_realloc... there are outstanding pointers */
  106792. if(vb->localstore){
  106793. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  106794. vb->totaluse+=vb->localtop;
  106795. link->next=vb->reap;
  106796. link->ptr=vb->localstore;
  106797. vb->reap=link;
  106798. }
  106799. /* highly conservative */
  106800. vb->localalloc=bytes;
  106801. vb->localstore=_ogg_malloc(vb->localalloc);
  106802. vb->localtop=0;
  106803. }
  106804. {
  106805. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  106806. vb->localtop+=bytes;
  106807. return ret;
  106808. }
  106809. }
  106810. /* reap the chain, pull the ripcord */
  106811. void _vorbis_block_ripcord(vorbis_block *vb){
  106812. /* reap the chain */
  106813. struct alloc_chain *reap=vb->reap;
  106814. while(reap){
  106815. struct alloc_chain *next=reap->next;
  106816. _ogg_free(reap->ptr);
  106817. memset(reap,0,sizeof(*reap));
  106818. _ogg_free(reap);
  106819. reap=next;
  106820. }
  106821. /* consolidate storage */
  106822. if(vb->totaluse){
  106823. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  106824. vb->localalloc+=vb->totaluse;
  106825. vb->totaluse=0;
  106826. }
  106827. /* pull the ripcord */
  106828. vb->localtop=0;
  106829. vb->reap=NULL;
  106830. }
  106831. int vorbis_block_clear(vorbis_block *vb){
  106832. int i;
  106833. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106834. _vorbis_block_ripcord(vb);
  106835. if(vb->localstore)_ogg_free(vb->localstore);
  106836. if(vbi){
  106837. for(i=0;i<PACKETBLOBS;i++){
  106838. oggpack_writeclear(vbi->packetblob[i]);
  106839. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  106840. }
  106841. _ogg_free(vbi);
  106842. }
  106843. memset(vb,0,sizeof(*vb));
  106844. return(0);
  106845. }
  106846. /* Analysis side code, but directly related to blocking. Thus it's
  106847. here and not in analysis.c (which is for analysis transforms only).
  106848. The init is here because some of it is shared */
  106849. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  106850. int i;
  106851. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106852. private_state *b=NULL;
  106853. int hs;
  106854. if(ci==NULL) return 1;
  106855. hs=ci->halfrate_flag;
  106856. memset(v,0,sizeof(*v));
  106857. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  106858. v->vi=vi;
  106859. b->modebits=ilog2(ci->modes);
  106860. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  106861. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  106862. /* MDCT is tranform 0 */
  106863. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106864. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106865. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  106866. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  106867. /* Vorbis I uses only window type 0 */
  106868. b->window[0]=ilog2(ci->blocksizes[0])-6;
  106869. b->window[1]=ilog2(ci->blocksizes[1])-6;
  106870. if(encp){ /* encode/decode differ here */
  106871. /* analysis always needs an fft */
  106872. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  106873. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  106874. /* finish the codebooks */
  106875. if(!ci->fullbooks){
  106876. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106877. for(i=0;i<ci->books;i++)
  106878. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  106879. }
  106880. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  106881. for(i=0;i<ci->psys;i++){
  106882. _vp_psy_init(b->psy+i,
  106883. ci->psy_param[i],
  106884. &ci->psy_g_param,
  106885. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  106886. vi->rate);
  106887. }
  106888. v->analysisp=1;
  106889. }else{
  106890. /* finish the codebooks */
  106891. if(!ci->fullbooks){
  106892. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106893. for(i=0;i<ci->books;i++){
  106894. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  106895. /* decode codebooks are now standalone after init */
  106896. vorbis_staticbook_destroy(ci->book_param[i]);
  106897. ci->book_param[i]=NULL;
  106898. }
  106899. }
  106900. }
  106901. /* initialize the storage vectors. blocksize[1] is small for encode,
  106902. but the correct size for decode */
  106903. v->pcm_storage=ci->blocksizes[1];
  106904. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  106905. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  106906. {
  106907. int i;
  106908. for(i=0;i<vi->channels;i++)
  106909. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  106910. }
  106911. /* all 1 (large block) or 0 (small block) */
  106912. /* explicitly set for the sake of clarity */
  106913. v->lW=0; /* previous window size */
  106914. v->W=0; /* current window size */
  106915. /* all vector indexes */
  106916. v->centerW=ci->blocksizes[1]/2;
  106917. v->pcm_current=v->centerW;
  106918. /* initialize all the backend lookups */
  106919. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  106920. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  106921. for(i=0;i<ci->floors;i++)
  106922. b->flr[i]=_floor_P[ci->floor_type[i]]->
  106923. look(v,ci->floor_param[i]);
  106924. for(i=0;i<ci->residues;i++)
  106925. b->residue[i]=_residue_P[ci->residue_type[i]]->
  106926. look(v,ci->residue_param[i]);
  106927. return 0;
  106928. }
  106929. /* arbitrary settings and spec-mandated numbers get filled in here */
  106930. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106931. private_state *b=NULL;
  106932. if(_vds_shared_init(v,vi,1))return 1;
  106933. b=(private_state*)v->backend_state;
  106934. b->psy_g_look=_vp_global_look(vi);
  106935. /* Initialize the envelope state storage */
  106936. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  106937. _ve_envelope_init(b->ve,vi);
  106938. vorbis_bitrate_init(vi,&b->bms);
  106939. /* compressed audio packets start after the headers
  106940. with sequence number 3 */
  106941. v->sequence=3;
  106942. return(0);
  106943. }
  106944. void vorbis_dsp_clear(vorbis_dsp_state *v){
  106945. int i;
  106946. if(v){
  106947. vorbis_info *vi=v->vi;
  106948. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  106949. private_state *b=(private_state*)v->backend_state;
  106950. if(b){
  106951. if(b->ve){
  106952. _ve_envelope_clear(b->ve);
  106953. _ogg_free(b->ve);
  106954. }
  106955. if(b->transform[0]){
  106956. mdct_clear((mdct_lookup*) b->transform[0][0]);
  106957. _ogg_free(b->transform[0][0]);
  106958. _ogg_free(b->transform[0]);
  106959. }
  106960. if(b->transform[1]){
  106961. mdct_clear((mdct_lookup*) b->transform[1][0]);
  106962. _ogg_free(b->transform[1][0]);
  106963. _ogg_free(b->transform[1]);
  106964. }
  106965. if(b->flr){
  106966. for(i=0;i<ci->floors;i++)
  106967. _floor_P[ci->floor_type[i]]->
  106968. free_look(b->flr[i]);
  106969. _ogg_free(b->flr);
  106970. }
  106971. if(b->residue){
  106972. for(i=0;i<ci->residues;i++)
  106973. _residue_P[ci->residue_type[i]]->
  106974. free_look(b->residue[i]);
  106975. _ogg_free(b->residue);
  106976. }
  106977. if(b->psy){
  106978. for(i=0;i<ci->psys;i++)
  106979. _vp_psy_clear(b->psy+i);
  106980. _ogg_free(b->psy);
  106981. }
  106982. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  106983. vorbis_bitrate_clear(&b->bms);
  106984. drft_clear(&b->fft_look[0]);
  106985. drft_clear(&b->fft_look[1]);
  106986. }
  106987. if(v->pcm){
  106988. for(i=0;i<vi->channels;i++)
  106989. if(v->pcm[i])_ogg_free(v->pcm[i]);
  106990. _ogg_free(v->pcm);
  106991. if(v->pcmret)_ogg_free(v->pcmret);
  106992. }
  106993. if(b){
  106994. /* free header, header1, header2 */
  106995. if(b->header)_ogg_free(b->header);
  106996. if(b->header1)_ogg_free(b->header1);
  106997. if(b->header2)_ogg_free(b->header2);
  106998. _ogg_free(b);
  106999. }
  107000. memset(v,0,sizeof(*v));
  107001. }
  107002. }
  107003. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  107004. int i;
  107005. vorbis_info *vi=v->vi;
  107006. private_state *b=(private_state*)v->backend_state;
  107007. /* free header, header1, header2 */
  107008. if(b->header)_ogg_free(b->header);b->header=NULL;
  107009. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  107010. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  107011. /* Do we have enough storage space for the requested buffer? If not,
  107012. expand the PCM (and envelope) storage */
  107013. if(v->pcm_current+vals>=v->pcm_storage){
  107014. v->pcm_storage=v->pcm_current+vals*2;
  107015. for(i=0;i<vi->channels;i++){
  107016. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  107017. }
  107018. }
  107019. for(i=0;i<vi->channels;i++)
  107020. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  107021. return(v->pcmret);
  107022. }
  107023. static void _preextrapolate_helper(vorbis_dsp_state *v){
  107024. int i;
  107025. int order=32;
  107026. float *lpc=(float*)alloca(order*sizeof(*lpc));
  107027. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  107028. long j;
  107029. v->preextrapolate=1;
  107030. if(v->pcm_current-v->centerW>order*2){ /* safety */
  107031. for(i=0;i<v->vi->channels;i++){
  107032. /* need to run the extrapolation in reverse! */
  107033. for(j=0;j<v->pcm_current;j++)
  107034. work[j]=v->pcm[i][v->pcm_current-j-1];
  107035. /* prime as above */
  107036. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  107037. /* run the predictor filter */
  107038. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  107039. order,
  107040. work+v->pcm_current-v->centerW,
  107041. v->centerW);
  107042. for(j=0;j<v->pcm_current;j++)
  107043. v->pcm[i][v->pcm_current-j-1]=work[j];
  107044. }
  107045. }
  107046. }
  107047. /* call with val<=0 to set eof */
  107048. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  107049. vorbis_info *vi=v->vi;
  107050. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107051. if(vals<=0){
  107052. int order=32;
  107053. int i;
  107054. float *lpc=(float*) alloca(order*sizeof(*lpc));
  107055. /* if it wasn't done earlier (very short sample) */
  107056. if(!v->preextrapolate)
  107057. _preextrapolate_helper(v);
  107058. /* We're encoding the end of the stream. Just make sure we have
  107059. [at least] a few full blocks of zeroes at the end. */
  107060. /* actually, we don't want zeroes; that could drop a large
  107061. amplitude off a cliff, creating spread spectrum noise that will
  107062. suck to encode. Extrapolate for the sake of cleanliness. */
  107063. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  107064. v->eofflag=v->pcm_current;
  107065. v->pcm_current+=ci->blocksizes[1]*3;
  107066. for(i=0;i<vi->channels;i++){
  107067. if(v->eofflag>order*2){
  107068. /* extrapolate with LPC to fill in */
  107069. long n;
  107070. /* make a predictor filter */
  107071. n=v->eofflag;
  107072. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  107073. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  107074. /* run the predictor filter */
  107075. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  107076. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  107077. }else{
  107078. /* not enough data to extrapolate (unlikely to happen due to
  107079. guarding the overlap, but bulletproof in case that
  107080. assumtion goes away). zeroes will do. */
  107081. memset(v->pcm[i]+v->eofflag,0,
  107082. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  107083. }
  107084. }
  107085. }else{
  107086. if(v->pcm_current+vals>v->pcm_storage)
  107087. return(OV_EINVAL);
  107088. v->pcm_current+=vals;
  107089. /* we may want to reverse extrapolate the beginning of a stream
  107090. too... in case we're beginning on a cliff! */
  107091. /* clumsy, but simple. It only runs once, so simple is good. */
  107092. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  107093. _preextrapolate_helper(v);
  107094. }
  107095. return(0);
  107096. }
  107097. /* do the deltas, envelope shaping, pre-echo and determine the size of
  107098. the next block on which to continue analysis */
  107099. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  107100. int i;
  107101. vorbis_info *vi=v->vi;
  107102. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107103. private_state *b=(private_state*)v->backend_state;
  107104. vorbis_look_psy_global *g=b->psy_g_look;
  107105. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  107106. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107107. /* check to see if we're started... */
  107108. if(!v->preextrapolate)return(0);
  107109. /* check to see if we're done... */
  107110. if(v->eofflag==-1)return(0);
  107111. /* By our invariant, we have lW, W and centerW set. Search for
  107112. the next boundary so we can determine nW (the next window size)
  107113. which lets us compute the shape of the current block's window */
  107114. /* we do an envelope search even on a single blocksize; we may still
  107115. be throwing more bits at impulses, and envelope search handles
  107116. marking impulses too. */
  107117. {
  107118. long bp=_ve_envelope_search(v);
  107119. if(bp==-1){
  107120. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  107121. full long block */
  107122. v->nW=0;
  107123. }else{
  107124. if(ci->blocksizes[0]==ci->blocksizes[1])
  107125. v->nW=0;
  107126. else
  107127. v->nW=bp;
  107128. }
  107129. }
  107130. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  107131. {
  107132. /* center of next block + next block maximum right side. */
  107133. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  107134. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  107135. although this check is
  107136. less strict that the
  107137. _ve_envelope_search,
  107138. the search is not run
  107139. if we only use one
  107140. block size */
  107141. }
  107142. /* fill in the block. Note that for a short window, lW and nW are *short*
  107143. regardless of actual settings in the stream */
  107144. _vorbis_block_ripcord(vb);
  107145. vb->lW=v->lW;
  107146. vb->W=v->W;
  107147. vb->nW=v->nW;
  107148. if(v->W){
  107149. if(!v->lW || !v->nW){
  107150. vbi->blocktype=BLOCKTYPE_TRANSITION;
  107151. /*fprintf(stderr,"-");*/
  107152. }else{
  107153. vbi->blocktype=BLOCKTYPE_LONG;
  107154. /*fprintf(stderr,"_");*/
  107155. }
  107156. }else{
  107157. if(_ve_envelope_mark(v)){
  107158. vbi->blocktype=BLOCKTYPE_IMPULSE;
  107159. /*fprintf(stderr,"|");*/
  107160. }else{
  107161. vbi->blocktype=BLOCKTYPE_PADDING;
  107162. /*fprintf(stderr,".");*/
  107163. }
  107164. }
  107165. vb->vd=v;
  107166. vb->sequence=v->sequence++;
  107167. vb->granulepos=v->granulepos;
  107168. vb->pcmend=ci->blocksizes[v->W];
  107169. /* copy the vectors; this uses the local storage in vb */
  107170. /* this tracks 'strongest peak' for later psychoacoustics */
  107171. /* moved to the global psy state; clean this mess up */
  107172. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  107173. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  107174. vbi->ampmax=g->ampmax;
  107175. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  107176. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  107177. for(i=0;i<vi->channels;i++){
  107178. vbi->pcmdelay[i]=
  107179. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107180. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107181. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  107182. /* before we added the delay
  107183. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  107184. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  107185. */
  107186. }
  107187. /* handle eof detection: eof==0 means that we've not yet received EOF
  107188. eof>0 marks the last 'real' sample in pcm[]
  107189. eof<0 'no more to do'; doesn't get here */
  107190. if(v->eofflag){
  107191. if(v->centerW>=v->eofflag){
  107192. v->eofflag=-1;
  107193. vb->eofflag=1;
  107194. return(1);
  107195. }
  107196. }
  107197. /* advance storage vectors and clean up */
  107198. {
  107199. int new_centerNext=ci->blocksizes[1]/2;
  107200. int movementW=centerNext-new_centerNext;
  107201. if(movementW>0){
  107202. _ve_envelope_shift(b->ve,movementW);
  107203. v->pcm_current-=movementW;
  107204. for(i=0;i<vi->channels;i++)
  107205. memmove(v->pcm[i],v->pcm[i]+movementW,
  107206. v->pcm_current*sizeof(*v->pcm[i]));
  107207. v->lW=v->W;
  107208. v->W=v->nW;
  107209. v->centerW=new_centerNext;
  107210. if(v->eofflag){
  107211. v->eofflag-=movementW;
  107212. if(v->eofflag<=0)v->eofflag=-1;
  107213. /* do not add padding to end of stream! */
  107214. if(v->centerW>=v->eofflag){
  107215. v->granulepos+=movementW-(v->centerW-v->eofflag);
  107216. }else{
  107217. v->granulepos+=movementW;
  107218. }
  107219. }else{
  107220. v->granulepos+=movementW;
  107221. }
  107222. }
  107223. }
  107224. /* done */
  107225. return(1);
  107226. }
  107227. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  107228. vorbis_info *vi=v->vi;
  107229. codec_setup_info *ci;
  107230. int hs;
  107231. if(!v->backend_state)return -1;
  107232. if(!vi)return -1;
  107233. ci=(codec_setup_info*) vi->codec_setup;
  107234. if(!ci)return -1;
  107235. hs=ci->halfrate_flag;
  107236. v->centerW=ci->blocksizes[1]>>(hs+1);
  107237. v->pcm_current=v->centerW>>hs;
  107238. v->pcm_returned=-1;
  107239. v->granulepos=-1;
  107240. v->sequence=-1;
  107241. v->eofflag=0;
  107242. ((private_state *)(v->backend_state))->sample_count=-1;
  107243. return(0);
  107244. }
  107245. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  107246. if(_vds_shared_init(v,vi,0)) return 1;
  107247. vorbis_synthesis_restart(v);
  107248. return 0;
  107249. }
  107250. /* Unlike in analysis, the window is only partially applied for each
  107251. block. The time domain envelope is not yet handled at the point of
  107252. calling (as it relies on the previous block). */
  107253. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  107254. vorbis_info *vi=v->vi;
  107255. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107256. private_state *b=(private_state*)v->backend_state;
  107257. int hs=ci->halfrate_flag;
  107258. int i,j;
  107259. if(!vb)return(OV_EINVAL);
  107260. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  107261. v->lW=v->W;
  107262. v->W=vb->W;
  107263. v->nW=-1;
  107264. if((v->sequence==-1)||
  107265. (v->sequence+1 != vb->sequence)){
  107266. v->granulepos=-1; /* out of sequence; lose count */
  107267. b->sample_count=-1;
  107268. }
  107269. v->sequence=vb->sequence;
  107270. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  107271. was called on block */
  107272. int n=ci->blocksizes[v->W]>>(hs+1);
  107273. int n0=ci->blocksizes[0]>>(hs+1);
  107274. int n1=ci->blocksizes[1]>>(hs+1);
  107275. int thisCenter;
  107276. int prevCenter;
  107277. v->glue_bits+=vb->glue_bits;
  107278. v->time_bits+=vb->time_bits;
  107279. v->floor_bits+=vb->floor_bits;
  107280. v->res_bits+=vb->res_bits;
  107281. if(v->centerW){
  107282. thisCenter=n1;
  107283. prevCenter=0;
  107284. }else{
  107285. thisCenter=0;
  107286. prevCenter=n1;
  107287. }
  107288. /* v->pcm is now used like a two-stage double buffer. We don't want
  107289. to have to constantly shift *or* adjust memory usage. Don't
  107290. accept a new block until the old is shifted out */
  107291. for(j=0;j<vi->channels;j++){
  107292. /* the overlap/add section */
  107293. if(v->lW){
  107294. if(v->W){
  107295. /* large/large */
  107296. float *w=_vorbis_window_get(b->window[1]-hs);
  107297. float *pcm=v->pcm[j]+prevCenter;
  107298. float *p=vb->pcm[j];
  107299. for(i=0;i<n1;i++)
  107300. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  107301. }else{
  107302. /* large/small */
  107303. float *w=_vorbis_window_get(b->window[0]-hs);
  107304. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  107305. float *p=vb->pcm[j];
  107306. for(i=0;i<n0;i++)
  107307. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107308. }
  107309. }else{
  107310. if(v->W){
  107311. /* small/large */
  107312. float *w=_vorbis_window_get(b->window[0]-hs);
  107313. float *pcm=v->pcm[j]+prevCenter;
  107314. float *p=vb->pcm[j]+n1/2-n0/2;
  107315. for(i=0;i<n0;i++)
  107316. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107317. for(;i<n1/2+n0/2;i++)
  107318. pcm[i]=p[i];
  107319. }else{
  107320. /* small/small */
  107321. float *w=_vorbis_window_get(b->window[0]-hs);
  107322. float *pcm=v->pcm[j]+prevCenter;
  107323. float *p=vb->pcm[j];
  107324. for(i=0;i<n0;i++)
  107325. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107326. }
  107327. }
  107328. /* the copy section */
  107329. {
  107330. float *pcm=v->pcm[j]+thisCenter;
  107331. float *p=vb->pcm[j]+n;
  107332. for(i=0;i<n;i++)
  107333. pcm[i]=p[i];
  107334. }
  107335. }
  107336. if(v->centerW)
  107337. v->centerW=0;
  107338. else
  107339. v->centerW=n1;
  107340. /* deal with initial packet state; we do this using the explicit
  107341. pcm_returned==-1 flag otherwise we're sensitive to first block
  107342. being short or long */
  107343. if(v->pcm_returned==-1){
  107344. v->pcm_returned=thisCenter;
  107345. v->pcm_current=thisCenter;
  107346. }else{
  107347. v->pcm_returned=prevCenter;
  107348. v->pcm_current=prevCenter+
  107349. ((ci->blocksizes[v->lW]/4+
  107350. ci->blocksizes[v->W]/4)>>hs);
  107351. }
  107352. }
  107353. /* track the frame number... This is for convenience, but also
  107354. making sure our last packet doesn't end with added padding. If
  107355. the last packet is partial, the number of samples we'll have to
  107356. return will be past the vb->granulepos.
  107357. This is not foolproof! It will be confused if we begin
  107358. decoding at the last page after a seek or hole. In that case,
  107359. we don't have a starting point to judge where the last frame
  107360. is. For this reason, vorbisfile will always try to make sure
  107361. it reads the last two marked pages in proper sequence */
  107362. if(b->sample_count==-1){
  107363. b->sample_count=0;
  107364. }else{
  107365. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107366. }
  107367. if(v->granulepos==-1){
  107368. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  107369. v->granulepos=vb->granulepos;
  107370. /* is this a short page? */
  107371. if(b->sample_count>v->granulepos){
  107372. /* corner case; if this is both the first and last audio page,
  107373. then spec says the end is cut, not beginning */
  107374. if(vb->eofflag){
  107375. /* trim the end */
  107376. /* no preceeding granulepos; assume we started at zero (we'd
  107377. have to in a short single-page stream) */
  107378. /* granulepos could be -1 due to a seek, but that would result
  107379. in a long count, not short count */
  107380. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  107381. }else{
  107382. /* trim the beginning */
  107383. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  107384. if(v->pcm_returned>v->pcm_current)
  107385. v->pcm_returned=v->pcm_current;
  107386. }
  107387. }
  107388. }
  107389. }else{
  107390. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107391. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  107392. if(v->granulepos>vb->granulepos){
  107393. long extra=v->granulepos-vb->granulepos;
  107394. if(extra)
  107395. if(vb->eofflag){
  107396. /* partial last frame. Strip the extra samples off */
  107397. v->pcm_current-=extra>>hs;
  107398. } /* else {Shouldn't happen *unless* the bitstream is out of
  107399. spec. Either way, believe the bitstream } */
  107400. } /* else {Shouldn't happen *unless* the bitstream is out of
  107401. spec. Either way, believe the bitstream } */
  107402. v->granulepos=vb->granulepos;
  107403. }
  107404. }
  107405. /* Update, cleanup */
  107406. if(vb->eofflag)v->eofflag=1;
  107407. return(0);
  107408. }
  107409. /* pcm==NULL indicates we just want the pending samples, no more */
  107410. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  107411. vorbis_info *vi=v->vi;
  107412. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  107413. if(pcm){
  107414. int i;
  107415. for(i=0;i<vi->channels;i++)
  107416. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107417. *pcm=v->pcmret;
  107418. }
  107419. return(v->pcm_current-v->pcm_returned);
  107420. }
  107421. return(0);
  107422. }
  107423. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  107424. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  107425. v->pcm_returned+=n;
  107426. return(0);
  107427. }
  107428. /* intended for use with a specific vorbisfile feature; we want access
  107429. to the [usually synthetic/postextrapolated] buffer and lapping at
  107430. the end of a decode cycle, specifically, a half-short-block worth.
  107431. This funtion works like pcmout above, except it will also expose
  107432. this implicit buffer data not normally decoded. */
  107433. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  107434. vorbis_info *vi=v->vi;
  107435. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107436. int hs=ci->halfrate_flag;
  107437. int n=ci->blocksizes[v->W]>>(hs+1);
  107438. int n0=ci->blocksizes[0]>>(hs+1);
  107439. int n1=ci->blocksizes[1]>>(hs+1);
  107440. int i,j;
  107441. if(v->pcm_returned<0)return 0;
  107442. /* our returned data ends at pcm_returned; because the synthesis pcm
  107443. buffer is a two-fragment ring, that means our data block may be
  107444. fragmented by buffering, wrapping or a short block not filling
  107445. out a buffer. To simplify things, we unfragment if it's at all
  107446. possibly needed. Otherwise, we'd need to call lapout more than
  107447. once as well as hold additional dsp state. Opt for
  107448. simplicity. */
  107449. /* centerW was advanced by blockin; it would be the center of the
  107450. *next* block */
  107451. if(v->centerW==n1){
  107452. /* the data buffer wraps; swap the halves */
  107453. /* slow, sure, small */
  107454. for(j=0;j<vi->channels;j++){
  107455. float *p=v->pcm[j];
  107456. for(i=0;i<n1;i++){
  107457. float temp=p[i];
  107458. p[i]=p[i+n1];
  107459. p[i+n1]=temp;
  107460. }
  107461. }
  107462. v->pcm_current-=n1;
  107463. v->pcm_returned-=n1;
  107464. v->centerW=0;
  107465. }
  107466. /* solidify buffer into contiguous space */
  107467. if((v->lW^v->W)==1){
  107468. /* long/short or short/long */
  107469. for(j=0;j<vi->channels;j++){
  107470. float *s=v->pcm[j];
  107471. float *d=v->pcm[j]+(n1-n0)/2;
  107472. for(i=(n1+n0)/2-1;i>=0;--i)
  107473. d[i]=s[i];
  107474. }
  107475. v->pcm_returned+=(n1-n0)/2;
  107476. v->pcm_current+=(n1-n0)/2;
  107477. }else{
  107478. if(v->lW==0){
  107479. /* short/short */
  107480. for(j=0;j<vi->channels;j++){
  107481. float *s=v->pcm[j];
  107482. float *d=v->pcm[j]+n1-n0;
  107483. for(i=n0-1;i>=0;--i)
  107484. d[i]=s[i];
  107485. }
  107486. v->pcm_returned+=n1-n0;
  107487. v->pcm_current+=n1-n0;
  107488. }
  107489. }
  107490. if(pcm){
  107491. int i;
  107492. for(i=0;i<vi->channels;i++)
  107493. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107494. *pcm=v->pcmret;
  107495. }
  107496. return(n1+n-v->pcm_returned);
  107497. }
  107498. float *vorbis_window(vorbis_dsp_state *v,int W){
  107499. vorbis_info *vi=v->vi;
  107500. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  107501. int hs=ci->halfrate_flag;
  107502. private_state *b=(private_state*)v->backend_state;
  107503. if(b->window[W]-1<0)return NULL;
  107504. return _vorbis_window_get(b->window[W]-hs);
  107505. }
  107506. #endif
  107507. /********* End of inlined file: block.c *********/
  107508. /********* Start of inlined file: codebook.c *********/
  107509. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107510. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107511. // tasks..
  107512. #if JUCE_MSVC
  107513. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107514. #endif
  107515. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107516. #if JUCE_USE_OGGVORBIS
  107517. #include <stdlib.h>
  107518. #include <string.h>
  107519. #include <math.h>
  107520. /* packs the given codebook into the bitstream **************************/
  107521. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  107522. long i,j;
  107523. int ordered=0;
  107524. /* first the basic parameters */
  107525. oggpack_write(opb,0x564342,24);
  107526. oggpack_write(opb,c->dim,16);
  107527. oggpack_write(opb,c->entries,24);
  107528. /* pack the codewords. There are two packings; length ordered and
  107529. length random. Decide between the two now. */
  107530. for(i=1;i<c->entries;i++)
  107531. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  107532. if(i==c->entries)ordered=1;
  107533. if(ordered){
  107534. /* length ordered. We only need to say how many codewords of
  107535. each length. The actual codewords are generated
  107536. deterministically */
  107537. long count=0;
  107538. oggpack_write(opb,1,1); /* ordered */
  107539. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  107540. for(i=1;i<c->entries;i++){
  107541. long thisx=c->lengthlist[i];
  107542. long last=c->lengthlist[i-1];
  107543. if(thisx>last){
  107544. for(j=last;j<thisx;j++){
  107545. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107546. count=i;
  107547. }
  107548. }
  107549. }
  107550. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107551. }else{
  107552. /* length random. Again, we don't code the codeword itself, just
  107553. the length. This time, though, we have to encode each length */
  107554. oggpack_write(opb,0,1); /* unordered */
  107555. /* algortihmic mapping has use for 'unused entries', which we tag
  107556. here. The algorithmic mapping happens as usual, but the unused
  107557. entry has no codeword. */
  107558. for(i=0;i<c->entries;i++)
  107559. if(c->lengthlist[i]==0)break;
  107560. if(i==c->entries){
  107561. oggpack_write(opb,0,1); /* no unused entries */
  107562. for(i=0;i<c->entries;i++)
  107563. oggpack_write(opb,c->lengthlist[i]-1,5);
  107564. }else{
  107565. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  107566. for(i=0;i<c->entries;i++){
  107567. if(c->lengthlist[i]==0){
  107568. oggpack_write(opb,0,1);
  107569. }else{
  107570. oggpack_write(opb,1,1);
  107571. oggpack_write(opb,c->lengthlist[i]-1,5);
  107572. }
  107573. }
  107574. }
  107575. }
  107576. /* is the entry number the desired return value, or do we have a
  107577. mapping? If we have a mapping, what type? */
  107578. oggpack_write(opb,c->maptype,4);
  107579. switch(c->maptype){
  107580. case 0:
  107581. /* no mapping */
  107582. break;
  107583. case 1:case 2:
  107584. /* implicitly populated value mapping */
  107585. /* explicitly populated value mapping */
  107586. if(!c->quantlist){
  107587. /* no quantlist? error */
  107588. return(-1);
  107589. }
  107590. /* values that define the dequantization */
  107591. oggpack_write(opb,c->q_min,32);
  107592. oggpack_write(opb,c->q_delta,32);
  107593. oggpack_write(opb,c->q_quant-1,4);
  107594. oggpack_write(opb,c->q_sequencep,1);
  107595. {
  107596. int quantvals;
  107597. switch(c->maptype){
  107598. case 1:
  107599. /* a single column of (c->entries/c->dim) quantized values for
  107600. building a full value list algorithmically (square lattice) */
  107601. quantvals=_book_maptype1_quantvals(c);
  107602. break;
  107603. case 2:
  107604. /* every value (c->entries*c->dim total) specified explicitly */
  107605. quantvals=c->entries*c->dim;
  107606. break;
  107607. default: /* NOT_REACHABLE */
  107608. quantvals=-1;
  107609. }
  107610. /* quantized values */
  107611. for(i=0;i<quantvals;i++)
  107612. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  107613. }
  107614. break;
  107615. default:
  107616. /* error case; we don't have any other map types now */
  107617. return(-1);
  107618. }
  107619. return(0);
  107620. }
  107621. /* unpacks a codebook from the packet buffer into the codebook struct,
  107622. readies the codebook auxiliary structures for decode *************/
  107623. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  107624. long i,j;
  107625. memset(s,0,sizeof(*s));
  107626. s->allocedp=1;
  107627. /* make sure alignment is correct */
  107628. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  107629. /* first the basic parameters */
  107630. s->dim=oggpack_read(opb,16);
  107631. s->entries=oggpack_read(opb,24);
  107632. if(s->entries==-1)goto _eofout;
  107633. /* codeword ordering.... length ordered or unordered? */
  107634. switch((int)oggpack_read(opb,1)){
  107635. case 0:
  107636. /* unordered */
  107637. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107638. /* allocated but unused entries? */
  107639. if(oggpack_read(opb,1)){
  107640. /* yes, unused entries */
  107641. for(i=0;i<s->entries;i++){
  107642. if(oggpack_read(opb,1)){
  107643. long num=oggpack_read(opb,5);
  107644. if(num==-1)goto _eofout;
  107645. s->lengthlist[i]=num+1;
  107646. }else
  107647. s->lengthlist[i]=0;
  107648. }
  107649. }else{
  107650. /* all entries used; no tagging */
  107651. for(i=0;i<s->entries;i++){
  107652. long num=oggpack_read(opb,5);
  107653. if(num==-1)goto _eofout;
  107654. s->lengthlist[i]=num+1;
  107655. }
  107656. }
  107657. break;
  107658. case 1:
  107659. /* ordered */
  107660. {
  107661. long length=oggpack_read(opb,5)+1;
  107662. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107663. for(i=0;i<s->entries;){
  107664. long num=oggpack_read(opb,_ilog(s->entries-i));
  107665. if(num==-1)goto _eofout;
  107666. for(j=0;j<num && i<s->entries;j++,i++)
  107667. s->lengthlist[i]=length;
  107668. length++;
  107669. }
  107670. }
  107671. break;
  107672. default:
  107673. /* EOF */
  107674. return(-1);
  107675. }
  107676. /* Do we have a mapping to unpack? */
  107677. switch((s->maptype=oggpack_read(opb,4))){
  107678. case 0:
  107679. /* no mapping */
  107680. break;
  107681. case 1: case 2:
  107682. /* implicitly populated value mapping */
  107683. /* explicitly populated value mapping */
  107684. s->q_min=oggpack_read(opb,32);
  107685. s->q_delta=oggpack_read(opb,32);
  107686. s->q_quant=oggpack_read(opb,4)+1;
  107687. s->q_sequencep=oggpack_read(opb,1);
  107688. {
  107689. int quantvals=0;
  107690. switch(s->maptype){
  107691. case 1:
  107692. quantvals=_book_maptype1_quantvals(s);
  107693. break;
  107694. case 2:
  107695. quantvals=s->entries*s->dim;
  107696. break;
  107697. }
  107698. /* quantized values */
  107699. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  107700. for(i=0;i<quantvals;i++)
  107701. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  107702. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  107703. }
  107704. break;
  107705. default:
  107706. goto _errout;
  107707. }
  107708. /* all set */
  107709. return(0);
  107710. _errout:
  107711. _eofout:
  107712. vorbis_staticbook_clear(s);
  107713. return(-1);
  107714. }
  107715. /* returns the number of bits ************************************************/
  107716. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  107717. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  107718. return(book->c->lengthlist[a]);
  107719. }
  107720. /* One the encode side, our vector writers are each designed for a
  107721. specific purpose, and the encoder is not flexible without modification:
  107722. The LSP vector coder uses a single stage nearest-match with no
  107723. interleave, so no step and no error return. This is specced by floor0
  107724. and doesn't change.
  107725. Residue0 encoding interleaves, uses multiple stages, and each stage
  107726. peels of a specific amount of resolution from a lattice (thus we want
  107727. to match by threshold, not nearest match). Residue doesn't *have* to
  107728. be encoded that way, but to change it, one will need to add more
  107729. infrastructure on the encode side (decode side is specced and simpler) */
  107730. /* floor0 LSP (single stage, non interleaved, nearest match) */
  107731. /* returns entry number and *modifies a* to the quantization value *****/
  107732. int vorbis_book_errorv(codebook *book,float *a){
  107733. int dim=book->dim,k;
  107734. int best=_best(book,a,1);
  107735. for(k=0;k<dim;k++)
  107736. a[k]=(book->valuelist+best*dim)[k];
  107737. return(best);
  107738. }
  107739. /* returns the number of bits and *modifies a* to the quantization value *****/
  107740. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  107741. int k,dim=book->dim;
  107742. for(k=0;k<dim;k++)
  107743. a[k]=(book->valuelist+best*dim)[k];
  107744. return(vorbis_book_encode(book,best,b));
  107745. }
  107746. /* the 'eliminate the decode tree' optimization actually requires the
  107747. codewords to be MSb first, not LSb. This is an annoying inelegancy
  107748. (and one of the first places where carefully thought out design
  107749. turned out to be wrong; Vorbis II and future Ogg codecs should go
  107750. to an MSb bitpacker), but not actually the huge hit it appears to
  107751. be. The first-stage decode table catches most words so that
  107752. bitreverse is not in the main execution path. */
  107753. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  107754. int read=book->dec_maxlength;
  107755. long lo,hi;
  107756. long lok = oggpack_look(b,book->dec_firsttablen);
  107757. if (lok >= 0) {
  107758. long entry = book->dec_firsttable[lok];
  107759. if(entry&0x80000000UL){
  107760. lo=(entry>>15)&0x7fff;
  107761. hi=book->used_entries-(entry&0x7fff);
  107762. }else{
  107763. oggpack_adv(b, book->dec_codelengths[entry-1]);
  107764. return(entry-1);
  107765. }
  107766. }else{
  107767. lo=0;
  107768. hi=book->used_entries;
  107769. }
  107770. lok = oggpack_look(b, read);
  107771. while(lok<0 && read>1)
  107772. lok = oggpack_look(b, --read);
  107773. if(lok<0)return -1;
  107774. /* bisect search for the codeword in the ordered list */
  107775. {
  107776. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  107777. while(hi-lo>1){
  107778. long p=(hi-lo)>>1;
  107779. long test=book->codelist[lo+p]>testword;
  107780. lo+=p&(test-1);
  107781. hi-=p&(-test);
  107782. }
  107783. if(book->dec_codelengths[lo]<=read){
  107784. oggpack_adv(b, book->dec_codelengths[lo]);
  107785. return(lo);
  107786. }
  107787. }
  107788. oggpack_adv(b, read);
  107789. return(-1);
  107790. }
  107791. /* Decode side is specced and easier, because we don't need to find
  107792. matches using different criteria; we simply read and map. There are
  107793. two things we need to do 'depending':
  107794. We may need to support interleave. We don't really, but it's
  107795. convenient to do it here rather than rebuild the vector later.
  107796. Cascades may be additive or multiplicitive; this is not inherent in
  107797. the codebook, but set in the code using the codebook. Like
  107798. interleaving, it's easiest to do it here.
  107799. addmul==0 -> declarative (set the value)
  107800. addmul==1 -> additive
  107801. addmul==2 -> multiplicitive */
  107802. /* returns the [original, not compacted] entry number or -1 on eof *********/
  107803. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  107804. long packed_entry=decode_packed_entry_number(book,b);
  107805. if(packed_entry>=0)
  107806. return(book->dec_index[packed_entry]);
  107807. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  107808. return(packed_entry);
  107809. }
  107810. /* returns 0 on OK or -1 on eof *************************************/
  107811. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107812. int step=n/book->dim;
  107813. long *entry = (long*)alloca(sizeof(*entry)*step);
  107814. float **t = (float**)alloca(sizeof(*t)*step);
  107815. int i,j,o;
  107816. for (i = 0; i < step; i++) {
  107817. entry[i]=decode_packed_entry_number(book,b);
  107818. if(entry[i]==-1)return(-1);
  107819. t[i] = book->valuelist+entry[i]*book->dim;
  107820. }
  107821. for(i=0,o=0;i<book->dim;i++,o+=step)
  107822. for (j=0;j<step;j++)
  107823. a[o+j]+=t[j][i];
  107824. return(0);
  107825. }
  107826. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107827. int i,j,entry;
  107828. float *t;
  107829. if(book->dim>8){
  107830. for(i=0;i<n;){
  107831. entry = decode_packed_entry_number(book,b);
  107832. if(entry==-1)return(-1);
  107833. t = book->valuelist+entry*book->dim;
  107834. for (j=0;j<book->dim;)
  107835. a[i++]+=t[j++];
  107836. }
  107837. }else{
  107838. for(i=0;i<n;){
  107839. entry = decode_packed_entry_number(book,b);
  107840. if(entry==-1)return(-1);
  107841. t = book->valuelist+entry*book->dim;
  107842. j=0;
  107843. switch((int)book->dim){
  107844. case 8:
  107845. a[i++]+=t[j++];
  107846. case 7:
  107847. a[i++]+=t[j++];
  107848. case 6:
  107849. a[i++]+=t[j++];
  107850. case 5:
  107851. a[i++]+=t[j++];
  107852. case 4:
  107853. a[i++]+=t[j++];
  107854. case 3:
  107855. a[i++]+=t[j++];
  107856. case 2:
  107857. a[i++]+=t[j++];
  107858. case 1:
  107859. a[i++]+=t[j++];
  107860. case 0:
  107861. break;
  107862. }
  107863. }
  107864. }
  107865. return(0);
  107866. }
  107867. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  107868. int i,j,entry;
  107869. float *t;
  107870. for(i=0;i<n;){
  107871. entry = decode_packed_entry_number(book,b);
  107872. if(entry==-1)return(-1);
  107873. t = book->valuelist+entry*book->dim;
  107874. for (j=0;j<book->dim;)
  107875. a[i++]=t[j++];
  107876. }
  107877. return(0);
  107878. }
  107879. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  107880. oggpack_buffer *b,int n){
  107881. long i,j,entry;
  107882. int chptr=0;
  107883. for(i=offset/ch;i<(offset+n)/ch;){
  107884. entry = decode_packed_entry_number(book,b);
  107885. if(entry==-1)return(-1);
  107886. {
  107887. const float *t = book->valuelist+entry*book->dim;
  107888. for (j=0;j<book->dim;j++){
  107889. a[chptr++][i]+=t[j];
  107890. if(chptr==ch){
  107891. chptr=0;
  107892. i++;
  107893. }
  107894. }
  107895. }
  107896. }
  107897. return(0);
  107898. }
  107899. #ifdef _V_SELFTEST
  107900. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  107901. number of vectors through (keeping track of the quantized values),
  107902. and decode using the unpacked book. quantized version of in should
  107903. exactly equal out */
  107904. #include <stdio.h>
  107905. #include "vorbis/book/lsp20_0.vqh"
  107906. #include "vorbis/book/res0a_13.vqh"
  107907. #define TESTSIZE 40
  107908. float test1[TESTSIZE]={
  107909. 0.105939f,
  107910. 0.215373f,
  107911. 0.429117f,
  107912. 0.587974f,
  107913. 0.181173f,
  107914. 0.296583f,
  107915. 0.515707f,
  107916. 0.715261f,
  107917. 0.162327f,
  107918. 0.263834f,
  107919. 0.342876f,
  107920. 0.406025f,
  107921. 0.103571f,
  107922. 0.223561f,
  107923. 0.368513f,
  107924. 0.540313f,
  107925. 0.136672f,
  107926. 0.395882f,
  107927. 0.587183f,
  107928. 0.652476f,
  107929. 0.114338f,
  107930. 0.417300f,
  107931. 0.525486f,
  107932. 0.698679f,
  107933. 0.147492f,
  107934. 0.324481f,
  107935. 0.643089f,
  107936. 0.757582f,
  107937. 0.139556f,
  107938. 0.215795f,
  107939. 0.324559f,
  107940. 0.399387f,
  107941. 0.120236f,
  107942. 0.267420f,
  107943. 0.446940f,
  107944. 0.608760f,
  107945. 0.115587f,
  107946. 0.287234f,
  107947. 0.571081f,
  107948. 0.708603f,
  107949. };
  107950. float test3[TESTSIZE]={
  107951. 0,1,-2,3,4,-5,6,7,8,9,
  107952. 8,-2,7,-1,4,6,8,3,1,-9,
  107953. 10,11,12,13,14,15,26,17,18,19,
  107954. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  107955. static_codebook *testlist[]={&_vq_book_lsp20_0,
  107956. &_vq_book_res0a_13,NULL};
  107957. float *testvec[]={test1,test3};
  107958. int main(){
  107959. oggpack_buffer write;
  107960. oggpack_buffer read;
  107961. long ptr=0,i;
  107962. oggpack_writeinit(&write);
  107963. fprintf(stderr,"Testing codebook abstraction...:\n");
  107964. while(testlist[ptr]){
  107965. codebook c;
  107966. static_codebook s;
  107967. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  107968. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  107969. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  107970. memset(iv,0,sizeof(*iv)*TESTSIZE);
  107971. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  107972. /* pack the codebook, write the testvector */
  107973. oggpack_reset(&write);
  107974. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  107975. we can write */
  107976. vorbis_staticbook_pack(testlist[ptr],&write);
  107977. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  107978. for(i=0;i<TESTSIZE;i+=c.dim){
  107979. int best=_best(&c,qv+i,1);
  107980. vorbis_book_encodev(&c,best,qv+i,&write);
  107981. }
  107982. vorbis_book_clear(&c);
  107983. fprintf(stderr,"OK.\n");
  107984. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  107985. /* transfer the write data to a read buffer and unpack/read */
  107986. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  107987. if(vorbis_staticbook_unpack(&read,&s)){
  107988. fprintf(stderr,"Error unpacking codebook.\n");
  107989. exit(1);
  107990. }
  107991. if(vorbis_book_init_decode(&c,&s)){
  107992. fprintf(stderr,"Error initializing codebook.\n");
  107993. exit(1);
  107994. }
  107995. for(i=0;i<TESTSIZE;i+=c.dim)
  107996. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  107997. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  107998. exit(1);
  107999. }
  108000. for(i=0;i<TESTSIZE;i++)
  108001. if(fabs(qv[i]-iv[i])>.000001){
  108002. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  108003. iv[i],qv[i],i);
  108004. exit(1);
  108005. }
  108006. fprintf(stderr,"OK\n");
  108007. ptr++;
  108008. }
  108009. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  108010. exit(0);
  108011. }
  108012. #endif
  108013. #endif
  108014. /********* End of inlined file: codebook.c *********/
  108015. /********* Start of inlined file: envelope.c *********/
  108016. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108017. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108018. // tasks..
  108019. #if JUCE_MSVC
  108020. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108021. #endif
  108022. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108023. #if JUCE_USE_OGGVORBIS
  108024. #include <stdlib.h>
  108025. #include <string.h>
  108026. #include <stdio.h>
  108027. #include <math.h>
  108028. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  108029. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108030. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108031. int ch=vi->channels;
  108032. int i,j;
  108033. int n=e->winlength=128;
  108034. e->searchstep=64; /* not random */
  108035. e->minenergy=gi->preecho_minenergy;
  108036. e->ch=ch;
  108037. e->storage=128;
  108038. e->cursor=ci->blocksizes[1]/2;
  108039. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  108040. mdct_init(&e->mdct,n);
  108041. for(i=0;i<n;i++){
  108042. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  108043. e->mdct_win[i]*=e->mdct_win[i];
  108044. }
  108045. /* magic follows */
  108046. e->band[0].begin=2; e->band[0].end=4;
  108047. e->band[1].begin=4; e->band[1].end=5;
  108048. e->band[2].begin=6; e->band[2].end=6;
  108049. e->band[3].begin=9; e->band[3].end=8;
  108050. e->band[4].begin=13; e->band[4].end=8;
  108051. e->band[5].begin=17; e->band[5].end=8;
  108052. e->band[6].begin=22; e->band[6].end=8;
  108053. for(j=0;j<VE_BANDS;j++){
  108054. n=e->band[j].end;
  108055. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  108056. for(i=0;i<n;i++){
  108057. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  108058. e->band[j].total+=e->band[j].window[i];
  108059. }
  108060. e->band[j].total=1./e->band[j].total;
  108061. }
  108062. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  108063. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  108064. }
  108065. void _ve_envelope_clear(envelope_lookup *e){
  108066. int i;
  108067. mdct_clear(&e->mdct);
  108068. for(i=0;i<VE_BANDS;i++)
  108069. _ogg_free(e->band[i].window);
  108070. _ogg_free(e->mdct_win);
  108071. _ogg_free(e->filter);
  108072. _ogg_free(e->mark);
  108073. memset(e,0,sizeof(*e));
  108074. }
  108075. /* fairly straight threshhold-by-band based until we find something
  108076. that works better and isn't patented. */
  108077. static int _ve_amp(envelope_lookup *ve,
  108078. vorbis_info_psy_global *gi,
  108079. float *data,
  108080. envelope_band *bands,
  108081. envelope_filter_state *filters,
  108082. long pos){
  108083. long n=ve->winlength;
  108084. int ret=0;
  108085. long i,j;
  108086. float decay;
  108087. /* we want to have a 'minimum bar' for energy, else we're just
  108088. basing blocks on quantization noise that outweighs the signal
  108089. itself (for low power signals) */
  108090. float minV=ve->minenergy;
  108091. float *vec=(float*) alloca(n*sizeof(*vec));
  108092. /* stretch is used to gradually lengthen the number of windows
  108093. considered prevoius-to-potential-trigger */
  108094. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  108095. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  108096. if(penalty<0.f)penalty=0.f;
  108097. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  108098. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  108099. totalshift+pos*ve->searchstep);*/
  108100. /* window and transform */
  108101. for(i=0;i<n;i++)
  108102. vec[i]=data[i]*ve->mdct_win[i];
  108103. mdct_forward(&ve->mdct,vec,vec);
  108104. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  108105. /* near-DC spreading function; this has nothing to do with
  108106. psychoacoustics, just sidelobe leakage and window size */
  108107. {
  108108. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  108109. int ptr=filters->nearptr;
  108110. /* the accumulation is regularly refreshed from scratch to avoid
  108111. floating point creep */
  108112. if(ptr==0){
  108113. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  108114. filters->nearDC_partialacc=temp;
  108115. }else{
  108116. decay=filters->nearDC_acc+=temp;
  108117. filters->nearDC_partialacc+=temp;
  108118. }
  108119. filters->nearDC_acc-=filters->nearDC[ptr];
  108120. filters->nearDC[ptr]=temp;
  108121. decay*=(1./(VE_NEARDC+1));
  108122. filters->nearptr++;
  108123. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  108124. decay=todB(&decay)*.5-15.f;
  108125. }
  108126. /* perform spreading and limiting, also smooth the spectrum. yes,
  108127. the MDCT results in all real coefficients, but it still *behaves*
  108128. like real/imaginary pairs */
  108129. for(i=0;i<n/2;i+=2){
  108130. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  108131. val=todB(&val)*.5f;
  108132. if(val<decay)val=decay;
  108133. if(val<minV)val=minV;
  108134. vec[i>>1]=val;
  108135. decay-=8.;
  108136. }
  108137. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  108138. /* perform preecho/postecho triggering by band */
  108139. for(j=0;j<VE_BANDS;j++){
  108140. float acc=0.;
  108141. float valmax,valmin;
  108142. /* accumulate amplitude */
  108143. for(i=0;i<bands[j].end;i++)
  108144. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  108145. acc*=bands[j].total;
  108146. /* convert amplitude to delta */
  108147. {
  108148. int p,thisx=filters[j].ampptr;
  108149. float postmax,postmin,premax=-99999.f,premin=99999.f;
  108150. p=thisx;
  108151. p--;
  108152. if(p<0)p+=VE_AMP;
  108153. postmax=max(acc,filters[j].ampbuf[p]);
  108154. postmin=min(acc,filters[j].ampbuf[p]);
  108155. for(i=0;i<stretch;i++){
  108156. p--;
  108157. if(p<0)p+=VE_AMP;
  108158. premax=max(premax,filters[j].ampbuf[p]);
  108159. premin=min(premin,filters[j].ampbuf[p]);
  108160. }
  108161. valmin=postmin-premin;
  108162. valmax=postmax-premax;
  108163. /*filters[j].markers[pos]=valmax;*/
  108164. filters[j].ampbuf[thisx]=acc;
  108165. filters[j].ampptr++;
  108166. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  108167. }
  108168. /* look at min/max, decide trigger */
  108169. if(valmax>gi->preecho_thresh[j]+penalty){
  108170. ret|=1;
  108171. ret|=4;
  108172. }
  108173. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  108174. }
  108175. return(ret);
  108176. }
  108177. #if 0
  108178. static int seq=0;
  108179. static ogg_int64_t totalshift=-1024;
  108180. #endif
  108181. long _ve_envelope_search(vorbis_dsp_state *v){
  108182. vorbis_info *vi=v->vi;
  108183. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108184. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108185. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108186. long i,j;
  108187. int first=ve->current/ve->searchstep;
  108188. int last=v->pcm_current/ve->searchstep-VE_WIN;
  108189. if(first<0)first=0;
  108190. /* make sure we have enough storage to match the PCM */
  108191. if(last+VE_WIN+VE_POST>ve->storage){
  108192. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  108193. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  108194. }
  108195. for(j=first;j<last;j++){
  108196. int ret=0;
  108197. ve->stretch++;
  108198. if(ve->stretch>VE_MAXSTRETCH*2)
  108199. ve->stretch=VE_MAXSTRETCH*2;
  108200. for(i=0;i<ve->ch;i++){
  108201. float *pcm=v->pcm[i]+ve->searchstep*(j);
  108202. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  108203. }
  108204. ve->mark[j+VE_POST]=0;
  108205. if(ret&1){
  108206. ve->mark[j]=1;
  108207. ve->mark[j+1]=1;
  108208. }
  108209. if(ret&2){
  108210. ve->mark[j]=1;
  108211. if(j>0)ve->mark[j-1]=1;
  108212. }
  108213. if(ret&4)ve->stretch=-1;
  108214. }
  108215. ve->current=last*ve->searchstep;
  108216. {
  108217. long centerW=v->centerW;
  108218. long testW=
  108219. centerW+
  108220. ci->blocksizes[v->W]/4+
  108221. ci->blocksizes[1]/2+
  108222. ci->blocksizes[0]/4;
  108223. j=ve->cursor;
  108224. while(j<ve->current-(ve->searchstep)){/* account for postecho
  108225. working back one window */
  108226. if(j>=testW)return(1);
  108227. ve->cursor=j;
  108228. if(ve->mark[j/ve->searchstep]){
  108229. if(j>centerW){
  108230. #if 0
  108231. if(j>ve->curmark){
  108232. float *marker=alloca(v->pcm_current*sizeof(*marker));
  108233. int l,m;
  108234. memset(marker,0,sizeof(*marker)*v->pcm_current);
  108235. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  108236. seq,
  108237. (totalshift+ve->cursor)/44100.,
  108238. (totalshift+j)/44100.);
  108239. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  108240. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  108241. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  108242. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  108243. for(m=0;m<VE_BANDS;m++){
  108244. char buf[80];
  108245. sprintf(buf,"delL%d",m);
  108246. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  108247. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108248. }
  108249. for(m=0;m<VE_BANDS;m++){
  108250. char buf[80];
  108251. sprintf(buf,"delR%d",m);
  108252. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  108253. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108254. }
  108255. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  108256. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  108257. seq++;
  108258. }
  108259. #endif
  108260. ve->curmark=j;
  108261. if(j>=testW)return(1);
  108262. return(0);
  108263. }
  108264. }
  108265. j+=ve->searchstep;
  108266. }
  108267. }
  108268. return(-1);
  108269. }
  108270. int _ve_envelope_mark(vorbis_dsp_state *v){
  108271. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108272. vorbis_info *vi=v->vi;
  108273. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108274. long centerW=v->centerW;
  108275. long beginW=centerW-ci->blocksizes[v->W]/4;
  108276. long endW=centerW+ci->blocksizes[v->W]/4;
  108277. if(v->W){
  108278. beginW-=ci->blocksizes[v->lW]/4;
  108279. endW+=ci->blocksizes[v->nW]/4;
  108280. }else{
  108281. beginW-=ci->blocksizes[0]/4;
  108282. endW+=ci->blocksizes[0]/4;
  108283. }
  108284. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  108285. {
  108286. long first=beginW/ve->searchstep;
  108287. long last=endW/ve->searchstep;
  108288. long i;
  108289. for(i=first;i<last;i++)
  108290. if(ve->mark[i])return(1);
  108291. }
  108292. return(0);
  108293. }
  108294. void _ve_envelope_shift(envelope_lookup *e,long shift){
  108295. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  108296. ahead of ve->current */
  108297. int smallshift=shift/e->searchstep;
  108298. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  108299. #if 0
  108300. for(i=0;i<VE_BANDS*e->ch;i++)
  108301. memmove(e->filter[i].markers,
  108302. e->filter[i].markers+smallshift,
  108303. (1024-smallshift)*sizeof(*(*e->filter).markers));
  108304. totalshift+=shift;
  108305. #endif
  108306. e->current-=shift;
  108307. if(e->curmark>=0)
  108308. e->curmark-=shift;
  108309. e->cursor-=shift;
  108310. }
  108311. #endif
  108312. /********* End of inlined file: envelope.c *********/
  108313. /********* Start of inlined file: floor0.c *********/
  108314. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108315. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108316. // tasks..
  108317. #if JUCE_MSVC
  108318. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108319. #endif
  108320. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108321. #if JUCE_USE_OGGVORBIS
  108322. #include <stdlib.h>
  108323. #include <string.h>
  108324. #include <math.h>
  108325. /********* Start of inlined file: lsp.h *********/
  108326. #ifndef _V_LSP_H_
  108327. #define _V_LSP_H_
  108328. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  108329. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  108330. float *lsp,int m,
  108331. float amp,float ampoffset);
  108332. #endif
  108333. /********* End of inlined file: lsp.h *********/
  108334. #include <stdio.h>
  108335. typedef struct {
  108336. int ln;
  108337. int m;
  108338. int **linearmap;
  108339. int n[2];
  108340. vorbis_info_floor0 *vi;
  108341. long bits;
  108342. long frames;
  108343. } vorbis_look_floor0;
  108344. /***********************************************/
  108345. static void floor0_free_info(vorbis_info_floor *i){
  108346. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  108347. if(info){
  108348. memset(info,0,sizeof(*info));
  108349. _ogg_free(info);
  108350. }
  108351. }
  108352. static void floor0_free_look(vorbis_look_floor *i){
  108353. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108354. if(look){
  108355. if(look->linearmap){
  108356. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  108357. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  108358. _ogg_free(look->linearmap);
  108359. }
  108360. memset(look,0,sizeof(*look));
  108361. _ogg_free(look);
  108362. }
  108363. }
  108364. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108365. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108366. int j;
  108367. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  108368. info->order=oggpack_read(opb,8);
  108369. info->rate=oggpack_read(opb,16);
  108370. info->barkmap=oggpack_read(opb,16);
  108371. info->ampbits=oggpack_read(opb,6);
  108372. info->ampdB=oggpack_read(opb,8);
  108373. info->numbooks=oggpack_read(opb,4)+1;
  108374. if(info->order<1)goto err_out;
  108375. if(info->rate<1)goto err_out;
  108376. if(info->barkmap<1)goto err_out;
  108377. if(info->numbooks<1)goto err_out;
  108378. for(j=0;j<info->numbooks;j++){
  108379. info->books[j]=oggpack_read(opb,8);
  108380. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  108381. }
  108382. return(info);
  108383. err_out:
  108384. floor0_free_info(info);
  108385. return(NULL);
  108386. }
  108387. /* initialize Bark scale and normalization lookups. We could do this
  108388. with static tables, but Vorbis allows a number of possible
  108389. combinations, so it's best to do it computationally.
  108390. The below is authoritative in terms of defining scale mapping.
  108391. Note that the scale depends on the sampling rate as well as the
  108392. linear block and mapping sizes */
  108393. static void floor0_map_lazy_init(vorbis_block *vb,
  108394. vorbis_info_floor *infoX,
  108395. vorbis_look_floor0 *look){
  108396. if(!look->linearmap[vb->W]){
  108397. vorbis_dsp_state *vd=vb->vd;
  108398. vorbis_info *vi=vd->vi;
  108399. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108400. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  108401. int W=vb->W;
  108402. int n=ci->blocksizes[W]/2,j;
  108403. /* we choose a scaling constant so that:
  108404. floor(bark(rate/2-1)*C)=mapped-1
  108405. floor(bark(rate/2)*C)=mapped */
  108406. float scale=look->ln/toBARK(info->rate/2.f);
  108407. /* the mapping from a linear scale to a smaller bark scale is
  108408. straightforward. We do *not* make sure that the linear mapping
  108409. does not skip bark-scale bins; the decoder simply skips them and
  108410. the encoder may do what it wishes in filling them. They're
  108411. necessary in some mapping combinations to keep the scale spacing
  108412. accurate */
  108413. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  108414. for(j=0;j<n;j++){
  108415. int val=floor( toBARK((info->rate/2.f)/n*j)
  108416. *scale); /* bark numbers represent band edges */
  108417. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  108418. look->linearmap[W][j]=val;
  108419. }
  108420. look->linearmap[W][j]=-1;
  108421. look->n[W]=n;
  108422. }
  108423. }
  108424. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  108425. vorbis_info_floor *i){
  108426. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  108427. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  108428. look->m=info->order;
  108429. look->ln=info->barkmap;
  108430. look->vi=info;
  108431. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  108432. return look;
  108433. }
  108434. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  108435. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108436. vorbis_info_floor0 *info=look->vi;
  108437. int j,k;
  108438. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  108439. if(ampraw>0){ /* also handles the -1 out of data case */
  108440. long maxval=(1<<info->ampbits)-1;
  108441. float amp=(float)ampraw/maxval*info->ampdB;
  108442. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  108443. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  108444. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  108445. codebook *b=ci->fullbooks+info->books[booknum];
  108446. float last=0.f;
  108447. /* the additional b->dim is a guard against any possible stack
  108448. smash; b->dim is provably more than we can overflow the
  108449. vector */
  108450. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  108451. for(j=0;j<look->m;j+=b->dim)
  108452. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  108453. for(j=0;j<look->m;){
  108454. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  108455. last=lsp[j-1];
  108456. }
  108457. lsp[look->m]=amp;
  108458. return(lsp);
  108459. }
  108460. }
  108461. eop:
  108462. return(NULL);
  108463. }
  108464. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  108465. void *memo,float *out){
  108466. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108467. vorbis_info_floor0 *info=look->vi;
  108468. floor0_map_lazy_init(vb,info,look);
  108469. if(memo){
  108470. float *lsp=(float *)memo;
  108471. float amp=lsp[look->m];
  108472. /* take the coefficients back to a spectral envelope curve */
  108473. vorbis_lsp_to_curve(out,
  108474. look->linearmap[vb->W],
  108475. look->n[vb->W],
  108476. look->ln,
  108477. lsp,look->m,amp,(float)info->ampdB);
  108478. return(1);
  108479. }
  108480. memset(out,0,sizeof(*out)*look->n[vb->W]);
  108481. return(0);
  108482. }
  108483. /* export hooks */
  108484. vorbis_func_floor floor0_exportbundle={
  108485. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  108486. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  108487. };
  108488. #endif
  108489. /********* End of inlined file: floor0.c *********/
  108490. /********* Start of inlined file: floor1.c *********/
  108491. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108492. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108493. // tasks..
  108494. #if JUCE_MSVC
  108495. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108496. #endif
  108497. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108498. #if JUCE_USE_OGGVORBIS
  108499. #include <stdlib.h>
  108500. #include <string.h>
  108501. #include <math.h>
  108502. #include <stdio.h>
  108503. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  108504. typedef struct {
  108505. int sorted_index[VIF_POSIT+2];
  108506. int forward_index[VIF_POSIT+2];
  108507. int reverse_index[VIF_POSIT+2];
  108508. int hineighbor[VIF_POSIT];
  108509. int loneighbor[VIF_POSIT];
  108510. int posts;
  108511. int n;
  108512. int quant_q;
  108513. vorbis_info_floor1 *vi;
  108514. long phrasebits;
  108515. long postbits;
  108516. long frames;
  108517. } vorbis_look_floor1;
  108518. typedef struct lsfit_acc{
  108519. long x0;
  108520. long x1;
  108521. long xa;
  108522. long ya;
  108523. long x2a;
  108524. long y2a;
  108525. long xya;
  108526. long an;
  108527. } lsfit_acc;
  108528. /***********************************************/
  108529. static void floor1_free_info(vorbis_info_floor *i){
  108530. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108531. if(info){
  108532. memset(info,0,sizeof(*info));
  108533. _ogg_free(info);
  108534. }
  108535. }
  108536. static void floor1_free_look(vorbis_look_floor *i){
  108537. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  108538. if(look){
  108539. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  108540. (float)look->phrasebits/look->frames,
  108541. (float)look->postbits/look->frames,
  108542. (float)(look->postbits+look->phrasebits)/look->frames);*/
  108543. memset(look,0,sizeof(*look));
  108544. _ogg_free(look);
  108545. }
  108546. }
  108547. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  108548. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108549. int j,k;
  108550. int count=0;
  108551. int rangebits;
  108552. int maxposit=info->postlist[1];
  108553. int maxclass=-1;
  108554. /* save out partitions */
  108555. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  108556. for(j=0;j<info->partitions;j++){
  108557. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  108558. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108559. }
  108560. /* save out partition classes */
  108561. for(j=0;j<maxclass+1;j++){
  108562. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  108563. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  108564. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  108565. for(k=0;k<(1<<info->class_subs[j]);k++)
  108566. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  108567. }
  108568. /* save out the post list */
  108569. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  108570. oggpack_write(opb,ilog2(maxposit),4);
  108571. rangebits=ilog2(maxposit);
  108572. for(j=0,k=0;j<info->partitions;j++){
  108573. count+=info->class_dim[info->partitionclass[j]];
  108574. for(;k<count;k++)
  108575. oggpack_write(opb,info->postlist[k+2],rangebits);
  108576. }
  108577. }
  108578. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108579. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108580. int j,k,count=0,maxclass=-1,rangebits;
  108581. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  108582. /* read partitions */
  108583. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  108584. for(j=0;j<info->partitions;j++){
  108585. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  108586. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108587. }
  108588. /* read partition classes */
  108589. for(j=0;j<maxclass+1;j++){
  108590. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  108591. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  108592. if(info->class_subs[j]<0)
  108593. goto err_out;
  108594. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  108595. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  108596. goto err_out;
  108597. for(k=0;k<(1<<info->class_subs[j]);k++){
  108598. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  108599. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  108600. goto err_out;
  108601. }
  108602. }
  108603. /* read the post list */
  108604. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  108605. rangebits=oggpack_read(opb,4);
  108606. for(j=0,k=0;j<info->partitions;j++){
  108607. count+=info->class_dim[info->partitionclass[j]];
  108608. for(;k<count;k++){
  108609. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  108610. if(t<0 || t>=(1<<rangebits))
  108611. goto err_out;
  108612. }
  108613. }
  108614. info->postlist[0]=0;
  108615. info->postlist[1]=1<<rangebits;
  108616. return(info);
  108617. err_out:
  108618. floor1_free_info(info);
  108619. return(NULL);
  108620. }
  108621. static int icomp(const void *a,const void *b){
  108622. return(**(int **)a-**(int **)b);
  108623. }
  108624. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  108625. vorbis_info_floor *in){
  108626. int *sortpointer[VIF_POSIT+2];
  108627. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  108628. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  108629. int i,j,n=0;
  108630. look->vi=info;
  108631. look->n=info->postlist[1];
  108632. /* we drop each position value in-between already decoded values,
  108633. and use linear interpolation to predict each new value past the
  108634. edges. The positions are read in the order of the position
  108635. list... we precompute the bounding positions in the lookup. Of
  108636. course, the neighbors can change (if a position is declined), but
  108637. this is an initial mapping */
  108638. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  108639. n+=2;
  108640. look->posts=n;
  108641. /* also store a sorted position index */
  108642. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  108643. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  108644. /* points from sort order back to range number */
  108645. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  108646. /* points from range order to sorted position */
  108647. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  108648. /* we actually need the post values too */
  108649. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  108650. /* quantize values to multiplier spec */
  108651. switch(info->mult){
  108652. case 1: /* 1024 -> 256 */
  108653. look->quant_q=256;
  108654. break;
  108655. case 2: /* 1024 -> 128 */
  108656. look->quant_q=128;
  108657. break;
  108658. case 3: /* 1024 -> 86 */
  108659. look->quant_q=86;
  108660. break;
  108661. case 4: /* 1024 -> 64 */
  108662. look->quant_q=64;
  108663. break;
  108664. }
  108665. /* discover our neighbors for decode where we don't use fit flags
  108666. (that would push the neighbors outward) */
  108667. for(i=0;i<n-2;i++){
  108668. int lo=0;
  108669. int hi=1;
  108670. int lx=0;
  108671. int hx=look->n;
  108672. int currentx=info->postlist[i+2];
  108673. for(j=0;j<i+2;j++){
  108674. int x=info->postlist[j];
  108675. if(x>lx && x<currentx){
  108676. lo=j;
  108677. lx=x;
  108678. }
  108679. if(x<hx && x>currentx){
  108680. hi=j;
  108681. hx=x;
  108682. }
  108683. }
  108684. look->loneighbor[i]=lo;
  108685. look->hineighbor[i]=hi;
  108686. }
  108687. return(look);
  108688. }
  108689. static int render_point(int x0,int x1,int y0,int y1,int x){
  108690. y0&=0x7fff; /* mask off flag */
  108691. y1&=0x7fff;
  108692. {
  108693. int dy=y1-y0;
  108694. int adx=x1-x0;
  108695. int ady=abs(dy);
  108696. int err=ady*(x-x0);
  108697. int off=err/adx;
  108698. if(dy<0)return(y0-off);
  108699. return(y0+off);
  108700. }
  108701. }
  108702. static int vorbis_dBquant(const float *x){
  108703. int i= *x*7.3142857f+1023.5f;
  108704. if(i>1023)return(1023);
  108705. if(i<0)return(0);
  108706. return i;
  108707. }
  108708. static float FLOOR1_fromdB_LOOKUP[256]={
  108709. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108710. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108711. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108712. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108713. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108714. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108715. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108716. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108717. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108718. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108719. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108720. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108721. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108722. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108723. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108724. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108725. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108726. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108727. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108728. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108729. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108730. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108731. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108732. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108733. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108734. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108735. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108736. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108737. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108738. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108739. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108740. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108741. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108742. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108743. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108744. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108745. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108746. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108747. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108748. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108749. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108750. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108751. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108752. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108753. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108754. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108755. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108756. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108757. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108758. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108759. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108760. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108761. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108762. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108763. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108764. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108765. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108766. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108767. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108768. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108769. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108770. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108771. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108772. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108773. };
  108774. static void render_line(int x0,int x1,int y0,int y1,float *d){
  108775. int dy=y1-y0;
  108776. int adx=x1-x0;
  108777. int ady=abs(dy);
  108778. int base=dy/adx;
  108779. int sy=(dy<0?base-1:base+1);
  108780. int x=x0;
  108781. int y=y0;
  108782. int err=0;
  108783. ady-=abs(base*adx);
  108784. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108785. while(++x<x1){
  108786. err=err+ady;
  108787. if(err>=adx){
  108788. err-=adx;
  108789. y+=sy;
  108790. }else{
  108791. y+=base;
  108792. }
  108793. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108794. }
  108795. }
  108796. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  108797. int dy=y1-y0;
  108798. int adx=x1-x0;
  108799. int ady=abs(dy);
  108800. int base=dy/adx;
  108801. int sy=(dy<0?base-1:base+1);
  108802. int x=x0;
  108803. int y=y0;
  108804. int err=0;
  108805. ady-=abs(base*adx);
  108806. d[x]=y;
  108807. while(++x<x1){
  108808. err=err+ady;
  108809. if(err>=adx){
  108810. err-=adx;
  108811. y+=sy;
  108812. }else{
  108813. y+=base;
  108814. }
  108815. d[x]=y;
  108816. }
  108817. }
  108818. /* the floor has already been filtered to only include relevant sections */
  108819. static int accumulate_fit(const float *flr,const float *mdct,
  108820. int x0, int x1,lsfit_acc *a,
  108821. int n,vorbis_info_floor1 *info){
  108822. long i;
  108823. long xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
  108824. memset(a,0,sizeof(*a));
  108825. a->x0=x0;
  108826. a->x1=x1;
  108827. if(x1>=n)x1=n-1;
  108828. for(i=x0;i<=x1;i++){
  108829. int quantized=vorbis_dBquant(flr+i);
  108830. if(quantized){
  108831. if(mdct[i]+info->twofitatten>=flr[i]){
  108832. xa += i;
  108833. ya += quantized;
  108834. x2a += i*i;
  108835. y2a += quantized*quantized;
  108836. xya += i*quantized;
  108837. na++;
  108838. }else{
  108839. xb += i;
  108840. yb += quantized;
  108841. x2b += i*i;
  108842. y2b += quantized*quantized;
  108843. xyb += i*quantized;
  108844. nb++;
  108845. }
  108846. }
  108847. }
  108848. xb+=xa;
  108849. yb+=ya;
  108850. x2b+=x2a;
  108851. y2b+=y2a;
  108852. xyb+=xya;
  108853. nb+=na;
  108854. /* weight toward the actually used frequencies if we meet the threshhold */
  108855. {
  108856. int weight=nb*info->twofitweight/(na+1);
  108857. a->xa=xa*weight+xb;
  108858. a->ya=ya*weight+yb;
  108859. a->x2a=x2a*weight+x2b;
  108860. a->y2a=y2a*weight+y2b;
  108861. a->xya=xya*weight+xyb;
  108862. a->an=na*weight+nb;
  108863. }
  108864. return(na);
  108865. }
  108866. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  108867. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  108868. long x0=a[0].x0;
  108869. long x1=a[fits-1].x1;
  108870. for(i=0;i<fits;i++){
  108871. x+=a[i].xa;
  108872. y+=a[i].ya;
  108873. x2+=a[i].x2a;
  108874. y2+=a[i].y2a;
  108875. xy+=a[i].xya;
  108876. an+=a[i].an;
  108877. }
  108878. if(*y0>=0){
  108879. x+= x0;
  108880. y+= *y0;
  108881. x2+= x0 * x0;
  108882. y2+= *y0 * *y0;
  108883. xy+= *y0 * x0;
  108884. an++;
  108885. }
  108886. if(*y1>=0){
  108887. x+= x1;
  108888. y+= *y1;
  108889. x2+= x1 * x1;
  108890. y2+= *y1 * *y1;
  108891. xy+= *y1 * x1;
  108892. an++;
  108893. }
  108894. if(an){
  108895. /* need 64 bit multiplies, which C doesn't give portably as int */
  108896. double fx=x;
  108897. double fy=y;
  108898. double fx2=x2;
  108899. double fxy=xy;
  108900. double denom=1./(an*fx2-fx*fx);
  108901. double a=(fy*fx2-fxy*fx)*denom;
  108902. double b=(an*fxy-fx*fy)*denom;
  108903. *y0=rint(a+b*x0);
  108904. *y1=rint(a+b*x1);
  108905. /* limit to our range! */
  108906. if(*y0>1023)*y0=1023;
  108907. if(*y1>1023)*y1=1023;
  108908. if(*y0<0)*y0=0;
  108909. if(*y1<0)*y1=0;
  108910. }else{
  108911. *y0=0;
  108912. *y1=0;
  108913. }
  108914. }
  108915. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  108916. long y=0;
  108917. int i;
  108918. for(i=0;i<fits && y==0;i++)
  108919. y+=a[i].ya;
  108920. *y0=*y1=y;
  108921. }*/
  108922. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  108923. const float *mdct,
  108924. vorbis_info_floor1 *info){
  108925. int dy=y1-y0;
  108926. int adx=x1-x0;
  108927. int ady=abs(dy);
  108928. int base=dy/adx;
  108929. int sy=(dy<0?base-1:base+1);
  108930. int x=x0;
  108931. int y=y0;
  108932. int err=0;
  108933. int val=vorbis_dBquant(mask+x);
  108934. int mse=0;
  108935. int n=0;
  108936. ady-=abs(base*adx);
  108937. mse=(y-val);
  108938. mse*=mse;
  108939. n++;
  108940. if(mdct[x]+info->twofitatten>=mask[x]){
  108941. if(y+info->maxover<val)return(1);
  108942. if(y-info->maxunder>val)return(1);
  108943. }
  108944. while(++x<x1){
  108945. err=err+ady;
  108946. if(err>=adx){
  108947. err-=adx;
  108948. y+=sy;
  108949. }else{
  108950. y+=base;
  108951. }
  108952. val=vorbis_dBquant(mask+x);
  108953. mse+=((y-val)*(y-val));
  108954. n++;
  108955. if(mdct[x]+info->twofitatten>=mask[x]){
  108956. if(val){
  108957. if(y+info->maxover<val)return(1);
  108958. if(y-info->maxunder>val)return(1);
  108959. }
  108960. }
  108961. }
  108962. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  108963. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  108964. if(mse/n>info->maxerr)return(1);
  108965. return(0);
  108966. }
  108967. static int post_Y(int *A,int *B,int pos){
  108968. if(A[pos]<0)
  108969. return B[pos];
  108970. if(B[pos]<0)
  108971. return A[pos];
  108972. return (A[pos]+B[pos])>>1;
  108973. }
  108974. int *floor1_fit(vorbis_block *vb,void *look_,
  108975. const float *logmdct, /* in */
  108976. const float *logmask){
  108977. long i,j;
  108978. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  108979. vorbis_info_floor1 *info=look->vi;
  108980. long n=look->n;
  108981. long posts=look->posts;
  108982. long nonzero=0;
  108983. lsfit_acc fits[VIF_POSIT+1];
  108984. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  108985. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  108986. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  108987. int hineighbor[VIF_POSIT+2];
  108988. int *output=NULL;
  108989. int memo[VIF_POSIT+2];
  108990. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  108991. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  108992. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  108993. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  108994. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  108995. /* quantize the relevant floor points and collect them into line fit
  108996. structures (one per minimal division) at the same time */
  108997. if(posts==0){
  108998. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  108999. }else{
  109000. for(i=0;i<posts-1;i++)
  109001. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  109002. look->sorted_index[i+1],fits+i,
  109003. n,info);
  109004. }
  109005. if(nonzero){
  109006. /* start by fitting the implicit base case.... */
  109007. int y0=-200;
  109008. int y1=-200;
  109009. fit_line(fits,posts-1,&y0,&y1);
  109010. fit_valueA[0]=y0;
  109011. fit_valueB[0]=y0;
  109012. fit_valueB[1]=y1;
  109013. fit_valueA[1]=y1;
  109014. /* Non degenerate case */
  109015. /* start progressive splitting. This is a greedy, non-optimal
  109016. algorithm, but simple and close enough to the best
  109017. answer. */
  109018. for(i=2;i<posts;i++){
  109019. int sortpos=look->reverse_index[i];
  109020. int ln=loneighbor[sortpos];
  109021. int hn=hineighbor[sortpos];
  109022. /* eliminate repeat searches of a particular range with a memo */
  109023. if(memo[ln]!=hn){
  109024. /* haven't performed this error search yet */
  109025. int lsortpos=look->reverse_index[ln];
  109026. int hsortpos=look->reverse_index[hn];
  109027. memo[ln]=hn;
  109028. {
  109029. /* A note: we want to bound/minimize *local*, not global, error */
  109030. int lx=info->postlist[ln];
  109031. int hx=info->postlist[hn];
  109032. int ly=post_Y(fit_valueA,fit_valueB,ln);
  109033. int hy=post_Y(fit_valueA,fit_valueB,hn);
  109034. if(ly==-1 || hy==-1){
  109035. exit(1);
  109036. }
  109037. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  109038. /* outside error bounds/begin search area. Split it. */
  109039. int ly0=-200;
  109040. int ly1=-200;
  109041. int hy0=-200;
  109042. int hy1=-200;
  109043. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  109044. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  109045. /* store new edge values */
  109046. fit_valueB[ln]=ly0;
  109047. if(ln==0)fit_valueA[ln]=ly0;
  109048. fit_valueA[i]=ly1;
  109049. fit_valueB[i]=hy0;
  109050. fit_valueA[hn]=hy1;
  109051. if(hn==1)fit_valueB[hn]=hy1;
  109052. if(ly1>=0 || hy0>=0){
  109053. /* store new neighbor values */
  109054. for(j=sortpos-1;j>=0;j--)
  109055. if(hineighbor[j]==hn)
  109056. hineighbor[j]=i;
  109057. else
  109058. break;
  109059. for(j=sortpos+1;j<posts;j++)
  109060. if(loneighbor[j]==ln)
  109061. loneighbor[j]=i;
  109062. else
  109063. break;
  109064. }
  109065. }else{
  109066. fit_valueA[i]=-200;
  109067. fit_valueB[i]=-200;
  109068. }
  109069. }
  109070. }
  109071. }
  109072. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109073. output[0]=post_Y(fit_valueA,fit_valueB,0);
  109074. output[1]=post_Y(fit_valueA,fit_valueB,1);
  109075. /* fill in posts marked as not using a fit; we will zero
  109076. back out to 'unused' when encoding them so long as curve
  109077. interpolation doesn't force them into use */
  109078. for(i=2;i<posts;i++){
  109079. int ln=look->loneighbor[i-2];
  109080. int hn=look->hineighbor[i-2];
  109081. int x0=info->postlist[ln];
  109082. int x1=info->postlist[hn];
  109083. int y0=output[ln];
  109084. int y1=output[hn];
  109085. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109086. int vx=post_Y(fit_valueA,fit_valueB,i);
  109087. if(vx>=0 && predicted!=vx){
  109088. output[i]=vx;
  109089. }else{
  109090. output[i]= predicted|0x8000;
  109091. }
  109092. }
  109093. }
  109094. return(output);
  109095. }
  109096. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  109097. int *A,int *B,
  109098. int del){
  109099. long i;
  109100. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  109101. long posts=look->posts;
  109102. int *output=NULL;
  109103. if(A && B){
  109104. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109105. for(i=0;i<posts;i++){
  109106. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  109107. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  109108. }
  109109. }
  109110. return(output);
  109111. }
  109112. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109113. void*look_,
  109114. int *post,int *ilogmask){
  109115. long i,j;
  109116. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  109117. vorbis_info_floor1 *info=look->vi;
  109118. long posts=look->posts;
  109119. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109120. int out[VIF_POSIT+2];
  109121. static_codebook **sbooks=ci->book_param;
  109122. codebook *books=ci->fullbooks;
  109123. static long seq=0;
  109124. /* quantize values to multiplier spec */
  109125. if(post){
  109126. for(i=0;i<posts;i++){
  109127. int val=post[i]&0x7fff;
  109128. switch(info->mult){
  109129. case 1: /* 1024 -> 256 */
  109130. val>>=2;
  109131. break;
  109132. case 2: /* 1024 -> 128 */
  109133. val>>=3;
  109134. break;
  109135. case 3: /* 1024 -> 86 */
  109136. val/=12;
  109137. break;
  109138. case 4: /* 1024 -> 64 */
  109139. val>>=4;
  109140. break;
  109141. }
  109142. post[i]=val | (post[i]&0x8000);
  109143. }
  109144. out[0]=post[0];
  109145. out[1]=post[1];
  109146. /* find prediction values for each post and subtract them */
  109147. for(i=2;i<posts;i++){
  109148. int ln=look->loneighbor[i-2];
  109149. int hn=look->hineighbor[i-2];
  109150. int x0=info->postlist[ln];
  109151. int x1=info->postlist[hn];
  109152. int y0=post[ln];
  109153. int y1=post[hn];
  109154. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109155. if((post[i]&0x8000) || (predicted==post[i])){
  109156. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  109157. in interpolation */
  109158. out[i]=0;
  109159. }else{
  109160. int headroom=(look->quant_q-predicted<predicted?
  109161. look->quant_q-predicted:predicted);
  109162. int val=post[i]-predicted;
  109163. /* at this point the 'deviation' value is in the range +/- max
  109164. range, but the real, unique range can always be mapped to
  109165. only [0-maxrange). So we want to wrap the deviation into
  109166. this limited range, but do it in the way that least screws
  109167. an essentially gaussian probability distribution. */
  109168. if(val<0)
  109169. if(val<-headroom)
  109170. val=headroom-val-1;
  109171. else
  109172. val=-1-(val<<1);
  109173. else
  109174. if(val>=headroom)
  109175. val= val+headroom;
  109176. else
  109177. val<<=1;
  109178. out[i]=val;
  109179. post[ln]&=0x7fff;
  109180. post[hn]&=0x7fff;
  109181. }
  109182. }
  109183. /* we have everything we need. pack it out */
  109184. /* mark nontrivial floor */
  109185. oggpack_write(opb,1,1);
  109186. /* beginning/end post */
  109187. look->frames++;
  109188. look->postbits+=ilog(look->quant_q-1)*2;
  109189. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  109190. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  109191. /* partition by partition */
  109192. for(i=0,j=2;i<info->partitions;i++){
  109193. int classx=info->partitionclass[i];
  109194. int cdim=info->class_dim[classx];
  109195. int csubbits=info->class_subs[classx];
  109196. int csub=1<<csubbits;
  109197. int bookas[8]={0,0,0,0,0,0,0,0};
  109198. int cval=0;
  109199. int cshift=0;
  109200. int k,l;
  109201. /* generate the partition's first stage cascade value */
  109202. if(csubbits){
  109203. int maxval[8];
  109204. for(k=0;k<csub;k++){
  109205. int booknum=info->class_subbook[classx][k];
  109206. if(booknum<0){
  109207. maxval[k]=1;
  109208. }else{
  109209. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  109210. }
  109211. }
  109212. for(k=0;k<cdim;k++){
  109213. for(l=0;l<csub;l++){
  109214. int val=out[j+k];
  109215. if(val<maxval[l]){
  109216. bookas[k]=l;
  109217. break;
  109218. }
  109219. }
  109220. cval|= bookas[k]<<cshift;
  109221. cshift+=csubbits;
  109222. }
  109223. /* write it */
  109224. look->phrasebits+=
  109225. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  109226. #ifdef TRAIN_FLOOR1
  109227. {
  109228. FILE *of;
  109229. char buffer[80];
  109230. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  109231. vb->pcmend/2,posts-2,class);
  109232. of=fopen(buffer,"a");
  109233. fprintf(of,"%d\n",cval);
  109234. fclose(of);
  109235. }
  109236. #endif
  109237. }
  109238. /* write post values */
  109239. for(k=0;k<cdim;k++){
  109240. int book=info->class_subbook[classx][bookas[k]];
  109241. if(book>=0){
  109242. /* hack to allow training with 'bad' books */
  109243. if(out[j+k]<(books+book)->entries)
  109244. look->postbits+=vorbis_book_encode(books+book,
  109245. out[j+k],opb);
  109246. /*else
  109247. fprintf(stderr,"+!");*/
  109248. #ifdef TRAIN_FLOOR1
  109249. {
  109250. FILE *of;
  109251. char buffer[80];
  109252. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  109253. vb->pcmend/2,posts-2,class,bookas[k]);
  109254. of=fopen(buffer,"a");
  109255. fprintf(of,"%d\n",out[j+k]);
  109256. fclose(of);
  109257. }
  109258. #endif
  109259. }
  109260. }
  109261. j+=cdim;
  109262. }
  109263. {
  109264. /* generate quantized floor equivalent to what we'd unpack in decode */
  109265. /* render the lines */
  109266. int hx=0;
  109267. int lx=0;
  109268. int ly=post[0]*info->mult;
  109269. for(j=1;j<look->posts;j++){
  109270. int current=look->forward_index[j];
  109271. int hy=post[current]&0x7fff;
  109272. if(hy==post[current]){
  109273. hy*=info->mult;
  109274. hx=info->postlist[current];
  109275. render_line0(lx,hx,ly,hy,ilogmask);
  109276. lx=hx;
  109277. ly=hy;
  109278. }
  109279. }
  109280. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  109281. seq++;
  109282. return(1);
  109283. }
  109284. }else{
  109285. oggpack_write(opb,0,1);
  109286. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  109287. seq++;
  109288. return(0);
  109289. }
  109290. }
  109291. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  109292. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109293. vorbis_info_floor1 *info=look->vi;
  109294. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109295. int i,j,k;
  109296. codebook *books=ci->fullbooks;
  109297. /* unpack wrapped/predicted values from stream */
  109298. if(oggpack_read(&vb->opb,1)==1){
  109299. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  109300. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109301. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109302. /* partition by partition */
  109303. for(i=0,j=2;i<info->partitions;i++){
  109304. int classx=info->partitionclass[i];
  109305. int cdim=info->class_dim[classx];
  109306. int csubbits=info->class_subs[classx];
  109307. int csub=1<<csubbits;
  109308. int cval=0;
  109309. /* decode the partition's first stage cascade value */
  109310. if(csubbits){
  109311. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  109312. if(cval==-1)goto eop;
  109313. }
  109314. for(k=0;k<cdim;k++){
  109315. int book=info->class_subbook[classx][cval&(csub-1)];
  109316. cval>>=csubbits;
  109317. if(book>=0){
  109318. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  109319. goto eop;
  109320. }else{
  109321. fit_value[j+k]=0;
  109322. }
  109323. }
  109324. j+=cdim;
  109325. }
  109326. /* unwrap positive values and reconsitute via linear interpolation */
  109327. for(i=2;i<look->posts;i++){
  109328. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  109329. info->postlist[look->hineighbor[i-2]],
  109330. fit_value[look->loneighbor[i-2]],
  109331. fit_value[look->hineighbor[i-2]],
  109332. info->postlist[i]);
  109333. int hiroom=look->quant_q-predicted;
  109334. int loroom=predicted;
  109335. int room=(hiroom<loroom?hiroom:loroom)<<1;
  109336. int val=fit_value[i];
  109337. if(val){
  109338. if(val>=room){
  109339. if(hiroom>loroom){
  109340. val = val-loroom;
  109341. }else{
  109342. val = -1-(val-hiroom);
  109343. }
  109344. }else{
  109345. if(val&1){
  109346. val= -((val+1)>>1);
  109347. }else{
  109348. val>>=1;
  109349. }
  109350. }
  109351. fit_value[i]=val+predicted;
  109352. fit_value[look->loneighbor[i-2]]&=0x7fff;
  109353. fit_value[look->hineighbor[i-2]]&=0x7fff;
  109354. }else{
  109355. fit_value[i]=predicted|0x8000;
  109356. }
  109357. }
  109358. return(fit_value);
  109359. }
  109360. eop:
  109361. return(NULL);
  109362. }
  109363. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  109364. float *out){
  109365. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109366. vorbis_info_floor1 *info=look->vi;
  109367. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109368. int n=ci->blocksizes[vb->W]/2;
  109369. int j;
  109370. if(memo){
  109371. /* render the lines */
  109372. int *fit_value=(int *)memo;
  109373. int hx=0;
  109374. int lx=0;
  109375. int ly=fit_value[0]*info->mult;
  109376. for(j=1;j<look->posts;j++){
  109377. int current=look->forward_index[j];
  109378. int hy=fit_value[current]&0x7fff;
  109379. if(hy==fit_value[current]){
  109380. hy*=info->mult;
  109381. hx=info->postlist[current];
  109382. render_line(lx,hx,ly,hy,out);
  109383. lx=hx;
  109384. ly=hy;
  109385. }
  109386. }
  109387. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  109388. return(1);
  109389. }
  109390. memset(out,0,sizeof(*out)*n);
  109391. return(0);
  109392. }
  109393. /* export hooks */
  109394. vorbis_func_floor floor1_exportbundle={
  109395. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  109396. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  109397. };
  109398. #endif
  109399. /********* End of inlined file: floor1.c *********/
  109400. /********* Start of inlined file: info.c *********/
  109401. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109402. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109403. // tasks..
  109404. #if JUCE_MSVC
  109405. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109406. #endif
  109407. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109408. #if JUCE_USE_OGGVORBIS
  109409. /* general handling of the header and the vorbis_info structure (and
  109410. substructures) */
  109411. #include <stdlib.h>
  109412. #include <string.h>
  109413. #include <ctype.h>
  109414. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  109415. while(bytes--){
  109416. oggpack_write(o,*s++,8);
  109417. }
  109418. }
  109419. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  109420. while(bytes--){
  109421. *buf++=oggpack_read(o,8);
  109422. }
  109423. }
  109424. void vorbis_comment_init(vorbis_comment *vc){
  109425. memset(vc,0,sizeof(*vc));
  109426. }
  109427. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  109428. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  109429. (vc->comments+2)*sizeof(*vc->user_comments));
  109430. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  109431. (vc->comments+2)*sizeof(*vc->comment_lengths));
  109432. vc->comment_lengths[vc->comments]=strlen(comment);
  109433. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  109434. strcpy(vc->user_comments[vc->comments], comment);
  109435. vc->comments++;
  109436. vc->user_comments[vc->comments]=NULL;
  109437. }
  109438. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  109439. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  109440. strcpy(comment, tag);
  109441. strcat(comment, "=");
  109442. strcat(comment, contents);
  109443. vorbis_comment_add(vc, comment);
  109444. }
  109445. /* This is more or less the same as strncasecmp - but that doesn't exist
  109446. * everywhere, and this is a fairly trivial function, so we include it */
  109447. static int tagcompare(const char *s1, const char *s2, int n){
  109448. int c=0;
  109449. while(c < n){
  109450. if(toupper(s1[c]) != toupper(s2[c]))
  109451. return !0;
  109452. c++;
  109453. }
  109454. return 0;
  109455. }
  109456. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  109457. long i;
  109458. int found = 0;
  109459. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109460. char *fulltag = (char*)alloca(taglen+ 1);
  109461. strcpy(fulltag, tag);
  109462. strcat(fulltag, "=");
  109463. for(i=0;i<vc->comments;i++){
  109464. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  109465. if(count == found)
  109466. /* We return a pointer to the data, not a copy */
  109467. return vc->user_comments[i] + taglen;
  109468. else
  109469. found++;
  109470. }
  109471. }
  109472. return NULL; /* didn't find anything */
  109473. }
  109474. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  109475. int i,count=0;
  109476. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109477. char *fulltag = (char*)alloca(taglen+1);
  109478. strcpy(fulltag,tag);
  109479. strcat(fulltag, "=");
  109480. for(i=0;i<vc->comments;i++){
  109481. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  109482. count++;
  109483. }
  109484. return count;
  109485. }
  109486. void vorbis_comment_clear(vorbis_comment *vc){
  109487. if(vc){
  109488. long i;
  109489. for(i=0;i<vc->comments;i++)
  109490. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  109491. if(vc->user_comments)_ogg_free(vc->user_comments);
  109492. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  109493. if(vc->vendor)_ogg_free(vc->vendor);
  109494. }
  109495. memset(vc,0,sizeof(*vc));
  109496. }
  109497. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  109498. They may be equal, but short will never ge greater than long */
  109499. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  109500. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  109501. return ci ? ci->blocksizes[zo] : -1;
  109502. }
  109503. /* used by synthesis, which has a full, alloced vi */
  109504. void vorbis_info_init(vorbis_info *vi){
  109505. memset(vi,0,sizeof(*vi));
  109506. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  109507. }
  109508. void vorbis_info_clear(vorbis_info *vi){
  109509. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109510. int i;
  109511. if(ci){
  109512. for(i=0;i<ci->modes;i++)
  109513. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  109514. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  109515. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  109516. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  109517. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  109518. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  109519. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  109520. for(i=0;i<ci->books;i++){
  109521. if(ci->book_param[i]){
  109522. /* knows if the book was not alloced */
  109523. vorbis_staticbook_destroy(ci->book_param[i]);
  109524. }
  109525. if(ci->fullbooks)
  109526. vorbis_book_clear(ci->fullbooks+i);
  109527. }
  109528. if(ci->fullbooks)
  109529. _ogg_free(ci->fullbooks);
  109530. for(i=0;i<ci->psys;i++)
  109531. _vi_psy_free(ci->psy_param[i]);
  109532. _ogg_free(ci);
  109533. }
  109534. memset(vi,0,sizeof(*vi));
  109535. }
  109536. /* Header packing/unpacking ********************************************/
  109537. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  109538. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109539. if(!ci)return(OV_EFAULT);
  109540. vi->version=oggpack_read(opb,32);
  109541. if(vi->version!=0)return(OV_EVERSION);
  109542. vi->channels=oggpack_read(opb,8);
  109543. vi->rate=oggpack_read(opb,32);
  109544. vi->bitrate_upper=oggpack_read(opb,32);
  109545. vi->bitrate_nominal=oggpack_read(opb,32);
  109546. vi->bitrate_lower=oggpack_read(opb,32);
  109547. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  109548. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  109549. if(vi->rate<1)goto err_out;
  109550. if(vi->channels<1)goto err_out;
  109551. if(ci->blocksizes[0]<8)goto err_out;
  109552. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  109553. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109554. return(0);
  109555. err_out:
  109556. vorbis_info_clear(vi);
  109557. return(OV_EBADHEADER);
  109558. }
  109559. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  109560. int i;
  109561. int vendorlen=oggpack_read(opb,32);
  109562. if(vendorlen<0)goto err_out;
  109563. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  109564. _v_readstring(opb,vc->vendor,vendorlen);
  109565. vc->comments=oggpack_read(opb,32);
  109566. if(vc->comments<0)goto err_out;
  109567. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  109568. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  109569. for(i=0;i<vc->comments;i++){
  109570. int len=oggpack_read(opb,32);
  109571. if(len<0)goto err_out;
  109572. vc->comment_lengths[i]=len;
  109573. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  109574. _v_readstring(opb,vc->user_comments[i],len);
  109575. }
  109576. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109577. return(0);
  109578. err_out:
  109579. vorbis_comment_clear(vc);
  109580. return(OV_EBADHEADER);
  109581. }
  109582. /* all of the real encoding details are here. The modes, books,
  109583. everything */
  109584. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  109585. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109586. int i;
  109587. if(!ci)return(OV_EFAULT);
  109588. /* codebooks */
  109589. ci->books=oggpack_read(opb,8)+1;
  109590. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  109591. for(i=0;i<ci->books;i++){
  109592. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  109593. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  109594. }
  109595. /* time backend settings; hooks are unused */
  109596. {
  109597. int times=oggpack_read(opb,6)+1;
  109598. for(i=0;i<times;i++){
  109599. int test=oggpack_read(opb,16);
  109600. if(test<0 || test>=VI_TIMEB)goto err_out;
  109601. }
  109602. }
  109603. /* floor backend settings */
  109604. ci->floors=oggpack_read(opb,6)+1;
  109605. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  109606. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  109607. for(i=0;i<ci->floors;i++){
  109608. ci->floor_type[i]=oggpack_read(opb,16);
  109609. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  109610. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  109611. if(!ci->floor_param[i])goto err_out;
  109612. }
  109613. /* residue backend settings */
  109614. ci->residues=oggpack_read(opb,6)+1;
  109615. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  109616. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  109617. for(i=0;i<ci->residues;i++){
  109618. ci->residue_type[i]=oggpack_read(opb,16);
  109619. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  109620. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  109621. if(!ci->residue_param[i])goto err_out;
  109622. }
  109623. /* map backend settings */
  109624. ci->maps=oggpack_read(opb,6)+1;
  109625. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  109626. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  109627. for(i=0;i<ci->maps;i++){
  109628. ci->map_type[i]=oggpack_read(opb,16);
  109629. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  109630. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  109631. if(!ci->map_param[i])goto err_out;
  109632. }
  109633. /* mode settings */
  109634. ci->modes=oggpack_read(opb,6)+1;
  109635. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  109636. for(i=0;i<ci->modes;i++){
  109637. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  109638. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  109639. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  109640. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  109641. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  109642. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  109643. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  109644. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  109645. }
  109646. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  109647. return(0);
  109648. err_out:
  109649. vorbis_info_clear(vi);
  109650. return(OV_EBADHEADER);
  109651. }
  109652. /* The Vorbis header is in three packets; the initial small packet in
  109653. the first page that identifies basic parameters, a second packet
  109654. with bitstream comments and a third packet that holds the
  109655. codebook. */
  109656. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  109657. oggpack_buffer opb;
  109658. if(op){
  109659. oggpack_readinit(&opb,op->packet,op->bytes);
  109660. /* Which of the three types of header is this? */
  109661. /* Also verify header-ness, vorbis */
  109662. {
  109663. char buffer[6];
  109664. int packtype=oggpack_read(&opb,8);
  109665. memset(buffer,0,6);
  109666. _v_readstring(&opb,buffer,6);
  109667. if(memcmp(buffer,"vorbis",6)){
  109668. /* not a vorbis header */
  109669. return(OV_ENOTVORBIS);
  109670. }
  109671. switch(packtype){
  109672. case 0x01: /* least significant *bit* is read first */
  109673. if(!op->b_o_s){
  109674. /* Not the initial packet */
  109675. return(OV_EBADHEADER);
  109676. }
  109677. if(vi->rate!=0){
  109678. /* previously initialized info header */
  109679. return(OV_EBADHEADER);
  109680. }
  109681. return(_vorbis_unpack_info(vi,&opb));
  109682. case 0x03: /* least significant *bit* is read first */
  109683. if(vi->rate==0){
  109684. /* um... we didn't get the initial header */
  109685. return(OV_EBADHEADER);
  109686. }
  109687. return(_vorbis_unpack_comment(vc,&opb));
  109688. case 0x05: /* least significant *bit* is read first */
  109689. if(vi->rate==0 || vc->vendor==NULL){
  109690. /* um... we didn;t get the initial header or comments yet */
  109691. return(OV_EBADHEADER);
  109692. }
  109693. return(_vorbis_unpack_books(vi,&opb));
  109694. default:
  109695. /* Not a valid vorbis header type */
  109696. return(OV_EBADHEADER);
  109697. break;
  109698. }
  109699. }
  109700. }
  109701. return(OV_EBADHEADER);
  109702. }
  109703. /* pack side **********************************************************/
  109704. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  109705. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109706. if(!ci)return(OV_EFAULT);
  109707. /* preamble */
  109708. oggpack_write(opb,0x01,8);
  109709. _v_writestring(opb,"vorbis", 6);
  109710. /* basic information about the stream */
  109711. oggpack_write(opb,0x00,32);
  109712. oggpack_write(opb,vi->channels,8);
  109713. oggpack_write(opb,vi->rate,32);
  109714. oggpack_write(opb,vi->bitrate_upper,32);
  109715. oggpack_write(opb,vi->bitrate_nominal,32);
  109716. oggpack_write(opb,vi->bitrate_lower,32);
  109717. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  109718. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  109719. oggpack_write(opb,1,1);
  109720. return(0);
  109721. }
  109722. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  109723. char temp[]="Xiph.Org libVorbis I 20050304";
  109724. int bytes = strlen(temp);
  109725. /* preamble */
  109726. oggpack_write(opb,0x03,8);
  109727. _v_writestring(opb,"vorbis", 6);
  109728. /* vendor */
  109729. oggpack_write(opb,bytes,32);
  109730. _v_writestring(opb,temp, bytes);
  109731. /* comments */
  109732. oggpack_write(opb,vc->comments,32);
  109733. if(vc->comments){
  109734. int i;
  109735. for(i=0;i<vc->comments;i++){
  109736. if(vc->user_comments[i]){
  109737. oggpack_write(opb,vc->comment_lengths[i],32);
  109738. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  109739. }else{
  109740. oggpack_write(opb,0,32);
  109741. }
  109742. }
  109743. }
  109744. oggpack_write(opb,1,1);
  109745. return(0);
  109746. }
  109747. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  109748. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109749. int i;
  109750. if(!ci)return(OV_EFAULT);
  109751. oggpack_write(opb,0x05,8);
  109752. _v_writestring(opb,"vorbis", 6);
  109753. /* books */
  109754. oggpack_write(opb,ci->books-1,8);
  109755. for(i=0;i<ci->books;i++)
  109756. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  109757. /* times; hook placeholders */
  109758. oggpack_write(opb,0,6);
  109759. oggpack_write(opb,0,16);
  109760. /* floors */
  109761. oggpack_write(opb,ci->floors-1,6);
  109762. for(i=0;i<ci->floors;i++){
  109763. oggpack_write(opb,ci->floor_type[i],16);
  109764. if(_floor_P[ci->floor_type[i]]->pack)
  109765. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  109766. else
  109767. goto err_out;
  109768. }
  109769. /* residues */
  109770. oggpack_write(opb,ci->residues-1,6);
  109771. for(i=0;i<ci->residues;i++){
  109772. oggpack_write(opb,ci->residue_type[i],16);
  109773. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  109774. }
  109775. /* maps */
  109776. oggpack_write(opb,ci->maps-1,6);
  109777. for(i=0;i<ci->maps;i++){
  109778. oggpack_write(opb,ci->map_type[i],16);
  109779. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  109780. }
  109781. /* modes */
  109782. oggpack_write(opb,ci->modes-1,6);
  109783. for(i=0;i<ci->modes;i++){
  109784. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  109785. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  109786. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  109787. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  109788. }
  109789. oggpack_write(opb,1,1);
  109790. return(0);
  109791. err_out:
  109792. return(-1);
  109793. }
  109794. int vorbis_commentheader_out(vorbis_comment *vc,
  109795. ogg_packet *op){
  109796. oggpack_buffer opb;
  109797. oggpack_writeinit(&opb);
  109798. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  109799. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109800. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  109801. op->bytes=oggpack_bytes(&opb);
  109802. op->b_o_s=0;
  109803. op->e_o_s=0;
  109804. op->granulepos=0;
  109805. op->packetno=1;
  109806. return 0;
  109807. }
  109808. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  109809. vorbis_comment *vc,
  109810. ogg_packet *op,
  109811. ogg_packet *op_comm,
  109812. ogg_packet *op_code){
  109813. int ret=OV_EIMPL;
  109814. vorbis_info *vi=v->vi;
  109815. oggpack_buffer opb;
  109816. private_state *b=(private_state*)v->backend_state;
  109817. if(!b){
  109818. ret=OV_EFAULT;
  109819. goto err_out;
  109820. }
  109821. /* first header packet **********************************************/
  109822. oggpack_writeinit(&opb);
  109823. if(_vorbis_pack_info(&opb,vi))goto err_out;
  109824. /* build the packet */
  109825. if(b->header)_ogg_free(b->header);
  109826. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109827. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  109828. op->packet=b->header;
  109829. op->bytes=oggpack_bytes(&opb);
  109830. op->b_o_s=1;
  109831. op->e_o_s=0;
  109832. op->granulepos=0;
  109833. op->packetno=0;
  109834. /* second header packet (comments) **********************************/
  109835. oggpack_reset(&opb);
  109836. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  109837. if(b->header1)_ogg_free(b->header1);
  109838. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109839. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  109840. op_comm->packet=b->header1;
  109841. op_comm->bytes=oggpack_bytes(&opb);
  109842. op_comm->b_o_s=0;
  109843. op_comm->e_o_s=0;
  109844. op_comm->granulepos=0;
  109845. op_comm->packetno=1;
  109846. /* third header packet (modes/codebooks) ****************************/
  109847. oggpack_reset(&opb);
  109848. if(_vorbis_pack_books(&opb,vi))goto err_out;
  109849. if(b->header2)_ogg_free(b->header2);
  109850. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109851. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  109852. op_code->packet=b->header2;
  109853. op_code->bytes=oggpack_bytes(&opb);
  109854. op_code->b_o_s=0;
  109855. op_code->e_o_s=0;
  109856. op_code->granulepos=0;
  109857. op_code->packetno=2;
  109858. oggpack_writeclear(&opb);
  109859. return(0);
  109860. err_out:
  109861. oggpack_writeclear(&opb);
  109862. memset(op,0,sizeof(*op));
  109863. memset(op_comm,0,sizeof(*op_comm));
  109864. memset(op_code,0,sizeof(*op_code));
  109865. if(b->header)_ogg_free(b->header);
  109866. if(b->header1)_ogg_free(b->header1);
  109867. if(b->header2)_ogg_free(b->header2);
  109868. b->header=NULL;
  109869. b->header1=NULL;
  109870. b->header2=NULL;
  109871. return(ret);
  109872. }
  109873. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  109874. if(granulepos>=0)
  109875. return((double)granulepos/v->vi->rate);
  109876. return(-1);
  109877. }
  109878. #endif
  109879. /********* End of inlined file: info.c *********/
  109880. /********* Start of inlined file: lpc.c *********/
  109881. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  109882. are derived from code written by Jutta Degener and Carsten Bormann;
  109883. thus we include their copyright below. The entirety of this file
  109884. is freely redistributable on the condition that both of these
  109885. copyright notices are preserved without modification. */
  109886. /* Preserved Copyright: *********************************************/
  109887. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  109888. Technische Universita"t Berlin
  109889. Any use of this software is permitted provided that this notice is not
  109890. removed and that neither the authors nor the Technische Universita"t
  109891. Berlin are deemed to have made any representations as to the
  109892. suitability of this software for any purpose nor are held responsible
  109893. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  109894. THIS SOFTWARE.
  109895. As a matter of courtesy, the authors request to be informed about uses
  109896. this software has found, about bugs in this software, and about any
  109897. improvements that may be of general interest.
  109898. Berlin, 28.11.1994
  109899. Jutta Degener
  109900. Carsten Bormann
  109901. *********************************************************************/
  109902. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109903. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109904. // tasks..
  109905. #if JUCE_MSVC
  109906. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109907. #endif
  109908. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109909. #if JUCE_USE_OGGVORBIS
  109910. #include <stdlib.h>
  109911. #include <string.h>
  109912. #include <math.h>
  109913. /* Autocorrelation LPC coeff generation algorithm invented by
  109914. N. Levinson in 1947, modified by J. Durbin in 1959. */
  109915. /* Input : n elements of time doamin data
  109916. Output: m lpc coefficients, excitation energy */
  109917. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  109918. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  109919. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  109920. double error;
  109921. int i,j;
  109922. /* autocorrelation, p+1 lag coefficients */
  109923. j=m+1;
  109924. while(j--){
  109925. double d=0; /* double needed for accumulator depth */
  109926. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  109927. aut[j]=d;
  109928. }
  109929. /* Generate lpc coefficients from autocorr values */
  109930. error=aut[0];
  109931. for(i=0;i<m;i++){
  109932. double r= -aut[i+1];
  109933. if(error==0){
  109934. memset(lpci,0,m*sizeof(*lpci));
  109935. return 0;
  109936. }
  109937. /* Sum up this iteration's reflection coefficient; note that in
  109938. Vorbis we don't save it. If anyone wants to recycle this code
  109939. and needs reflection coefficients, save the results of 'r' from
  109940. each iteration. */
  109941. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  109942. r/=error;
  109943. /* Update LPC coefficients and total error */
  109944. lpc[i]=r;
  109945. for(j=0;j<i/2;j++){
  109946. double tmp=lpc[j];
  109947. lpc[j]+=r*lpc[i-1-j];
  109948. lpc[i-1-j]+=r*tmp;
  109949. }
  109950. if(i%2)lpc[j]+=lpc[j]*r;
  109951. error*=1.f-r*r;
  109952. }
  109953. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  109954. /* we need the error value to know how big an impulse to hit the
  109955. filter with later */
  109956. return error;
  109957. }
  109958. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109959. float *data,long n){
  109960. /* in: coeff[0...m-1] LPC coefficients
  109961. prime[0...m-1] initial values (allocated size of n+m-1)
  109962. out: data[0...n-1] data samples */
  109963. long i,j,o,p;
  109964. float y;
  109965. float *work=(float*)alloca(sizeof(*work)*(m+n));
  109966. if(!prime)
  109967. for(i=0;i<m;i++)
  109968. work[i]=0.f;
  109969. else
  109970. for(i=0;i<m;i++)
  109971. work[i]=prime[i];
  109972. for(i=0;i<n;i++){
  109973. y=0;
  109974. o=i;
  109975. p=m;
  109976. for(j=0;j<m;j++)
  109977. y-=work[o++]*coeff[--p];
  109978. data[i]=work[o]=y;
  109979. }
  109980. }
  109981. #endif
  109982. /********* End of inlined file: lpc.c *********/
  109983. /********* Start of inlined file: lsp.c *********/
  109984. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  109985. an iterative root polisher (CACM algorithm 283). It *is* possible
  109986. to confuse this algorithm into not converging; that should only
  109987. happen with absurdly closely spaced roots (very sharp peaks in the
  109988. LPC f response) which in turn should be impossible in our use of
  109989. the code. If this *does* happen anyway, it's a bug in the floor
  109990. finder; find the cause of the confusion (probably a single bin
  109991. spike or accidental near-float-limit resolution problems) and
  109992. correct it. */
  109993. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109994. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109995. // tasks..
  109996. #if JUCE_MSVC
  109997. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109998. #endif
  109999. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110000. #if JUCE_USE_OGGVORBIS
  110001. #include <math.h>
  110002. #include <string.h>
  110003. #include <stdlib.h>
  110004. /********* Start of inlined file: lookup.h *********/
  110005. #ifndef _V_LOOKUP_H_
  110006. #ifdef FLOAT_LOOKUP
  110007. extern float vorbis_coslook(float a);
  110008. extern float vorbis_invsqlook(float a);
  110009. extern float vorbis_invsq2explook(int a);
  110010. extern float vorbis_fromdBlook(float a);
  110011. #endif
  110012. #ifdef INT_LOOKUP
  110013. extern long vorbis_invsqlook_i(long a,long e);
  110014. extern long vorbis_coslook_i(long a);
  110015. extern float vorbis_fromdBlook_i(long a);
  110016. #endif
  110017. #endif
  110018. /********* End of inlined file: lookup.h *********/
  110019. /* three possible LSP to f curve functions; the exact computation
  110020. (float), a lookup based float implementation, and an integer
  110021. implementation. The float lookup is likely the optimal choice on
  110022. any machine with an FPU. The integer implementation is *not* fixed
  110023. point (due to the need for a large dynamic range and thus a
  110024. seperately tracked exponent) and thus much more complex than the
  110025. relatively simple float implementations. It's mostly for future
  110026. work on a fully fixed point implementation for processors like the
  110027. ARM family. */
  110028. /* undefine both for the 'old' but more precise implementation */
  110029. #define FLOAT_LOOKUP
  110030. #undef INT_LOOKUP
  110031. #ifdef FLOAT_LOOKUP
  110032. /********* Start of inlined file: lookup.c *********/
  110033. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110034. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110035. // tasks..
  110036. #if JUCE_MSVC
  110037. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110038. #endif
  110039. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110040. #if JUCE_USE_OGGVORBIS
  110041. #include <math.h>
  110042. /********* Start of inlined file: lookup.h *********/
  110043. #ifndef _V_LOOKUP_H_
  110044. #ifdef FLOAT_LOOKUP
  110045. extern float vorbis_coslook(float a);
  110046. extern float vorbis_invsqlook(float a);
  110047. extern float vorbis_invsq2explook(int a);
  110048. extern float vorbis_fromdBlook(float a);
  110049. #endif
  110050. #ifdef INT_LOOKUP
  110051. extern long vorbis_invsqlook_i(long a,long e);
  110052. extern long vorbis_coslook_i(long a);
  110053. extern float vorbis_fromdBlook_i(long a);
  110054. #endif
  110055. #endif
  110056. /********* End of inlined file: lookup.h *********/
  110057. /********* Start of inlined file: lookup_data.h *********/
  110058. #ifndef _V_LOOKUP_DATA_H_
  110059. #ifdef FLOAT_LOOKUP
  110060. #define COS_LOOKUP_SZ 128
  110061. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110062. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110063. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110064. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110065. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110066. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110067. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110068. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110069. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110070. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110071. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110072. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110073. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110074. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110075. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110076. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110077. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110078. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110079. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110080. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110081. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110082. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110083. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110084. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110085. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110086. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110087. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110088. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110089. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110090. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110091. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110092. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110093. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110094. -1.0000000000000f,
  110095. };
  110096. #define INVSQ_LOOKUP_SZ 32
  110097. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110098. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110099. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110100. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110101. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110102. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110103. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110104. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110105. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110106. 1.000000000000f,
  110107. };
  110108. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110109. #define INVSQ2EXP_LOOKUP_MAX 32
  110110. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110111. INVSQ2EXP_LOOKUP_MIN+1]={
  110112. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110113. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110114. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110115. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110116. 256.f, 181.019336f, 128.f, 90.50966799f,
  110117. 64.f, 45.254834f, 32.f, 22.627417f,
  110118. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110119. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110120. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110121. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110122. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110123. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110124. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110125. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110126. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110127. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110128. 1.525878906e-05f,
  110129. };
  110130. #endif
  110131. #define FROMdB_LOOKUP_SZ 35
  110132. #define FROMdB2_LOOKUP_SZ 32
  110133. #define FROMdB_SHIFT 5
  110134. #define FROMdB2_SHIFT 3
  110135. #define FROMdB2_MASK 31
  110136. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110137. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110138. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110139. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110140. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110141. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110142. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110143. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110144. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110145. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110146. };
  110147. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110148. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110149. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110150. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110151. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110152. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110153. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110154. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110155. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110156. };
  110157. #ifdef INT_LOOKUP
  110158. #define INVSQ_LOOKUP_I_SHIFT 10
  110159. #define INVSQ_LOOKUP_I_MASK 1023
  110160. static long INVSQ_LOOKUP_I[64+1]={
  110161. 92682l, 91966l, 91267l, 90583l,
  110162. 89915l, 89261l, 88621l, 87995l,
  110163. 87381l, 86781l, 86192l, 85616l,
  110164. 85051l, 84497l, 83953l, 83420l,
  110165. 82897l, 82384l, 81880l, 81385l,
  110166. 80899l, 80422l, 79953l, 79492l,
  110167. 79039l, 78594l, 78156l, 77726l,
  110168. 77302l, 76885l, 76475l, 76072l,
  110169. 75674l, 75283l, 74898l, 74519l,
  110170. 74146l, 73778l, 73415l, 73058l,
  110171. 72706l, 72359l, 72016l, 71679l,
  110172. 71347l, 71019l, 70695l, 70376l,
  110173. 70061l, 69750l, 69444l, 69141l,
  110174. 68842l, 68548l, 68256l, 67969l,
  110175. 67685l, 67405l, 67128l, 66855l,
  110176. 66585l, 66318l, 66054l, 65794l,
  110177. 65536l,
  110178. };
  110179. #define COS_LOOKUP_I_SHIFT 9
  110180. #define COS_LOOKUP_I_MASK 511
  110181. #define COS_LOOKUP_I_SZ 128
  110182. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110183. 16384l, 16379l, 16364l, 16340l,
  110184. 16305l, 16261l, 16207l, 16143l,
  110185. 16069l, 15986l, 15893l, 15791l,
  110186. 15679l, 15557l, 15426l, 15286l,
  110187. 15137l, 14978l, 14811l, 14635l,
  110188. 14449l, 14256l, 14053l, 13842l,
  110189. 13623l, 13395l, 13160l, 12916l,
  110190. 12665l, 12406l, 12140l, 11866l,
  110191. 11585l, 11297l, 11003l, 10702l,
  110192. 10394l, 10080l, 9760l, 9434l,
  110193. 9102l, 8765l, 8423l, 8076l,
  110194. 7723l, 7366l, 7005l, 6639l,
  110195. 6270l, 5897l, 5520l, 5139l,
  110196. 4756l, 4370l, 3981l, 3590l,
  110197. 3196l, 2801l, 2404l, 2006l,
  110198. 1606l, 1205l, 804l, 402l,
  110199. 0l, -401l, -803l, -1204l,
  110200. -1605l, -2005l, -2403l, -2800l,
  110201. -3195l, -3589l, -3980l, -4369l,
  110202. -4755l, -5138l, -5519l, -5896l,
  110203. -6269l, -6638l, -7004l, -7365l,
  110204. -7722l, -8075l, -8422l, -8764l,
  110205. -9101l, -9433l, -9759l, -10079l,
  110206. -10393l, -10701l, -11002l, -11296l,
  110207. -11584l, -11865l, -12139l, -12405l,
  110208. -12664l, -12915l, -13159l, -13394l,
  110209. -13622l, -13841l, -14052l, -14255l,
  110210. -14448l, -14634l, -14810l, -14977l,
  110211. -15136l, -15285l, -15425l, -15556l,
  110212. -15678l, -15790l, -15892l, -15985l,
  110213. -16068l, -16142l, -16206l, -16260l,
  110214. -16304l, -16339l, -16363l, -16378l,
  110215. -16383l,
  110216. };
  110217. #endif
  110218. #endif
  110219. /********* End of inlined file: lookup_data.h *********/
  110220. #ifdef FLOAT_LOOKUP
  110221. /* interpolated lookup based cos function, domain 0 to PI only */
  110222. float vorbis_coslook(float a){
  110223. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110224. int i=vorbis_ftoi(d-.5);
  110225. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110226. }
  110227. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110228. float vorbis_invsqlook(float a){
  110229. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110230. int i=vorbis_ftoi(d-.5f);
  110231. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110232. }
  110233. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110234. float vorbis_invsq2explook(int a){
  110235. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110236. }
  110237. #include <stdio.h>
  110238. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110239. float vorbis_fromdBlook(float a){
  110240. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110241. return (i<0)?1.f:
  110242. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110243. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110244. }
  110245. #endif
  110246. #ifdef INT_LOOKUP
  110247. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110248. 16.16 format
  110249. returns in m.8 format */
  110250. long vorbis_invsqlook_i(long a,long e){
  110251. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110252. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110253. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110254. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110255. d)>>16); /* result 1.16 */
  110256. e+=32;
  110257. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110258. e=(e>>1)-8;
  110259. return(val>>e);
  110260. }
  110261. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110262. /* a is in n.12 format */
  110263. float vorbis_fromdBlook_i(long a){
  110264. int i=(-a)>>(12-FROMdB2_SHIFT);
  110265. return (i<0)?1.f:
  110266. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110267. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110268. }
  110269. /* interpolated lookup based cos function, domain 0 to PI only */
  110270. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110271. long vorbis_coslook_i(long a){
  110272. int i=a>>COS_LOOKUP_I_SHIFT;
  110273. int d=a&COS_LOOKUP_I_MASK;
  110274. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110275. COS_LOOKUP_I_SHIFT);
  110276. }
  110277. #endif
  110278. #endif
  110279. /********* End of inlined file: lookup.c *********/
  110280. /* catch this in the build system; we #include for
  110281. compilers (like gcc) that can't inline across
  110282. modules */
  110283. /* side effect: changes *lsp to cosines of lsp */
  110284. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110285. float amp,float ampoffset){
  110286. int i;
  110287. float wdel=M_PI/ln;
  110288. vorbis_fpu_control fpu;
  110289. (void) fpu; // to avoid an unused variable warning
  110290. vorbis_fpu_setround(&fpu);
  110291. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  110292. i=0;
  110293. while(i<n){
  110294. int k=map[i];
  110295. int qexp;
  110296. float p=.7071067812f;
  110297. float q=.7071067812f;
  110298. float w=vorbis_coslook(wdel*k);
  110299. float *ftmp=lsp;
  110300. int c=m>>1;
  110301. do{
  110302. q*=ftmp[0]-w;
  110303. p*=ftmp[1]-w;
  110304. ftmp+=2;
  110305. }while(--c);
  110306. if(m&1){
  110307. /* odd order filter; slightly assymetric */
  110308. /* the last coefficient */
  110309. q*=ftmp[0]-w;
  110310. q*=q;
  110311. p*=p*(1.f-w*w);
  110312. }else{
  110313. /* even order filter; still symmetric */
  110314. q*=q*(1.f+w);
  110315. p*=p*(1.f-w);
  110316. }
  110317. q=frexp(p+q,&qexp);
  110318. q=vorbis_fromdBlook(amp*
  110319. vorbis_invsqlook(q)*
  110320. vorbis_invsq2explook(qexp+m)-
  110321. ampoffset);
  110322. do{
  110323. curve[i++]*=q;
  110324. }while(map[i]==k);
  110325. }
  110326. vorbis_fpu_restore(fpu);
  110327. }
  110328. #else
  110329. #ifdef INT_LOOKUP
  110330. /********* Start of inlined file: lookup.c *********/
  110331. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110332. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110333. // tasks..
  110334. #if JUCE_MSVC
  110335. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110336. #endif
  110337. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110338. #if JUCE_USE_OGGVORBIS
  110339. #include <math.h>
  110340. /********* Start of inlined file: lookup.h *********/
  110341. #ifndef _V_LOOKUP_H_
  110342. #ifdef FLOAT_LOOKUP
  110343. extern float vorbis_coslook(float a);
  110344. extern float vorbis_invsqlook(float a);
  110345. extern float vorbis_invsq2explook(int a);
  110346. extern float vorbis_fromdBlook(float a);
  110347. #endif
  110348. #ifdef INT_LOOKUP
  110349. extern long vorbis_invsqlook_i(long a,long e);
  110350. extern long vorbis_coslook_i(long a);
  110351. extern float vorbis_fromdBlook_i(long a);
  110352. #endif
  110353. #endif
  110354. /********* End of inlined file: lookup.h *********/
  110355. /********* Start of inlined file: lookup_data.h *********/
  110356. #ifndef _V_LOOKUP_DATA_H_
  110357. #ifdef FLOAT_LOOKUP
  110358. #define COS_LOOKUP_SZ 128
  110359. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110360. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110361. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110362. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110363. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110364. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110365. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110366. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110367. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110368. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110369. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110370. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110371. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110372. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110373. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110374. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110375. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110376. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110377. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110378. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110379. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110380. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110381. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110382. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110383. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110384. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110385. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110386. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110387. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110388. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110389. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110390. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110391. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110392. -1.0000000000000f,
  110393. };
  110394. #define INVSQ_LOOKUP_SZ 32
  110395. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110396. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110397. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110398. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110399. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110400. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110401. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110402. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110403. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110404. 1.000000000000f,
  110405. };
  110406. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110407. #define INVSQ2EXP_LOOKUP_MAX 32
  110408. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110409. INVSQ2EXP_LOOKUP_MIN+1]={
  110410. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110411. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110412. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110413. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110414. 256.f, 181.019336f, 128.f, 90.50966799f,
  110415. 64.f, 45.254834f, 32.f, 22.627417f,
  110416. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110417. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110418. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110419. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110420. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110421. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110422. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110423. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110424. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110425. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110426. 1.525878906e-05f,
  110427. };
  110428. #endif
  110429. #define FROMdB_LOOKUP_SZ 35
  110430. #define FROMdB2_LOOKUP_SZ 32
  110431. #define FROMdB_SHIFT 5
  110432. #define FROMdB2_SHIFT 3
  110433. #define FROMdB2_MASK 31
  110434. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110435. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110436. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110437. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110438. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110439. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110440. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110441. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110442. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110443. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110444. };
  110445. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110446. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110447. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110448. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110449. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110450. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110451. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110452. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110453. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110454. };
  110455. #ifdef INT_LOOKUP
  110456. #define INVSQ_LOOKUP_I_SHIFT 10
  110457. #define INVSQ_LOOKUP_I_MASK 1023
  110458. static long INVSQ_LOOKUP_I[64+1]={
  110459. 92682l, 91966l, 91267l, 90583l,
  110460. 89915l, 89261l, 88621l, 87995l,
  110461. 87381l, 86781l, 86192l, 85616l,
  110462. 85051l, 84497l, 83953l, 83420l,
  110463. 82897l, 82384l, 81880l, 81385l,
  110464. 80899l, 80422l, 79953l, 79492l,
  110465. 79039l, 78594l, 78156l, 77726l,
  110466. 77302l, 76885l, 76475l, 76072l,
  110467. 75674l, 75283l, 74898l, 74519l,
  110468. 74146l, 73778l, 73415l, 73058l,
  110469. 72706l, 72359l, 72016l, 71679l,
  110470. 71347l, 71019l, 70695l, 70376l,
  110471. 70061l, 69750l, 69444l, 69141l,
  110472. 68842l, 68548l, 68256l, 67969l,
  110473. 67685l, 67405l, 67128l, 66855l,
  110474. 66585l, 66318l, 66054l, 65794l,
  110475. 65536l,
  110476. };
  110477. #define COS_LOOKUP_I_SHIFT 9
  110478. #define COS_LOOKUP_I_MASK 511
  110479. #define COS_LOOKUP_I_SZ 128
  110480. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110481. 16384l, 16379l, 16364l, 16340l,
  110482. 16305l, 16261l, 16207l, 16143l,
  110483. 16069l, 15986l, 15893l, 15791l,
  110484. 15679l, 15557l, 15426l, 15286l,
  110485. 15137l, 14978l, 14811l, 14635l,
  110486. 14449l, 14256l, 14053l, 13842l,
  110487. 13623l, 13395l, 13160l, 12916l,
  110488. 12665l, 12406l, 12140l, 11866l,
  110489. 11585l, 11297l, 11003l, 10702l,
  110490. 10394l, 10080l, 9760l, 9434l,
  110491. 9102l, 8765l, 8423l, 8076l,
  110492. 7723l, 7366l, 7005l, 6639l,
  110493. 6270l, 5897l, 5520l, 5139l,
  110494. 4756l, 4370l, 3981l, 3590l,
  110495. 3196l, 2801l, 2404l, 2006l,
  110496. 1606l, 1205l, 804l, 402l,
  110497. 0l, -401l, -803l, -1204l,
  110498. -1605l, -2005l, -2403l, -2800l,
  110499. -3195l, -3589l, -3980l, -4369l,
  110500. -4755l, -5138l, -5519l, -5896l,
  110501. -6269l, -6638l, -7004l, -7365l,
  110502. -7722l, -8075l, -8422l, -8764l,
  110503. -9101l, -9433l, -9759l, -10079l,
  110504. -10393l, -10701l, -11002l, -11296l,
  110505. -11584l, -11865l, -12139l, -12405l,
  110506. -12664l, -12915l, -13159l, -13394l,
  110507. -13622l, -13841l, -14052l, -14255l,
  110508. -14448l, -14634l, -14810l, -14977l,
  110509. -15136l, -15285l, -15425l, -15556l,
  110510. -15678l, -15790l, -15892l, -15985l,
  110511. -16068l, -16142l, -16206l, -16260l,
  110512. -16304l, -16339l, -16363l, -16378l,
  110513. -16383l,
  110514. };
  110515. #endif
  110516. #endif
  110517. /********* End of inlined file: lookup_data.h *********/
  110518. #ifdef FLOAT_LOOKUP
  110519. /* interpolated lookup based cos function, domain 0 to PI only */
  110520. float vorbis_coslook(float a){
  110521. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110522. int i=vorbis_ftoi(d-.5);
  110523. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110524. }
  110525. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110526. float vorbis_invsqlook(float a){
  110527. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110528. int i=vorbis_ftoi(d-.5f);
  110529. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110530. }
  110531. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110532. float vorbis_invsq2explook(int a){
  110533. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110534. }
  110535. #include <stdio.h>
  110536. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110537. float vorbis_fromdBlook(float a){
  110538. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110539. return (i<0)?1.f:
  110540. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110541. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110542. }
  110543. #endif
  110544. #ifdef INT_LOOKUP
  110545. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110546. 16.16 format
  110547. returns in m.8 format */
  110548. long vorbis_invsqlook_i(long a,long e){
  110549. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110550. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110551. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110552. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110553. d)>>16); /* result 1.16 */
  110554. e+=32;
  110555. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110556. e=(e>>1)-8;
  110557. return(val>>e);
  110558. }
  110559. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110560. /* a is in n.12 format */
  110561. float vorbis_fromdBlook_i(long a){
  110562. int i=(-a)>>(12-FROMdB2_SHIFT);
  110563. return (i<0)?1.f:
  110564. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110565. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110566. }
  110567. /* interpolated lookup based cos function, domain 0 to PI only */
  110568. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110569. long vorbis_coslook_i(long a){
  110570. int i=a>>COS_LOOKUP_I_SHIFT;
  110571. int d=a&COS_LOOKUP_I_MASK;
  110572. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110573. COS_LOOKUP_I_SHIFT);
  110574. }
  110575. #endif
  110576. #endif
  110577. /********* End of inlined file: lookup.c *********/
  110578. /* catch this in the build system; we #include for
  110579. compilers (like gcc) that can't inline across
  110580. modules */
  110581. static int MLOOP_1[64]={
  110582. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  110583. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  110584. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110585. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110586. };
  110587. static int MLOOP_2[64]={
  110588. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  110589. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  110590. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110591. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110592. };
  110593. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  110594. /* side effect: changes *lsp to cosines of lsp */
  110595. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110596. float amp,float ampoffset){
  110597. /* 0 <= m < 256 */
  110598. /* set up for using all int later */
  110599. int i;
  110600. int ampoffseti=rint(ampoffset*4096.f);
  110601. int ampi=rint(amp*16.f);
  110602. long *ilsp=alloca(m*sizeof(*ilsp));
  110603. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  110604. i=0;
  110605. while(i<n){
  110606. int j,k=map[i];
  110607. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  110608. unsigned long qi=46341;
  110609. int qexp=0,shift;
  110610. long wi=vorbis_coslook_i(k*65536/ln);
  110611. qi*=labs(ilsp[0]-wi);
  110612. pi*=labs(ilsp[1]-wi);
  110613. for(j=3;j<m;j+=2){
  110614. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110615. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110616. shift=MLOOP_3[(pi|qi)>>16];
  110617. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110618. pi=(pi>>shift)*labs(ilsp[j]-wi);
  110619. qexp+=shift;
  110620. }
  110621. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110622. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110623. shift=MLOOP_3[(pi|qi)>>16];
  110624. /* pi,qi normalized collectively, both tracked using qexp */
  110625. if(m&1){
  110626. /* odd order filter; slightly assymetric */
  110627. /* the last coefficient */
  110628. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110629. pi=(pi>>shift)<<14;
  110630. qexp+=shift;
  110631. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110632. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110633. shift=MLOOP_3[(pi|qi)>>16];
  110634. pi>>=shift;
  110635. qi>>=shift;
  110636. qexp+=shift-14*((m+1)>>1);
  110637. pi=((pi*pi)>>16);
  110638. qi=((qi*qi)>>16);
  110639. qexp=qexp*2+m;
  110640. pi*=(1<<14)-((wi*wi)>>14);
  110641. qi+=pi>>14;
  110642. }else{
  110643. /* even order filter; still symmetric */
  110644. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  110645. worth tracking step by step */
  110646. pi>>=shift;
  110647. qi>>=shift;
  110648. qexp+=shift-7*m;
  110649. pi=((pi*pi)>>16);
  110650. qi=((qi*qi)>>16);
  110651. qexp=qexp*2+m;
  110652. pi*=(1<<14)-wi;
  110653. qi*=(1<<14)+wi;
  110654. qi=(qi+pi)>>14;
  110655. }
  110656. /* we've let the normalization drift because it wasn't important;
  110657. however, for the lookup, things must be normalized again. We
  110658. need at most one right shift or a number of left shifts */
  110659. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  110660. qi>>=1; qexp++;
  110661. }else
  110662. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  110663. qi<<=1; qexp--;
  110664. }
  110665. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  110666. vorbis_invsqlook_i(qi,qexp)-
  110667. /* m.8, m+n<=8 */
  110668. ampoffseti); /* 8.12[0] */
  110669. curve[i]*=amp;
  110670. while(map[++i]==k)curve[i]*=amp;
  110671. }
  110672. }
  110673. #else
  110674. /* old, nonoptimized but simple version for any poor sap who needs to
  110675. figure out what the hell this code does, or wants the other
  110676. fraction of a dB precision */
  110677. /* side effect: changes *lsp to cosines of lsp */
  110678. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110679. float amp,float ampoffset){
  110680. int i;
  110681. float wdel=M_PI/ln;
  110682. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  110683. i=0;
  110684. while(i<n){
  110685. int j,k=map[i];
  110686. float p=.5f;
  110687. float q=.5f;
  110688. float w=2.f*cos(wdel*k);
  110689. for(j=1;j<m;j+=2){
  110690. q *= w-lsp[j-1];
  110691. p *= w-lsp[j];
  110692. }
  110693. if(j==m){
  110694. /* odd order filter; slightly assymetric */
  110695. /* the last coefficient */
  110696. q*=w-lsp[j-1];
  110697. p*=p*(4.f-w*w);
  110698. q*=q;
  110699. }else{
  110700. /* even order filter; still symmetric */
  110701. p*=p*(2.f-w);
  110702. q*=q*(2.f+w);
  110703. }
  110704. q=fromdB(amp/sqrt(p+q)-ampoffset);
  110705. curve[i]*=q;
  110706. while(map[++i]==k)curve[i]*=q;
  110707. }
  110708. }
  110709. #endif
  110710. #endif
  110711. static void cheby(float *g, int ord) {
  110712. int i, j;
  110713. g[0] *= .5f;
  110714. for(i=2; i<= ord; i++) {
  110715. for(j=ord; j >= i; j--) {
  110716. g[j-2] -= g[j];
  110717. g[j] += g[j];
  110718. }
  110719. }
  110720. }
  110721. static int comp(const void *a,const void *b){
  110722. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  110723. }
  110724. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  110725. but there are root sets for which it gets into limit cycles
  110726. (exacerbated by zero suppression) and fails. We can't afford to
  110727. fail, even if the failure is 1 in 100,000,000, so we now use
  110728. Laguerre and later polish with Newton-Raphson (which can then
  110729. afford to fail) */
  110730. #define EPSILON 10e-7
  110731. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  110732. int i,m;
  110733. double lastdelta=0.f;
  110734. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  110735. for(i=0;i<=ord;i++)defl[i]=a[i];
  110736. for(m=ord;m>0;m--){
  110737. double newx=0.f,delta;
  110738. /* iterate a root */
  110739. while(1){
  110740. double p=defl[m],pp=0.f,ppp=0.f,denom;
  110741. /* eval the polynomial and its first two derivatives */
  110742. for(i=m;i>0;i--){
  110743. ppp = newx*ppp + pp;
  110744. pp = newx*pp + p;
  110745. p = newx*p + defl[i-1];
  110746. }
  110747. /* Laguerre's method */
  110748. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  110749. if(denom<0)
  110750. return(-1); /* complex root! The LPC generator handed us a bad filter */
  110751. if(pp>0){
  110752. denom = pp + sqrt(denom);
  110753. if(denom<EPSILON)denom=EPSILON;
  110754. }else{
  110755. denom = pp - sqrt(denom);
  110756. if(denom>-(EPSILON))denom=-(EPSILON);
  110757. }
  110758. delta = m*p/denom;
  110759. newx -= delta;
  110760. if(delta<0.f)delta*=-1;
  110761. if(fabs(delta/newx)<10e-12)break;
  110762. lastdelta=delta;
  110763. }
  110764. r[m-1]=newx;
  110765. /* forward deflation */
  110766. for(i=m;i>0;i--)
  110767. defl[i-1]+=newx*defl[i];
  110768. defl++;
  110769. }
  110770. return(0);
  110771. }
  110772. /* for spit-and-polish only */
  110773. static int Newton_Raphson(float *a,int ord,float *r){
  110774. int i, k, count=0;
  110775. double error=1.f;
  110776. double *root=(double*)alloca(ord*sizeof(*root));
  110777. for(i=0; i<ord;i++) root[i] = r[i];
  110778. while(error>1e-20){
  110779. error=0;
  110780. for(i=0; i<ord; i++) { /* Update each point. */
  110781. double pp=0.,delta;
  110782. double rooti=root[i];
  110783. double p=a[ord];
  110784. for(k=ord-1; k>= 0; k--) {
  110785. pp= pp* rooti + p;
  110786. p = p * rooti + a[k];
  110787. }
  110788. delta = p/pp;
  110789. root[i] -= delta;
  110790. error+= delta*delta;
  110791. }
  110792. if(count>40)return(-1);
  110793. count++;
  110794. }
  110795. /* Replaced the original bubble sort with a real sort. With your
  110796. help, we can eliminate the bubble sort in our lifetime. --Monty */
  110797. for(i=0; i<ord;i++) r[i] = root[i];
  110798. return(0);
  110799. }
  110800. /* Convert lpc coefficients to lsp coefficients */
  110801. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  110802. int order2=(m+1)>>1;
  110803. int g1_order,g2_order;
  110804. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  110805. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  110806. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  110807. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  110808. int i;
  110809. /* even and odd are slightly different base cases */
  110810. g1_order=(m+1)>>1;
  110811. g2_order=(m) >>1;
  110812. /* Compute the lengths of the x polynomials. */
  110813. /* Compute the first half of K & R F1 & F2 polynomials. */
  110814. /* Compute half of the symmetric and antisymmetric polynomials. */
  110815. /* Remove the roots at +1 and -1. */
  110816. g1[g1_order] = 1.f;
  110817. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  110818. g2[g2_order] = 1.f;
  110819. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  110820. if(g1_order>g2_order){
  110821. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  110822. }else{
  110823. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  110824. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  110825. }
  110826. /* Convert into polynomials in cos(alpha) */
  110827. cheby(g1,g1_order);
  110828. cheby(g2,g2_order);
  110829. /* Find the roots of the 2 even polynomials.*/
  110830. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  110831. Laguerre_With_Deflation(g2,g2_order,g2r))
  110832. return(-1);
  110833. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  110834. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  110835. qsort(g1r,g1_order,sizeof(*g1r),comp);
  110836. qsort(g2r,g2_order,sizeof(*g2r),comp);
  110837. for(i=0;i<g1_order;i++)
  110838. lsp[i*2] = acos(g1r[i]);
  110839. for(i=0;i<g2_order;i++)
  110840. lsp[i*2+1] = acos(g2r[i]);
  110841. return(0);
  110842. }
  110843. #endif
  110844. /********* End of inlined file: lsp.c *********/
  110845. /********* Start of inlined file: mapping0.c *********/
  110846. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110847. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110848. // tasks..
  110849. #if JUCE_MSVC
  110850. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110851. #endif
  110852. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110853. #if JUCE_USE_OGGVORBIS
  110854. #include <stdlib.h>
  110855. #include <stdio.h>
  110856. #include <string.h>
  110857. #include <math.h>
  110858. /* simplistic, wasteful way of doing this (unique lookup for each
  110859. mode/submapping); there should be a central repository for
  110860. identical lookups. That will require minor work, so I'm putting it
  110861. off as low priority.
  110862. Why a lookup for each backend in a given mode? Because the
  110863. blocksize is set by the mode, and low backend lookups may require
  110864. parameters from other areas of the mode/mapping */
  110865. static void mapping0_free_info(vorbis_info_mapping *i){
  110866. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  110867. if(info){
  110868. memset(info,0,sizeof(*info));
  110869. _ogg_free(info);
  110870. }
  110871. }
  110872. static int ilog3(unsigned int v){
  110873. int ret=0;
  110874. if(v)--v;
  110875. while(v){
  110876. ret++;
  110877. v>>=1;
  110878. }
  110879. return(ret);
  110880. }
  110881. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  110882. oggpack_buffer *opb){
  110883. int i;
  110884. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  110885. /* another 'we meant to do it this way' hack... up to beta 4, we
  110886. packed 4 binary zeros here to signify one submapping in use. We
  110887. now redefine that to mean four bitflags that indicate use of
  110888. deeper features; bit0:submappings, bit1:coupling,
  110889. bit2,3:reserved. This is backward compatable with all actual uses
  110890. of the beta code. */
  110891. if(info->submaps>1){
  110892. oggpack_write(opb,1,1);
  110893. oggpack_write(opb,info->submaps-1,4);
  110894. }else
  110895. oggpack_write(opb,0,1);
  110896. if(info->coupling_steps>0){
  110897. oggpack_write(opb,1,1);
  110898. oggpack_write(opb,info->coupling_steps-1,8);
  110899. for(i=0;i<info->coupling_steps;i++){
  110900. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  110901. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  110902. }
  110903. }else
  110904. oggpack_write(opb,0,1);
  110905. oggpack_write(opb,0,2); /* 2,3:reserved */
  110906. /* we don't write the channel submappings if we only have one... */
  110907. if(info->submaps>1){
  110908. for(i=0;i<vi->channels;i++)
  110909. oggpack_write(opb,info->chmuxlist[i],4);
  110910. }
  110911. for(i=0;i<info->submaps;i++){
  110912. oggpack_write(opb,0,8); /* time submap unused */
  110913. oggpack_write(opb,info->floorsubmap[i],8);
  110914. oggpack_write(opb,info->residuesubmap[i],8);
  110915. }
  110916. }
  110917. /* also responsible for range checking */
  110918. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  110919. int i;
  110920. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  110921. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110922. memset(info,0,sizeof(*info));
  110923. if(oggpack_read(opb,1))
  110924. info->submaps=oggpack_read(opb,4)+1;
  110925. else
  110926. info->submaps=1;
  110927. if(oggpack_read(opb,1)){
  110928. info->coupling_steps=oggpack_read(opb,8)+1;
  110929. for(i=0;i<info->coupling_steps;i++){
  110930. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  110931. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  110932. if(testM<0 ||
  110933. testA<0 ||
  110934. testM==testA ||
  110935. testM>=vi->channels ||
  110936. testA>=vi->channels) goto err_out;
  110937. }
  110938. }
  110939. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  110940. if(info->submaps>1){
  110941. for(i=0;i<vi->channels;i++){
  110942. info->chmuxlist[i]=oggpack_read(opb,4);
  110943. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  110944. }
  110945. }
  110946. for(i=0;i<info->submaps;i++){
  110947. oggpack_read(opb,8); /* time submap unused */
  110948. info->floorsubmap[i]=oggpack_read(opb,8);
  110949. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  110950. info->residuesubmap[i]=oggpack_read(opb,8);
  110951. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  110952. }
  110953. return info;
  110954. err_out:
  110955. mapping0_free_info(info);
  110956. return(NULL);
  110957. }
  110958. #if 0
  110959. static long seq=0;
  110960. static ogg_int64_t total=0;
  110961. static float FLOOR1_fromdB_LOOKUP[256]={
  110962. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  110963. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  110964. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  110965. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  110966. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  110967. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  110968. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  110969. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  110970. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  110971. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  110972. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  110973. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  110974. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  110975. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  110976. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  110977. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  110978. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110979. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110980. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110981. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110982. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110983. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110984. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110985. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110986. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110987. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110988. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110989. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110990. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110991. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110992. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110993. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110994. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110995. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110996. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110997. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110998. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110999. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111000. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111001. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  111002. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  111003. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  111004. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  111005. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  111006. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  111007. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  111008. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  111009. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  111010. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  111011. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  111012. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  111013. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  111014. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  111015. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  111016. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  111017. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  111018. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  111019. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  111020. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  111021. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  111022. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  111023. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  111024. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  111025. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  111026. };
  111027. #endif
  111028. extern int *floor1_fit(vorbis_block *vb,void *look,
  111029. const float *logmdct, /* in */
  111030. const float *logmask);
  111031. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  111032. int *A,int *B,
  111033. int del);
  111034. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  111035. void*look,
  111036. int *post,int *ilogmask);
  111037. static int mapping0_forward(vorbis_block *vb){
  111038. vorbis_dsp_state *vd=vb->vd;
  111039. vorbis_info *vi=vd->vi;
  111040. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111041. private_state *b=(private_state*)vb->vd->backend_state;
  111042. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111043. int n=vb->pcmend;
  111044. int i,j,k;
  111045. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  111046. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  111047. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  111048. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  111049. float global_ampmax=vbi->ampmax;
  111050. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  111051. int blocktype=vbi->blocktype;
  111052. int modenumber=vb->W;
  111053. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  111054. vorbis_look_psy *psy_look=
  111055. b->psy+blocktype+(vb->W?2:0);
  111056. vb->mode=modenumber;
  111057. for(i=0;i<vi->channels;i++){
  111058. float scale=4.f/n;
  111059. float scale_dB;
  111060. float *pcm =vb->pcm[i];
  111061. float *logfft =pcm;
  111062. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111063. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  111064. todB estimation used on IEEE 754
  111065. compliant machines had a bug that
  111066. returned dB values about a third
  111067. of a decibel too high. The bug
  111068. was harmless because tunings
  111069. implicitly took that into
  111070. account. However, fixing the bug
  111071. in the estimator requires
  111072. changing all the tunings as well.
  111073. For now, it's easier to sync
  111074. things back up here, and
  111075. recalibrate the tunings in the
  111076. next major model upgrade. */
  111077. #if 0
  111078. if(vi->channels==2)
  111079. if(i==0)
  111080. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  111081. else
  111082. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  111083. #endif
  111084. /* window the PCM data */
  111085. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  111086. #if 0
  111087. if(vi->channels==2)
  111088. if(i==0)
  111089. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  111090. else
  111091. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  111092. #endif
  111093. /* transform the PCM data */
  111094. /* only MDCT right now.... */
  111095. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  111096. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  111097. drft_forward(&b->fft_look[vb->W],pcm);
  111098. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  111099. original todB estimation used on
  111100. IEEE 754 compliant machines had a
  111101. bug that returned dB values about
  111102. a third of a decibel too high.
  111103. The bug was harmless because
  111104. tunings implicitly took that into
  111105. account. However, fixing the bug
  111106. in the estimator requires
  111107. changing all the tunings as well.
  111108. For now, it's easier to sync
  111109. things back up here, and
  111110. recalibrate the tunings in the
  111111. next major model upgrade. */
  111112. local_ampmax[i]=logfft[0];
  111113. for(j=1;j<n-1;j+=2){
  111114. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  111115. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  111116. .345 is a hack; the original todB
  111117. estimation used on IEEE 754
  111118. compliant machines had a bug that
  111119. returned dB values about a third
  111120. of a decibel too high. The bug
  111121. was harmless because tunings
  111122. implicitly took that into
  111123. account. However, fixing the bug
  111124. in the estimator requires
  111125. changing all the tunings as well.
  111126. For now, it's easier to sync
  111127. things back up here, and
  111128. recalibrate the tunings in the
  111129. next major model upgrade. */
  111130. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  111131. }
  111132. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  111133. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  111134. #if 0
  111135. if(vi->channels==2){
  111136. if(i==0){
  111137. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  111138. }else{
  111139. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  111140. }
  111141. }
  111142. #endif
  111143. }
  111144. {
  111145. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  111146. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  111147. for(i=0;i<vi->channels;i++){
  111148. /* the encoder setup assumes that all the modes used by any
  111149. specific bitrate tweaking use the same floor */
  111150. int submap=info->chmuxlist[i];
  111151. /* the following makes things clearer to *me* anyway */
  111152. float *mdct =gmdct[i];
  111153. float *logfft =vb->pcm[i];
  111154. float *logmdct =logfft+n/2;
  111155. float *logmask =logfft;
  111156. vb->mode=modenumber;
  111157. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  111158. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  111159. for(j=0;j<n/2;j++)
  111160. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  111161. todB estimation used on IEEE 754
  111162. compliant machines had a bug that
  111163. returned dB values about a third
  111164. of a decibel too high. The bug
  111165. was harmless because tunings
  111166. implicitly took that into
  111167. account. However, fixing the bug
  111168. in the estimator requires
  111169. changing all the tunings as well.
  111170. For now, it's easier to sync
  111171. things back up here, and
  111172. recalibrate the tunings in the
  111173. next major model upgrade. */
  111174. #if 0
  111175. if(vi->channels==2){
  111176. if(i==0)
  111177. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  111178. else
  111179. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  111180. }else{
  111181. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  111182. }
  111183. #endif
  111184. /* first step; noise masking. Not only does 'noise masking'
  111185. give us curves from which we can decide how much resolution
  111186. to give noise parts of the spectrum, it also implicitly hands
  111187. us a tonality estimate (the larger the value in the
  111188. 'noise_depth' vector, the more tonal that area is) */
  111189. _vp_noisemask(psy_look,
  111190. logmdct,
  111191. noise); /* noise does not have by-frequency offset
  111192. bias applied yet */
  111193. #if 0
  111194. if(vi->channels==2){
  111195. if(i==0)
  111196. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  111197. else
  111198. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  111199. }
  111200. #endif
  111201. /* second step: 'all the other crap'; all the stuff that isn't
  111202. computed/fit for bitrate management goes in the second psy
  111203. vector. This includes tone masking, peak limiting and ATH */
  111204. _vp_tonemask(psy_look,
  111205. logfft,
  111206. tone,
  111207. global_ampmax,
  111208. local_ampmax[i]);
  111209. #if 0
  111210. if(vi->channels==2){
  111211. if(i==0)
  111212. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  111213. else
  111214. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  111215. }
  111216. #endif
  111217. /* third step; we offset the noise vectors, overlay tone
  111218. masking. We then do a floor1-specific line fit. If we're
  111219. performing bitrate management, the line fit is performed
  111220. multiple times for up/down tweakage on demand. */
  111221. #if 0
  111222. {
  111223. float aotuv[psy_look->n];
  111224. #endif
  111225. _vp_offset_and_mix(psy_look,
  111226. noise,
  111227. tone,
  111228. 1,
  111229. logmask,
  111230. mdct,
  111231. logmdct);
  111232. #if 0
  111233. if(vi->channels==2){
  111234. if(i==0)
  111235. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  111236. else
  111237. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  111238. }
  111239. }
  111240. #endif
  111241. #if 0
  111242. if(vi->channels==2){
  111243. if(i==0)
  111244. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  111245. else
  111246. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  111247. }
  111248. #endif
  111249. /* this algorithm is hardwired to floor 1 for now; abort out if
  111250. we're *not* floor1. This won't happen unless someone has
  111251. broken the encode setup lib. Guard it anyway. */
  111252. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  111253. floor_posts[i][PACKETBLOBS/2]=
  111254. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111255. logmdct,
  111256. logmask);
  111257. /* are we managing bitrate? If so, perform two more fits for
  111258. later rate tweaking (fits represent hi/lo) */
  111259. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  111260. /* higher rate by way of lower noise curve */
  111261. _vp_offset_and_mix(psy_look,
  111262. noise,
  111263. tone,
  111264. 2,
  111265. logmask,
  111266. mdct,
  111267. logmdct);
  111268. #if 0
  111269. if(vi->channels==2){
  111270. if(i==0)
  111271. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  111272. else
  111273. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  111274. }
  111275. #endif
  111276. floor_posts[i][PACKETBLOBS-1]=
  111277. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111278. logmdct,
  111279. logmask);
  111280. /* lower rate by way of higher noise curve */
  111281. _vp_offset_and_mix(psy_look,
  111282. noise,
  111283. tone,
  111284. 0,
  111285. logmask,
  111286. mdct,
  111287. logmdct);
  111288. #if 0
  111289. if(vi->channels==2)
  111290. if(i==0)
  111291. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  111292. else
  111293. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  111294. #endif
  111295. floor_posts[i][0]=
  111296. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111297. logmdct,
  111298. logmask);
  111299. /* we also interpolate a range of intermediate curves for
  111300. intermediate rates */
  111301. for(k=1;k<PACKETBLOBS/2;k++)
  111302. floor_posts[i][k]=
  111303. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111304. floor_posts[i][0],
  111305. floor_posts[i][PACKETBLOBS/2],
  111306. k*65536/(PACKETBLOBS/2));
  111307. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  111308. floor_posts[i][k]=
  111309. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111310. floor_posts[i][PACKETBLOBS/2],
  111311. floor_posts[i][PACKETBLOBS-1],
  111312. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  111313. }
  111314. }
  111315. }
  111316. vbi->ampmax=global_ampmax;
  111317. /*
  111318. the next phases are performed once for vbr-only and PACKETBLOB
  111319. times for bitrate managed modes.
  111320. 1) encode actual mode being used
  111321. 2) encode the floor for each channel, compute coded mask curve/res
  111322. 3) normalize and couple.
  111323. 4) encode residue
  111324. 5) save packet bytes to the packetblob vector
  111325. */
  111326. /* iterate over the many masking curve fits we've created */
  111327. {
  111328. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  111329. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  111330. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111331. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  111332. float **mag_memo;
  111333. int **mag_sort;
  111334. if(info->coupling_steps){
  111335. mag_memo=_vp_quantize_couple_memo(vb,
  111336. &ci->psy_g_param,
  111337. psy_look,
  111338. info,
  111339. gmdct);
  111340. mag_sort=_vp_quantize_couple_sort(vb,
  111341. psy_look,
  111342. info,
  111343. mag_memo);
  111344. hf_reduction(&ci->psy_g_param,
  111345. psy_look,
  111346. info,
  111347. mag_memo);
  111348. }
  111349. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  111350. if(psy_look->vi->normal_channel_p){
  111351. for(i=0;i<vi->channels;i++){
  111352. float *mdct =gmdct[i];
  111353. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  111354. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  111355. }
  111356. }
  111357. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  111358. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  111359. k++){
  111360. oggpack_buffer *opb=vbi->packetblob[k];
  111361. /* start out our new packet blob with packet type and mode */
  111362. /* Encode the packet type */
  111363. oggpack_write(opb,0,1);
  111364. /* Encode the modenumber */
  111365. /* Encode frame mode, pre,post windowsize, then dispatch */
  111366. oggpack_write(opb,modenumber,b->modebits);
  111367. if(vb->W){
  111368. oggpack_write(opb,vb->lW,1);
  111369. oggpack_write(opb,vb->nW,1);
  111370. }
  111371. /* encode floor, compute masking curve, sep out residue */
  111372. for(i=0;i<vi->channels;i++){
  111373. int submap=info->chmuxlist[i];
  111374. float *mdct =gmdct[i];
  111375. float *res =vb->pcm[i];
  111376. int *ilogmask=ilogmaskch[i]=
  111377. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111378. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  111379. floor_posts[i][k],
  111380. ilogmask);
  111381. #if 0
  111382. {
  111383. char buf[80];
  111384. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  111385. float work[n/2];
  111386. for(j=0;j<n/2;j++)
  111387. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  111388. _analysis_output(buf,seq,work,n/2,1,1,0);
  111389. }
  111390. #endif
  111391. _vp_remove_floor(psy_look,
  111392. mdct,
  111393. ilogmask,
  111394. res,
  111395. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111396. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  111397. #if 0
  111398. {
  111399. char buf[80];
  111400. float work[n/2];
  111401. for(j=0;j<n/2;j++)
  111402. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  111403. sprintf(buf,"resI%c%d",i?'R':'L',k);
  111404. _analysis_output(buf,seq,work,n/2,1,1,0);
  111405. }
  111406. #endif
  111407. }
  111408. /* our iteration is now based on masking curve, not prequant and
  111409. coupling. Only one prequant/coupling step */
  111410. /* quantize/couple */
  111411. /* incomplete implementation that assumes the tree is all depth
  111412. one, or no tree at all */
  111413. if(info->coupling_steps){
  111414. _vp_couple(k,
  111415. &ci->psy_g_param,
  111416. psy_look,
  111417. info,
  111418. vb->pcm,
  111419. mag_memo,
  111420. mag_sort,
  111421. ilogmaskch,
  111422. nonzero,
  111423. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111424. }
  111425. /* classify and encode by submap */
  111426. for(i=0;i<info->submaps;i++){
  111427. int ch_in_bundle=0;
  111428. long **classifications;
  111429. int resnum=info->residuesubmap[i];
  111430. for(j=0;j<vi->channels;j++){
  111431. if(info->chmuxlist[j]==i){
  111432. zerobundle[ch_in_bundle]=0;
  111433. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  111434. res_bundle[ch_in_bundle]=vb->pcm[j];
  111435. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  111436. }
  111437. }
  111438. classifications=_residue_P[ci->residue_type[resnum]]->
  111439. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  111440. _residue_P[ci->residue_type[resnum]]->
  111441. forward(opb,vb,b->residue[resnum],
  111442. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  111443. }
  111444. /* ok, done encoding. Next protopacket. */
  111445. }
  111446. }
  111447. #if 0
  111448. seq++;
  111449. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  111450. #endif
  111451. return(0);
  111452. }
  111453. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  111454. vorbis_dsp_state *vd=vb->vd;
  111455. vorbis_info *vi=vd->vi;
  111456. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111457. private_state *b=(private_state*)vd->backend_state;
  111458. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  111459. int i,j;
  111460. long n=vb->pcmend=ci->blocksizes[vb->W];
  111461. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  111462. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111463. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  111464. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  111465. /* recover the spectral envelope; store it in the PCM vector for now */
  111466. for(i=0;i<vi->channels;i++){
  111467. int submap=info->chmuxlist[i];
  111468. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111469. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  111470. if(floormemo[i])
  111471. nonzero[i]=1;
  111472. else
  111473. nonzero[i]=0;
  111474. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  111475. }
  111476. /* channel coupling can 'dirty' the nonzero listing */
  111477. for(i=0;i<info->coupling_steps;i++){
  111478. if(nonzero[info->coupling_mag[i]] ||
  111479. nonzero[info->coupling_ang[i]]){
  111480. nonzero[info->coupling_mag[i]]=1;
  111481. nonzero[info->coupling_ang[i]]=1;
  111482. }
  111483. }
  111484. /* recover the residue into our working vectors */
  111485. for(i=0;i<info->submaps;i++){
  111486. int ch_in_bundle=0;
  111487. for(j=0;j<vi->channels;j++){
  111488. if(info->chmuxlist[j]==i){
  111489. if(nonzero[j])
  111490. zerobundle[ch_in_bundle]=1;
  111491. else
  111492. zerobundle[ch_in_bundle]=0;
  111493. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  111494. }
  111495. }
  111496. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  111497. inverse(vb,b->residue[info->residuesubmap[i]],
  111498. pcmbundle,zerobundle,ch_in_bundle);
  111499. }
  111500. /* channel coupling */
  111501. for(i=info->coupling_steps-1;i>=0;i--){
  111502. float *pcmM=vb->pcm[info->coupling_mag[i]];
  111503. float *pcmA=vb->pcm[info->coupling_ang[i]];
  111504. for(j=0;j<n/2;j++){
  111505. float mag=pcmM[j];
  111506. float ang=pcmA[j];
  111507. if(mag>0)
  111508. if(ang>0){
  111509. pcmM[j]=mag;
  111510. pcmA[j]=mag-ang;
  111511. }else{
  111512. pcmA[j]=mag;
  111513. pcmM[j]=mag+ang;
  111514. }
  111515. else
  111516. if(ang>0){
  111517. pcmM[j]=mag;
  111518. pcmA[j]=mag+ang;
  111519. }else{
  111520. pcmA[j]=mag;
  111521. pcmM[j]=mag-ang;
  111522. }
  111523. }
  111524. }
  111525. /* compute and apply spectral envelope */
  111526. for(i=0;i<vi->channels;i++){
  111527. float *pcm=vb->pcm[i];
  111528. int submap=info->chmuxlist[i];
  111529. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111530. inverse2(vb,b->flr[info->floorsubmap[submap]],
  111531. floormemo[i],pcm);
  111532. }
  111533. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  111534. /* only MDCT right now.... */
  111535. for(i=0;i<vi->channels;i++){
  111536. float *pcm=vb->pcm[i];
  111537. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  111538. }
  111539. /* all done! */
  111540. return(0);
  111541. }
  111542. /* export hooks */
  111543. vorbis_func_mapping mapping0_exportbundle={
  111544. &mapping0_pack,
  111545. &mapping0_unpack,
  111546. &mapping0_free_info,
  111547. &mapping0_forward,
  111548. &mapping0_inverse
  111549. };
  111550. #endif
  111551. /********* End of inlined file: mapping0.c *********/
  111552. /********* Start of inlined file: mdct.c *********/
  111553. /* this can also be run as an integer transform by uncommenting a
  111554. define in mdct.h; the integerization is a first pass and although
  111555. it's likely stable for Vorbis, the dynamic range is constrained and
  111556. roundoff isn't done (so it's noisy). Consider it functional, but
  111557. only a starting point. There's no point on a machine with an FPU */
  111558. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111559. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111560. // tasks..
  111561. #if JUCE_MSVC
  111562. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111563. #endif
  111564. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111565. #if JUCE_USE_OGGVORBIS
  111566. #include <stdio.h>
  111567. #include <stdlib.h>
  111568. #include <string.h>
  111569. #include <math.h>
  111570. /* build lookups for trig functions; also pre-figure scaling and
  111571. some window function algebra. */
  111572. void mdct_init(mdct_lookup *lookup,int n){
  111573. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  111574. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  111575. int i;
  111576. int n2=n>>1;
  111577. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  111578. lookup->n=n;
  111579. lookup->trig=T;
  111580. lookup->bitrev=bitrev;
  111581. /* trig lookups... */
  111582. for(i=0;i<n/4;i++){
  111583. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  111584. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  111585. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  111586. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  111587. }
  111588. for(i=0;i<n/8;i++){
  111589. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  111590. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  111591. }
  111592. /* bitreverse lookup... */
  111593. {
  111594. int mask=(1<<(log2n-1))-1,i,j;
  111595. int msb=1<<(log2n-2);
  111596. for(i=0;i<n/8;i++){
  111597. int acc=0;
  111598. for(j=0;msb>>j;j++)
  111599. if((msb>>j)&i)acc|=1<<j;
  111600. bitrev[i*2]=((~acc)&mask)-1;
  111601. bitrev[i*2+1]=acc;
  111602. }
  111603. }
  111604. lookup->scale=FLOAT_CONV(4.f/n);
  111605. }
  111606. /* 8 point butterfly (in place, 4 register) */
  111607. STIN void mdct_butterfly_8(DATA_TYPE *x){
  111608. REG_TYPE r0 = x[6] + x[2];
  111609. REG_TYPE r1 = x[6] - x[2];
  111610. REG_TYPE r2 = x[4] + x[0];
  111611. REG_TYPE r3 = x[4] - x[0];
  111612. x[6] = r0 + r2;
  111613. x[4] = r0 - r2;
  111614. r0 = x[5] - x[1];
  111615. r2 = x[7] - x[3];
  111616. x[0] = r1 + r0;
  111617. x[2] = r1 - r0;
  111618. r0 = x[5] + x[1];
  111619. r1 = x[7] + x[3];
  111620. x[3] = r2 + r3;
  111621. x[1] = r2 - r3;
  111622. x[7] = r1 + r0;
  111623. x[5] = r1 - r0;
  111624. }
  111625. /* 16 point butterfly (in place, 4 register) */
  111626. STIN void mdct_butterfly_16(DATA_TYPE *x){
  111627. REG_TYPE r0 = x[1] - x[9];
  111628. REG_TYPE r1 = x[0] - x[8];
  111629. x[8] += x[0];
  111630. x[9] += x[1];
  111631. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  111632. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  111633. r0 = x[3] - x[11];
  111634. r1 = x[10] - x[2];
  111635. x[10] += x[2];
  111636. x[11] += x[3];
  111637. x[2] = r0;
  111638. x[3] = r1;
  111639. r0 = x[12] - x[4];
  111640. r1 = x[13] - x[5];
  111641. x[12] += x[4];
  111642. x[13] += x[5];
  111643. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  111644. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  111645. r0 = x[14] - x[6];
  111646. r1 = x[15] - x[7];
  111647. x[14] += x[6];
  111648. x[15] += x[7];
  111649. x[6] = r0;
  111650. x[7] = r1;
  111651. mdct_butterfly_8(x);
  111652. mdct_butterfly_8(x+8);
  111653. }
  111654. /* 32 point butterfly (in place, 4 register) */
  111655. STIN void mdct_butterfly_32(DATA_TYPE *x){
  111656. REG_TYPE r0 = x[30] - x[14];
  111657. REG_TYPE r1 = x[31] - x[15];
  111658. x[30] += x[14];
  111659. x[31] += x[15];
  111660. x[14] = r0;
  111661. x[15] = r1;
  111662. r0 = x[28] - x[12];
  111663. r1 = x[29] - x[13];
  111664. x[28] += x[12];
  111665. x[29] += x[13];
  111666. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  111667. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  111668. r0 = x[26] - x[10];
  111669. r1 = x[27] - x[11];
  111670. x[26] += x[10];
  111671. x[27] += x[11];
  111672. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  111673. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  111674. r0 = x[24] - x[8];
  111675. r1 = x[25] - x[9];
  111676. x[24] += x[8];
  111677. x[25] += x[9];
  111678. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  111679. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111680. r0 = x[22] - x[6];
  111681. r1 = x[7] - x[23];
  111682. x[22] += x[6];
  111683. x[23] += x[7];
  111684. x[6] = r1;
  111685. x[7] = r0;
  111686. r0 = x[4] - x[20];
  111687. r1 = x[5] - x[21];
  111688. x[20] += x[4];
  111689. x[21] += x[5];
  111690. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  111691. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  111692. r0 = x[2] - x[18];
  111693. r1 = x[3] - x[19];
  111694. x[18] += x[2];
  111695. x[19] += x[3];
  111696. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  111697. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  111698. r0 = x[0] - x[16];
  111699. r1 = x[1] - x[17];
  111700. x[16] += x[0];
  111701. x[17] += x[1];
  111702. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111703. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  111704. mdct_butterfly_16(x);
  111705. mdct_butterfly_16(x+16);
  111706. }
  111707. /* N point first stage butterfly (in place, 2 register) */
  111708. STIN void mdct_butterfly_first(DATA_TYPE *T,
  111709. DATA_TYPE *x,
  111710. int points){
  111711. DATA_TYPE *x1 = x + points - 8;
  111712. DATA_TYPE *x2 = x + (points>>1) - 8;
  111713. REG_TYPE r0;
  111714. REG_TYPE r1;
  111715. do{
  111716. r0 = x1[6] - x2[6];
  111717. r1 = x1[7] - x2[7];
  111718. x1[6] += x2[6];
  111719. x1[7] += x2[7];
  111720. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111721. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111722. r0 = x1[4] - x2[4];
  111723. r1 = x1[5] - x2[5];
  111724. x1[4] += x2[4];
  111725. x1[5] += x2[5];
  111726. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  111727. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  111728. r0 = x1[2] - x2[2];
  111729. r1 = x1[3] - x2[3];
  111730. x1[2] += x2[2];
  111731. x1[3] += x2[3];
  111732. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  111733. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  111734. r0 = x1[0] - x2[0];
  111735. r1 = x1[1] - x2[1];
  111736. x1[0] += x2[0];
  111737. x1[1] += x2[1];
  111738. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  111739. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  111740. x1-=8;
  111741. x2-=8;
  111742. T+=16;
  111743. }while(x2>=x);
  111744. }
  111745. /* N/stage point generic N stage butterfly (in place, 2 register) */
  111746. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  111747. DATA_TYPE *x,
  111748. int points,
  111749. int trigint){
  111750. DATA_TYPE *x1 = x + points - 8;
  111751. DATA_TYPE *x2 = x + (points>>1) - 8;
  111752. REG_TYPE r0;
  111753. REG_TYPE r1;
  111754. do{
  111755. r0 = x1[6] - x2[6];
  111756. r1 = x1[7] - x2[7];
  111757. x1[6] += x2[6];
  111758. x1[7] += x2[7];
  111759. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111760. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111761. T+=trigint;
  111762. r0 = x1[4] - x2[4];
  111763. r1 = x1[5] - x2[5];
  111764. x1[4] += x2[4];
  111765. x1[5] += x2[5];
  111766. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111767. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111768. T+=trigint;
  111769. r0 = x1[2] - x2[2];
  111770. r1 = x1[3] - x2[3];
  111771. x1[2] += x2[2];
  111772. x1[3] += x2[3];
  111773. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111774. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111775. T+=trigint;
  111776. r0 = x1[0] - x2[0];
  111777. r1 = x1[1] - x2[1];
  111778. x1[0] += x2[0];
  111779. x1[1] += x2[1];
  111780. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111781. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111782. T+=trigint;
  111783. x1-=8;
  111784. x2-=8;
  111785. }while(x2>=x);
  111786. }
  111787. STIN void mdct_butterflies(mdct_lookup *init,
  111788. DATA_TYPE *x,
  111789. int points){
  111790. DATA_TYPE *T=init->trig;
  111791. int stages=init->log2n-5;
  111792. int i,j;
  111793. if(--stages>0){
  111794. mdct_butterfly_first(T,x,points);
  111795. }
  111796. for(i=1;--stages>0;i++){
  111797. for(j=0;j<(1<<i);j++)
  111798. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  111799. }
  111800. for(j=0;j<points;j+=32)
  111801. mdct_butterfly_32(x+j);
  111802. }
  111803. void mdct_clear(mdct_lookup *l){
  111804. if(l){
  111805. if(l->trig)_ogg_free(l->trig);
  111806. if(l->bitrev)_ogg_free(l->bitrev);
  111807. memset(l,0,sizeof(*l));
  111808. }
  111809. }
  111810. STIN void mdct_bitreverse(mdct_lookup *init,
  111811. DATA_TYPE *x){
  111812. int n = init->n;
  111813. int *bit = init->bitrev;
  111814. DATA_TYPE *w0 = x;
  111815. DATA_TYPE *w1 = x = w0+(n>>1);
  111816. DATA_TYPE *T = init->trig+n;
  111817. do{
  111818. DATA_TYPE *x0 = x+bit[0];
  111819. DATA_TYPE *x1 = x+bit[1];
  111820. REG_TYPE r0 = x0[1] - x1[1];
  111821. REG_TYPE r1 = x0[0] + x1[0];
  111822. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  111823. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  111824. w1 -= 4;
  111825. r0 = HALVE(x0[1] + x1[1]);
  111826. r1 = HALVE(x0[0] - x1[0]);
  111827. w0[0] = r0 + r2;
  111828. w1[2] = r0 - r2;
  111829. w0[1] = r1 + r3;
  111830. w1[3] = r3 - r1;
  111831. x0 = x+bit[2];
  111832. x1 = x+bit[3];
  111833. r0 = x0[1] - x1[1];
  111834. r1 = x0[0] + x1[0];
  111835. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  111836. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  111837. r0 = HALVE(x0[1] + x1[1]);
  111838. r1 = HALVE(x0[0] - x1[0]);
  111839. w0[2] = r0 + r2;
  111840. w1[0] = r0 - r2;
  111841. w0[3] = r1 + r3;
  111842. w1[1] = r3 - r1;
  111843. T += 4;
  111844. bit += 4;
  111845. w0 += 4;
  111846. }while(w0<w1);
  111847. }
  111848. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111849. int n=init->n;
  111850. int n2=n>>1;
  111851. int n4=n>>2;
  111852. /* rotate */
  111853. DATA_TYPE *iX = in+n2-7;
  111854. DATA_TYPE *oX = out+n2+n4;
  111855. DATA_TYPE *T = init->trig+n4;
  111856. do{
  111857. oX -= 4;
  111858. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  111859. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  111860. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  111861. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  111862. iX -= 8;
  111863. T += 4;
  111864. }while(iX>=in);
  111865. iX = in+n2-8;
  111866. oX = out+n2+n4;
  111867. T = init->trig+n4;
  111868. do{
  111869. T -= 4;
  111870. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  111871. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  111872. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  111873. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  111874. iX -= 8;
  111875. oX += 4;
  111876. }while(iX>=in);
  111877. mdct_butterflies(init,out+n2,n2);
  111878. mdct_bitreverse(init,out);
  111879. /* roatate + window */
  111880. {
  111881. DATA_TYPE *oX1=out+n2+n4;
  111882. DATA_TYPE *oX2=out+n2+n4;
  111883. DATA_TYPE *iX =out;
  111884. T =init->trig+n2;
  111885. do{
  111886. oX1-=4;
  111887. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  111888. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  111889. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  111890. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  111891. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  111892. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  111893. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  111894. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  111895. oX2+=4;
  111896. iX += 8;
  111897. T += 8;
  111898. }while(iX<oX1);
  111899. iX=out+n2+n4;
  111900. oX1=out+n4;
  111901. oX2=oX1;
  111902. do{
  111903. oX1-=4;
  111904. iX-=4;
  111905. oX2[0] = -(oX1[3] = iX[3]);
  111906. oX2[1] = -(oX1[2] = iX[2]);
  111907. oX2[2] = -(oX1[1] = iX[1]);
  111908. oX2[3] = -(oX1[0] = iX[0]);
  111909. oX2+=4;
  111910. }while(oX2<iX);
  111911. iX=out+n2+n4;
  111912. oX1=out+n2+n4;
  111913. oX2=out+n2;
  111914. do{
  111915. oX1-=4;
  111916. oX1[0]= iX[3];
  111917. oX1[1]= iX[2];
  111918. oX1[2]= iX[1];
  111919. oX1[3]= iX[0];
  111920. iX+=4;
  111921. }while(oX1>oX2);
  111922. }
  111923. }
  111924. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111925. int n=init->n;
  111926. int n2=n>>1;
  111927. int n4=n>>2;
  111928. int n8=n>>3;
  111929. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  111930. DATA_TYPE *w2=w+n2;
  111931. /* rotate */
  111932. /* window + rotate + step 1 */
  111933. REG_TYPE r0;
  111934. REG_TYPE r1;
  111935. DATA_TYPE *x0=in+n2+n4;
  111936. DATA_TYPE *x1=x0+1;
  111937. DATA_TYPE *T=init->trig+n2;
  111938. int i=0;
  111939. for(i=0;i<n8;i+=2){
  111940. x0 -=4;
  111941. T-=2;
  111942. r0= x0[2] + x1[0];
  111943. r1= x0[0] + x1[2];
  111944. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111945. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111946. x1 +=4;
  111947. }
  111948. x1=in+1;
  111949. for(;i<n2-n8;i+=2){
  111950. T-=2;
  111951. x0 -=4;
  111952. r0= x0[2] - x1[0];
  111953. r1= x0[0] - x1[2];
  111954. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111955. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111956. x1 +=4;
  111957. }
  111958. x0=in+n;
  111959. for(;i<n2;i+=2){
  111960. T-=2;
  111961. x0 -=4;
  111962. r0= -x0[2] - x1[0];
  111963. r1= -x0[0] - x1[2];
  111964. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111965. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111966. x1 +=4;
  111967. }
  111968. mdct_butterflies(init,w+n2,n2);
  111969. mdct_bitreverse(init,w);
  111970. /* roatate + window */
  111971. T=init->trig+n2;
  111972. x0=out+n2;
  111973. for(i=0;i<n4;i++){
  111974. x0--;
  111975. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  111976. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  111977. w+=2;
  111978. T+=2;
  111979. }
  111980. }
  111981. #endif
  111982. /********* End of inlined file: mdct.c *********/
  111983. /********* Start of inlined file: psy.c *********/
  111984. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111985. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111986. // tasks..
  111987. #if JUCE_MSVC
  111988. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111989. #endif
  111990. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111991. #if JUCE_USE_OGGVORBIS
  111992. #include <stdlib.h>
  111993. #include <math.h>
  111994. #include <string.h>
  111995. /********* Start of inlined file: masking.h *********/
  111996. #ifndef _V_MASKING_H_
  111997. #define _V_MASKING_H_
  111998. /* more detailed ATH; the bass if flat to save stressing the floor
  111999. overly for only a bin or two of savings. */
  112000. #define MAX_ATH 88
  112001. static float ATH[]={
  112002. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  112003. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  112004. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  112005. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  112006. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  112007. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  112008. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  112009. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  112010. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  112011. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  112012. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  112013. };
  112014. /* The tone masking curves from Ehmer's and Fielder's papers have been
  112015. replaced by an empirically collected data set. The previously
  112016. published values were, far too often, simply on crack. */
  112017. #define EHMER_OFFSET 16
  112018. #define EHMER_MAX 56
  112019. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  112020. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  112021. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  112022. for collection of these curves) */
  112023. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  112024. /* 62.5 Hz */
  112025. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  112026. -60, -60, -60, -60, -62, -62, -65, -73,
  112027. -69, -68, -68, -67, -70, -70, -72, -74,
  112028. -75, -79, -79, -80, -83, -88, -93, -100,
  112029. -110, -999, -999, -999, -999, -999, -999, -999,
  112030. -999, -999, -999, -999, -999, -999, -999, -999,
  112031. -999, -999, -999, -999, -999, -999, -999, -999},
  112032. { -48, -48, -48, -48, -48, -48, -48, -48,
  112033. -48, -48, -48, -48, -48, -53, -61, -66,
  112034. -66, -68, -67, -70, -76, -76, -72, -73,
  112035. -75, -76, -78, -79, -83, -88, -93, -100,
  112036. -110, -999, -999, -999, -999, -999, -999, -999,
  112037. -999, -999, -999, -999, -999, -999, -999, -999,
  112038. -999, -999, -999, -999, -999, -999, -999, -999},
  112039. { -37, -37, -37, -37, -37, -37, -37, -37,
  112040. -38, -40, -42, -46, -48, -53, -55, -62,
  112041. -65, -58, -56, -56, -61, -60, -65, -67,
  112042. -69, -71, -77, -77, -78, -80, -82, -84,
  112043. -88, -93, -98, -106, -112, -999, -999, -999,
  112044. -999, -999, -999, -999, -999, -999, -999, -999,
  112045. -999, -999, -999, -999, -999, -999, -999, -999},
  112046. { -25, -25, -25, -25, -25, -25, -25, -25,
  112047. -25, -26, -27, -29, -32, -38, -48, -52,
  112048. -52, -50, -48, -48, -51, -52, -54, -60,
  112049. -67, -67, -66, -68, -69, -73, -73, -76,
  112050. -80, -81, -81, -85, -85, -86, -88, -93,
  112051. -100, -110, -999, -999, -999, -999, -999, -999,
  112052. -999, -999, -999, -999, -999, -999, -999, -999},
  112053. { -16, -16, -16, -16, -16, -16, -16, -16,
  112054. -17, -19, -20, -22, -26, -28, -31, -40,
  112055. -47, -39, -39, -40, -42, -43, -47, -51,
  112056. -57, -52, -55, -55, -60, -58, -62, -63,
  112057. -70, -67, -69, -72, -73, -77, -80, -82,
  112058. -83, -87, -90, -94, -98, -104, -115, -999,
  112059. -999, -999, -999, -999, -999, -999, -999, -999},
  112060. { -8, -8, -8, -8, -8, -8, -8, -8,
  112061. -8, -8, -10, -11, -15, -19, -25, -30,
  112062. -34, -31, -30, -31, -29, -32, -35, -42,
  112063. -48, -42, -44, -46, -50, -50, -51, -52,
  112064. -59, -54, -55, -55, -58, -62, -63, -66,
  112065. -72, -73, -76, -75, -78, -80, -80, -81,
  112066. -84, -88, -90, -94, -98, -101, -106, -110}},
  112067. /* 88Hz */
  112068. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  112069. -66, -66, -66, -66, -66, -67, -67, -67,
  112070. -76, -72, -71, -74, -76, -76, -75, -78,
  112071. -79, -79, -81, -83, -86, -89, -93, -97,
  112072. -100, -105, -110, -999, -999, -999, -999, -999,
  112073. -999, -999, -999, -999, -999, -999, -999, -999,
  112074. -999, -999, -999, -999, -999, -999, -999, -999},
  112075. { -47, -47, -47, -47, -47, -47, -47, -47,
  112076. -47, -47, -47, -48, -51, -55, -59, -66,
  112077. -66, -66, -67, -66, -68, -69, -70, -74,
  112078. -79, -77, -77, -78, -80, -81, -82, -84,
  112079. -86, -88, -91, -95, -100, -108, -116, -999,
  112080. -999, -999, -999, -999, -999, -999, -999, -999,
  112081. -999, -999, -999, -999, -999, -999, -999, -999},
  112082. { -36, -36, -36, -36, -36, -36, -36, -36,
  112083. -36, -37, -37, -41, -44, -48, -51, -58,
  112084. -62, -60, -57, -59, -59, -60, -63, -65,
  112085. -72, -71, -70, -72, -74, -77, -76, -78,
  112086. -81, -81, -80, -83, -86, -91, -96, -100,
  112087. -105, -110, -999, -999, -999, -999, -999, -999,
  112088. -999, -999, -999, -999, -999, -999, -999, -999},
  112089. { -28, -28, -28, -28, -28, -28, -28, -28,
  112090. -28, -30, -32, -32, -33, -35, -41, -49,
  112091. -50, -49, -47, -48, -48, -52, -51, -57,
  112092. -65, -61, -59, -61, -64, -69, -70, -74,
  112093. -77, -77, -78, -81, -84, -85, -87, -90,
  112094. -92, -96, -100, -107, -112, -999, -999, -999,
  112095. -999, -999, -999, -999, -999, -999, -999, -999},
  112096. { -19, -19, -19, -19, -19, -19, -19, -19,
  112097. -20, -21, -23, -27, -30, -35, -36, -41,
  112098. -46, -44, -42, -40, -41, -41, -43, -48,
  112099. -55, -53, -52, -53, -56, -59, -58, -60,
  112100. -67, -66, -69, -71, -72, -75, -79, -81,
  112101. -84, -87, -90, -93, -97, -101, -107, -114,
  112102. -999, -999, -999, -999, -999, -999, -999, -999},
  112103. { -9, -9, -9, -9, -9, -9, -9, -9,
  112104. -11, -12, -12, -15, -16, -20, -23, -30,
  112105. -37, -34, -33, -34, -31, -32, -32, -38,
  112106. -47, -44, -41, -40, -47, -49, -46, -46,
  112107. -58, -50, -50, -54, -58, -62, -64, -67,
  112108. -67, -70, -72, -76, -79, -83, -87, -91,
  112109. -96, -100, -104, -110, -999, -999, -999, -999}},
  112110. /* 125 Hz */
  112111. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  112112. -62, -62, -63, -64, -66, -67, -66, -68,
  112113. -75, -72, -76, -75, -76, -78, -79, -82,
  112114. -84, -85, -90, -94, -101, -110, -999, -999,
  112115. -999, -999, -999, -999, -999, -999, -999, -999,
  112116. -999, -999, -999, -999, -999, -999, -999, -999,
  112117. -999, -999, -999, -999, -999, -999, -999, -999},
  112118. { -59, -59, -59, -59, -59, -59, -59, -59,
  112119. -59, -59, -59, -60, -60, -61, -63, -66,
  112120. -71, -68, -70, -70, -71, -72, -72, -75,
  112121. -81, -78, -79, -82, -83, -86, -90, -97,
  112122. -103, -113, -999, -999, -999, -999, -999, -999,
  112123. -999, -999, -999, -999, -999, -999, -999, -999,
  112124. -999, -999, -999, -999, -999, -999, -999, -999},
  112125. { -53, -53, -53, -53, -53, -53, -53, -53,
  112126. -53, -54, -55, -57, -56, -57, -55, -61,
  112127. -65, -60, -60, -62, -63, -63, -66, -68,
  112128. -74, -73, -75, -75, -78, -80, -80, -82,
  112129. -85, -90, -96, -101, -108, -999, -999, -999,
  112130. -999, -999, -999, -999, -999, -999, -999, -999,
  112131. -999, -999, -999, -999, -999, -999, -999, -999},
  112132. { -46, -46, -46, -46, -46, -46, -46, -46,
  112133. -46, -46, -47, -47, -47, -47, -48, -51,
  112134. -57, -51, -49, -50, -51, -53, -54, -59,
  112135. -66, -60, -62, -67, -67, -70, -72, -75,
  112136. -76, -78, -81, -85, -88, -94, -97, -104,
  112137. -112, -999, -999, -999, -999, -999, -999, -999,
  112138. -999, -999, -999, -999, -999, -999, -999, -999},
  112139. { -36, -36, -36, -36, -36, -36, -36, -36,
  112140. -39, -41, -42, -42, -39, -38, -41, -43,
  112141. -52, -44, -40, -39, -37, -37, -40, -47,
  112142. -54, -50, -48, -50, -55, -61, -59, -62,
  112143. -66, -66, -66, -69, -69, -73, -74, -74,
  112144. -75, -77, -79, -82, -87, -91, -95, -100,
  112145. -108, -115, -999, -999, -999, -999, -999, -999},
  112146. { -28, -26, -24, -22, -20, -20, -23, -29,
  112147. -30, -31, -28, -27, -28, -28, -28, -35,
  112148. -40, -33, -32, -29, -30, -30, -30, -37,
  112149. -45, -41, -37, -38, -45, -47, -47, -48,
  112150. -53, -49, -48, -50, -49, -49, -51, -52,
  112151. -58, -56, -57, -56, -60, -61, -62, -70,
  112152. -72, -74, -78, -83, -88, -93, -100, -106}},
  112153. /* 177 Hz */
  112154. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112155. -999, -110, -105, -100, -95, -91, -87, -83,
  112156. -80, -78, -76, -78, -78, -81, -83, -85,
  112157. -86, -85, -86, -87, -90, -97, -107, -999,
  112158. -999, -999, -999, -999, -999, -999, -999, -999,
  112159. -999, -999, -999, -999, -999, -999, -999, -999,
  112160. -999, -999, -999, -999, -999, -999, -999, -999},
  112161. {-999, -999, -999, -110, -105, -100, -95, -90,
  112162. -85, -81, -77, -73, -70, -67, -67, -68,
  112163. -75, -73, -70, -69, -70, -72, -75, -79,
  112164. -84, -83, -84, -86, -88, -89, -89, -93,
  112165. -98, -105, -112, -999, -999, -999, -999, -999,
  112166. -999, -999, -999, -999, -999, -999, -999, -999,
  112167. -999, -999, -999, -999, -999, -999, -999, -999},
  112168. {-105, -100, -95, -90, -85, -80, -76, -71,
  112169. -68, -68, -65, -63, -63, -62, -62, -64,
  112170. -65, -64, -61, -62, -63, -64, -66, -68,
  112171. -73, -73, -74, -75, -76, -81, -83, -85,
  112172. -88, -89, -92, -95, -100, -108, -999, -999,
  112173. -999, -999, -999, -999, -999, -999, -999, -999,
  112174. -999, -999, -999, -999, -999, -999, -999, -999},
  112175. { -80, -75, -71, -68, -65, -63, -62, -61,
  112176. -61, -61, -61, -59, -56, -57, -53, -50,
  112177. -58, -52, -50, -50, -52, -53, -54, -58,
  112178. -67, -63, -67, -68, -72, -75, -78, -80,
  112179. -81, -81, -82, -85, -89, -90, -93, -97,
  112180. -101, -107, -114, -999, -999, -999, -999, -999,
  112181. -999, -999, -999, -999, -999, -999, -999, -999},
  112182. { -65, -61, -59, -57, -56, -55, -55, -56,
  112183. -56, -57, -55, -53, -52, -47, -44, -44,
  112184. -50, -44, -41, -39, -39, -42, -40, -46,
  112185. -51, -49, -50, -53, -54, -63, -60, -61,
  112186. -62, -66, -66, -66, -70, -73, -74, -75,
  112187. -76, -75, -79, -85, -89, -91, -96, -102,
  112188. -110, -999, -999, -999, -999, -999, -999, -999},
  112189. { -52, -50, -49, -49, -48, -48, -48, -49,
  112190. -50, -50, -49, -46, -43, -39, -35, -33,
  112191. -38, -36, -32, -29, -32, -32, -32, -35,
  112192. -44, -39, -38, -38, -46, -50, -45, -46,
  112193. -53, -50, -50, -50, -54, -54, -53, -53,
  112194. -56, -57, -59, -66, -70, -72, -74, -79,
  112195. -83, -85, -90, -97, -114, -999, -999, -999}},
  112196. /* 250 Hz */
  112197. {{-999, -999, -999, -999, -999, -999, -110, -105,
  112198. -100, -95, -90, -86, -80, -75, -75, -79,
  112199. -80, -79, -80, -81, -82, -88, -95, -103,
  112200. -110, -999, -999, -999, -999, -999, -999, -999,
  112201. -999, -999, -999, -999, -999, -999, -999, -999,
  112202. -999, -999, -999, -999, -999, -999, -999, -999,
  112203. -999, -999, -999, -999, -999, -999, -999, -999},
  112204. {-999, -999, -999, -999, -108, -103, -98, -93,
  112205. -88, -83, -79, -78, -75, -71, -67, -68,
  112206. -73, -73, -72, -73, -75, -77, -80, -82,
  112207. -88, -93, -100, -107, -114, -999, -999, -999,
  112208. -999, -999, -999, -999, -999, -999, -999, -999,
  112209. -999, -999, -999, -999, -999, -999, -999, -999,
  112210. -999, -999, -999, -999, -999, -999, -999, -999},
  112211. {-999, -999, -999, -110, -105, -101, -96, -90,
  112212. -86, -81, -77, -73, -69, -66, -61, -62,
  112213. -66, -64, -62, -65, -66, -70, -72, -76,
  112214. -81, -80, -84, -90, -95, -102, -110, -999,
  112215. -999, -999, -999, -999, -999, -999, -999, -999,
  112216. -999, -999, -999, -999, -999, -999, -999, -999,
  112217. -999, -999, -999, -999, -999, -999, -999, -999},
  112218. {-999, -999, -999, -107, -103, -97, -92, -88,
  112219. -83, -79, -74, -70, -66, -59, -53, -58,
  112220. -62, -55, -54, -54, -54, -58, -61, -62,
  112221. -72, -70, -72, -75, -78, -80, -81, -80,
  112222. -83, -83, -88, -93, -100, -107, -115, -999,
  112223. -999, -999, -999, -999, -999, -999, -999, -999,
  112224. -999, -999, -999, -999, -999, -999, -999, -999},
  112225. {-999, -999, -999, -105, -100, -95, -90, -85,
  112226. -80, -75, -70, -66, -62, -56, -48, -44,
  112227. -48, -46, -46, -43, -46, -48, -48, -51,
  112228. -58, -58, -59, -60, -62, -62, -61, -61,
  112229. -65, -64, -65, -68, -70, -74, -75, -78,
  112230. -81, -86, -95, -110, -999, -999, -999, -999,
  112231. -999, -999, -999, -999, -999, -999, -999, -999},
  112232. {-999, -999, -105, -100, -95, -90, -85, -80,
  112233. -75, -70, -65, -61, -55, -49, -39, -33,
  112234. -40, -35, -32, -38, -40, -33, -35, -37,
  112235. -46, -41, -45, -44, -46, -42, -45, -46,
  112236. -52, -50, -50, -50, -54, -54, -55, -57,
  112237. -62, -64, -66, -68, -70, -76, -81, -90,
  112238. -100, -110, -999, -999, -999, -999, -999, -999}},
  112239. /* 354 hz */
  112240. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112241. -105, -98, -90, -85, -82, -83, -80, -78,
  112242. -84, -79, -80, -83, -87, -89, -91, -93,
  112243. -99, -106, -117, -999, -999, -999, -999, -999,
  112244. -999, -999, -999, -999, -999, -999, -999, -999,
  112245. -999, -999, -999, -999, -999, -999, -999, -999,
  112246. -999, -999, -999, -999, -999, -999, -999, -999},
  112247. {-999, -999, -999, -999, -999, -999, -999, -999,
  112248. -105, -98, -90, -85, -80, -75, -70, -68,
  112249. -74, -72, -74, -77, -80, -82, -85, -87,
  112250. -92, -89, -91, -95, -100, -106, -112, -999,
  112251. -999, -999, -999, -999, -999, -999, -999, -999,
  112252. -999, -999, -999, -999, -999, -999, -999, -999,
  112253. -999, -999, -999, -999, -999, -999, -999, -999},
  112254. {-999, -999, -999, -999, -999, -999, -999, -999,
  112255. -105, -98, -90, -83, -75, -71, -63, -64,
  112256. -67, -62, -64, -67, -70, -73, -77, -81,
  112257. -84, -83, -85, -89, -90, -93, -98, -104,
  112258. -109, -114, -999, -999, -999, -999, -999, -999,
  112259. -999, -999, -999, -999, -999, -999, -999, -999,
  112260. -999, -999, -999, -999, -999, -999, -999, -999},
  112261. {-999, -999, -999, -999, -999, -999, -999, -999,
  112262. -103, -96, -88, -81, -75, -68, -58, -54,
  112263. -56, -54, -56, -56, -58, -60, -63, -66,
  112264. -74, -69, -72, -72, -75, -74, -77, -81,
  112265. -81, -82, -84, -87, -93, -96, -99, -104,
  112266. -110, -999, -999, -999, -999, -999, -999, -999,
  112267. -999, -999, -999, -999, -999, -999, -999, -999},
  112268. {-999, -999, -999, -999, -999, -108, -102, -96,
  112269. -91, -85, -80, -74, -68, -60, -51, -46,
  112270. -48, -46, -43, -45, -47, -47, -49, -48,
  112271. -56, -53, -55, -58, -57, -63, -58, -60,
  112272. -66, -64, -67, -70, -70, -74, -77, -84,
  112273. -86, -89, -91, -93, -94, -101, -109, -118,
  112274. -999, -999, -999, -999, -999, -999, -999, -999},
  112275. {-999, -999, -999, -108, -103, -98, -93, -88,
  112276. -83, -78, -73, -68, -60, -53, -44, -35,
  112277. -38, -38, -34, -34, -36, -40, -41, -44,
  112278. -51, -45, -46, -47, -46, -54, -50, -49,
  112279. -50, -50, -50, -51, -54, -57, -58, -60,
  112280. -66, -66, -66, -64, -65, -68, -77, -82,
  112281. -87, -95, -110, -999, -999, -999, -999, -999}},
  112282. /* 500 Hz */
  112283. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112284. -107, -102, -97, -92, -87, -83, -78, -75,
  112285. -82, -79, -83, -85, -89, -92, -95, -98,
  112286. -101, -105, -109, -113, -999, -999, -999, -999,
  112287. -999, -999, -999, -999, -999, -999, -999, -999,
  112288. -999, -999, -999, -999, -999, -999, -999, -999,
  112289. -999, -999, -999, -999, -999, -999, -999, -999},
  112290. {-999, -999, -999, -999, -999, -999, -999, -106,
  112291. -100, -95, -90, -86, -81, -78, -74, -69,
  112292. -74, -74, -76, -79, -83, -84, -86, -89,
  112293. -92, -97, -93, -100, -103, -107, -110, -999,
  112294. -999, -999, -999, -999, -999, -999, -999, -999,
  112295. -999, -999, -999, -999, -999, -999, -999, -999,
  112296. -999, -999, -999, -999, -999, -999, -999, -999},
  112297. {-999, -999, -999, -999, -999, -999, -106, -100,
  112298. -95, -90, -87, -83, -80, -75, -69, -60,
  112299. -66, -66, -68, -70, -74, -78, -79, -81,
  112300. -81, -83, -84, -87, -93, -96, -99, -103,
  112301. -107, -110, -999, -999, -999, -999, -999, -999,
  112302. -999, -999, -999, -999, -999, -999, -999, -999,
  112303. -999, -999, -999, -999, -999, -999, -999, -999},
  112304. {-999, -999, -999, -999, -999, -108, -103, -98,
  112305. -93, -89, -85, -82, -78, -71, -62, -55,
  112306. -58, -58, -54, -54, -55, -59, -61, -62,
  112307. -70, -66, -66, -67, -70, -72, -75, -78,
  112308. -84, -84, -84, -88, -91, -90, -95, -98,
  112309. -102, -103, -106, -110, -999, -999, -999, -999,
  112310. -999, -999, -999, -999, -999, -999, -999, -999},
  112311. {-999, -999, -999, -999, -108, -103, -98, -94,
  112312. -90, -87, -82, -79, -73, -67, -58, -47,
  112313. -50, -45, -41, -45, -48, -44, -44, -49,
  112314. -54, -51, -48, -47, -49, -50, -51, -57,
  112315. -58, -60, -63, -69, -70, -69, -71, -74,
  112316. -78, -82, -90, -95, -101, -105, -110, -999,
  112317. -999, -999, -999, -999, -999, -999, -999, -999},
  112318. {-999, -999, -999, -105, -101, -97, -93, -90,
  112319. -85, -80, -77, -72, -65, -56, -48, -37,
  112320. -40, -36, -34, -40, -50, -47, -38, -41,
  112321. -47, -38, -35, -39, -38, -43, -40, -45,
  112322. -50, -45, -44, -47, -50, -55, -48, -48,
  112323. -52, -66, -70, -76, -82, -90, -97, -105,
  112324. -110, -999, -999, -999, -999, -999, -999, -999}},
  112325. /* 707 Hz */
  112326. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112327. -999, -108, -103, -98, -93, -86, -79, -76,
  112328. -83, -81, -85, -87, -89, -93, -98, -102,
  112329. -107, -112, -999, -999, -999, -999, -999, -999,
  112330. -999, -999, -999, -999, -999, -999, -999, -999,
  112331. -999, -999, -999, -999, -999, -999, -999, -999,
  112332. -999, -999, -999, -999, -999, -999, -999, -999},
  112333. {-999, -999, -999, -999, -999, -999, -999, -999,
  112334. -999, -108, -103, -98, -93, -86, -79, -71,
  112335. -77, -74, -77, -79, -81, -84, -85, -90,
  112336. -92, -93, -92, -98, -101, -108, -112, -999,
  112337. -999, -999, -999, -999, -999, -999, -999, -999,
  112338. -999, -999, -999, -999, -999, -999, -999, -999,
  112339. -999, -999, -999, -999, -999, -999, -999, -999},
  112340. {-999, -999, -999, -999, -999, -999, -999, -999,
  112341. -108, -103, -98, -93, -87, -78, -68, -65,
  112342. -66, -62, -65, -67, -70, -73, -75, -78,
  112343. -82, -82, -83, -84, -91, -93, -98, -102,
  112344. -106, -110, -999, -999, -999, -999, -999, -999,
  112345. -999, -999, -999, -999, -999, -999, -999, -999,
  112346. -999, -999, -999, -999, -999, -999, -999, -999},
  112347. {-999, -999, -999, -999, -999, -999, -999, -999,
  112348. -105, -100, -95, -90, -82, -74, -62, -57,
  112349. -58, -56, -51, -52, -52, -54, -54, -58,
  112350. -66, -59, -60, -63, -66, -69, -73, -79,
  112351. -83, -84, -80, -81, -81, -82, -88, -92,
  112352. -98, -105, -113, -999, -999, -999, -999, -999,
  112353. -999, -999, -999, -999, -999, -999, -999, -999},
  112354. {-999, -999, -999, -999, -999, -999, -999, -107,
  112355. -102, -97, -92, -84, -79, -69, -57, -47,
  112356. -52, -47, -44, -45, -50, -52, -42, -42,
  112357. -53, -43, -43, -48, -51, -56, -55, -52,
  112358. -57, -59, -61, -62, -67, -71, -78, -83,
  112359. -86, -94, -98, -103, -110, -999, -999, -999,
  112360. -999, -999, -999, -999, -999, -999, -999, -999},
  112361. {-999, -999, -999, -999, -999, -999, -105, -100,
  112362. -95, -90, -84, -78, -70, -61, -51, -41,
  112363. -40, -38, -40, -46, -52, -51, -41, -40,
  112364. -46, -40, -38, -38, -41, -46, -41, -46,
  112365. -47, -43, -43, -45, -41, -45, -56, -67,
  112366. -68, -83, -87, -90, -95, -102, -107, -113,
  112367. -999, -999, -999, -999, -999, -999, -999, -999}},
  112368. /* 1000 Hz */
  112369. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112370. -999, -109, -105, -101, -96, -91, -84, -77,
  112371. -82, -82, -85, -89, -94, -100, -106, -110,
  112372. -999, -999, -999, -999, -999, -999, -999, -999,
  112373. -999, -999, -999, -999, -999, -999, -999, -999,
  112374. -999, -999, -999, -999, -999, -999, -999, -999,
  112375. -999, -999, -999, -999, -999, -999, -999, -999},
  112376. {-999, -999, -999, -999, -999, -999, -999, -999,
  112377. -999, -106, -103, -98, -92, -85, -80, -71,
  112378. -75, -72, -76, -80, -84, -86, -89, -93,
  112379. -100, -107, -113, -999, -999, -999, -999, -999,
  112380. -999, -999, -999, -999, -999, -999, -999, -999,
  112381. -999, -999, -999, -999, -999, -999, -999, -999,
  112382. -999, -999, -999, -999, -999, -999, -999, -999},
  112383. {-999, -999, -999, -999, -999, -999, -999, -107,
  112384. -104, -101, -97, -92, -88, -84, -80, -64,
  112385. -66, -63, -64, -66, -69, -73, -77, -83,
  112386. -83, -86, -91, -98, -104, -111, -999, -999,
  112387. -999, -999, -999, -999, -999, -999, -999, -999,
  112388. -999, -999, -999, -999, -999, -999, -999, -999,
  112389. -999, -999, -999, -999, -999, -999, -999, -999},
  112390. {-999, -999, -999, -999, -999, -999, -999, -107,
  112391. -104, -101, -97, -92, -90, -84, -74, -57,
  112392. -58, -52, -55, -54, -50, -52, -50, -52,
  112393. -63, -62, -69, -76, -77, -78, -78, -79,
  112394. -82, -88, -94, -100, -106, -111, -999, -999,
  112395. -999, -999, -999, -999, -999, -999, -999, -999,
  112396. -999, -999, -999, -999, -999, -999, -999, -999},
  112397. {-999, -999, -999, -999, -999, -999, -106, -102,
  112398. -98, -95, -90, -85, -83, -78, -70, -50,
  112399. -50, -41, -44, -49, -47, -50, -50, -44,
  112400. -55, -46, -47, -48, -48, -54, -49, -49,
  112401. -58, -62, -71, -81, -87, -92, -97, -102,
  112402. -108, -114, -999, -999, -999, -999, -999, -999,
  112403. -999, -999, -999, -999, -999, -999, -999, -999},
  112404. {-999, -999, -999, -999, -999, -999, -106, -102,
  112405. -98, -95, -90, -85, -83, -78, -70, -45,
  112406. -43, -41, -47, -50, -51, -50, -49, -45,
  112407. -47, -41, -44, -41, -39, -43, -38, -37,
  112408. -40, -41, -44, -50, -58, -65, -73, -79,
  112409. -85, -92, -97, -101, -105, -109, -113, -999,
  112410. -999, -999, -999, -999, -999, -999, -999, -999}},
  112411. /* 1414 Hz */
  112412. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112413. -999, -999, -999, -107, -100, -95, -87, -81,
  112414. -85, -83, -88, -93, -100, -107, -114, -999,
  112415. -999, -999, -999, -999, -999, -999, -999, -999,
  112416. -999, -999, -999, -999, -999, -999, -999, -999,
  112417. -999, -999, -999, -999, -999, -999, -999, -999,
  112418. -999, -999, -999, -999, -999, -999, -999, -999},
  112419. {-999, -999, -999, -999, -999, -999, -999, -999,
  112420. -999, -999, -107, -101, -95, -88, -83, -76,
  112421. -73, -72, -79, -84, -90, -95, -100, -105,
  112422. -110, -115, -999, -999, -999, -999, -999, -999,
  112423. -999, -999, -999, -999, -999, -999, -999, -999,
  112424. -999, -999, -999, -999, -999, -999, -999, -999,
  112425. -999, -999, -999, -999, -999, -999, -999, -999},
  112426. {-999, -999, -999, -999, -999, -999, -999, -999,
  112427. -999, -999, -104, -98, -92, -87, -81, -70,
  112428. -65, -62, -67, -71, -74, -80, -85, -91,
  112429. -95, -99, -103, -108, -111, -114, -999, -999,
  112430. -999, -999, -999, -999, -999, -999, -999, -999,
  112431. -999, -999, -999, -999, -999, -999, -999, -999,
  112432. -999, -999, -999, -999, -999, -999, -999, -999},
  112433. {-999, -999, -999, -999, -999, -999, -999, -999,
  112434. -999, -999, -103, -97, -90, -85, -76, -60,
  112435. -56, -54, -60, -62, -61, -56, -63, -65,
  112436. -73, -74, -77, -75, -78, -81, -86, -87,
  112437. -88, -91, -94, -98, -103, -110, -999, -999,
  112438. -999, -999, -999, -999, -999, -999, -999, -999,
  112439. -999, -999, -999, -999, -999, -999, -999, -999},
  112440. {-999, -999, -999, -999, -999, -999, -999, -105,
  112441. -100, -97, -92, -86, -81, -79, -70, -57,
  112442. -51, -47, -51, -58, -60, -56, -53, -50,
  112443. -58, -52, -50, -50, -53, -55, -64, -69,
  112444. -71, -85, -82, -78, -81, -85, -95, -102,
  112445. -112, -999, -999, -999, -999, -999, -999, -999,
  112446. -999, -999, -999, -999, -999, -999, -999, -999},
  112447. {-999, -999, -999, -999, -999, -999, -999, -105,
  112448. -100, -97, -92, -85, -83, -79, -72, -49,
  112449. -40, -43, -43, -54, -56, -51, -50, -40,
  112450. -43, -38, -36, -35, -37, -38, -37, -44,
  112451. -54, -60, -57, -60, -70, -75, -84, -92,
  112452. -103, -112, -999, -999, -999, -999, -999, -999,
  112453. -999, -999, -999, -999, -999, -999, -999, -999}},
  112454. /* 2000 Hz */
  112455. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112456. -999, -999, -999, -110, -102, -95, -89, -82,
  112457. -83, -84, -90, -92, -99, -107, -113, -999,
  112458. -999, -999, -999, -999, -999, -999, -999, -999,
  112459. -999, -999, -999, -999, -999, -999, -999, -999,
  112460. -999, -999, -999, -999, -999, -999, -999, -999,
  112461. -999, -999, -999, -999, -999, -999, -999, -999},
  112462. {-999, -999, -999, -999, -999, -999, -999, -999,
  112463. -999, -999, -107, -101, -95, -89, -83, -72,
  112464. -74, -78, -85, -88, -88, -90, -92, -98,
  112465. -105, -111, -999, -999, -999, -999, -999, -999,
  112466. -999, -999, -999, -999, -999, -999, -999, -999,
  112467. -999, -999, -999, -999, -999, -999, -999, -999,
  112468. -999, -999, -999, -999, -999, -999, -999, -999},
  112469. {-999, -999, -999, -999, -999, -999, -999, -999,
  112470. -999, -109, -103, -97, -93, -87, -81, -70,
  112471. -70, -67, -75, -73, -76, -79, -81, -83,
  112472. -88, -89, -97, -103, -110, -999, -999, -999,
  112473. -999, -999, -999, -999, -999, -999, -999, -999,
  112474. -999, -999, -999, -999, -999, -999, -999, -999,
  112475. -999, -999, -999, -999, -999, -999, -999, -999},
  112476. {-999, -999, -999, -999, -999, -999, -999, -999,
  112477. -999, -107, -100, -94, -88, -83, -75, -63,
  112478. -59, -59, -63, -66, -60, -62, -67, -67,
  112479. -77, -76, -81, -88, -86, -92, -96, -102,
  112480. -109, -116, -999, -999, -999, -999, -999, -999,
  112481. -999, -999, -999, -999, -999, -999, -999, -999,
  112482. -999, -999, -999, -999, -999, -999, -999, -999},
  112483. {-999, -999, -999, -999, -999, -999, -999, -999,
  112484. -999, -105, -98, -92, -86, -81, -73, -56,
  112485. -52, -47, -55, -60, -58, -52, -51, -45,
  112486. -49, -50, -53, -54, -61, -71, -70, -69,
  112487. -78, -79, -87, -90, -96, -104, -112, -999,
  112488. -999, -999, -999, -999, -999, -999, -999, -999,
  112489. -999, -999, -999, -999, -999, -999, -999, -999},
  112490. {-999, -999, -999, -999, -999, -999, -999, -999,
  112491. -999, -103, -96, -90, -86, -78, -70, -51,
  112492. -42, -47, -48, -55, -54, -54, -53, -42,
  112493. -35, -28, -33, -38, -37, -44, -47, -49,
  112494. -54, -63, -68, -78, -82, -89, -94, -99,
  112495. -104, -109, -114, -999, -999, -999, -999, -999,
  112496. -999, -999, -999, -999, -999, -999, -999, -999}},
  112497. /* 2828 Hz */
  112498. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112499. -999, -999, -999, -999, -110, -100, -90, -79,
  112500. -85, -81, -82, -82, -89, -94, -99, -103,
  112501. -109, -115, -999, -999, -999, -999, -999, -999,
  112502. -999, -999, -999, -999, -999, -999, -999, -999,
  112503. -999, -999, -999, -999, -999, -999, -999, -999,
  112504. -999, -999, -999, -999, -999, -999, -999, -999},
  112505. {-999, -999, -999, -999, -999, -999, -999, -999,
  112506. -999, -999, -999, -999, -105, -97, -85, -72,
  112507. -74, -70, -70, -70, -76, -85, -91, -93,
  112508. -97, -103, -109, -115, -999, -999, -999, -999,
  112509. -999, -999, -999, -999, -999, -999, -999, -999,
  112510. -999, -999, -999, -999, -999, -999, -999, -999,
  112511. -999, -999, -999, -999, -999, -999, -999, -999},
  112512. {-999, -999, -999, -999, -999, -999, -999, -999,
  112513. -999, -999, -999, -999, -112, -93, -81, -68,
  112514. -62, -60, -60, -57, -63, -70, -77, -82,
  112515. -90, -93, -98, -104, -109, -113, -999, -999,
  112516. -999, -999, -999, -999, -999, -999, -999, -999,
  112517. -999, -999, -999, -999, -999, -999, -999, -999,
  112518. -999, -999, -999, -999, -999, -999, -999, -999},
  112519. {-999, -999, -999, -999, -999, -999, -999, -999,
  112520. -999, -999, -999, -113, -100, -93, -84, -63,
  112521. -58, -48, -53, -54, -52, -52, -57, -64,
  112522. -66, -76, -83, -81, -85, -85, -90, -95,
  112523. -98, -101, -103, -106, -108, -111, -999, -999,
  112524. -999, -999, -999, -999, -999, -999, -999, -999,
  112525. -999, -999, -999, -999, -999, -999, -999, -999},
  112526. {-999, -999, -999, -999, -999, -999, -999, -999,
  112527. -999, -999, -999, -105, -95, -86, -74, -53,
  112528. -50, -38, -43, -49, -43, -42, -39, -39,
  112529. -46, -52, -57, -56, -72, -69, -74, -81,
  112530. -87, -92, -94, -97, -99, -102, -105, -108,
  112531. -999, -999, -999, -999, -999, -999, -999, -999,
  112532. -999, -999, -999, -999, -999, -999, -999, -999},
  112533. {-999, -999, -999, -999, -999, -999, -999, -999,
  112534. -999, -999, -108, -99, -90, -76, -66, -45,
  112535. -43, -41, -44, -47, -43, -47, -40, -30,
  112536. -31, -31, -39, -33, -40, -41, -43, -53,
  112537. -59, -70, -73, -77, -79, -82, -84, -87,
  112538. -999, -999, -999, -999, -999, -999, -999, -999,
  112539. -999, -999, -999, -999, -999, -999, -999, -999}},
  112540. /* 4000 Hz */
  112541. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112542. -999, -999, -999, -999, -999, -110, -91, -76,
  112543. -75, -85, -93, -98, -104, -110, -999, -999,
  112544. -999, -999, -999, -999, -999, -999, -999, -999,
  112545. -999, -999, -999, -999, -999, -999, -999, -999,
  112546. -999, -999, -999, -999, -999, -999, -999, -999,
  112547. -999, -999, -999, -999, -999, -999, -999, -999},
  112548. {-999, -999, -999, -999, -999, -999, -999, -999,
  112549. -999, -999, -999, -999, -999, -110, -91, -70,
  112550. -70, -75, -86, -89, -94, -98, -101, -106,
  112551. -110, -999, -999, -999, -999, -999, -999, -999,
  112552. -999, -999, -999, -999, -999, -999, -999, -999,
  112553. -999, -999, -999, -999, -999, -999, -999, -999,
  112554. -999, -999, -999, -999, -999, -999, -999, -999},
  112555. {-999, -999, -999, -999, -999, -999, -999, -999,
  112556. -999, -999, -999, -999, -110, -95, -80, -60,
  112557. -65, -64, -74, -83, -88, -91, -95, -99,
  112558. -103, -107, -110, -999, -999, -999, -999, -999,
  112559. -999, -999, -999, -999, -999, -999, -999, -999,
  112560. -999, -999, -999, -999, -999, -999, -999, -999,
  112561. -999, -999, -999, -999, -999, -999, -999, -999},
  112562. {-999, -999, -999, -999, -999, -999, -999, -999,
  112563. -999, -999, -999, -999, -110, -95, -80, -58,
  112564. -55, -49, -66, -68, -71, -78, -78, -80,
  112565. -88, -85, -89, -97, -100, -105, -110, -999,
  112566. -999, -999, -999, -999, -999, -999, -999, -999,
  112567. -999, -999, -999, -999, -999, -999, -999, -999,
  112568. -999, -999, -999, -999, -999, -999, -999, -999},
  112569. {-999, -999, -999, -999, -999, -999, -999, -999,
  112570. -999, -999, -999, -999, -110, -95, -80, -53,
  112571. -52, -41, -59, -59, -49, -58, -56, -63,
  112572. -86, -79, -90, -93, -98, -103, -107, -112,
  112573. -999, -999, -999, -999, -999, -999, -999, -999,
  112574. -999, -999, -999, -999, -999, -999, -999, -999,
  112575. -999, -999, -999, -999, -999, -999, -999, -999},
  112576. {-999, -999, -999, -999, -999, -999, -999, -999,
  112577. -999, -999, -999, -110, -97, -91, -73, -45,
  112578. -40, -33, -53, -61, -49, -54, -50, -50,
  112579. -60, -52, -67, -74, -81, -92, -96, -100,
  112580. -105, -110, -999, -999, -999, -999, -999, -999,
  112581. -999, -999, -999, -999, -999, -999, -999, -999,
  112582. -999, -999, -999, -999, -999, -999, -999, -999}},
  112583. /* 5657 Hz */
  112584. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112585. -999, -999, -999, -113, -106, -99, -92, -77,
  112586. -80, -88, -97, -106, -115, -999, -999, -999,
  112587. -999, -999, -999, -999, -999, -999, -999, -999,
  112588. -999, -999, -999, -999, -999, -999, -999, -999,
  112589. -999, -999, -999, -999, -999, -999, -999, -999,
  112590. -999, -999, -999, -999, -999, -999, -999, -999},
  112591. {-999, -999, -999, -999, -999, -999, -999, -999,
  112592. -999, -999, -116, -109, -102, -95, -89, -74,
  112593. -72, -88, -87, -95, -102, -109, -116, -999,
  112594. -999, -999, -999, -999, -999, -999, -999, -999,
  112595. -999, -999, -999, -999, -999, -999, -999, -999,
  112596. -999, -999, -999, -999, -999, -999, -999, -999,
  112597. -999, -999, -999, -999, -999, -999, -999, -999},
  112598. {-999, -999, -999, -999, -999, -999, -999, -999,
  112599. -999, -999, -116, -109, -102, -95, -89, -75,
  112600. -66, -74, -77, -78, -86, -87, -90, -96,
  112601. -105, -115, -999, -999, -999, -999, -999, -999,
  112602. -999, -999, -999, -999, -999, -999, -999, -999,
  112603. -999, -999, -999, -999, -999, -999, -999, -999,
  112604. -999, -999, -999, -999, -999, -999, -999, -999},
  112605. {-999, -999, -999, -999, -999, -999, -999, -999,
  112606. -999, -999, -115, -108, -101, -94, -88, -66,
  112607. -56, -61, -70, -65, -78, -72, -83, -84,
  112608. -93, -98, -105, -110, -999, -999, -999, -999,
  112609. -999, -999, -999, -999, -999, -999, -999, -999,
  112610. -999, -999, -999, -999, -999, -999, -999, -999,
  112611. -999, -999, -999, -999, -999, -999, -999, -999},
  112612. {-999, -999, -999, -999, -999, -999, -999, -999,
  112613. -999, -999, -110, -105, -95, -89, -82, -57,
  112614. -52, -52, -59, -56, -59, -58, -69, -67,
  112615. -88, -82, -82, -89, -94, -100, -108, -999,
  112616. -999, -999, -999, -999, -999, -999, -999, -999,
  112617. -999, -999, -999, -999, -999, -999, -999, -999,
  112618. -999, -999, -999, -999, -999, -999, -999, -999},
  112619. {-999, -999, -999, -999, -999, -999, -999, -999,
  112620. -999, -110, -101, -96, -90, -83, -77, -54,
  112621. -43, -38, -50, -48, -52, -48, -42, -42,
  112622. -51, -52, -53, -59, -65, -71, -78, -85,
  112623. -95, -999, -999, -999, -999, -999, -999, -999,
  112624. -999, -999, -999, -999, -999, -999, -999, -999,
  112625. -999, -999, -999, -999, -999, -999, -999, -999}},
  112626. /* 8000 Hz */
  112627. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112628. -999, -999, -999, -999, -120, -105, -86, -68,
  112629. -78, -79, -90, -100, -110, -999, -999, -999,
  112630. -999, -999, -999, -999, -999, -999, -999, -999,
  112631. -999, -999, -999, -999, -999, -999, -999, -999,
  112632. -999, -999, -999, -999, -999, -999, -999, -999,
  112633. -999, -999, -999, -999, -999, -999, -999, -999},
  112634. {-999, -999, -999, -999, -999, -999, -999, -999,
  112635. -999, -999, -999, -999, -120, -105, -86, -66,
  112636. -73, -77, -88, -96, -105, -115, -999, -999,
  112637. -999, -999, -999, -999, -999, -999, -999, -999,
  112638. -999, -999, -999, -999, -999, -999, -999, -999,
  112639. -999, -999, -999, -999, -999, -999, -999, -999,
  112640. -999, -999, -999, -999, -999, -999, -999, -999},
  112641. {-999, -999, -999, -999, -999, -999, -999, -999,
  112642. -999, -999, -999, -120, -105, -92, -80, -61,
  112643. -64, -68, -80, -87, -92, -100, -110, -999,
  112644. -999, -999, -999, -999, -999, -999, -999, -999,
  112645. -999, -999, -999, -999, -999, -999, -999, -999,
  112646. -999, -999, -999, -999, -999, -999, -999, -999,
  112647. -999, -999, -999, -999, -999, -999, -999, -999},
  112648. {-999, -999, -999, -999, -999, -999, -999, -999,
  112649. -999, -999, -999, -120, -104, -91, -79, -52,
  112650. -60, -54, -64, -69, -77, -80, -82, -84,
  112651. -85, -87, -88, -90, -999, -999, -999, -999,
  112652. -999, -999, -999, -999, -999, -999, -999, -999,
  112653. -999, -999, -999, -999, -999, -999, -999, -999,
  112654. -999, -999, -999, -999, -999, -999, -999, -999},
  112655. {-999, -999, -999, -999, -999, -999, -999, -999,
  112656. -999, -999, -999, -118, -100, -87, -77, -49,
  112657. -50, -44, -58, -61, -61, -67, -65, -62,
  112658. -62, -62, -65, -68, -999, -999, -999, -999,
  112659. -999, -999, -999, -999, -999, -999, -999, -999,
  112660. -999, -999, -999, -999, -999, -999, -999, -999,
  112661. -999, -999, -999, -999, -999, -999, -999, -999},
  112662. {-999, -999, -999, -999, -999, -999, -999, -999,
  112663. -999, -999, -999, -115, -98, -84, -62, -49,
  112664. -44, -38, -46, -49, -49, -46, -39, -37,
  112665. -39, -40, -42, -43, -999, -999, -999, -999,
  112666. -999, -999, -999, -999, -999, -999, -999, -999,
  112667. -999, -999, -999, -999, -999, -999, -999, -999,
  112668. -999, -999, -999, -999, -999, -999, -999, -999}},
  112669. /* 11314 Hz */
  112670. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112671. -999, -999, -999, -999, -999, -110, -88, -74,
  112672. -77, -82, -82, -85, -90, -94, -99, -104,
  112673. -999, -999, -999, -999, -999, -999, -999, -999,
  112674. -999, -999, -999, -999, -999, -999, -999, -999,
  112675. -999, -999, -999, -999, -999, -999, -999, -999,
  112676. -999, -999, -999, -999, -999, -999, -999, -999},
  112677. {-999, -999, -999, -999, -999, -999, -999, -999,
  112678. -999, -999, -999, -999, -999, -110, -88, -66,
  112679. -70, -81, -80, -81, -84, -88, -91, -93,
  112680. -999, -999, -999, -999, -999, -999, -999, -999,
  112681. -999, -999, -999, -999, -999, -999, -999, -999,
  112682. -999, -999, -999, -999, -999, -999, -999, -999,
  112683. -999, -999, -999, -999, -999, -999, -999, -999},
  112684. {-999, -999, -999, -999, -999, -999, -999, -999,
  112685. -999, -999, -999, -999, -999, -110, -88, -61,
  112686. -63, -70, -71, -74, -77, -80, -83, -85,
  112687. -999, -999, -999, -999, -999, -999, -999, -999,
  112688. -999, -999, -999, -999, -999, -999, -999, -999,
  112689. -999, -999, -999, -999, -999, -999, -999, -999,
  112690. -999, -999, -999, -999, -999, -999, -999, -999},
  112691. {-999, -999, -999, -999, -999, -999, -999, -999,
  112692. -999, -999, -999, -999, -999, -110, -86, -62,
  112693. -63, -62, -62, -58, -52, -50, -50, -52,
  112694. -54, -999, -999, -999, -999, -999, -999, -999,
  112695. -999, -999, -999, -999, -999, -999, -999, -999,
  112696. -999, -999, -999, -999, -999, -999, -999, -999,
  112697. -999, -999, -999, -999, -999, -999, -999, -999},
  112698. {-999, -999, -999, -999, -999, -999, -999, -999,
  112699. -999, -999, -999, -999, -118, -108, -84, -53,
  112700. -50, -50, -50, -55, -47, -45, -40, -40,
  112701. -40, -999, -999, -999, -999, -999, -999, -999,
  112702. -999, -999, -999, -999, -999, -999, -999, -999,
  112703. -999, -999, -999, -999, -999, -999, -999, -999,
  112704. -999, -999, -999, -999, -999, -999, -999, -999},
  112705. {-999, -999, -999, -999, -999, -999, -999, -999,
  112706. -999, -999, -999, -999, -118, -100, -73, -43,
  112707. -37, -42, -43, -53, -38, -37, -35, -35,
  112708. -38, -999, -999, -999, -999, -999, -999, -999,
  112709. -999, -999, -999, -999, -999, -999, -999, -999,
  112710. -999, -999, -999, -999, -999, -999, -999, -999,
  112711. -999, -999, -999, -999, -999, -999, -999, -999}},
  112712. /* 16000 Hz */
  112713. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112714. -999, -999, -999, -110, -100, -91, -84, -74,
  112715. -80, -80, -80, -80, -80, -999, -999, -999,
  112716. -999, -999, -999, -999, -999, -999, -999, -999,
  112717. -999, -999, -999, -999, -999, -999, -999, -999,
  112718. -999, -999, -999, -999, -999, -999, -999, -999,
  112719. -999, -999, -999, -999, -999, -999, -999, -999},
  112720. {-999, -999, -999, -999, -999, -999, -999, -999,
  112721. -999, -999, -999, -110, -100, -91, -84, -74,
  112722. -68, -68, -68, -68, -68, -999, -999, -999,
  112723. -999, -999, -999, -999, -999, -999, -999, -999,
  112724. -999, -999, -999, -999, -999, -999, -999, -999,
  112725. -999, -999, -999, -999, -999, -999, -999, -999,
  112726. -999, -999, -999, -999, -999, -999, -999, -999},
  112727. {-999, -999, -999, -999, -999, -999, -999, -999,
  112728. -999, -999, -999, -110, -100, -86, -78, -70,
  112729. -60, -45, -30, -21, -999, -999, -999, -999,
  112730. -999, -999, -999, -999, -999, -999, -999, -999,
  112731. -999, -999, -999, -999, -999, -999, -999, -999,
  112732. -999, -999, -999, -999, -999, -999, -999, -999,
  112733. -999, -999, -999, -999, -999, -999, -999, -999},
  112734. {-999, -999, -999, -999, -999, -999, -999, -999,
  112735. -999, -999, -999, -110, -100, -87, -78, -67,
  112736. -48, -38, -29, -21, -999, -999, -999, -999,
  112737. -999, -999, -999, -999, -999, -999, -999, -999,
  112738. -999, -999, -999, -999, -999, -999, -999, -999,
  112739. -999, -999, -999, -999, -999, -999, -999, -999,
  112740. -999, -999, -999, -999, -999, -999, -999, -999},
  112741. {-999, -999, -999, -999, -999, -999, -999, -999,
  112742. -999, -999, -999, -110, -100, -86, -69, -56,
  112743. -45, -35, -33, -29, -999, -999, -999, -999,
  112744. -999, -999, -999, -999, -999, -999, -999, -999,
  112745. -999, -999, -999, -999, -999, -999, -999, -999,
  112746. -999, -999, -999, -999, -999, -999, -999, -999,
  112747. -999, -999, -999, -999, -999, -999, -999, -999},
  112748. {-999, -999, -999, -999, -999, -999, -999, -999,
  112749. -999, -999, -999, -110, -100, -83, -71, -48,
  112750. -27, -38, -37, -34, -999, -999, -999, -999,
  112751. -999, -999, -999, -999, -999, -999, -999, -999,
  112752. -999, -999, -999, -999, -999, -999, -999, -999,
  112753. -999, -999, -999, -999, -999, -999, -999, -999,
  112754. -999, -999, -999, -999, -999, -999, -999, -999}}
  112755. };
  112756. #endif
  112757. /********* End of inlined file: masking.h *********/
  112758. #define NEGINF -9999.f
  112759. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  112760. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  112761. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  112762. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112763. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112764. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  112765. look->channels=vi->channels;
  112766. look->ampmax=-9999.;
  112767. look->gi=gi;
  112768. return(look);
  112769. }
  112770. void _vp_global_free(vorbis_look_psy_global *look){
  112771. if(look){
  112772. memset(look,0,sizeof(*look));
  112773. _ogg_free(look);
  112774. }
  112775. }
  112776. void _vi_gpsy_free(vorbis_info_psy_global *i){
  112777. if(i){
  112778. memset(i,0,sizeof(*i));
  112779. _ogg_free(i);
  112780. }
  112781. }
  112782. void _vi_psy_free(vorbis_info_psy *i){
  112783. if(i){
  112784. memset(i,0,sizeof(*i));
  112785. _ogg_free(i);
  112786. }
  112787. }
  112788. static void min_curve(float *c,
  112789. float *c2){
  112790. int i;
  112791. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  112792. }
  112793. static void max_curve(float *c,
  112794. float *c2){
  112795. int i;
  112796. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  112797. }
  112798. static void attenuate_curve(float *c,float att){
  112799. int i;
  112800. for(i=0;i<EHMER_MAX;i++)
  112801. c[i]+=att;
  112802. }
  112803. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  112804. float center_boost, float center_decay_rate){
  112805. int i,j,k,m;
  112806. float ath[EHMER_MAX];
  112807. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  112808. float athc[P_LEVELS][EHMER_MAX];
  112809. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  112810. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  112811. memset(workc,0,sizeof(workc));
  112812. for(i=0;i<P_BANDS;i++){
  112813. /* we add back in the ATH to avoid low level curves falling off to
  112814. -infinity and unnecessarily cutting off high level curves in the
  112815. curve limiting (last step). */
  112816. /* A half-band's settings must be valid over the whole band, and
  112817. it's better to mask too little than too much */
  112818. int ath_offset=i*4;
  112819. for(j=0;j<EHMER_MAX;j++){
  112820. float min=999.;
  112821. for(k=0;k<4;k++)
  112822. if(j+k+ath_offset<MAX_ATH){
  112823. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  112824. }else{
  112825. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  112826. }
  112827. ath[j]=min;
  112828. }
  112829. /* copy curves into working space, replicate the 50dB curve to 30
  112830. and 40, replicate the 100dB curve to 110 */
  112831. for(j=0;j<6;j++)
  112832. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  112833. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112834. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112835. /* apply centered curve boost/decay */
  112836. for(j=0;j<P_LEVELS;j++){
  112837. for(k=0;k<EHMER_MAX;k++){
  112838. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  112839. if(adj<0. && center_boost>0)adj=0.;
  112840. if(adj>0. && center_boost<0)adj=0.;
  112841. workc[i][j][k]+=adj;
  112842. }
  112843. }
  112844. /* normalize curves so the driving amplitude is 0dB */
  112845. /* make temp curves with the ATH overlayed */
  112846. for(j=0;j<P_LEVELS;j++){
  112847. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  112848. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  112849. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  112850. max_curve(athc[j],workc[i][j]);
  112851. }
  112852. /* Now limit the louder curves.
  112853. the idea is this: We don't know what the playback attenuation
  112854. will be; 0dB SL moves every time the user twiddles the volume
  112855. knob. So that means we have to use a single 'most pessimal' curve
  112856. for all masking amplitudes, right? Wrong. The *loudest* sound
  112857. can be in (we assume) a range of ...+100dB] SL. However, sounds
  112858. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  112859. etc... */
  112860. for(j=1;j<P_LEVELS;j++){
  112861. min_curve(athc[j],athc[j-1]);
  112862. min_curve(workc[i][j],athc[j]);
  112863. }
  112864. }
  112865. for(i=0;i<P_BANDS;i++){
  112866. int hi_curve,lo_curve,bin;
  112867. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  112868. /* low frequency curves are measured with greater resolution than
  112869. the MDCT/FFT will actually give us; we want the curve applied
  112870. to the tone data to be pessimistic and thus apply the minimum
  112871. masking possible for a given bin. That means that a single bin
  112872. could span more than one octave and that the curve will be a
  112873. composite of multiple octaves. It also may mean that a single
  112874. bin may span > an eighth of an octave and that the eighth
  112875. octave values may also be composited. */
  112876. /* which octave curves will we be compositing? */
  112877. bin=floor(fromOC(i*.5)/binHz);
  112878. lo_curve= ceil(toOC(bin*binHz+1)*2);
  112879. hi_curve= floor(toOC((bin+1)*binHz)*2);
  112880. if(lo_curve>i)lo_curve=i;
  112881. if(lo_curve<0)lo_curve=0;
  112882. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  112883. for(m=0;m<P_LEVELS;m++){
  112884. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  112885. for(j=0;j<n;j++)brute_buffer[j]=999.;
  112886. /* render the curve into bins, then pull values back into curve.
  112887. The point is that any inherent subsampling aliasing results in
  112888. a safe minimum */
  112889. for(k=lo_curve;k<=hi_curve;k++){
  112890. int l=0;
  112891. for(j=0;j<EHMER_MAX;j++){
  112892. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  112893. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  112894. if(lo_bin<0)lo_bin=0;
  112895. if(lo_bin>n)lo_bin=n;
  112896. if(lo_bin<l)l=lo_bin;
  112897. if(hi_bin<0)hi_bin=0;
  112898. if(hi_bin>n)hi_bin=n;
  112899. for(;l<hi_bin && l<n;l++)
  112900. if(brute_buffer[l]>workc[k][m][j])
  112901. brute_buffer[l]=workc[k][m][j];
  112902. }
  112903. for(;l<n;l++)
  112904. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112905. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112906. }
  112907. /* be equally paranoid about being valid up to next half ocatve */
  112908. if(i+1<P_BANDS){
  112909. int l=0;
  112910. k=i+1;
  112911. for(j=0;j<EHMER_MAX;j++){
  112912. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  112913. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  112914. if(lo_bin<0)lo_bin=0;
  112915. if(lo_bin>n)lo_bin=n;
  112916. if(lo_bin<l)l=lo_bin;
  112917. if(hi_bin<0)hi_bin=0;
  112918. if(hi_bin>n)hi_bin=n;
  112919. for(;l<hi_bin && l<n;l++)
  112920. if(brute_buffer[l]>workc[k][m][j])
  112921. brute_buffer[l]=workc[k][m][j];
  112922. }
  112923. for(;l<n;l++)
  112924. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112925. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112926. }
  112927. for(j=0;j<EHMER_MAX;j++){
  112928. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  112929. if(bin<0){
  112930. ret[i][m][j+2]=-999.;
  112931. }else{
  112932. if(bin>=n){
  112933. ret[i][m][j+2]=-999.;
  112934. }else{
  112935. ret[i][m][j+2]=brute_buffer[bin];
  112936. }
  112937. }
  112938. }
  112939. /* add fenceposts */
  112940. for(j=0;j<EHMER_OFFSET;j++)
  112941. if(ret[i][m][j+2]>-200.f)break;
  112942. ret[i][m][0]=j;
  112943. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  112944. if(ret[i][m][j+2]>-200.f)
  112945. break;
  112946. ret[i][m][1]=j;
  112947. }
  112948. }
  112949. return(ret);
  112950. }
  112951. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  112952. vorbis_info_psy_global *gi,int n,long rate){
  112953. long i,j,lo=-99,hi=1;
  112954. long maxoc;
  112955. memset(p,0,sizeof(*p));
  112956. p->eighth_octave_lines=gi->eighth_octave_lines;
  112957. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  112958. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  112959. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  112960. p->total_octave_lines=maxoc-p->firstoc+1;
  112961. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  112962. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  112963. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  112964. p->vi=vi;
  112965. p->n=n;
  112966. p->rate=rate;
  112967. /* AoTuV HF weighting */
  112968. p->m_val = 1.;
  112969. if(rate < 26000) p->m_val = 0;
  112970. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  112971. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  112972. /* set up the lookups for a given blocksize and sample rate */
  112973. for(i=0,j=0;i<MAX_ATH-1;i++){
  112974. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  112975. float base=ATH[i];
  112976. if(j<endpos){
  112977. float delta=(ATH[i+1]-base)/(endpos-j);
  112978. for(;j<endpos && j<n;j++){
  112979. p->ath[j]=base+100.;
  112980. base+=delta;
  112981. }
  112982. }
  112983. }
  112984. for(i=0;i<n;i++){
  112985. float bark=toBARK(rate/(2*n)*i);
  112986. for(;lo+vi->noisewindowlomin<i &&
  112987. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  112988. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  112989. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  112990. p->bark[i]=((lo-1)<<16)+(hi-1);
  112991. }
  112992. for(i=0;i<n;i++)
  112993. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  112994. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  112995. vi->tone_centerboost,vi->tone_decay);
  112996. /* set up rolling noise median */
  112997. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  112998. for(i=0;i<P_NOISECURVES;i++)
  112999. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  113000. for(i=0;i<n;i++){
  113001. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  113002. int inthalfoc;
  113003. float del;
  113004. if(halfoc<0)halfoc=0;
  113005. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  113006. inthalfoc=(int)halfoc;
  113007. del=halfoc-inthalfoc;
  113008. for(j=0;j<P_NOISECURVES;j++)
  113009. p->noiseoffset[j][i]=
  113010. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  113011. p->vi->noiseoff[j][inthalfoc+1]*del;
  113012. }
  113013. #if 0
  113014. {
  113015. static int ls=0;
  113016. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  113017. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  113018. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  113019. }
  113020. #endif
  113021. }
  113022. void _vp_psy_clear(vorbis_look_psy *p){
  113023. int i,j;
  113024. if(p){
  113025. if(p->ath)_ogg_free(p->ath);
  113026. if(p->octave)_ogg_free(p->octave);
  113027. if(p->bark)_ogg_free(p->bark);
  113028. if(p->tonecurves){
  113029. for(i=0;i<P_BANDS;i++){
  113030. for(j=0;j<P_LEVELS;j++){
  113031. _ogg_free(p->tonecurves[i][j]);
  113032. }
  113033. _ogg_free(p->tonecurves[i]);
  113034. }
  113035. _ogg_free(p->tonecurves);
  113036. }
  113037. if(p->noiseoffset){
  113038. for(i=0;i<P_NOISECURVES;i++){
  113039. _ogg_free(p->noiseoffset[i]);
  113040. }
  113041. _ogg_free(p->noiseoffset);
  113042. }
  113043. memset(p,0,sizeof(*p));
  113044. }
  113045. }
  113046. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  113047. static void seed_curve(float *seed,
  113048. const float **curves,
  113049. float amp,
  113050. int oc, int n,
  113051. int linesper,float dBoffset){
  113052. int i,post1;
  113053. int seedptr;
  113054. const float *posts,*curve;
  113055. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  113056. choice=max(choice,0);
  113057. choice=min(choice,P_LEVELS-1);
  113058. posts=curves[choice];
  113059. curve=posts+2;
  113060. post1=(int)posts[1];
  113061. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  113062. for(i=posts[0];i<post1;i++){
  113063. if(seedptr>0){
  113064. float lin=amp+curve[i];
  113065. if(seed[seedptr]<lin)seed[seedptr]=lin;
  113066. }
  113067. seedptr+=linesper;
  113068. if(seedptr>=n)break;
  113069. }
  113070. }
  113071. static void seed_loop(vorbis_look_psy *p,
  113072. const float ***curves,
  113073. const float *f,
  113074. const float *flr,
  113075. float *seed,
  113076. float specmax){
  113077. vorbis_info_psy *vi=p->vi;
  113078. long n=p->n,i;
  113079. float dBoffset=vi->max_curve_dB-specmax;
  113080. /* prime the working vector with peak values */
  113081. for(i=0;i<n;i++){
  113082. float max=f[i];
  113083. long oc=p->octave[i];
  113084. while(i+1<n && p->octave[i+1]==oc){
  113085. i++;
  113086. if(f[i]>max)max=f[i];
  113087. }
  113088. if(max+6.f>flr[i]){
  113089. oc=oc>>p->shiftoc;
  113090. if(oc>=P_BANDS)oc=P_BANDS-1;
  113091. if(oc<0)oc=0;
  113092. seed_curve(seed,
  113093. curves[oc],
  113094. max,
  113095. p->octave[i]-p->firstoc,
  113096. p->total_octave_lines,
  113097. p->eighth_octave_lines,
  113098. dBoffset);
  113099. }
  113100. }
  113101. }
  113102. static void seed_chase(float *seeds, int linesper, long n){
  113103. long *posstack=(long*)alloca(n*sizeof(*posstack));
  113104. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  113105. long stack=0;
  113106. long pos=0;
  113107. long i;
  113108. for(i=0;i<n;i++){
  113109. if(stack<2){
  113110. posstack[stack]=i;
  113111. ampstack[stack++]=seeds[i];
  113112. }else{
  113113. while(1){
  113114. if(seeds[i]<ampstack[stack-1]){
  113115. posstack[stack]=i;
  113116. ampstack[stack++]=seeds[i];
  113117. break;
  113118. }else{
  113119. if(i<posstack[stack-1]+linesper){
  113120. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  113121. i<posstack[stack-2]+linesper){
  113122. /* we completely overlap, making stack-1 irrelevant. pop it */
  113123. stack--;
  113124. continue;
  113125. }
  113126. }
  113127. posstack[stack]=i;
  113128. ampstack[stack++]=seeds[i];
  113129. break;
  113130. }
  113131. }
  113132. }
  113133. }
  113134. /* the stack now contains only the positions that are relevant. Scan
  113135. 'em straight through */
  113136. for(i=0;i<stack;i++){
  113137. long endpos;
  113138. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  113139. endpos=posstack[i+1];
  113140. }else{
  113141. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  113142. discarded in short frames */
  113143. }
  113144. if(endpos>n)endpos=n;
  113145. for(;pos<endpos;pos++)
  113146. seeds[pos]=ampstack[i];
  113147. }
  113148. /* there. Linear time. I now remember this was on a problem set I
  113149. had in Grad Skool... I didn't solve it at the time ;-) */
  113150. }
  113151. /* bleaugh, this is more complicated than it needs to be */
  113152. #include<stdio.h>
  113153. static void max_seeds(vorbis_look_psy *p,
  113154. float *seed,
  113155. float *flr){
  113156. long n=p->total_octave_lines;
  113157. int linesper=p->eighth_octave_lines;
  113158. long linpos=0;
  113159. long pos;
  113160. seed_chase(seed,linesper,n); /* for masking */
  113161. pos=p->octave[0]-p->firstoc-(linesper>>1);
  113162. while(linpos+1<p->n){
  113163. float minV=seed[pos];
  113164. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  113165. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  113166. while(pos+1<=end){
  113167. pos++;
  113168. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  113169. minV=seed[pos];
  113170. }
  113171. end=pos+p->firstoc;
  113172. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  113173. if(flr[linpos]<minV)flr[linpos]=minV;
  113174. }
  113175. {
  113176. float minV=seed[p->total_octave_lines-1];
  113177. for(;linpos<p->n;linpos++)
  113178. if(flr[linpos]<minV)flr[linpos]=minV;
  113179. }
  113180. }
  113181. static void bark_noise_hybridmp(int n,const long *b,
  113182. const float *f,
  113183. float *noise,
  113184. const float offset,
  113185. const int fixed){
  113186. float *N=(float*) alloca(n*sizeof(*N));
  113187. float *X=(float*) alloca(n*sizeof(*N));
  113188. float *XX=(float*) alloca(n*sizeof(*N));
  113189. float *Y=(float*) alloca(n*sizeof(*N));
  113190. float *XY=(float*) alloca(n*sizeof(*N));
  113191. float tN, tX, tXX, tY, tXY;
  113192. int i;
  113193. int lo, hi;
  113194. float R, A, B, D;
  113195. float w, x, y;
  113196. tN = tX = tXX = tY = tXY = 0.f;
  113197. y = f[0] + offset;
  113198. if (y < 1.f) y = 1.f;
  113199. w = y * y * .5;
  113200. tN += w;
  113201. tX += w;
  113202. tY += w * y;
  113203. N[0] = tN;
  113204. X[0] = tX;
  113205. XX[0] = tXX;
  113206. Y[0] = tY;
  113207. XY[0] = tXY;
  113208. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  113209. y = f[i] + offset;
  113210. if (y < 1.f) y = 1.f;
  113211. w = y * y;
  113212. tN += w;
  113213. tX += w * x;
  113214. tXX += w * x * x;
  113215. tY += w * y;
  113216. tXY += w * x * y;
  113217. N[i] = tN;
  113218. X[i] = tX;
  113219. XX[i] = tXX;
  113220. Y[i] = tY;
  113221. XY[i] = tXY;
  113222. }
  113223. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113224. lo = b[i] >> 16;
  113225. if( lo>=0 ) break;
  113226. hi = b[i] & 0xffff;
  113227. tN = N[hi] + N[-lo];
  113228. tX = X[hi] - X[-lo];
  113229. tXX = XX[hi] + XX[-lo];
  113230. tY = Y[hi] + Y[-lo];
  113231. tXY = XY[hi] - XY[-lo];
  113232. A = tY * tXX - tX * tXY;
  113233. B = tN * tXY - tX * tY;
  113234. D = tN * tXX - tX * tX;
  113235. R = (A + x * B) / D;
  113236. if (R < 0.f)
  113237. R = 0.f;
  113238. noise[i] = R - offset;
  113239. }
  113240. for ( ;; i++, x += 1.f) {
  113241. lo = b[i] >> 16;
  113242. hi = b[i] & 0xffff;
  113243. if(hi>=n)break;
  113244. tN = N[hi] - N[lo];
  113245. tX = X[hi] - X[lo];
  113246. tXX = XX[hi] - XX[lo];
  113247. tY = Y[hi] - Y[lo];
  113248. tXY = XY[hi] - XY[lo];
  113249. A = tY * tXX - tX * tXY;
  113250. B = tN * tXY - tX * tY;
  113251. D = tN * tXX - tX * tX;
  113252. R = (A + x * B) / D;
  113253. if (R < 0.f) R = 0.f;
  113254. noise[i] = R - offset;
  113255. }
  113256. for ( ; i < n; i++, x += 1.f) {
  113257. R = (A + x * B) / D;
  113258. if (R < 0.f) R = 0.f;
  113259. noise[i] = R - offset;
  113260. }
  113261. if (fixed <= 0) return;
  113262. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113263. hi = i + fixed / 2;
  113264. lo = hi - fixed;
  113265. if(lo>=0)break;
  113266. tN = N[hi] + N[-lo];
  113267. tX = X[hi] - X[-lo];
  113268. tXX = XX[hi] + XX[-lo];
  113269. tY = Y[hi] + Y[-lo];
  113270. tXY = XY[hi] - XY[-lo];
  113271. A = tY * tXX - tX * tXY;
  113272. B = tN * tXY - tX * tY;
  113273. D = tN * tXX - tX * tX;
  113274. R = (A + x * B) / D;
  113275. if (R - offset < noise[i]) noise[i] = R - offset;
  113276. }
  113277. for ( ;; i++, x += 1.f) {
  113278. hi = i + fixed / 2;
  113279. lo = hi - fixed;
  113280. if(hi>=n)break;
  113281. tN = N[hi] - N[lo];
  113282. tX = X[hi] - X[lo];
  113283. tXX = XX[hi] - XX[lo];
  113284. tY = Y[hi] - Y[lo];
  113285. tXY = XY[hi] - XY[lo];
  113286. A = tY * tXX - tX * tXY;
  113287. B = tN * tXY - tX * tY;
  113288. D = tN * tXX - tX * tX;
  113289. R = (A + x * B) / D;
  113290. if (R - offset < noise[i]) noise[i] = R - offset;
  113291. }
  113292. for ( ; i < n; i++, x += 1.f) {
  113293. R = (A + x * B) / D;
  113294. if (R - offset < noise[i]) noise[i] = R - offset;
  113295. }
  113296. }
  113297. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  113298. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  113299. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  113300. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  113301. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  113302. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  113303. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  113304. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  113305. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  113306. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  113307. 973377.F, 913981.F, 858210.F, 805842.F,
  113308. 756669.F, 710497.F, 667142.F, 626433.F,
  113309. 588208.F, 552316.F, 518613.F, 486967.F,
  113310. 457252.F, 429351.F, 403152.F, 378551.F,
  113311. 355452.F, 333762.F, 313396.F, 294273.F,
  113312. 276316.F, 259455.F, 243623.F, 228757.F,
  113313. 214798.F, 201691.F, 189384.F, 177828.F,
  113314. 166977.F, 156788.F, 147221.F, 138237.F,
  113315. 129802.F, 121881.F, 114444.F, 107461.F,
  113316. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  113317. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  113318. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  113319. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  113320. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  113321. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  113322. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  113323. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  113324. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  113325. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  113326. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  113327. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  113328. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  113329. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  113330. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  113331. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  113332. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  113333. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  113334. 1084.32F, 1018.15F, 956.024F, 897.687F,
  113335. 842.910F, 791.475F, 743.179F, 697.830F,
  113336. 655.249F, 615.265F, 577.722F, 542.469F,
  113337. 509.367F, 478.286F, 449.101F, 421.696F,
  113338. 395.964F, 371.803F, 349.115F, 327.812F,
  113339. 307.809F, 289.026F, 271.390F, 254.830F,
  113340. 239.280F, 224.679F, 210.969F, 198.096F,
  113341. 186.008F, 174.658F, 164.000F, 153.993F,
  113342. 144.596F, 135.773F, 127.488F, 119.708F,
  113343. 112.404F, 105.545F, 99.1046F, 93.0572F,
  113344. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  113345. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  113346. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  113347. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  113348. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  113349. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  113350. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  113351. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  113352. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  113353. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  113354. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  113355. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  113356. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  113357. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  113358. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  113359. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  113360. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  113361. 1.20790F, 1.13419F, 1.06499F, 1.F
  113362. };
  113363. void _vp_remove_floor(vorbis_look_psy *p,
  113364. float *mdct,
  113365. int *codedflr,
  113366. float *residue,
  113367. int sliding_lowpass){
  113368. int i,n=p->n;
  113369. if(sliding_lowpass>n)sliding_lowpass=n;
  113370. for(i=0;i<sliding_lowpass;i++){
  113371. residue[i]=
  113372. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  113373. }
  113374. for(;i<n;i++)
  113375. residue[i]=0.;
  113376. }
  113377. void _vp_noisemask(vorbis_look_psy *p,
  113378. float *logmdct,
  113379. float *logmask){
  113380. int i,n=p->n;
  113381. float *work=(float*) alloca(n*sizeof(*work));
  113382. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  113383. 140.,-1);
  113384. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  113385. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  113386. p->vi->noisewindowfixed);
  113387. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  113388. #if 0
  113389. {
  113390. static int seq=0;
  113391. float work2[n];
  113392. for(i=0;i<n;i++){
  113393. work2[i]=logmask[i]+work[i];
  113394. }
  113395. if(seq&1)
  113396. _analysis_output("median2R",seq/2,work,n,1,0,0);
  113397. else
  113398. _analysis_output("median2L",seq/2,work,n,1,0,0);
  113399. if(seq&1)
  113400. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  113401. else
  113402. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  113403. seq++;
  113404. }
  113405. #endif
  113406. for(i=0;i<n;i++){
  113407. int dB=logmask[i]+.5;
  113408. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  113409. if(dB<0)dB=0;
  113410. logmask[i]= work[i]+p->vi->noisecompand[dB];
  113411. }
  113412. }
  113413. void _vp_tonemask(vorbis_look_psy *p,
  113414. float *logfft,
  113415. float *logmask,
  113416. float global_specmax,
  113417. float local_specmax){
  113418. int i,n=p->n;
  113419. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  113420. float att=local_specmax+p->vi->ath_adjatt;
  113421. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  113422. /* set the ATH (floating below localmax, not global max by a
  113423. specified att) */
  113424. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  113425. for(i=0;i<n;i++)
  113426. logmask[i]=p->ath[i]+att;
  113427. /* tone masking */
  113428. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  113429. max_seeds(p,seed,logmask);
  113430. }
  113431. void _vp_offset_and_mix(vorbis_look_psy *p,
  113432. float *noise,
  113433. float *tone,
  113434. int offset_select,
  113435. float *logmask,
  113436. float *mdct,
  113437. float *logmdct){
  113438. int i,n=p->n;
  113439. float de, coeffi, cx;/* AoTuV */
  113440. float toneatt=p->vi->tone_masteratt[offset_select];
  113441. cx = p->m_val;
  113442. for(i=0;i<n;i++){
  113443. float val= noise[i]+p->noiseoffset[offset_select][i];
  113444. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  113445. logmask[i]=max(val,tone[i]+toneatt);
  113446. /* AoTuV */
  113447. /** @ M1 **
  113448. The following codes improve a noise problem.
  113449. A fundamental idea uses the value of masking and carries out
  113450. the relative compensation of the MDCT.
  113451. However, this code is not perfect and all noise problems cannot be solved.
  113452. by Aoyumi @ 2004/04/18
  113453. */
  113454. if(offset_select == 1) {
  113455. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  113456. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  113457. if(val > coeffi){
  113458. /* mdct value is > -17.2 dB below floor */
  113459. de = 1.0-((val-coeffi)*0.005*cx);
  113460. /* pro-rated attenuation:
  113461. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  113462. -0.77 dB boost if mdct value is 0dB (relative to floor)
  113463. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  113464. etc... */
  113465. if(de < 0) de = 0.0001;
  113466. }else
  113467. /* mdct value is <= -17.2 dB below floor */
  113468. de = 1.0-((val-coeffi)*0.0003*cx);
  113469. /* pro-rated attenuation:
  113470. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  113471. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  113472. etc... */
  113473. mdct[i] *= de;
  113474. }
  113475. }
  113476. }
  113477. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  113478. vorbis_info *vi=vd->vi;
  113479. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113480. vorbis_info_psy_global *gi=&ci->psy_g_param;
  113481. int n=ci->blocksizes[vd->W]/2;
  113482. float secs=(float)n/vi->rate;
  113483. amp+=secs*gi->ampmax_att_per_sec;
  113484. if(amp<-9999)amp=-9999;
  113485. return(amp);
  113486. }
  113487. static void couple_lossless(float A, float B,
  113488. float *qA, float *qB){
  113489. int test1=fabs(*qA)>fabs(*qB);
  113490. test1-= fabs(*qA)<fabs(*qB);
  113491. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  113492. if(test1==1){
  113493. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  113494. }else{
  113495. float temp=*qB;
  113496. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  113497. *qA=temp;
  113498. }
  113499. if(*qB>fabs(*qA)*1.9999f){
  113500. *qB= -fabs(*qA)*2.f;
  113501. *qA= -*qA;
  113502. }
  113503. }
  113504. static float hypot_lookup[32]={
  113505. -0.009935, -0.011245, -0.012726, -0.014397,
  113506. -0.016282, -0.018407, -0.020800, -0.023494,
  113507. -0.026522, -0.029923, -0.033737, -0.038010,
  113508. -0.042787, -0.048121, -0.054064, -0.060671,
  113509. -0.068000, -0.076109, -0.085054, -0.094892,
  113510. -0.105675, -0.117451, -0.130260, -0.144134,
  113511. -0.159093, -0.175146, -0.192286, -0.210490,
  113512. -0.229718, -0.249913, -0.271001, -0.292893};
  113513. static void precomputed_couple_point(float premag,
  113514. int floorA,int floorB,
  113515. float *mag, float *ang){
  113516. int test=(floorA>floorB)-1;
  113517. int offset=31-abs(floorA-floorB);
  113518. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  113519. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  113520. *mag=premag*floormag;
  113521. *ang=0.f;
  113522. }
  113523. /* just like below, this is currently set up to only do
  113524. single-step-depth coupling. Otherwise, we'd have to do more
  113525. copying (which will be inevitable later) */
  113526. /* doing the real circular magnitude calculation is audibly superior
  113527. to (A+B)/sqrt(2) */
  113528. static float dipole_hypot(float a, float b){
  113529. if(a>0.){
  113530. if(b>0.)return sqrt(a*a+b*b);
  113531. if(a>-b)return sqrt(a*a-b*b);
  113532. return -sqrt(b*b-a*a);
  113533. }
  113534. if(b<0.)return -sqrt(a*a+b*b);
  113535. if(-a>b)return -sqrt(a*a-b*b);
  113536. return sqrt(b*b-a*a);
  113537. }
  113538. static float round_hypot(float a, float b){
  113539. if(a>0.){
  113540. if(b>0.)return sqrt(a*a+b*b);
  113541. if(a>-b)return sqrt(a*a+b*b);
  113542. return -sqrt(b*b+a*a);
  113543. }
  113544. if(b<0.)return -sqrt(a*a+b*b);
  113545. if(-a>b)return -sqrt(a*a+b*b);
  113546. return sqrt(b*b+a*a);
  113547. }
  113548. /* revert to round hypot for now */
  113549. float **_vp_quantize_couple_memo(vorbis_block *vb,
  113550. vorbis_info_psy_global *g,
  113551. vorbis_look_psy *p,
  113552. vorbis_info_mapping0 *vi,
  113553. float **mdct){
  113554. int i,j,n=p->n;
  113555. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113556. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113557. for(i=0;i<vi->coupling_steps;i++){
  113558. float *mdctM=mdct[vi->coupling_mag[i]];
  113559. float *mdctA=mdct[vi->coupling_ang[i]];
  113560. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113561. for(j=0;j<limit;j++)
  113562. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  113563. for(;j<n;j++)
  113564. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  113565. }
  113566. return(ret);
  113567. }
  113568. /* this is for per-channel noise normalization */
  113569. static int apsort(const void *a, const void *b){
  113570. float f1=fabs(**(float**)a);
  113571. float f2=fabs(**(float**)b);
  113572. return (f1<f2)-(f1>f2);
  113573. }
  113574. int **_vp_quantize_couple_sort(vorbis_block *vb,
  113575. vorbis_look_psy *p,
  113576. vorbis_info_mapping0 *vi,
  113577. float **mags){
  113578. if(p->vi->normal_point_p){
  113579. int i,j,k,n=p->n;
  113580. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113581. int partition=p->vi->normal_partition;
  113582. float **work=(float**) alloca(sizeof(*work)*partition);
  113583. for(i=0;i<vi->coupling_steps;i++){
  113584. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113585. for(j=0;j<n;j+=partition){
  113586. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  113587. qsort(work,partition,sizeof(*work),apsort);
  113588. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  113589. }
  113590. }
  113591. return(ret);
  113592. }
  113593. return(NULL);
  113594. }
  113595. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  113596. float *magnitudes,int *sortedindex){
  113597. int i,j,n=p->n;
  113598. vorbis_info_psy *vi=p->vi;
  113599. int partition=vi->normal_partition;
  113600. float **work=(float**) alloca(sizeof(*work)*partition);
  113601. int start=vi->normal_start;
  113602. for(j=start;j<n;j+=partition){
  113603. if(j+partition>n)partition=n-j;
  113604. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  113605. qsort(work,partition,sizeof(*work),apsort);
  113606. for(i=0;i<partition;i++){
  113607. sortedindex[i+j-start]=work[i]-magnitudes;
  113608. }
  113609. }
  113610. }
  113611. void _vp_noise_normalize(vorbis_look_psy *p,
  113612. float *in,float *out,int *sortedindex){
  113613. int flag=0,i,j=0,n=p->n;
  113614. vorbis_info_psy *vi=p->vi;
  113615. int partition=vi->normal_partition;
  113616. int start=vi->normal_start;
  113617. if(start>n)start=n;
  113618. if(vi->normal_channel_p){
  113619. for(;j<start;j++)
  113620. out[j]=rint(in[j]);
  113621. for(;j+partition<=n;j+=partition){
  113622. float acc=0.;
  113623. int k;
  113624. for(i=j;i<j+partition;i++)
  113625. acc+=in[i]*in[i];
  113626. for(i=0;i<partition;i++){
  113627. k=sortedindex[i+j-start];
  113628. if(in[k]*in[k]>=.25f){
  113629. out[k]=rint(in[k]);
  113630. acc-=in[k]*in[k];
  113631. flag=1;
  113632. }else{
  113633. if(acc<vi->normal_thresh)break;
  113634. out[k]=unitnorm(in[k]);
  113635. acc-=1.;
  113636. }
  113637. }
  113638. for(;i<partition;i++){
  113639. k=sortedindex[i+j-start];
  113640. out[k]=0.;
  113641. }
  113642. }
  113643. }
  113644. for(;j<n;j++)
  113645. out[j]=rint(in[j]);
  113646. }
  113647. void _vp_couple(int blobno,
  113648. vorbis_info_psy_global *g,
  113649. vorbis_look_psy *p,
  113650. vorbis_info_mapping0 *vi,
  113651. float **res,
  113652. float **mag_memo,
  113653. int **mag_sort,
  113654. int **ifloor,
  113655. int *nonzero,
  113656. int sliding_lowpass){
  113657. int i,j,k,n=p->n;
  113658. /* perform any requested channel coupling */
  113659. /* point stereo can only be used in a first stage (in this encoder)
  113660. because of the dependency on floor lookups */
  113661. for(i=0;i<vi->coupling_steps;i++){
  113662. /* once we're doing multistage coupling in which a channel goes
  113663. through more than one coupling step, the floor vector
  113664. magnitudes will also have to be recalculated an propogated
  113665. along with PCM. Right now, we're not (that will wait until 5.1
  113666. most likely), so the code isn't here yet. The memory management
  113667. here is all assuming single depth couplings anyway. */
  113668. /* make sure coupling a zero and a nonzero channel results in two
  113669. nonzero channels. */
  113670. if(nonzero[vi->coupling_mag[i]] ||
  113671. nonzero[vi->coupling_ang[i]]){
  113672. float *rM=res[vi->coupling_mag[i]];
  113673. float *rA=res[vi->coupling_ang[i]];
  113674. float *qM=rM+n;
  113675. float *qA=rA+n;
  113676. int *floorM=ifloor[vi->coupling_mag[i]];
  113677. int *floorA=ifloor[vi->coupling_ang[i]];
  113678. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  113679. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  113680. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  113681. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  113682. int pointlimit=limit;
  113683. nonzero[vi->coupling_mag[i]]=1;
  113684. nonzero[vi->coupling_ang[i]]=1;
  113685. /* The threshold of a stereo is changed with the size of n */
  113686. if(n > 1000)
  113687. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  113688. for(j=0;j<p->n;j+=partition){
  113689. float acc=0.f;
  113690. for(k=0;k<partition;k++){
  113691. int l=k+j;
  113692. if(l<sliding_lowpass){
  113693. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  113694. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  113695. precomputed_couple_point(mag_memo[i][l],
  113696. floorM[l],floorA[l],
  113697. qM+l,qA+l);
  113698. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  113699. }else{
  113700. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  113701. }
  113702. }else{
  113703. qM[l]=0.;
  113704. qA[l]=0.;
  113705. }
  113706. }
  113707. if(p->vi->normal_point_p){
  113708. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  113709. int l=mag_sort[i][j+k];
  113710. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  113711. qM[l]=unitnorm(qM[l]);
  113712. acc-=1.f;
  113713. }
  113714. }
  113715. }
  113716. }
  113717. }
  113718. }
  113719. }
  113720. /* AoTuV */
  113721. /** @ M2 **
  113722. The boost problem by the combination of noise normalization and point stereo is eased.
  113723. However, this is a temporary patch.
  113724. by Aoyumi @ 2004/04/18
  113725. */
  113726. void hf_reduction(vorbis_info_psy_global *g,
  113727. vorbis_look_psy *p,
  113728. vorbis_info_mapping0 *vi,
  113729. float **mdct){
  113730. int i,j,n=p->n, de=0.3*p->m_val;
  113731. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113732. for(i=0; i<vi->coupling_steps; i++){
  113733. /* for(j=start; j<limit; j++){} // ???*/
  113734. for(j=limit; j<n; j++)
  113735. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  113736. }
  113737. }
  113738. #endif
  113739. /********* End of inlined file: psy.c *********/
  113740. /********* Start of inlined file: registry.c *********/
  113741. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113742. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113743. // tasks..
  113744. #if JUCE_MSVC
  113745. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113746. #endif
  113747. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113748. #if JUCE_USE_OGGVORBIS
  113749. /* seems like major overkill now; the backend numbers will grow into
  113750. the infrastructure soon enough */
  113751. extern vorbis_func_floor floor0_exportbundle;
  113752. extern vorbis_func_floor floor1_exportbundle;
  113753. extern vorbis_func_residue residue0_exportbundle;
  113754. extern vorbis_func_residue residue1_exportbundle;
  113755. extern vorbis_func_residue residue2_exportbundle;
  113756. extern vorbis_func_mapping mapping0_exportbundle;
  113757. vorbis_func_floor *_floor_P[]={
  113758. &floor0_exportbundle,
  113759. &floor1_exportbundle,
  113760. };
  113761. vorbis_func_residue *_residue_P[]={
  113762. &residue0_exportbundle,
  113763. &residue1_exportbundle,
  113764. &residue2_exportbundle,
  113765. };
  113766. vorbis_func_mapping *_mapping_P[]={
  113767. &mapping0_exportbundle,
  113768. };
  113769. #endif
  113770. /********* End of inlined file: registry.c *********/
  113771. /********* Start of inlined file: res0.c *********/
  113772. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  113773. encode/decode loops are coded for clarity and performance is not
  113774. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  113775. it's slow. */
  113776. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113777. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113778. // tasks..
  113779. #if JUCE_MSVC
  113780. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113781. #endif
  113782. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113783. #if JUCE_USE_OGGVORBIS
  113784. #include <stdlib.h>
  113785. #include <string.h>
  113786. #include <math.h>
  113787. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113788. #include <stdio.h>
  113789. #endif
  113790. typedef struct {
  113791. vorbis_info_residue0 *info;
  113792. int parts;
  113793. int stages;
  113794. codebook *fullbooks;
  113795. codebook *phrasebook;
  113796. codebook ***partbooks;
  113797. int partvals;
  113798. int **decodemap;
  113799. long postbits;
  113800. long phrasebits;
  113801. long frames;
  113802. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  113803. int train_seq;
  113804. long *training_data[8][64];
  113805. float training_max[8][64];
  113806. float training_min[8][64];
  113807. float tmin;
  113808. float tmax;
  113809. #endif
  113810. } vorbis_look_residue0;
  113811. void res0_free_info(vorbis_info_residue *i){
  113812. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  113813. if(info){
  113814. memset(info,0,sizeof(*info));
  113815. _ogg_free(info);
  113816. }
  113817. }
  113818. void res0_free_look(vorbis_look_residue *i){
  113819. int j;
  113820. if(i){
  113821. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  113822. #ifdef TRAIN_RES
  113823. {
  113824. int j,k,l;
  113825. for(j=0;j<look->parts;j++){
  113826. /*fprintf(stderr,"partition %d: ",j);*/
  113827. for(k=0;k<8;k++)
  113828. if(look->training_data[k][j]){
  113829. char buffer[80];
  113830. FILE *of;
  113831. codebook *statebook=look->partbooks[j][k];
  113832. /* long and short into the same bucket by current convention */
  113833. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  113834. of=fopen(buffer,"a");
  113835. for(l=0;l<statebook->entries;l++)
  113836. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  113837. fclose(of);
  113838. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  113839. look->training_min[k][j],look->training_max[k][j]);*/
  113840. _ogg_free(look->training_data[k][j]);
  113841. look->training_data[k][j]=NULL;
  113842. }
  113843. /*fprintf(stderr,"\n");*/
  113844. }
  113845. }
  113846. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  113847. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  113848. (float)look->phrasebits/look->frames,
  113849. (float)look->postbits/look->frames,
  113850. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113851. #endif
  113852. /*vorbis_info_residue0 *info=look->info;
  113853. fprintf(stderr,
  113854. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  113855. "(%g/frame) \n",look->frames,look->phrasebits,
  113856. look->resbitsflat,
  113857. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  113858. for(j=0;j<look->parts;j++){
  113859. long acc=0;
  113860. fprintf(stderr,"\t[%d] == ",j);
  113861. for(k=0;k<look->stages;k++)
  113862. if((info->secondstages[j]>>k)&1){
  113863. fprintf(stderr,"%ld,",look->resbits[j][k]);
  113864. acc+=look->resbits[j][k];
  113865. }
  113866. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  113867. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  113868. }
  113869. fprintf(stderr,"\n");*/
  113870. for(j=0;j<look->parts;j++)
  113871. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  113872. _ogg_free(look->partbooks);
  113873. for(j=0;j<look->partvals;j++)
  113874. _ogg_free(look->decodemap[j]);
  113875. _ogg_free(look->decodemap);
  113876. memset(look,0,sizeof(*look));
  113877. _ogg_free(look);
  113878. }
  113879. }
  113880. static int icount(unsigned int v){
  113881. int ret=0;
  113882. while(v){
  113883. ret+=v&1;
  113884. v>>=1;
  113885. }
  113886. return(ret);
  113887. }
  113888. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  113889. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113890. int j,acc=0;
  113891. oggpack_write(opb,info->begin,24);
  113892. oggpack_write(opb,info->end,24);
  113893. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  113894. code with a partitioned book */
  113895. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  113896. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  113897. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  113898. bitmask of one indicates this partition class has bits to write
  113899. this pass */
  113900. for(j=0;j<info->partitions;j++){
  113901. if(ilog(info->secondstages[j])>3){
  113902. /* yes, this is a minor hack due to not thinking ahead */
  113903. oggpack_write(opb,info->secondstages[j],3);
  113904. oggpack_write(opb,1,1);
  113905. oggpack_write(opb,info->secondstages[j]>>3,5);
  113906. }else
  113907. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  113908. acc+=icount(info->secondstages[j]);
  113909. }
  113910. for(j=0;j<acc;j++)
  113911. oggpack_write(opb,info->booklist[j],8);
  113912. }
  113913. /* vorbis_info is for range checking */
  113914. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  113915. int j,acc=0;
  113916. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  113917. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113918. info->begin=oggpack_read(opb,24);
  113919. info->end=oggpack_read(opb,24);
  113920. info->grouping=oggpack_read(opb,24)+1;
  113921. info->partitions=oggpack_read(opb,6)+1;
  113922. info->groupbook=oggpack_read(opb,8);
  113923. for(j=0;j<info->partitions;j++){
  113924. int cascade=oggpack_read(opb,3);
  113925. if(oggpack_read(opb,1))
  113926. cascade|=(oggpack_read(opb,5)<<3);
  113927. info->secondstages[j]=cascade;
  113928. acc+=icount(cascade);
  113929. }
  113930. for(j=0;j<acc;j++)
  113931. info->booklist[j]=oggpack_read(opb,8);
  113932. if(info->groupbook>=ci->books)goto errout;
  113933. for(j=0;j<acc;j++)
  113934. if(info->booklist[j]>=ci->books)goto errout;
  113935. return(info);
  113936. errout:
  113937. res0_free_info(info);
  113938. return(NULL);
  113939. }
  113940. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  113941. vorbis_info_residue *vr){
  113942. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113943. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  113944. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  113945. int j,k,acc=0;
  113946. int dim;
  113947. int maxstage=0;
  113948. look->info=info;
  113949. look->parts=info->partitions;
  113950. look->fullbooks=ci->fullbooks;
  113951. look->phrasebook=ci->fullbooks+info->groupbook;
  113952. dim=look->phrasebook->dim;
  113953. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  113954. for(j=0;j<look->parts;j++){
  113955. int stages=ilog(info->secondstages[j]);
  113956. if(stages){
  113957. if(stages>maxstage)maxstage=stages;
  113958. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  113959. for(k=0;k<stages;k++)
  113960. if(info->secondstages[j]&(1<<k)){
  113961. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  113962. #ifdef TRAIN_RES
  113963. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  113964. sizeof(***look->training_data));
  113965. #endif
  113966. }
  113967. }
  113968. }
  113969. look->partvals=rint(pow((float)look->parts,(float)dim));
  113970. look->stages=maxstage;
  113971. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  113972. for(j=0;j<look->partvals;j++){
  113973. long val=j;
  113974. long mult=look->partvals/look->parts;
  113975. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  113976. for(k=0;k<dim;k++){
  113977. long deco=val/mult;
  113978. val-=deco*mult;
  113979. mult/=look->parts;
  113980. look->decodemap[j][k]=deco;
  113981. }
  113982. }
  113983. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113984. {
  113985. static int train_seq=0;
  113986. look->train_seq=train_seq++;
  113987. }
  113988. #endif
  113989. return(look);
  113990. }
  113991. /* break an abstraction and copy some code for performance purposes */
  113992. static int local_book_besterror(codebook *book,float *a){
  113993. int dim=book->dim,i,k,o;
  113994. int best=0;
  113995. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113996. /* find the quant val of each scalar */
  113997. for(k=0,o=dim;k<dim;++k){
  113998. float val=a[--o];
  113999. i=tt->threshvals>>1;
  114000. if(val<tt->quantthresh[i]){
  114001. if(val<tt->quantthresh[i-1]){
  114002. for(--i;i>0;--i)
  114003. if(val>=tt->quantthresh[i-1])
  114004. break;
  114005. }
  114006. }else{
  114007. for(++i;i<tt->threshvals-1;++i)
  114008. if(val<tt->quantthresh[i])break;
  114009. }
  114010. best=(best*tt->quantvals)+tt->quantmap[i];
  114011. }
  114012. /* regular lattices are easy :-) */
  114013. if(book->c->lengthlist[best]<=0){
  114014. const static_codebook *c=book->c;
  114015. int i,j;
  114016. float bestf=0.f;
  114017. float *e=book->valuelist;
  114018. best=-1;
  114019. for(i=0;i<book->entries;i++){
  114020. if(c->lengthlist[i]>0){
  114021. float thisx=0.f;
  114022. for(j=0;j<dim;j++){
  114023. float val=(e[j]-a[j]);
  114024. thisx+=val*val;
  114025. }
  114026. if(best==-1 || thisx<bestf){
  114027. bestf=thisx;
  114028. best=i;
  114029. }
  114030. }
  114031. e+=dim;
  114032. }
  114033. }
  114034. {
  114035. float *ptr=book->valuelist+best*dim;
  114036. for(i=0;i<dim;i++)
  114037. *a++ -= *ptr++;
  114038. }
  114039. return(best);
  114040. }
  114041. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  114042. codebook *book,long *acc){
  114043. int i,bits=0;
  114044. int dim=book->dim;
  114045. int step=n/dim;
  114046. for(i=0;i<step;i++){
  114047. int entry=local_book_besterror(book,vec+i*dim);
  114048. #ifdef TRAIN_RES
  114049. acc[entry]++;
  114050. #endif
  114051. bits+=vorbis_book_encode(book,entry,opb);
  114052. }
  114053. return(bits);
  114054. }
  114055. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  114056. float **in,int ch){
  114057. long i,j,k;
  114058. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114059. vorbis_info_residue0 *info=look->info;
  114060. /* move all this setup out later */
  114061. int samples_per_partition=info->grouping;
  114062. int possible_partitions=info->partitions;
  114063. int n=info->end-info->begin;
  114064. int partvals=n/samples_per_partition;
  114065. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  114066. float scale=100./samples_per_partition;
  114067. /* we find the partition type for each partition of each
  114068. channel. We'll go back and do the interleaved encoding in a
  114069. bit. For now, clarity */
  114070. for(i=0;i<ch;i++){
  114071. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  114072. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  114073. }
  114074. for(i=0;i<partvals;i++){
  114075. int offset=i*samples_per_partition+info->begin;
  114076. for(j=0;j<ch;j++){
  114077. float max=0.;
  114078. float ent=0.;
  114079. for(k=0;k<samples_per_partition;k++){
  114080. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  114081. ent+=fabs(rint(in[j][offset+k]));
  114082. }
  114083. ent*=scale;
  114084. for(k=0;k<possible_partitions-1;k++)
  114085. if(max<=info->classmetric1[k] &&
  114086. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  114087. break;
  114088. partword[j][i]=k;
  114089. }
  114090. }
  114091. #ifdef TRAIN_RESAUX
  114092. {
  114093. FILE *of;
  114094. char buffer[80];
  114095. for(i=0;i<ch;i++){
  114096. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114097. of=fopen(buffer,"a");
  114098. for(j=0;j<partvals;j++)
  114099. fprintf(of,"%ld, ",partword[i][j]);
  114100. fprintf(of,"\n");
  114101. fclose(of);
  114102. }
  114103. }
  114104. #endif
  114105. look->frames++;
  114106. return(partword);
  114107. }
  114108. /* designed for stereo or other modes where the partition size is an
  114109. integer multiple of the number of channels encoded in the current
  114110. submap */
  114111. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  114112. int ch){
  114113. long i,j,k,l;
  114114. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114115. vorbis_info_residue0 *info=look->info;
  114116. /* move all this setup out later */
  114117. int samples_per_partition=info->grouping;
  114118. int possible_partitions=info->partitions;
  114119. int n=info->end-info->begin;
  114120. int partvals=n/samples_per_partition;
  114121. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  114122. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114123. FILE *of;
  114124. char buffer[80];
  114125. #endif
  114126. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  114127. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  114128. for(i=0,l=info->begin/ch;i<partvals;i++){
  114129. float magmax=0.f;
  114130. float angmax=0.f;
  114131. for(j=0;j<samples_per_partition;j+=ch){
  114132. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  114133. for(k=1;k<ch;k++)
  114134. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  114135. l++;
  114136. }
  114137. for(j=0;j<possible_partitions-1;j++)
  114138. if(magmax<=info->classmetric1[j] &&
  114139. angmax<=info->classmetric2[j])
  114140. break;
  114141. partword[0][i]=j;
  114142. }
  114143. #ifdef TRAIN_RESAUX
  114144. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114145. of=fopen(buffer,"a");
  114146. for(i=0;i<partvals;i++)
  114147. fprintf(of,"%ld, ",partword[0][i]);
  114148. fprintf(of,"\n");
  114149. fclose(of);
  114150. #endif
  114151. look->frames++;
  114152. return(partword);
  114153. }
  114154. static int _01forward(oggpack_buffer *opb,
  114155. vorbis_block *vb,vorbis_look_residue *vl,
  114156. float **in,int ch,
  114157. long **partword,
  114158. int (*encode)(oggpack_buffer *,float *,int,
  114159. codebook *,long *)){
  114160. long i,j,k,s;
  114161. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114162. vorbis_info_residue0 *info=look->info;
  114163. /* move all this setup out later */
  114164. int samples_per_partition=info->grouping;
  114165. int possible_partitions=info->partitions;
  114166. int partitions_per_word=look->phrasebook->dim;
  114167. int n=info->end-info->begin;
  114168. int partvals=n/samples_per_partition;
  114169. long resbits[128];
  114170. long resvals[128];
  114171. #ifdef TRAIN_RES
  114172. for(i=0;i<ch;i++)
  114173. for(j=info->begin;j<info->end;j++){
  114174. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  114175. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  114176. }
  114177. #endif
  114178. memset(resbits,0,sizeof(resbits));
  114179. memset(resvals,0,sizeof(resvals));
  114180. /* we code the partition words for each channel, then the residual
  114181. words for a partition per channel until we've written all the
  114182. residual words for that partition word. Then write the next
  114183. partition channel words... */
  114184. for(s=0;s<look->stages;s++){
  114185. for(i=0;i<partvals;){
  114186. /* first we encode a partition codeword for each channel */
  114187. if(s==0){
  114188. for(j=0;j<ch;j++){
  114189. long val=partword[j][i];
  114190. for(k=1;k<partitions_per_word;k++){
  114191. val*=possible_partitions;
  114192. if(i+k<partvals)
  114193. val+=partword[j][i+k];
  114194. }
  114195. /* training hack */
  114196. if(val<look->phrasebook->entries)
  114197. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  114198. #if 0 /*def TRAIN_RES*/
  114199. else
  114200. fprintf(stderr,"!");
  114201. #endif
  114202. }
  114203. }
  114204. /* now we encode interleaved residual values for the partitions */
  114205. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  114206. long offset=i*samples_per_partition+info->begin;
  114207. for(j=0;j<ch;j++){
  114208. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  114209. if(info->secondstages[partword[j][i]]&(1<<s)){
  114210. codebook *statebook=look->partbooks[partword[j][i]][s];
  114211. if(statebook){
  114212. int ret;
  114213. long *accumulator=NULL;
  114214. #ifdef TRAIN_RES
  114215. accumulator=look->training_data[s][partword[j][i]];
  114216. {
  114217. int l;
  114218. float *samples=in[j]+offset;
  114219. for(l=0;l<samples_per_partition;l++){
  114220. if(samples[l]<look->training_min[s][partword[j][i]])
  114221. look->training_min[s][partword[j][i]]=samples[l];
  114222. if(samples[l]>look->training_max[s][partword[j][i]])
  114223. look->training_max[s][partword[j][i]]=samples[l];
  114224. }
  114225. }
  114226. #endif
  114227. ret=encode(opb,in[j]+offset,samples_per_partition,
  114228. statebook,accumulator);
  114229. look->postbits+=ret;
  114230. resbits[partword[j][i]]+=ret;
  114231. }
  114232. }
  114233. }
  114234. }
  114235. }
  114236. }
  114237. /*{
  114238. long total=0;
  114239. long totalbits=0;
  114240. fprintf(stderr,"%d :: ",vb->mode);
  114241. for(k=0;k<possible_partitions;k++){
  114242. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  114243. total+=resvals[k];
  114244. totalbits+=resbits[k];
  114245. }
  114246. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  114247. }*/
  114248. return(0);
  114249. }
  114250. /* a truncated packet here just means 'stop working'; it's not an error */
  114251. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114252. float **in,int ch,
  114253. long (*decodepart)(codebook *, float *,
  114254. oggpack_buffer *,int)){
  114255. long i,j,k,l,s;
  114256. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114257. vorbis_info_residue0 *info=look->info;
  114258. /* move all this setup out later */
  114259. int samples_per_partition=info->grouping;
  114260. int partitions_per_word=look->phrasebook->dim;
  114261. int n=info->end-info->begin;
  114262. int partvals=n/samples_per_partition;
  114263. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114264. int ***partword=(int***)alloca(ch*sizeof(*partword));
  114265. for(j=0;j<ch;j++)
  114266. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  114267. for(s=0;s<look->stages;s++){
  114268. /* each loop decodes on partition codeword containing
  114269. partitions_pre_word partitions */
  114270. for(i=0,l=0;i<partvals;l++){
  114271. if(s==0){
  114272. /* fetch the partition word for each channel */
  114273. for(j=0;j<ch;j++){
  114274. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114275. if(temp==-1)goto eopbreak;
  114276. partword[j][l]=look->decodemap[temp];
  114277. if(partword[j][l]==NULL)goto errout;
  114278. }
  114279. }
  114280. /* now we decode residual values for the partitions */
  114281. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114282. for(j=0;j<ch;j++){
  114283. long offset=info->begin+i*samples_per_partition;
  114284. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  114285. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  114286. if(stagebook){
  114287. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  114288. samples_per_partition)==-1)goto eopbreak;
  114289. }
  114290. }
  114291. }
  114292. }
  114293. }
  114294. errout:
  114295. eopbreak:
  114296. return(0);
  114297. }
  114298. #if 0
  114299. /* residue 0 and 1 are just slight variants of one another. 0 is
  114300. interleaved, 1 is not */
  114301. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  114302. float **in,int *nonzero,int ch){
  114303. /* we encode only the nonzero parts of a bundle */
  114304. int i,used=0;
  114305. for(i=0;i<ch;i++)
  114306. if(nonzero[i])
  114307. in[used++]=in[i];
  114308. if(used)
  114309. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  114310. return(_01class(vb,vl,in,used));
  114311. else
  114312. return(0);
  114313. }
  114314. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  114315. float **in,float **out,int *nonzero,int ch,
  114316. long **partword){
  114317. /* we encode only the nonzero parts of a bundle */
  114318. int i,j,used=0,n=vb->pcmend/2;
  114319. for(i=0;i<ch;i++)
  114320. if(nonzero[i]){
  114321. if(out)
  114322. for(j=0;j<n;j++)
  114323. out[i][j]+=in[i][j];
  114324. in[used++]=in[i];
  114325. }
  114326. if(used){
  114327. int ret=_01forward(vb,vl,in,used,partword,
  114328. _interleaved_encodepart);
  114329. if(out){
  114330. used=0;
  114331. for(i=0;i<ch;i++)
  114332. if(nonzero[i]){
  114333. for(j=0;j<n;j++)
  114334. out[i][j]-=in[used][j];
  114335. used++;
  114336. }
  114337. }
  114338. return(ret);
  114339. }else{
  114340. return(0);
  114341. }
  114342. }
  114343. #endif
  114344. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114345. float **in,int *nonzero,int ch){
  114346. int i,used=0;
  114347. for(i=0;i<ch;i++)
  114348. if(nonzero[i])
  114349. in[used++]=in[i];
  114350. if(used)
  114351. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  114352. else
  114353. return(0);
  114354. }
  114355. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  114356. float **in,float **out,int *nonzero,int ch,
  114357. long **partword){
  114358. int i,j,used=0,n=vb->pcmend/2;
  114359. for(i=0;i<ch;i++)
  114360. if(nonzero[i]){
  114361. if(out)
  114362. for(j=0;j<n;j++)
  114363. out[i][j]+=in[i][j];
  114364. in[used++]=in[i];
  114365. }
  114366. if(used){
  114367. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  114368. if(out){
  114369. used=0;
  114370. for(i=0;i<ch;i++)
  114371. if(nonzero[i]){
  114372. for(j=0;j<n;j++)
  114373. out[i][j]-=in[used][j];
  114374. used++;
  114375. }
  114376. }
  114377. return(ret);
  114378. }else{
  114379. return(0);
  114380. }
  114381. }
  114382. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  114383. float **in,int *nonzero,int ch){
  114384. int i,used=0;
  114385. for(i=0;i<ch;i++)
  114386. if(nonzero[i])
  114387. in[used++]=in[i];
  114388. if(used)
  114389. return(_01class(vb,vl,in,used));
  114390. else
  114391. return(0);
  114392. }
  114393. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114394. float **in,int *nonzero,int ch){
  114395. int i,used=0;
  114396. for(i=0;i<ch;i++)
  114397. if(nonzero[i])
  114398. in[used++]=in[i];
  114399. if(used)
  114400. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  114401. else
  114402. return(0);
  114403. }
  114404. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  114405. float **in,int *nonzero,int ch){
  114406. int i,used=0;
  114407. for(i=0;i<ch;i++)
  114408. if(nonzero[i])used++;
  114409. if(used)
  114410. return(_2class(vb,vl,in,ch));
  114411. else
  114412. return(0);
  114413. }
  114414. /* res2 is slightly more different; all the channels are interleaved
  114415. into a single vector and encoded. */
  114416. int res2_forward(oggpack_buffer *opb,
  114417. vorbis_block *vb,vorbis_look_residue *vl,
  114418. float **in,float **out,int *nonzero,int ch,
  114419. long **partword){
  114420. long i,j,k,n=vb->pcmend/2,used=0;
  114421. /* don't duplicate the code; use a working vector hack for now and
  114422. reshape ourselves into a single channel res1 */
  114423. /* ugly; reallocs for each coupling pass :-( */
  114424. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  114425. for(i=0;i<ch;i++){
  114426. float *pcm=in[i];
  114427. if(nonzero[i])used++;
  114428. for(j=0,k=i;j<n;j++,k+=ch)
  114429. work[k]=pcm[j];
  114430. }
  114431. if(used){
  114432. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  114433. /* update the sofar vector */
  114434. if(out){
  114435. for(i=0;i<ch;i++){
  114436. float *pcm=in[i];
  114437. float *sofar=out[i];
  114438. for(j=0,k=i;j<n;j++,k+=ch)
  114439. sofar[j]+=pcm[j]-work[k];
  114440. }
  114441. }
  114442. return(ret);
  114443. }else{
  114444. return(0);
  114445. }
  114446. }
  114447. /* duplicate code here as speed is somewhat more important */
  114448. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114449. float **in,int *nonzero,int ch){
  114450. long i,k,l,s;
  114451. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114452. vorbis_info_residue0 *info=look->info;
  114453. /* move all this setup out later */
  114454. int samples_per_partition=info->grouping;
  114455. int partitions_per_word=look->phrasebook->dim;
  114456. int n=info->end-info->begin;
  114457. int partvals=n/samples_per_partition;
  114458. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114459. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  114460. for(i=0;i<ch;i++)if(nonzero[i])break;
  114461. if(i==ch)return(0); /* no nonzero vectors */
  114462. for(s=0;s<look->stages;s++){
  114463. for(i=0,l=0;i<partvals;l++){
  114464. if(s==0){
  114465. /* fetch the partition word */
  114466. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114467. if(temp==-1)goto eopbreak;
  114468. partword[l]=look->decodemap[temp];
  114469. if(partword[l]==NULL)goto errout;
  114470. }
  114471. /* now we decode residual values for the partitions */
  114472. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114473. if(info->secondstages[partword[l][k]]&(1<<s)){
  114474. codebook *stagebook=look->partbooks[partword[l][k]][s];
  114475. if(stagebook){
  114476. if(vorbis_book_decodevv_add(stagebook,in,
  114477. i*samples_per_partition+info->begin,ch,
  114478. &vb->opb,samples_per_partition)==-1)
  114479. goto eopbreak;
  114480. }
  114481. }
  114482. }
  114483. }
  114484. errout:
  114485. eopbreak:
  114486. return(0);
  114487. }
  114488. vorbis_func_residue residue0_exportbundle={
  114489. NULL,
  114490. &res0_unpack,
  114491. &res0_look,
  114492. &res0_free_info,
  114493. &res0_free_look,
  114494. NULL,
  114495. NULL,
  114496. &res0_inverse
  114497. };
  114498. vorbis_func_residue residue1_exportbundle={
  114499. &res0_pack,
  114500. &res0_unpack,
  114501. &res0_look,
  114502. &res0_free_info,
  114503. &res0_free_look,
  114504. &res1_class,
  114505. &res1_forward,
  114506. &res1_inverse
  114507. };
  114508. vorbis_func_residue residue2_exportbundle={
  114509. &res0_pack,
  114510. &res0_unpack,
  114511. &res0_look,
  114512. &res0_free_info,
  114513. &res0_free_look,
  114514. &res2_class,
  114515. &res2_forward,
  114516. &res2_inverse
  114517. };
  114518. #endif
  114519. /********* End of inlined file: res0.c *********/
  114520. /********* Start of inlined file: sharedbook.c *********/
  114521. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114522. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114523. // tasks..
  114524. #if JUCE_MSVC
  114525. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114526. #endif
  114527. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114528. #if JUCE_USE_OGGVORBIS
  114529. #include <stdlib.h>
  114530. #include <math.h>
  114531. #include <string.h>
  114532. /**** pack/unpack helpers ******************************************/
  114533. int _ilog(unsigned int v){
  114534. int ret=0;
  114535. while(v){
  114536. ret++;
  114537. v>>=1;
  114538. }
  114539. return(ret);
  114540. }
  114541. /* 32 bit float (not IEEE; nonnormalized mantissa +
  114542. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  114543. Why not IEEE? It's just not that important here. */
  114544. #define VQ_FEXP 10
  114545. #define VQ_FMAN 21
  114546. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  114547. /* doesn't currently guard under/overflow */
  114548. long _float32_pack(float val){
  114549. int sign=0;
  114550. long exp;
  114551. long mant;
  114552. if(val<0){
  114553. sign=0x80000000;
  114554. val= -val;
  114555. }
  114556. exp= floor(log(val)/log(2.f));
  114557. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  114558. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  114559. return(sign|exp|mant);
  114560. }
  114561. float _float32_unpack(long val){
  114562. double mant=val&0x1fffff;
  114563. int sign=val&0x80000000;
  114564. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  114565. if(sign)mant= -mant;
  114566. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  114567. }
  114568. /* given a list of word lengths, generate a list of codewords. Works
  114569. for length ordered or unordered, always assigns the lowest valued
  114570. codewords first. Extended to handle unused entries (length 0) */
  114571. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  114572. long i,j,count=0;
  114573. ogg_uint32_t marker[33];
  114574. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  114575. memset(marker,0,sizeof(marker));
  114576. for(i=0;i<n;i++){
  114577. long length=l[i];
  114578. if(length>0){
  114579. ogg_uint32_t entry=marker[length];
  114580. /* when we claim a node for an entry, we also claim the nodes
  114581. below it (pruning off the imagined tree that may have dangled
  114582. from it) as well as blocking the use of any nodes directly
  114583. above for leaves */
  114584. /* update ourself */
  114585. if(length<32 && (entry>>length)){
  114586. /* error condition; the lengths must specify an overpopulated tree */
  114587. _ogg_free(r);
  114588. return(NULL);
  114589. }
  114590. r[count++]=entry;
  114591. /* Look to see if the next shorter marker points to the node
  114592. above. if so, update it and repeat. */
  114593. {
  114594. for(j=length;j>0;j--){
  114595. if(marker[j]&1){
  114596. /* have to jump branches */
  114597. if(j==1)
  114598. marker[1]++;
  114599. else
  114600. marker[j]=marker[j-1]<<1;
  114601. break; /* invariant says next upper marker would already
  114602. have been moved if it was on the same path */
  114603. }
  114604. marker[j]++;
  114605. }
  114606. }
  114607. /* prune the tree; the implicit invariant says all the longer
  114608. markers were dangling from our just-taken node. Dangle them
  114609. from our *new* node. */
  114610. for(j=length+1;j<33;j++)
  114611. if((marker[j]>>1) == entry){
  114612. entry=marker[j];
  114613. marker[j]=marker[j-1]<<1;
  114614. }else
  114615. break;
  114616. }else
  114617. if(sparsecount==0)count++;
  114618. }
  114619. /* bitreverse the words because our bitwise packer/unpacker is LSb
  114620. endian */
  114621. for(i=0,count=0;i<n;i++){
  114622. ogg_uint32_t temp=0;
  114623. for(j=0;j<l[i];j++){
  114624. temp<<=1;
  114625. temp|=(r[count]>>j)&1;
  114626. }
  114627. if(sparsecount){
  114628. if(l[i])
  114629. r[count++]=temp;
  114630. }else
  114631. r[count++]=temp;
  114632. }
  114633. return(r);
  114634. }
  114635. /* there might be a straightforward one-line way to do the below
  114636. that's portable and totally safe against roundoff, but I haven't
  114637. thought of it. Therefore, we opt on the side of caution */
  114638. long _book_maptype1_quantvals(const static_codebook *b){
  114639. long vals=floor(pow((float)b->entries,1.f/b->dim));
  114640. /* the above *should* be reliable, but we'll not assume that FP is
  114641. ever reliable when bitstream sync is at stake; verify via integer
  114642. means that vals really is the greatest value of dim for which
  114643. vals^b->bim <= b->entries */
  114644. /* treat the above as an initial guess */
  114645. while(1){
  114646. long acc=1;
  114647. long acc1=1;
  114648. int i;
  114649. for(i=0;i<b->dim;i++){
  114650. acc*=vals;
  114651. acc1*=vals+1;
  114652. }
  114653. if(acc<=b->entries && acc1>b->entries){
  114654. return(vals);
  114655. }else{
  114656. if(acc>b->entries){
  114657. vals--;
  114658. }else{
  114659. vals++;
  114660. }
  114661. }
  114662. }
  114663. }
  114664. /* unpack the quantized list of values for encode/decode ***********/
  114665. /* we need to deal with two map types: in map type 1, the values are
  114666. generated algorithmically (each column of the vector counts through
  114667. the values in the quant vector). in map type 2, all the values came
  114668. in in an explicit list. Both value lists must be unpacked */
  114669. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  114670. long j,k,count=0;
  114671. if(b->maptype==1 || b->maptype==2){
  114672. int quantvals;
  114673. float mindel=_float32_unpack(b->q_min);
  114674. float delta=_float32_unpack(b->q_delta);
  114675. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  114676. /* maptype 1 and 2 both use a quantized value vector, but
  114677. different sizes */
  114678. switch(b->maptype){
  114679. case 1:
  114680. /* most of the time, entries%dimensions == 0, but we need to be
  114681. well defined. We define that the possible vales at each
  114682. scalar is values == entries/dim. If entries%dim != 0, we'll
  114683. have 'too few' values (values*dim<entries), which means that
  114684. we'll have 'left over' entries; left over entries use zeroed
  114685. values (and are wasted). So don't generate codebooks like
  114686. that */
  114687. quantvals=_book_maptype1_quantvals(b);
  114688. for(j=0;j<b->entries;j++){
  114689. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114690. float last=0.f;
  114691. int indexdiv=1;
  114692. for(k=0;k<b->dim;k++){
  114693. int index= (j/indexdiv)%quantvals;
  114694. float val=b->quantlist[index];
  114695. val=fabs(val)*delta+mindel+last;
  114696. if(b->q_sequencep)last=val;
  114697. if(sparsemap)
  114698. r[sparsemap[count]*b->dim+k]=val;
  114699. else
  114700. r[count*b->dim+k]=val;
  114701. indexdiv*=quantvals;
  114702. }
  114703. count++;
  114704. }
  114705. }
  114706. break;
  114707. case 2:
  114708. for(j=0;j<b->entries;j++){
  114709. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114710. float last=0.f;
  114711. for(k=0;k<b->dim;k++){
  114712. float val=b->quantlist[j*b->dim+k];
  114713. val=fabs(val)*delta+mindel+last;
  114714. if(b->q_sequencep)last=val;
  114715. if(sparsemap)
  114716. r[sparsemap[count]*b->dim+k]=val;
  114717. else
  114718. r[count*b->dim+k]=val;
  114719. }
  114720. count++;
  114721. }
  114722. }
  114723. break;
  114724. }
  114725. return(r);
  114726. }
  114727. return(NULL);
  114728. }
  114729. void vorbis_staticbook_clear(static_codebook *b){
  114730. if(b->allocedp){
  114731. if(b->quantlist)_ogg_free(b->quantlist);
  114732. if(b->lengthlist)_ogg_free(b->lengthlist);
  114733. if(b->nearest_tree){
  114734. _ogg_free(b->nearest_tree->ptr0);
  114735. _ogg_free(b->nearest_tree->ptr1);
  114736. _ogg_free(b->nearest_tree->p);
  114737. _ogg_free(b->nearest_tree->q);
  114738. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  114739. _ogg_free(b->nearest_tree);
  114740. }
  114741. if(b->thresh_tree){
  114742. _ogg_free(b->thresh_tree->quantthresh);
  114743. _ogg_free(b->thresh_tree->quantmap);
  114744. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  114745. _ogg_free(b->thresh_tree);
  114746. }
  114747. memset(b,0,sizeof(*b));
  114748. }
  114749. }
  114750. void vorbis_staticbook_destroy(static_codebook *b){
  114751. if(b->allocedp){
  114752. vorbis_staticbook_clear(b);
  114753. _ogg_free(b);
  114754. }
  114755. }
  114756. void vorbis_book_clear(codebook *b){
  114757. /* static book is not cleared; we're likely called on the lookup and
  114758. the static codebook belongs to the info struct */
  114759. if(b->valuelist)_ogg_free(b->valuelist);
  114760. if(b->codelist)_ogg_free(b->codelist);
  114761. if(b->dec_index)_ogg_free(b->dec_index);
  114762. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  114763. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  114764. memset(b,0,sizeof(*b));
  114765. }
  114766. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  114767. memset(c,0,sizeof(*c));
  114768. c->c=s;
  114769. c->entries=s->entries;
  114770. c->used_entries=s->entries;
  114771. c->dim=s->dim;
  114772. c->codelist=_make_words(s->lengthlist,s->entries,0);
  114773. c->valuelist=_book_unquantize(s,s->entries,NULL);
  114774. return(0);
  114775. }
  114776. static int sort32a(const void *a,const void *b){
  114777. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  114778. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  114779. }
  114780. /* decode codebook arrangement is more heavily optimized than encode */
  114781. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  114782. int i,j,n=0,tabn;
  114783. int *sortindex;
  114784. memset(c,0,sizeof(*c));
  114785. /* count actually used entries */
  114786. for(i=0;i<s->entries;i++)
  114787. if(s->lengthlist[i]>0)
  114788. n++;
  114789. c->entries=s->entries;
  114790. c->used_entries=n;
  114791. c->dim=s->dim;
  114792. /* two different remappings go on here.
  114793. First, we collapse the likely sparse codebook down only to
  114794. actually represented values/words. This collapsing needs to be
  114795. indexed as map-valueless books are used to encode original entry
  114796. positions as integers.
  114797. Second, we reorder all vectors, including the entry index above,
  114798. by sorted bitreversed codeword to allow treeless decode. */
  114799. {
  114800. /* perform sort */
  114801. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  114802. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  114803. if(codes==NULL)goto err_out;
  114804. for(i=0;i<n;i++){
  114805. codes[i]=ogg_bitreverse(codes[i]);
  114806. codep[i]=codes+i;
  114807. }
  114808. qsort(codep,n,sizeof(*codep),sort32a);
  114809. sortindex=(int*)alloca(n*sizeof(*sortindex));
  114810. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  114811. /* the index is a reverse index */
  114812. for(i=0;i<n;i++){
  114813. int position=codep[i]-codes;
  114814. sortindex[position]=i;
  114815. }
  114816. for(i=0;i<n;i++)
  114817. c->codelist[sortindex[i]]=codes[i];
  114818. _ogg_free(codes);
  114819. }
  114820. c->valuelist=_book_unquantize(s,n,sortindex);
  114821. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  114822. for(n=0,i=0;i<s->entries;i++)
  114823. if(s->lengthlist[i]>0)
  114824. c->dec_index[sortindex[n++]]=i;
  114825. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  114826. for(n=0,i=0;i<s->entries;i++)
  114827. if(s->lengthlist[i]>0)
  114828. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  114829. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  114830. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  114831. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  114832. tabn=1<<c->dec_firsttablen;
  114833. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  114834. c->dec_maxlength=0;
  114835. for(i=0;i<n;i++){
  114836. if(c->dec_maxlength<c->dec_codelengths[i])
  114837. c->dec_maxlength=c->dec_codelengths[i];
  114838. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  114839. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  114840. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  114841. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  114842. }
  114843. }
  114844. /* now fill in 'unused' entries in the firsttable with hi/lo search
  114845. hints for the non-direct-hits */
  114846. {
  114847. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  114848. long lo=0,hi=0;
  114849. for(i=0;i<tabn;i++){
  114850. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  114851. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  114852. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  114853. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  114854. /* we only actually have 15 bits per hint to play with here.
  114855. In order to overflow gracefully (nothing breaks, efficiency
  114856. just drops), encode as the difference from the extremes. */
  114857. {
  114858. unsigned long loval=lo;
  114859. unsigned long hival=n-hi;
  114860. if(loval>0x7fff)loval=0x7fff;
  114861. if(hival>0x7fff)hival=0x7fff;
  114862. c->dec_firsttable[ogg_bitreverse(word)]=
  114863. 0x80000000UL | (loval<<15) | hival;
  114864. }
  114865. }
  114866. }
  114867. }
  114868. return(0);
  114869. err_out:
  114870. vorbis_book_clear(c);
  114871. return(-1);
  114872. }
  114873. static float _dist(int el,float *ref, float *b,int step){
  114874. int i;
  114875. float acc=0.f;
  114876. for(i=0;i<el;i++){
  114877. float val=(ref[i]-b[i*step]);
  114878. acc+=val*val;
  114879. }
  114880. return(acc);
  114881. }
  114882. int _best(codebook *book, float *a, int step){
  114883. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114884. #if 0
  114885. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  114886. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  114887. #endif
  114888. int dim=book->dim;
  114889. int k,o;
  114890. /*int savebest=-1;
  114891. float saverr;*/
  114892. /* do we have a threshhold encode hint? */
  114893. if(tt){
  114894. int index=0,i;
  114895. /* find the quant val of each scalar */
  114896. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114897. i=tt->threshvals>>1;
  114898. if(a[o]<tt->quantthresh[i]){
  114899. for(;i>0;i--)
  114900. if(a[o]>=tt->quantthresh[i-1])
  114901. break;
  114902. }else{
  114903. for(i++;i<tt->threshvals-1;i++)
  114904. if(a[o]<tt->quantthresh[i])break;
  114905. }
  114906. index=(index*tt->quantvals)+tt->quantmap[i];
  114907. }
  114908. /* regular lattices are easy :-) */
  114909. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  114910. use a decision tree after all
  114911. and fall through*/
  114912. return(index);
  114913. }
  114914. #if 0
  114915. /* do we have a pigeonhole encode hint? */
  114916. if(pt){
  114917. const static_codebook *c=book->c;
  114918. int i,besti=-1;
  114919. float best=0.f;
  114920. int entry=0;
  114921. /* dealing with sequentialness is a pain in the ass */
  114922. if(c->q_sequencep){
  114923. int pv;
  114924. long mul=1;
  114925. float qlast=0;
  114926. for(k=0,o=0;k<dim;k++,o+=step){
  114927. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  114928. if(pv<0 || pv>=pt->mapentries)break;
  114929. entry+=pt->pigeonmap[pv]*mul;
  114930. mul*=pt->quantvals;
  114931. qlast+=pv*pt->del+pt->min;
  114932. }
  114933. }else{
  114934. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114935. int pv=(int)((a[o]-pt->min)/pt->del);
  114936. if(pv<0 || pv>=pt->mapentries)break;
  114937. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  114938. }
  114939. }
  114940. /* must be within the pigeonholable range; if we quant outside (or
  114941. in an entry that we define no list for), brute force it */
  114942. if(k==dim && pt->fitlength[entry]){
  114943. /* search the abbreviated list */
  114944. long *list=pt->fitlist+pt->fitmap[entry];
  114945. for(i=0;i<pt->fitlength[entry];i++){
  114946. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  114947. if(besti==-1 || this<best){
  114948. best=this;
  114949. besti=list[i];
  114950. }
  114951. }
  114952. return(besti);
  114953. }
  114954. }
  114955. if(nt){
  114956. /* optimized using the decision tree */
  114957. while(1){
  114958. float c=0.f;
  114959. float *p=book->valuelist+nt->p[ptr];
  114960. float *q=book->valuelist+nt->q[ptr];
  114961. for(k=0,o=0;k<dim;k++,o+=step)
  114962. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  114963. if(c>0.f) /* in A */
  114964. ptr= -nt->ptr0[ptr];
  114965. else /* in B */
  114966. ptr= -nt->ptr1[ptr];
  114967. if(ptr<=0)break;
  114968. }
  114969. return(-ptr);
  114970. }
  114971. #endif
  114972. /* brute force it! */
  114973. {
  114974. const static_codebook *c=book->c;
  114975. int i,besti=-1;
  114976. float best=0.f;
  114977. float *e=book->valuelist;
  114978. for(i=0;i<book->entries;i++){
  114979. if(c->lengthlist[i]>0){
  114980. float thisx=_dist(dim,e,a,step);
  114981. if(besti==-1 || thisx<best){
  114982. best=thisx;
  114983. besti=i;
  114984. }
  114985. }
  114986. e+=dim;
  114987. }
  114988. /*if(savebest!=-1 && savebest!=besti){
  114989. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  114990. "original:");
  114991. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  114992. fprintf(stderr,"\n"
  114993. "pigeonhole (entry %d, err %g):",savebest,saverr);
  114994. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114995. (book->valuelist+savebest*dim)[i]);
  114996. fprintf(stderr,"\n"
  114997. "bruteforce (entry %d, err %g):",besti,best);
  114998. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114999. (book->valuelist+besti*dim)[i]);
  115000. fprintf(stderr,"\n");
  115001. }*/
  115002. return(besti);
  115003. }
  115004. }
  115005. long vorbis_book_codeword(codebook *book,int entry){
  115006. if(book->c) /* only use with encode; decode optimizations are
  115007. allowed to break this */
  115008. return book->codelist[entry];
  115009. return -1;
  115010. }
  115011. long vorbis_book_codelen(codebook *book,int entry){
  115012. if(book->c) /* only use with encode; decode optimizations are
  115013. allowed to break this */
  115014. return book->c->lengthlist[entry];
  115015. return -1;
  115016. }
  115017. #ifdef _V_SELFTEST
  115018. /* Unit tests of the dequantizer; this stuff will be OK
  115019. cross-platform, I simply want to be sure that special mapping cases
  115020. actually work properly; a bug could go unnoticed for a while */
  115021. #include <stdio.h>
  115022. /* cases:
  115023. no mapping
  115024. full, explicit mapping
  115025. algorithmic mapping
  115026. nonsequential
  115027. sequential
  115028. */
  115029. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  115030. static long partial_quantlist1[]={0,7,2};
  115031. /* no mapping */
  115032. static_codebook test1={
  115033. 4,16,
  115034. NULL,
  115035. 0,
  115036. 0,0,0,0,
  115037. NULL,
  115038. NULL,NULL
  115039. };
  115040. static float *test1_result=NULL;
  115041. /* linear, full mapping, nonsequential */
  115042. static_codebook test2={
  115043. 4,3,
  115044. NULL,
  115045. 2,
  115046. -533200896,1611661312,4,0,
  115047. full_quantlist1,
  115048. NULL,NULL
  115049. };
  115050. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  115051. /* linear, full mapping, sequential */
  115052. static_codebook test3={
  115053. 4,3,
  115054. NULL,
  115055. 2,
  115056. -533200896,1611661312,4,1,
  115057. full_quantlist1,
  115058. NULL,NULL
  115059. };
  115060. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  115061. /* linear, algorithmic mapping, nonsequential */
  115062. static_codebook test4={
  115063. 3,27,
  115064. NULL,
  115065. 1,
  115066. -533200896,1611661312,4,0,
  115067. partial_quantlist1,
  115068. NULL,NULL
  115069. };
  115070. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  115071. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  115072. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  115073. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  115074. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  115075. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  115076. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  115077. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  115078. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  115079. /* linear, algorithmic mapping, sequential */
  115080. static_codebook test5={
  115081. 3,27,
  115082. NULL,
  115083. 1,
  115084. -533200896,1611661312,4,1,
  115085. partial_quantlist1,
  115086. NULL,NULL
  115087. };
  115088. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  115089. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  115090. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  115091. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  115092. -3, 1, 5, 4, 8,12, -1, 3, 7,
  115093. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  115094. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  115095. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  115096. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  115097. void run_test(static_codebook *b,float *comp){
  115098. float *out=_book_unquantize(b,b->entries,NULL);
  115099. int i;
  115100. if(comp){
  115101. if(!out){
  115102. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  115103. exit(1);
  115104. }
  115105. for(i=0;i<b->entries*b->dim;i++)
  115106. if(fabs(out[i]-comp[i])>.0001){
  115107. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  115108. "position %d, %g != %g\n",i,out[i],comp[i]);
  115109. exit(1);
  115110. }
  115111. }else{
  115112. if(out){
  115113. fprintf(stderr,"_book_unquantize returned a value array: \n"
  115114. " correct result should have been NULL\n");
  115115. exit(1);
  115116. }
  115117. }
  115118. }
  115119. int main(){
  115120. /* run the nine dequant tests, and compare to the hand-rolled results */
  115121. fprintf(stderr,"Dequant test 1... ");
  115122. run_test(&test1,test1_result);
  115123. fprintf(stderr,"OK\nDequant test 2... ");
  115124. run_test(&test2,test2_result);
  115125. fprintf(stderr,"OK\nDequant test 3... ");
  115126. run_test(&test3,test3_result);
  115127. fprintf(stderr,"OK\nDequant test 4... ");
  115128. run_test(&test4,test4_result);
  115129. fprintf(stderr,"OK\nDequant test 5... ");
  115130. run_test(&test5,test5_result);
  115131. fprintf(stderr,"OK\n\n");
  115132. return(0);
  115133. }
  115134. #endif
  115135. #endif
  115136. /********* End of inlined file: sharedbook.c *********/
  115137. /********* Start of inlined file: smallft.c *********/
  115138. /* FFT implementation from OggSquish, minus cosine transforms,
  115139. * minus all but radix 2/4 case. In Vorbis we only need this
  115140. * cut-down version.
  115141. *
  115142. * To do more than just power-of-two sized vectors, see the full
  115143. * version I wrote for NetLib.
  115144. *
  115145. * Note that the packing is a little strange; rather than the FFT r/i
  115146. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  115147. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  115148. * FORTRAN version
  115149. */
  115150. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115151. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115152. // tasks..
  115153. #if JUCE_MSVC
  115154. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115155. #endif
  115156. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115157. #if JUCE_USE_OGGVORBIS
  115158. #include <stdlib.h>
  115159. #include <string.h>
  115160. #include <math.h>
  115161. static void drfti1(int n, float *wa, int *ifac){
  115162. static int ntryh[4] = { 4,2,3,5 };
  115163. static float tpi = 6.28318530717958648f;
  115164. float arg,argh,argld,fi;
  115165. int ntry=0,i,j=-1;
  115166. int k1, l1, l2, ib;
  115167. int ld, ii, ip, is, nq, nr;
  115168. int ido, ipm, nfm1;
  115169. int nl=n;
  115170. int nf=0;
  115171. L101:
  115172. j++;
  115173. if (j < 4)
  115174. ntry=ntryh[j];
  115175. else
  115176. ntry+=2;
  115177. L104:
  115178. nq=nl/ntry;
  115179. nr=nl-ntry*nq;
  115180. if (nr!=0) goto L101;
  115181. nf++;
  115182. ifac[nf+1]=ntry;
  115183. nl=nq;
  115184. if(ntry!=2)goto L107;
  115185. if(nf==1)goto L107;
  115186. for (i=1;i<nf;i++){
  115187. ib=nf-i+1;
  115188. ifac[ib+1]=ifac[ib];
  115189. }
  115190. ifac[2] = 2;
  115191. L107:
  115192. if(nl!=1)goto L104;
  115193. ifac[0]=n;
  115194. ifac[1]=nf;
  115195. argh=tpi/n;
  115196. is=0;
  115197. nfm1=nf-1;
  115198. l1=1;
  115199. if(nfm1==0)return;
  115200. for (k1=0;k1<nfm1;k1++){
  115201. ip=ifac[k1+2];
  115202. ld=0;
  115203. l2=l1*ip;
  115204. ido=n/l2;
  115205. ipm=ip-1;
  115206. for (j=0;j<ipm;j++){
  115207. ld+=l1;
  115208. i=is;
  115209. argld=(float)ld*argh;
  115210. fi=0.f;
  115211. for (ii=2;ii<ido;ii+=2){
  115212. fi+=1.f;
  115213. arg=fi*argld;
  115214. wa[i++]=cos(arg);
  115215. wa[i++]=sin(arg);
  115216. }
  115217. is+=ido;
  115218. }
  115219. l1=l2;
  115220. }
  115221. }
  115222. static void fdrffti(int n, float *wsave, int *ifac){
  115223. if (n == 1) return;
  115224. drfti1(n, wsave+n, ifac);
  115225. }
  115226. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  115227. int i,k;
  115228. float ti2,tr2;
  115229. int t0,t1,t2,t3,t4,t5,t6;
  115230. t1=0;
  115231. t0=(t2=l1*ido);
  115232. t3=ido<<1;
  115233. for(k=0;k<l1;k++){
  115234. ch[t1<<1]=cc[t1]+cc[t2];
  115235. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  115236. t1+=ido;
  115237. t2+=ido;
  115238. }
  115239. if(ido<2)return;
  115240. if(ido==2)goto L105;
  115241. t1=0;
  115242. t2=t0;
  115243. for(k=0;k<l1;k++){
  115244. t3=t2;
  115245. t4=(t1<<1)+(ido<<1);
  115246. t5=t1;
  115247. t6=t1+t1;
  115248. for(i=2;i<ido;i+=2){
  115249. t3+=2;
  115250. t4-=2;
  115251. t5+=2;
  115252. t6+=2;
  115253. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115254. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115255. ch[t6]=cc[t5]+ti2;
  115256. ch[t4]=ti2-cc[t5];
  115257. ch[t6-1]=cc[t5-1]+tr2;
  115258. ch[t4-1]=cc[t5-1]-tr2;
  115259. }
  115260. t1+=ido;
  115261. t2+=ido;
  115262. }
  115263. if(ido%2==1)return;
  115264. L105:
  115265. t3=(t2=(t1=ido)-1);
  115266. t2+=t0;
  115267. for(k=0;k<l1;k++){
  115268. ch[t1]=-cc[t2];
  115269. ch[t1-1]=cc[t3];
  115270. t1+=ido<<1;
  115271. t2+=ido;
  115272. t3+=ido;
  115273. }
  115274. }
  115275. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  115276. float *wa2,float *wa3){
  115277. static float hsqt2 = .70710678118654752f;
  115278. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115279. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115280. t0=l1*ido;
  115281. t1=t0;
  115282. t4=t1<<1;
  115283. t2=t1+(t1<<1);
  115284. t3=0;
  115285. for(k=0;k<l1;k++){
  115286. tr1=cc[t1]+cc[t2];
  115287. tr2=cc[t3]+cc[t4];
  115288. ch[t5=t3<<2]=tr1+tr2;
  115289. ch[(ido<<2)+t5-1]=tr2-tr1;
  115290. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  115291. ch[t5]=cc[t2]-cc[t1];
  115292. t1+=ido;
  115293. t2+=ido;
  115294. t3+=ido;
  115295. t4+=ido;
  115296. }
  115297. if(ido<2)return;
  115298. if(ido==2)goto L105;
  115299. t1=0;
  115300. for(k=0;k<l1;k++){
  115301. t2=t1;
  115302. t4=t1<<2;
  115303. t5=(t6=ido<<1)+t4;
  115304. for(i=2;i<ido;i+=2){
  115305. t3=(t2+=2);
  115306. t4+=2;
  115307. t5-=2;
  115308. t3+=t0;
  115309. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115310. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115311. t3+=t0;
  115312. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  115313. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  115314. t3+=t0;
  115315. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  115316. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  115317. tr1=cr2+cr4;
  115318. tr4=cr4-cr2;
  115319. ti1=ci2+ci4;
  115320. ti4=ci2-ci4;
  115321. ti2=cc[t2]+ci3;
  115322. ti3=cc[t2]-ci3;
  115323. tr2=cc[t2-1]+cr3;
  115324. tr3=cc[t2-1]-cr3;
  115325. ch[t4-1]=tr1+tr2;
  115326. ch[t4]=ti1+ti2;
  115327. ch[t5-1]=tr3-ti4;
  115328. ch[t5]=tr4-ti3;
  115329. ch[t4+t6-1]=ti4+tr3;
  115330. ch[t4+t6]=tr4+ti3;
  115331. ch[t5+t6-1]=tr2-tr1;
  115332. ch[t5+t6]=ti1-ti2;
  115333. }
  115334. t1+=ido;
  115335. }
  115336. if(ido&1)return;
  115337. L105:
  115338. t2=(t1=t0+ido-1)+(t0<<1);
  115339. t3=ido<<2;
  115340. t4=ido;
  115341. t5=ido<<1;
  115342. t6=ido;
  115343. for(k=0;k<l1;k++){
  115344. ti1=-hsqt2*(cc[t1]+cc[t2]);
  115345. tr1=hsqt2*(cc[t1]-cc[t2]);
  115346. ch[t4-1]=tr1+cc[t6-1];
  115347. ch[t4+t5-1]=cc[t6-1]-tr1;
  115348. ch[t4]=ti1-cc[t1+t0];
  115349. ch[t4+t5]=ti1+cc[t1+t0];
  115350. t1+=ido;
  115351. t2+=ido;
  115352. t4+=t3;
  115353. t6+=ido;
  115354. }
  115355. }
  115356. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115357. float *c2,float *ch,float *ch2,float *wa){
  115358. static float tpi=6.283185307179586f;
  115359. int idij,ipph,i,j,k,l,ic,ik,is;
  115360. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115361. float dc2,ai1,ai2,ar1,ar2,ds2;
  115362. int nbd;
  115363. float dcp,arg,dsp,ar1h,ar2h;
  115364. int idp2,ipp2;
  115365. arg=tpi/(float)ip;
  115366. dcp=cos(arg);
  115367. dsp=sin(arg);
  115368. ipph=(ip+1)>>1;
  115369. ipp2=ip;
  115370. idp2=ido;
  115371. nbd=(ido-1)>>1;
  115372. t0=l1*ido;
  115373. t10=ip*ido;
  115374. if(ido==1)goto L119;
  115375. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  115376. t1=0;
  115377. for(j=1;j<ip;j++){
  115378. t1+=t0;
  115379. t2=t1;
  115380. for(k=0;k<l1;k++){
  115381. ch[t2]=c1[t2];
  115382. t2+=ido;
  115383. }
  115384. }
  115385. is=-ido;
  115386. t1=0;
  115387. if(nbd>l1){
  115388. for(j=1;j<ip;j++){
  115389. t1+=t0;
  115390. is+=ido;
  115391. t2= -ido+t1;
  115392. for(k=0;k<l1;k++){
  115393. idij=is-1;
  115394. t2+=ido;
  115395. t3=t2;
  115396. for(i=2;i<ido;i+=2){
  115397. idij+=2;
  115398. t3+=2;
  115399. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115400. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115401. }
  115402. }
  115403. }
  115404. }else{
  115405. for(j=1;j<ip;j++){
  115406. is+=ido;
  115407. idij=is-1;
  115408. t1+=t0;
  115409. t2=t1;
  115410. for(i=2;i<ido;i+=2){
  115411. idij+=2;
  115412. t2+=2;
  115413. t3=t2;
  115414. for(k=0;k<l1;k++){
  115415. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115416. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115417. t3+=ido;
  115418. }
  115419. }
  115420. }
  115421. }
  115422. t1=0;
  115423. t2=ipp2*t0;
  115424. if(nbd<l1){
  115425. for(j=1;j<ipph;j++){
  115426. t1+=t0;
  115427. t2-=t0;
  115428. t3=t1;
  115429. t4=t2;
  115430. for(i=2;i<ido;i+=2){
  115431. t3+=2;
  115432. t4+=2;
  115433. t5=t3-ido;
  115434. t6=t4-ido;
  115435. for(k=0;k<l1;k++){
  115436. t5+=ido;
  115437. t6+=ido;
  115438. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115439. c1[t6-1]=ch[t5]-ch[t6];
  115440. c1[t5]=ch[t5]+ch[t6];
  115441. c1[t6]=ch[t6-1]-ch[t5-1];
  115442. }
  115443. }
  115444. }
  115445. }else{
  115446. for(j=1;j<ipph;j++){
  115447. t1+=t0;
  115448. t2-=t0;
  115449. t3=t1;
  115450. t4=t2;
  115451. for(k=0;k<l1;k++){
  115452. t5=t3;
  115453. t6=t4;
  115454. for(i=2;i<ido;i+=2){
  115455. t5+=2;
  115456. t6+=2;
  115457. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115458. c1[t6-1]=ch[t5]-ch[t6];
  115459. c1[t5]=ch[t5]+ch[t6];
  115460. c1[t6]=ch[t6-1]-ch[t5-1];
  115461. }
  115462. t3+=ido;
  115463. t4+=ido;
  115464. }
  115465. }
  115466. }
  115467. L119:
  115468. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115469. t1=0;
  115470. t2=ipp2*idl1;
  115471. for(j=1;j<ipph;j++){
  115472. t1+=t0;
  115473. t2-=t0;
  115474. t3=t1-ido;
  115475. t4=t2-ido;
  115476. for(k=0;k<l1;k++){
  115477. t3+=ido;
  115478. t4+=ido;
  115479. c1[t3]=ch[t3]+ch[t4];
  115480. c1[t4]=ch[t4]-ch[t3];
  115481. }
  115482. }
  115483. ar1=1.f;
  115484. ai1=0.f;
  115485. t1=0;
  115486. t2=ipp2*idl1;
  115487. t3=(ip-1)*idl1;
  115488. for(l=1;l<ipph;l++){
  115489. t1+=idl1;
  115490. t2-=idl1;
  115491. ar1h=dcp*ar1-dsp*ai1;
  115492. ai1=dcp*ai1+dsp*ar1;
  115493. ar1=ar1h;
  115494. t4=t1;
  115495. t5=t2;
  115496. t6=t3;
  115497. t7=idl1;
  115498. for(ik=0;ik<idl1;ik++){
  115499. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  115500. ch2[t5++]=ai1*c2[t6++];
  115501. }
  115502. dc2=ar1;
  115503. ds2=ai1;
  115504. ar2=ar1;
  115505. ai2=ai1;
  115506. t4=idl1;
  115507. t5=(ipp2-1)*idl1;
  115508. for(j=2;j<ipph;j++){
  115509. t4+=idl1;
  115510. t5-=idl1;
  115511. ar2h=dc2*ar2-ds2*ai2;
  115512. ai2=dc2*ai2+ds2*ar2;
  115513. ar2=ar2h;
  115514. t6=t1;
  115515. t7=t2;
  115516. t8=t4;
  115517. t9=t5;
  115518. for(ik=0;ik<idl1;ik++){
  115519. ch2[t6++]+=ar2*c2[t8++];
  115520. ch2[t7++]+=ai2*c2[t9++];
  115521. }
  115522. }
  115523. }
  115524. t1=0;
  115525. for(j=1;j<ipph;j++){
  115526. t1+=idl1;
  115527. t2=t1;
  115528. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  115529. }
  115530. if(ido<l1)goto L132;
  115531. t1=0;
  115532. t2=0;
  115533. for(k=0;k<l1;k++){
  115534. t3=t1;
  115535. t4=t2;
  115536. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  115537. t1+=ido;
  115538. t2+=t10;
  115539. }
  115540. goto L135;
  115541. L132:
  115542. for(i=0;i<ido;i++){
  115543. t1=i;
  115544. t2=i;
  115545. for(k=0;k<l1;k++){
  115546. cc[t2]=ch[t1];
  115547. t1+=ido;
  115548. t2+=t10;
  115549. }
  115550. }
  115551. L135:
  115552. t1=0;
  115553. t2=ido<<1;
  115554. t3=0;
  115555. t4=ipp2*t0;
  115556. for(j=1;j<ipph;j++){
  115557. t1+=t2;
  115558. t3+=t0;
  115559. t4-=t0;
  115560. t5=t1;
  115561. t6=t3;
  115562. t7=t4;
  115563. for(k=0;k<l1;k++){
  115564. cc[t5-1]=ch[t6];
  115565. cc[t5]=ch[t7];
  115566. t5+=t10;
  115567. t6+=ido;
  115568. t7+=ido;
  115569. }
  115570. }
  115571. if(ido==1)return;
  115572. if(nbd<l1)goto L141;
  115573. t1=-ido;
  115574. t3=0;
  115575. t4=0;
  115576. t5=ipp2*t0;
  115577. for(j=1;j<ipph;j++){
  115578. t1+=t2;
  115579. t3+=t2;
  115580. t4+=t0;
  115581. t5-=t0;
  115582. t6=t1;
  115583. t7=t3;
  115584. t8=t4;
  115585. t9=t5;
  115586. for(k=0;k<l1;k++){
  115587. for(i=2;i<ido;i+=2){
  115588. ic=idp2-i;
  115589. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  115590. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  115591. cc[i+t7]=ch[i+t8]+ch[i+t9];
  115592. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  115593. }
  115594. t6+=t10;
  115595. t7+=t10;
  115596. t8+=ido;
  115597. t9+=ido;
  115598. }
  115599. }
  115600. return;
  115601. L141:
  115602. t1=-ido;
  115603. t3=0;
  115604. t4=0;
  115605. t5=ipp2*t0;
  115606. for(j=1;j<ipph;j++){
  115607. t1+=t2;
  115608. t3+=t2;
  115609. t4+=t0;
  115610. t5-=t0;
  115611. for(i=2;i<ido;i+=2){
  115612. t6=idp2+t1-i;
  115613. t7=i+t3;
  115614. t8=i+t4;
  115615. t9=i+t5;
  115616. for(k=0;k<l1;k++){
  115617. cc[t7-1]=ch[t8-1]+ch[t9-1];
  115618. cc[t6-1]=ch[t8-1]-ch[t9-1];
  115619. cc[t7]=ch[t8]+ch[t9];
  115620. cc[t6]=ch[t9]-ch[t8];
  115621. t6+=t10;
  115622. t7+=t10;
  115623. t8+=ido;
  115624. t9+=ido;
  115625. }
  115626. }
  115627. }
  115628. }
  115629. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  115630. int i,k1,l1,l2;
  115631. int na,kh,nf;
  115632. int ip,iw,ido,idl1,ix2,ix3;
  115633. nf=ifac[1];
  115634. na=1;
  115635. l2=n;
  115636. iw=n;
  115637. for(k1=0;k1<nf;k1++){
  115638. kh=nf-k1;
  115639. ip=ifac[kh+1];
  115640. l1=l2/ip;
  115641. ido=n/l2;
  115642. idl1=ido*l1;
  115643. iw-=(ip-1)*ido;
  115644. na=1-na;
  115645. if(ip!=4)goto L102;
  115646. ix2=iw+ido;
  115647. ix3=ix2+ido;
  115648. if(na!=0)
  115649. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115650. else
  115651. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115652. goto L110;
  115653. L102:
  115654. if(ip!=2)goto L104;
  115655. if(na!=0)goto L103;
  115656. dradf2(ido,l1,c,ch,wa+iw-1);
  115657. goto L110;
  115658. L103:
  115659. dradf2(ido,l1,ch,c,wa+iw-1);
  115660. goto L110;
  115661. L104:
  115662. if(ido==1)na=1-na;
  115663. if(na!=0)goto L109;
  115664. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115665. na=1;
  115666. goto L110;
  115667. L109:
  115668. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115669. na=0;
  115670. L110:
  115671. l2=l1;
  115672. }
  115673. if(na==1)return;
  115674. for(i=0;i<n;i++)c[i]=ch[i];
  115675. }
  115676. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  115677. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115678. float ti2,tr2;
  115679. t0=l1*ido;
  115680. t1=0;
  115681. t2=0;
  115682. t3=(ido<<1)-1;
  115683. for(k=0;k<l1;k++){
  115684. ch[t1]=cc[t2]+cc[t3+t2];
  115685. ch[t1+t0]=cc[t2]-cc[t3+t2];
  115686. t2=(t1+=ido)<<1;
  115687. }
  115688. if(ido<2)return;
  115689. if(ido==2)goto L105;
  115690. t1=0;
  115691. t2=0;
  115692. for(k=0;k<l1;k++){
  115693. t3=t1;
  115694. t5=(t4=t2)+(ido<<1);
  115695. t6=t0+t1;
  115696. for(i=2;i<ido;i+=2){
  115697. t3+=2;
  115698. t4+=2;
  115699. t5-=2;
  115700. t6+=2;
  115701. ch[t3-1]=cc[t4-1]+cc[t5-1];
  115702. tr2=cc[t4-1]-cc[t5-1];
  115703. ch[t3]=cc[t4]-cc[t5];
  115704. ti2=cc[t4]+cc[t5];
  115705. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  115706. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  115707. }
  115708. t2=(t1+=ido)<<1;
  115709. }
  115710. if(ido%2==1)return;
  115711. L105:
  115712. t1=ido-1;
  115713. t2=ido-1;
  115714. for(k=0;k<l1;k++){
  115715. ch[t1]=cc[t2]+cc[t2];
  115716. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  115717. t1+=ido;
  115718. t2+=ido<<1;
  115719. }
  115720. }
  115721. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  115722. float *wa2){
  115723. static float taur = -.5f;
  115724. static float taui = .8660254037844386f;
  115725. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115726. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  115727. t0=l1*ido;
  115728. t1=0;
  115729. t2=t0<<1;
  115730. t3=ido<<1;
  115731. t4=ido+(ido<<1);
  115732. t5=0;
  115733. for(k=0;k<l1;k++){
  115734. tr2=cc[t3-1]+cc[t3-1];
  115735. cr2=cc[t5]+(taur*tr2);
  115736. ch[t1]=cc[t5]+tr2;
  115737. ci3=taui*(cc[t3]+cc[t3]);
  115738. ch[t1+t0]=cr2-ci3;
  115739. ch[t1+t2]=cr2+ci3;
  115740. t1+=ido;
  115741. t3+=t4;
  115742. t5+=t4;
  115743. }
  115744. if(ido==1)return;
  115745. t1=0;
  115746. t3=ido<<1;
  115747. for(k=0;k<l1;k++){
  115748. t7=t1+(t1<<1);
  115749. t6=(t5=t7+t3);
  115750. t8=t1;
  115751. t10=(t9=t1+t0)+t0;
  115752. for(i=2;i<ido;i+=2){
  115753. t5+=2;
  115754. t6-=2;
  115755. t7+=2;
  115756. t8+=2;
  115757. t9+=2;
  115758. t10+=2;
  115759. tr2=cc[t5-1]+cc[t6-1];
  115760. cr2=cc[t7-1]+(taur*tr2);
  115761. ch[t8-1]=cc[t7-1]+tr2;
  115762. ti2=cc[t5]-cc[t6];
  115763. ci2=cc[t7]+(taur*ti2);
  115764. ch[t8]=cc[t7]+ti2;
  115765. cr3=taui*(cc[t5-1]-cc[t6-1]);
  115766. ci3=taui*(cc[t5]+cc[t6]);
  115767. dr2=cr2-ci3;
  115768. dr3=cr2+ci3;
  115769. di2=ci2+cr3;
  115770. di3=ci2-cr3;
  115771. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  115772. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  115773. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  115774. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  115775. }
  115776. t1+=ido;
  115777. }
  115778. }
  115779. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  115780. float *wa2,float *wa3){
  115781. static float sqrt2=1.414213562373095f;
  115782. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  115783. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115784. t0=l1*ido;
  115785. t1=0;
  115786. t2=ido<<2;
  115787. t3=0;
  115788. t6=ido<<1;
  115789. for(k=0;k<l1;k++){
  115790. t4=t3+t6;
  115791. t5=t1;
  115792. tr3=cc[t4-1]+cc[t4-1];
  115793. tr4=cc[t4]+cc[t4];
  115794. tr1=cc[t3]-cc[(t4+=t6)-1];
  115795. tr2=cc[t3]+cc[t4-1];
  115796. ch[t5]=tr2+tr3;
  115797. ch[t5+=t0]=tr1-tr4;
  115798. ch[t5+=t0]=tr2-tr3;
  115799. ch[t5+=t0]=tr1+tr4;
  115800. t1+=ido;
  115801. t3+=t2;
  115802. }
  115803. if(ido<2)return;
  115804. if(ido==2)goto L105;
  115805. t1=0;
  115806. for(k=0;k<l1;k++){
  115807. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  115808. t7=t1;
  115809. for(i=2;i<ido;i+=2){
  115810. t2+=2;
  115811. t3+=2;
  115812. t4-=2;
  115813. t5-=2;
  115814. t7+=2;
  115815. ti1=cc[t2]+cc[t5];
  115816. ti2=cc[t2]-cc[t5];
  115817. ti3=cc[t3]-cc[t4];
  115818. tr4=cc[t3]+cc[t4];
  115819. tr1=cc[t2-1]-cc[t5-1];
  115820. tr2=cc[t2-1]+cc[t5-1];
  115821. ti4=cc[t3-1]-cc[t4-1];
  115822. tr3=cc[t3-1]+cc[t4-1];
  115823. ch[t7-1]=tr2+tr3;
  115824. cr3=tr2-tr3;
  115825. ch[t7]=ti2+ti3;
  115826. ci3=ti2-ti3;
  115827. cr2=tr1-tr4;
  115828. cr4=tr1+tr4;
  115829. ci2=ti1+ti4;
  115830. ci4=ti1-ti4;
  115831. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  115832. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  115833. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  115834. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  115835. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  115836. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  115837. }
  115838. t1+=ido;
  115839. }
  115840. if(ido%2 == 1)return;
  115841. L105:
  115842. t1=ido;
  115843. t2=ido<<2;
  115844. t3=ido-1;
  115845. t4=ido+(ido<<1);
  115846. for(k=0;k<l1;k++){
  115847. t5=t3;
  115848. ti1=cc[t1]+cc[t4];
  115849. ti2=cc[t4]-cc[t1];
  115850. tr1=cc[t1-1]-cc[t4-1];
  115851. tr2=cc[t1-1]+cc[t4-1];
  115852. ch[t5]=tr2+tr2;
  115853. ch[t5+=t0]=sqrt2*(tr1-ti1);
  115854. ch[t5+=t0]=ti2+ti2;
  115855. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  115856. t3+=ido;
  115857. t1+=t2;
  115858. t4+=t2;
  115859. }
  115860. }
  115861. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115862. float *c2,float *ch,float *ch2,float *wa){
  115863. static float tpi=6.283185307179586f;
  115864. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  115865. t11,t12;
  115866. float dc2,ai1,ai2,ar1,ar2,ds2;
  115867. int nbd;
  115868. float dcp,arg,dsp,ar1h,ar2h;
  115869. int ipp2;
  115870. t10=ip*ido;
  115871. t0=l1*ido;
  115872. arg=tpi/(float)ip;
  115873. dcp=cos(arg);
  115874. dsp=sin(arg);
  115875. nbd=(ido-1)>>1;
  115876. ipp2=ip;
  115877. ipph=(ip+1)>>1;
  115878. if(ido<l1)goto L103;
  115879. t1=0;
  115880. t2=0;
  115881. for(k=0;k<l1;k++){
  115882. t3=t1;
  115883. t4=t2;
  115884. for(i=0;i<ido;i++){
  115885. ch[t3]=cc[t4];
  115886. t3++;
  115887. t4++;
  115888. }
  115889. t1+=ido;
  115890. t2+=t10;
  115891. }
  115892. goto L106;
  115893. L103:
  115894. t1=0;
  115895. for(i=0;i<ido;i++){
  115896. t2=t1;
  115897. t3=t1;
  115898. for(k=0;k<l1;k++){
  115899. ch[t2]=cc[t3];
  115900. t2+=ido;
  115901. t3+=t10;
  115902. }
  115903. t1++;
  115904. }
  115905. L106:
  115906. t1=0;
  115907. t2=ipp2*t0;
  115908. t7=(t5=ido<<1);
  115909. for(j=1;j<ipph;j++){
  115910. t1+=t0;
  115911. t2-=t0;
  115912. t3=t1;
  115913. t4=t2;
  115914. t6=t5;
  115915. for(k=0;k<l1;k++){
  115916. ch[t3]=cc[t6-1]+cc[t6-1];
  115917. ch[t4]=cc[t6]+cc[t6];
  115918. t3+=ido;
  115919. t4+=ido;
  115920. t6+=t10;
  115921. }
  115922. t5+=t7;
  115923. }
  115924. if (ido == 1)goto L116;
  115925. if(nbd<l1)goto L112;
  115926. t1=0;
  115927. t2=ipp2*t0;
  115928. t7=0;
  115929. for(j=1;j<ipph;j++){
  115930. t1+=t0;
  115931. t2-=t0;
  115932. t3=t1;
  115933. t4=t2;
  115934. t7+=(ido<<1);
  115935. t8=t7;
  115936. for(k=0;k<l1;k++){
  115937. t5=t3;
  115938. t6=t4;
  115939. t9=t8;
  115940. t11=t8;
  115941. for(i=2;i<ido;i+=2){
  115942. t5+=2;
  115943. t6+=2;
  115944. t9+=2;
  115945. t11-=2;
  115946. ch[t5-1]=cc[t9-1]+cc[t11-1];
  115947. ch[t6-1]=cc[t9-1]-cc[t11-1];
  115948. ch[t5]=cc[t9]-cc[t11];
  115949. ch[t6]=cc[t9]+cc[t11];
  115950. }
  115951. t3+=ido;
  115952. t4+=ido;
  115953. t8+=t10;
  115954. }
  115955. }
  115956. goto L116;
  115957. L112:
  115958. t1=0;
  115959. t2=ipp2*t0;
  115960. t7=0;
  115961. for(j=1;j<ipph;j++){
  115962. t1+=t0;
  115963. t2-=t0;
  115964. t3=t1;
  115965. t4=t2;
  115966. t7+=(ido<<1);
  115967. t8=t7;
  115968. t9=t7;
  115969. for(i=2;i<ido;i+=2){
  115970. t3+=2;
  115971. t4+=2;
  115972. t8+=2;
  115973. t9-=2;
  115974. t5=t3;
  115975. t6=t4;
  115976. t11=t8;
  115977. t12=t9;
  115978. for(k=0;k<l1;k++){
  115979. ch[t5-1]=cc[t11-1]+cc[t12-1];
  115980. ch[t6-1]=cc[t11-1]-cc[t12-1];
  115981. ch[t5]=cc[t11]-cc[t12];
  115982. ch[t6]=cc[t11]+cc[t12];
  115983. t5+=ido;
  115984. t6+=ido;
  115985. t11+=t10;
  115986. t12+=t10;
  115987. }
  115988. }
  115989. }
  115990. L116:
  115991. ar1=1.f;
  115992. ai1=0.f;
  115993. t1=0;
  115994. t9=(t2=ipp2*idl1);
  115995. t3=(ip-1)*idl1;
  115996. for(l=1;l<ipph;l++){
  115997. t1+=idl1;
  115998. t2-=idl1;
  115999. ar1h=dcp*ar1-dsp*ai1;
  116000. ai1=dcp*ai1+dsp*ar1;
  116001. ar1=ar1h;
  116002. t4=t1;
  116003. t5=t2;
  116004. t6=0;
  116005. t7=idl1;
  116006. t8=t3;
  116007. for(ik=0;ik<idl1;ik++){
  116008. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  116009. c2[t5++]=ai1*ch2[t8++];
  116010. }
  116011. dc2=ar1;
  116012. ds2=ai1;
  116013. ar2=ar1;
  116014. ai2=ai1;
  116015. t6=idl1;
  116016. t7=t9-idl1;
  116017. for(j=2;j<ipph;j++){
  116018. t6+=idl1;
  116019. t7-=idl1;
  116020. ar2h=dc2*ar2-ds2*ai2;
  116021. ai2=dc2*ai2+ds2*ar2;
  116022. ar2=ar2h;
  116023. t4=t1;
  116024. t5=t2;
  116025. t11=t6;
  116026. t12=t7;
  116027. for(ik=0;ik<idl1;ik++){
  116028. c2[t4++]+=ar2*ch2[t11++];
  116029. c2[t5++]+=ai2*ch2[t12++];
  116030. }
  116031. }
  116032. }
  116033. t1=0;
  116034. for(j=1;j<ipph;j++){
  116035. t1+=idl1;
  116036. t2=t1;
  116037. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  116038. }
  116039. t1=0;
  116040. t2=ipp2*t0;
  116041. for(j=1;j<ipph;j++){
  116042. t1+=t0;
  116043. t2-=t0;
  116044. t3=t1;
  116045. t4=t2;
  116046. for(k=0;k<l1;k++){
  116047. ch[t3]=c1[t3]-c1[t4];
  116048. ch[t4]=c1[t3]+c1[t4];
  116049. t3+=ido;
  116050. t4+=ido;
  116051. }
  116052. }
  116053. if(ido==1)goto L132;
  116054. if(nbd<l1)goto L128;
  116055. t1=0;
  116056. t2=ipp2*t0;
  116057. for(j=1;j<ipph;j++){
  116058. t1+=t0;
  116059. t2-=t0;
  116060. t3=t1;
  116061. t4=t2;
  116062. for(k=0;k<l1;k++){
  116063. t5=t3;
  116064. t6=t4;
  116065. for(i=2;i<ido;i+=2){
  116066. t5+=2;
  116067. t6+=2;
  116068. ch[t5-1]=c1[t5-1]-c1[t6];
  116069. ch[t6-1]=c1[t5-1]+c1[t6];
  116070. ch[t5]=c1[t5]+c1[t6-1];
  116071. ch[t6]=c1[t5]-c1[t6-1];
  116072. }
  116073. t3+=ido;
  116074. t4+=ido;
  116075. }
  116076. }
  116077. goto L132;
  116078. L128:
  116079. t1=0;
  116080. t2=ipp2*t0;
  116081. for(j=1;j<ipph;j++){
  116082. t1+=t0;
  116083. t2-=t0;
  116084. t3=t1;
  116085. t4=t2;
  116086. for(i=2;i<ido;i+=2){
  116087. t3+=2;
  116088. t4+=2;
  116089. t5=t3;
  116090. t6=t4;
  116091. for(k=0;k<l1;k++){
  116092. ch[t5-1]=c1[t5-1]-c1[t6];
  116093. ch[t6-1]=c1[t5-1]+c1[t6];
  116094. ch[t5]=c1[t5]+c1[t6-1];
  116095. ch[t6]=c1[t5]-c1[t6-1];
  116096. t5+=ido;
  116097. t6+=ido;
  116098. }
  116099. }
  116100. }
  116101. L132:
  116102. if(ido==1)return;
  116103. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116104. t1=0;
  116105. for(j=1;j<ip;j++){
  116106. t2=(t1+=t0);
  116107. for(k=0;k<l1;k++){
  116108. c1[t2]=ch[t2];
  116109. t2+=ido;
  116110. }
  116111. }
  116112. if(nbd>l1)goto L139;
  116113. is= -ido-1;
  116114. t1=0;
  116115. for(j=1;j<ip;j++){
  116116. is+=ido;
  116117. t1+=t0;
  116118. idij=is;
  116119. t2=t1;
  116120. for(i=2;i<ido;i+=2){
  116121. t2+=2;
  116122. idij+=2;
  116123. t3=t2;
  116124. for(k=0;k<l1;k++){
  116125. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116126. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116127. t3+=ido;
  116128. }
  116129. }
  116130. }
  116131. return;
  116132. L139:
  116133. is= -ido-1;
  116134. t1=0;
  116135. for(j=1;j<ip;j++){
  116136. is+=ido;
  116137. t1+=t0;
  116138. t2=t1;
  116139. for(k=0;k<l1;k++){
  116140. idij=is;
  116141. t3=t2;
  116142. for(i=2;i<ido;i+=2){
  116143. idij+=2;
  116144. t3+=2;
  116145. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116146. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116147. }
  116148. t2+=ido;
  116149. }
  116150. }
  116151. }
  116152. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  116153. int i,k1,l1,l2;
  116154. int na;
  116155. int nf,ip,iw,ix2,ix3,ido,idl1;
  116156. nf=ifac[1];
  116157. na=0;
  116158. l1=1;
  116159. iw=1;
  116160. for(k1=0;k1<nf;k1++){
  116161. ip=ifac[k1 + 2];
  116162. l2=ip*l1;
  116163. ido=n/l2;
  116164. idl1=ido*l1;
  116165. if(ip!=4)goto L103;
  116166. ix2=iw+ido;
  116167. ix3=ix2+ido;
  116168. if(na!=0)
  116169. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116170. else
  116171. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116172. na=1-na;
  116173. goto L115;
  116174. L103:
  116175. if(ip!=2)goto L106;
  116176. if(na!=0)
  116177. dradb2(ido,l1,ch,c,wa+iw-1);
  116178. else
  116179. dradb2(ido,l1,c,ch,wa+iw-1);
  116180. na=1-na;
  116181. goto L115;
  116182. L106:
  116183. if(ip!=3)goto L109;
  116184. ix2=iw+ido;
  116185. if(na!=0)
  116186. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  116187. else
  116188. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  116189. na=1-na;
  116190. goto L115;
  116191. L109:
  116192. /* The radix five case can be translated later..... */
  116193. /* if(ip!=5)goto L112;
  116194. ix2=iw+ido;
  116195. ix3=ix2+ido;
  116196. ix4=ix3+ido;
  116197. if(na!=0)
  116198. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116199. else
  116200. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116201. na=1-na;
  116202. goto L115;
  116203. L112:*/
  116204. if(na!=0)
  116205. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116206. else
  116207. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116208. if(ido==1)na=1-na;
  116209. L115:
  116210. l1=l2;
  116211. iw+=(ip-1)*ido;
  116212. }
  116213. if(na==0)return;
  116214. for(i=0;i<n;i++)c[i]=ch[i];
  116215. }
  116216. void drft_forward(drft_lookup *l,float *data){
  116217. if(l->n==1)return;
  116218. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116219. }
  116220. void drft_backward(drft_lookup *l,float *data){
  116221. if (l->n==1)return;
  116222. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116223. }
  116224. void drft_init(drft_lookup *l,int n){
  116225. l->n=n;
  116226. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  116227. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  116228. fdrffti(n, l->trigcache, l->splitcache);
  116229. }
  116230. void drft_clear(drft_lookup *l){
  116231. if(l){
  116232. if(l->trigcache)_ogg_free(l->trigcache);
  116233. if(l->splitcache)_ogg_free(l->splitcache);
  116234. memset(l,0,sizeof(*l));
  116235. }
  116236. }
  116237. #endif
  116238. /********* End of inlined file: smallft.c *********/
  116239. /********* Start of inlined file: synthesis.c *********/
  116240. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116241. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116242. // tasks..
  116243. #if JUCE_MSVC
  116244. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116245. #endif
  116246. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116247. #if JUCE_USE_OGGVORBIS
  116248. #include <stdio.h>
  116249. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  116250. vorbis_dsp_state *vd=vb->vd;
  116251. private_state *b=(private_state*)vd->backend_state;
  116252. vorbis_info *vi=vd->vi;
  116253. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  116254. oggpack_buffer *opb=&vb->opb;
  116255. int type,mode,i;
  116256. /* first things first. Make sure decode is ready */
  116257. _vorbis_block_ripcord(vb);
  116258. oggpack_readinit(opb,op->packet,op->bytes);
  116259. /* Check the packet type */
  116260. if(oggpack_read(opb,1)!=0){
  116261. /* Oops. This is not an audio data packet */
  116262. return(OV_ENOTAUDIO);
  116263. }
  116264. /* read our mode and pre/post windowsize */
  116265. mode=oggpack_read(opb,b->modebits);
  116266. if(mode==-1)return(OV_EBADPACKET);
  116267. vb->mode=mode;
  116268. vb->W=ci->mode_param[mode]->blockflag;
  116269. if(vb->W){
  116270. /* this doesn;t get mapped through mode selection as it's used
  116271. only for window selection */
  116272. vb->lW=oggpack_read(opb,1);
  116273. vb->nW=oggpack_read(opb,1);
  116274. if(vb->nW==-1) return(OV_EBADPACKET);
  116275. }else{
  116276. vb->lW=0;
  116277. vb->nW=0;
  116278. }
  116279. /* more setup */
  116280. vb->granulepos=op->granulepos;
  116281. vb->sequence=op->packetno;
  116282. vb->eofflag=op->e_o_s;
  116283. /* alloc pcm passback storage */
  116284. vb->pcmend=ci->blocksizes[vb->W];
  116285. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  116286. for(i=0;i<vi->channels;i++)
  116287. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  116288. /* unpack_header enforces range checking */
  116289. type=ci->map_type[ci->mode_param[mode]->mapping];
  116290. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  116291. mapping]));
  116292. }
  116293. /* used to track pcm position without actually performing decode.
  116294. Useful for sequential 'fast forward' */
  116295. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  116296. vorbis_dsp_state *vd=vb->vd;
  116297. private_state *b=(private_state*)vd->backend_state;
  116298. vorbis_info *vi=vd->vi;
  116299. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116300. oggpack_buffer *opb=&vb->opb;
  116301. int mode;
  116302. /* first things first. Make sure decode is ready */
  116303. _vorbis_block_ripcord(vb);
  116304. oggpack_readinit(opb,op->packet,op->bytes);
  116305. /* Check the packet type */
  116306. if(oggpack_read(opb,1)!=0){
  116307. /* Oops. This is not an audio data packet */
  116308. return(OV_ENOTAUDIO);
  116309. }
  116310. /* read our mode and pre/post windowsize */
  116311. mode=oggpack_read(opb,b->modebits);
  116312. if(mode==-1)return(OV_EBADPACKET);
  116313. vb->mode=mode;
  116314. vb->W=ci->mode_param[mode]->blockflag;
  116315. if(vb->W){
  116316. vb->lW=oggpack_read(opb,1);
  116317. vb->nW=oggpack_read(opb,1);
  116318. if(vb->nW==-1) return(OV_EBADPACKET);
  116319. }else{
  116320. vb->lW=0;
  116321. vb->nW=0;
  116322. }
  116323. /* more setup */
  116324. vb->granulepos=op->granulepos;
  116325. vb->sequence=op->packetno;
  116326. vb->eofflag=op->e_o_s;
  116327. /* no pcm */
  116328. vb->pcmend=0;
  116329. vb->pcm=NULL;
  116330. return(0);
  116331. }
  116332. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  116333. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116334. oggpack_buffer opb;
  116335. int mode;
  116336. oggpack_readinit(&opb,op->packet,op->bytes);
  116337. /* Check the packet type */
  116338. if(oggpack_read(&opb,1)!=0){
  116339. /* Oops. This is not an audio data packet */
  116340. return(OV_ENOTAUDIO);
  116341. }
  116342. {
  116343. int modebits=0;
  116344. int v=ci->modes;
  116345. while(v>1){
  116346. modebits++;
  116347. v>>=1;
  116348. }
  116349. /* read our mode and pre/post windowsize */
  116350. mode=oggpack_read(&opb,modebits);
  116351. }
  116352. if(mode==-1)return(OV_EBADPACKET);
  116353. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  116354. }
  116355. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  116356. /* set / clear half-sample-rate mode */
  116357. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116358. /* right now, our MDCT can't handle < 64 sample windows. */
  116359. if(ci->blocksizes[0]<=64 && flag)return -1;
  116360. ci->halfrate_flag=(flag?1:0);
  116361. return 0;
  116362. }
  116363. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  116364. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116365. return ci->halfrate_flag;
  116366. }
  116367. #endif
  116368. /********* End of inlined file: synthesis.c *********/
  116369. /********* Start of inlined file: vorbisenc.c *********/
  116370. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116371. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116372. // tasks..
  116373. #if JUCE_MSVC
  116374. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116375. #endif
  116376. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116377. #if JUCE_USE_OGGVORBIS
  116378. #include <stdlib.h>
  116379. #include <string.h>
  116380. #include <math.h>
  116381. /* careful with this; it's using static array sizing to make managing
  116382. all the modes a little less annoying. If we use a residue backend
  116383. with > 12 partition types, or a different division of iteration,
  116384. this needs to be updated. */
  116385. typedef struct {
  116386. static_codebook *books[12][3];
  116387. } static_bookblock;
  116388. typedef struct {
  116389. int res_type;
  116390. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  116391. vorbis_info_residue0 *res;
  116392. static_codebook *book_aux;
  116393. static_codebook *book_aux_managed;
  116394. static_bookblock *books_base;
  116395. static_bookblock *books_base_managed;
  116396. } vorbis_residue_template;
  116397. typedef struct {
  116398. vorbis_info_mapping0 *map;
  116399. vorbis_residue_template *res;
  116400. } vorbis_mapping_template;
  116401. typedef struct vp_adjblock{
  116402. int block[P_BANDS];
  116403. } vp_adjblock;
  116404. typedef struct {
  116405. int data[NOISE_COMPAND_LEVELS];
  116406. } compandblock;
  116407. /* high level configuration information for setting things up
  116408. step-by-step with the detailed vorbis_encode_ctl interface.
  116409. There's a fair amount of redundancy such that interactive setup
  116410. does not directly deal with any vorbis_info or codec_setup_info
  116411. initialization; it's all stored (until full init) in this highlevel
  116412. setup, then flushed out to the real codec setup structs later. */
  116413. typedef struct {
  116414. int att[P_NOISECURVES];
  116415. float boost;
  116416. float decay;
  116417. } att3;
  116418. typedef struct { int data[P_NOISECURVES]; } adj3;
  116419. typedef struct {
  116420. int pre[PACKETBLOBS];
  116421. int post[PACKETBLOBS];
  116422. float kHz[PACKETBLOBS];
  116423. float lowpasskHz[PACKETBLOBS];
  116424. } adj_stereo;
  116425. typedef struct {
  116426. int lo;
  116427. int hi;
  116428. int fixed;
  116429. } noiseguard;
  116430. typedef struct {
  116431. int data[P_NOISECURVES][17];
  116432. } noise3;
  116433. typedef struct {
  116434. int mappings;
  116435. double *rate_mapping;
  116436. double *quality_mapping;
  116437. int coupling_restriction;
  116438. long samplerate_min_restriction;
  116439. long samplerate_max_restriction;
  116440. int *blocksize_short;
  116441. int *blocksize_long;
  116442. att3 *psy_tone_masteratt;
  116443. int *psy_tone_0dB;
  116444. int *psy_tone_dBsuppress;
  116445. vp_adjblock *psy_tone_adj_impulse;
  116446. vp_adjblock *psy_tone_adj_long;
  116447. vp_adjblock *psy_tone_adj_other;
  116448. noiseguard *psy_noiseguards;
  116449. noise3 *psy_noise_bias_impulse;
  116450. noise3 *psy_noise_bias_padding;
  116451. noise3 *psy_noise_bias_trans;
  116452. noise3 *psy_noise_bias_long;
  116453. int *psy_noise_dBsuppress;
  116454. compandblock *psy_noise_compand;
  116455. double *psy_noise_compand_short_mapping;
  116456. double *psy_noise_compand_long_mapping;
  116457. int *psy_noise_normal_start[2];
  116458. int *psy_noise_normal_partition[2];
  116459. double *psy_noise_normal_thresh;
  116460. int *psy_ath_float;
  116461. int *psy_ath_abs;
  116462. double *psy_lowpass;
  116463. vorbis_info_psy_global *global_params;
  116464. double *global_mapping;
  116465. adj_stereo *stereo_modes;
  116466. static_codebook ***floor_books;
  116467. vorbis_info_floor1 *floor_params;
  116468. int *floor_short_mapping;
  116469. int *floor_long_mapping;
  116470. vorbis_mapping_template *maps;
  116471. } ve_setup_data_template;
  116472. /* a few static coder conventions */
  116473. static vorbis_info_mode _mode_template[2]={
  116474. {0,0,0,0},
  116475. {1,0,0,1}
  116476. };
  116477. static vorbis_info_mapping0 _map_nominal[2]={
  116478. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  116479. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  116480. };
  116481. /********* Start of inlined file: setup_44.h *********/
  116482. /********* Start of inlined file: floor_all.h *********/
  116483. /********* Start of inlined file: floor_books.h *********/
  116484. static long _huff_lengthlist_line_256x7_0sub1[] = {
  116485. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  116486. };
  116487. static static_codebook _huff_book_line_256x7_0sub1 = {
  116488. 1, 9,
  116489. _huff_lengthlist_line_256x7_0sub1,
  116490. 0, 0, 0, 0, 0,
  116491. NULL,
  116492. NULL,
  116493. NULL,
  116494. NULL,
  116495. 0
  116496. };
  116497. static long _huff_lengthlist_line_256x7_0sub2[] = {
  116498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  116499. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  116500. };
  116501. static static_codebook _huff_book_line_256x7_0sub2 = {
  116502. 1, 25,
  116503. _huff_lengthlist_line_256x7_0sub2,
  116504. 0, 0, 0, 0, 0,
  116505. NULL,
  116506. NULL,
  116507. NULL,
  116508. NULL,
  116509. 0
  116510. };
  116511. static long _huff_lengthlist_line_256x7_0sub3[] = {
  116512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  116514. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  116515. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  116516. };
  116517. static static_codebook _huff_book_line_256x7_0sub3 = {
  116518. 1, 64,
  116519. _huff_lengthlist_line_256x7_0sub3,
  116520. 0, 0, 0, 0, 0,
  116521. NULL,
  116522. NULL,
  116523. NULL,
  116524. NULL,
  116525. 0
  116526. };
  116527. static long _huff_lengthlist_line_256x7_1sub1[] = {
  116528. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  116529. };
  116530. static static_codebook _huff_book_line_256x7_1sub1 = {
  116531. 1, 9,
  116532. _huff_lengthlist_line_256x7_1sub1,
  116533. 0, 0, 0, 0, 0,
  116534. NULL,
  116535. NULL,
  116536. NULL,
  116537. NULL,
  116538. 0
  116539. };
  116540. static long _huff_lengthlist_line_256x7_1sub2[] = {
  116541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  116542. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  116543. };
  116544. static static_codebook _huff_book_line_256x7_1sub2 = {
  116545. 1, 25,
  116546. _huff_lengthlist_line_256x7_1sub2,
  116547. 0, 0, 0, 0, 0,
  116548. NULL,
  116549. NULL,
  116550. NULL,
  116551. NULL,
  116552. 0
  116553. };
  116554. static long _huff_lengthlist_line_256x7_1sub3[] = {
  116555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  116557. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116558. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  116559. };
  116560. static static_codebook _huff_book_line_256x7_1sub3 = {
  116561. 1, 64,
  116562. _huff_lengthlist_line_256x7_1sub3,
  116563. 0, 0, 0, 0, 0,
  116564. NULL,
  116565. NULL,
  116566. NULL,
  116567. NULL,
  116568. 0
  116569. };
  116570. static long _huff_lengthlist_line_256x7_class0[] = {
  116571. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  116572. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  116573. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  116574. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  116575. };
  116576. static static_codebook _huff_book_line_256x7_class0 = {
  116577. 1, 64,
  116578. _huff_lengthlist_line_256x7_class0,
  116579. 0, 0, 0, 0, 0,
  116580. NULL,
  116581. NULL,
  116582. NULL,
  116583. NULL,
  116584. 0
  116585. };
  116586. static long _huff_lengthlist_line_256x7_class1[] = {
  116587. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  116588. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  116589. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  116590. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  116591. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  116592. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  116593. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  116594. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  116595. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  116596. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  116597. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  116598. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  116599. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116600. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116601. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  116602. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  116603. };
  116604. static static_codebook _huff_book_line_256x7_class1 = {
  116605. 1, 256,
  116606. _huff_lengthlist_line_256x7_class1,
  116607. 0, 0, 0, 0, 0,
  116608. NULL,
  116609. NULL,
  116610. NULL,
  116611. NULL,
  116612. 0
  116613. };
  116614. static long _huff_lengthlist_line_512x17_0sub0[] = {
  116615. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  116616. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  116617. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  116618. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  116619. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  116620. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  116621. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  116622. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  116623. };
  116624. static static_codebook _huff_book_line_512x17_0sub0 = {
  116625. 1, 128,
  116626. _huff_lengthlist_line_512x17_0sub0,
  116627. 0, 0, 0, 0, 0,
  116628. NULL,
  116629. NULL,
  116630. NULL,
  116631. NULL,
  116632. 0
  116633. };
  116634. static long _huff_lengthlist_line_512x17_1sub0[] = {
  116635. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116636. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  116637. };
  116638. static static_codebook _huff_book_line_512x17_1sub0 = {
  116639. 1, 32,
  116640. _huff_lengthlist_line_512x17_1sub0,
  116641. 0, 0, 0, 0, 0,
  116642. NULL,
  116643. NULL,
  116644. NULL,
  116645. NULL,
  116646. 0
  116647. };
  116648. static long _huff_lengthlist_line_512x17_1sub1[] = {
  116649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116651. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  116652. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  116653. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  116654. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  116655. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  116656. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116657. };
  116658. static static_codebook _huff_book_line_512x17_1sub1 = {
  116659. 1, 128,
  116660. _huff_lengthlist_line_512x17_1sub1,
  116661. 0, 0, 0, 0, 0,
  116662. NULL,
  116663. NULL,
  116664. NULL,
  116665. NULL,
  116666. 0
  116667. };
  116668. static long _huff_lengthlist_line_512x17_2sub1[] = {
  116669. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  116670. 5, 3,
  116671. };
  116672. static static_codebook _huff_book_line_512x17_2sub1 = {
  116673. 1, 18,
  116674. _huff_lengthlist_line_512x17_2sub1,
  116675. 0, 0, 0, 0, 0,
  116676. NULL,
  116677. NULL,
  116678. NULL,
  116679. NULL,
  116680. 0
  116681. };
  116682. static long _huff_lengthlist_line_512x17_2sub2[] = {
  116683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116684. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  116685. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  116686. 9, 8,
  116687. };
  116688. static static_codebook _huff_book_line_512x17_2sub2 = {
  116689. 1, 50,
  116690. _huff_lengthlist_line_512x17_2sub2,
  116691. 0, 0, 0, 0, 0,
  116692. NULL,
  116693. NULL,
  116694. NULL,
  116695. NULL,
  116696. 0
  116697. };
  116698. static long _huff_lengthlist_line_512x17_2sub3[] = {
  116699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116702. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  116703. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  116704. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116707. };
  116708. static static_codebook _huff_book_line_512x17_2sub3 = {
  116709. 1, 128,
  116710. _huff_lengthlist_line_512x17_2sub3,
  116711. 0, 0, 0, 0, 0,
  116712. NULL,
  116713. NULL,
  116714. NULL,
  116715. NULL,
  116716. 0
  116717. };
  116718. static long _huff_lengthlist_line_512x17_3sub1[] = {
  116719. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  116720. 5, 5,
  116721. };
  116722. static static_codebook _huff_book_line_512x17_3sub1 = {
  116723. 1, 18,
  116724. _huff_lengthlist_line_512x17_3sub1,
  116725. 0, 0, 0, 0, 0,
  116726. NULL,
  116727. NULL,
  116728. NULL,
  116729. NULL,
  116730. 0
  116731. };
  116732. static long _huff_lengthlist_line_512x17_3sub2[] = {
  116733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116734. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  116735. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  116736. 11,14,
  116737. };
  116738. static static_codebook _huff_book_line_512x17_3sub2 = {
  116739. 1, 50,
  116740. _huff_lengthlist_line_512x17_3sub2,
  116741. 0, 0, 0, 0, 0,
  116742. NULL,
  116743. NULL,
  116744. NULL,
  116745. NULL,
  116746. 0
  116747. };
  116748. static long _huff_lengthlist_line_512x17_3sub3[] = {
  116749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116752. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  116753. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116754. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116755. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116756. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116757. };
  116758. static static_codebook _huff_book_line_512x17_3sub3 = {
  116759. 1, 128,
  116760. _huff_lengthlist_line_512x17_3sub3,
  116761. 0, 0, 0, 0, 0,
  116762. NULL,
  116763. NULL,
  116764. NULL,
  116765. NULL,
  116766. 0
  116767. };
  116768. static long _huff_lengthlist_line_512x17_class1[] = {
  116769. 1, 2, 3, 6, 5, 4, 7, 7,
  116770. };
  116771. static static_codebook _huff_book_line_512x17_class1 = {
  116772. 1, 8,
  116773. _huff_lengthlist_line_512x17_class1,
  116774. 0, 0, 0, 0, 0,
  116775. NULL,
  116776. NULL,
  116777. NULL,
  116778. NULL,
  116779. 0
  116780. };
  116781. static long _huff_lengthlist_line_512x17_class2[] = {
  116782. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  116783. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  116784. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  116785. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  116786. };
  116787. static static_codebook _huff_book_line_512x17_class2 = {
  116788. 1, 64,
  116789. _huff_lengthlist_line_512x17_class2,
  116790. 0, 0, 0, 0, 0,
  116791. NULL,
  116792. NULL,
  116793. NULL,
  116794. NULL,
  116795. 0
  116796. };
  116797. static long _huff_lengthlist_line_512x17_class3[] = {
  116798. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  116799. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  116800. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  116801. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  116802. };
  116803. static static_codebook _huff_book_line_512x17_class3 = {
  116804. 1, 64,
  116805. _huff_lengthlist_line_512x17_class3,
  116806. 0, 0, 0, 0, 0,
  116807. NULL,
  116808. NULL,
  116809. NULL,
  116810. NULL,
  116811. 0
  116812. };
  116813. static long _huff_lengthlist_line_128x4_class0[] = {
  116814. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  116815. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  116816. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  116817. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  116818. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  116819. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  116820. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  116821. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  116822. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  116823. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  116824. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  116825. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  116826. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  116827. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  116828. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  116829. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  116830. };
  116831. static static_codebook _huff_book_line_128x4_class0 = {
  116832. 1, 256,
  116833. _huff_lengthlist_line_128x4_class0,
  116834. 0, 0, 0, 0, 0,
  116835. NULL,
  116836. NULL,
  116837. NULL,
  116838. NULL,
  116839. 0
  116840. };
  116841. static long _huff_lengthlist_line_128x4_0sub0[] = {
  116842. 2, 2, 2, 2,
  116843. };
  116844. static static_codebook _huff_book_line_128x4_0sub0 = {
  116845. 1, 4,
  116846. _huff_lengthlist_line_128x4_0sub0,
  116847. 0, 0, 0, 0, 0,
  116848. NULL,
  116849. NULL,
  116850. NULL,
  116851. NULL,
  116852. 0
  116853. };
  116854. static long _huff_lengthlist_line_128x4_0sub1[] = {
  116855. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  116856. };
  116857. static static_codebook _huff_book_line_128x4_0sub1 = {
  116858. 1, 10,
  116859. _huff_lengthlist_line_128x4_0sub1,
  116860. 0, 0, 0, 0, 0,
  116861. NULL,
  116862. NULL,
  116863. NULL,
  116864. NULL,
  116865. 0
  116866. };
  116867. static long _huff_lengthlist_line_128x4_0sub2[] = {
  116868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  116869. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  116870. };
  116871. static static_codebook _huff_book_line_128x4_0sub2 = {
  116872. 1, 25,
  116873. _huff_lengthlist_line_128x4_0sub2,
  116874. 0, 0, 0, 0, 0,
  116875. NULL,
  116876. NULL,
  116877. NULL,
  116878. NULL,
  116879. 0
  116880. };
  116881. static long _huff_lengthlist_line_128x4_0sub3[] = {
  116882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116884. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  116885. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  116886. };
  116887. static static_codebook _huff_book_line_128x4_0sub3 = {
  116888. 1, 64,
  116889. _huff_lengthlist_line_128x4_0sub3,
  116890. 0, 0, 0, 0, 0,
  116891. NULL,
  116892. NULL,
  116893. NULL,
  116894. NULL,
  116895. 0
  116896. };
  116897. static long _huff_lengthlist_line_256x4_class0[] = {
  116898. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  116899. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  116900. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  116901. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  116902. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  116903. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  116904. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  116905. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  116906. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  116907. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  116908. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  116909. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  116910. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  116911. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  116912. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  116913. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  116914. };
  116915. static static_codebook _huff_book_line_256x4_class0 = {
  116916. 1, 256,
  116917. _huff_lengthlist_line_256x4_class0,
  116918. 0, 0, 0, 0, 0,
  116919. NULL,
  116920. NULL,
  116921. NULL,
  116922. NULL,
  116923. 0
  116924. };
  116925. static long _huff_lengthlist_line_256x4_0sub0[] = {
  116926. 2, 2, 2, 2,
  116927. };
  116928. static static_codebook _huff_book_line_256x4_0sub0 = {
  116929. 1, 4,
  116930. _huff_lengthlist_line_256x4_0sub0,
  116931. 0, 0, 0, 0, 0,
  116932. NULL,
  116933. NULL,
  116934. NULL,
  116935. NULL,
  116936. 0
  116937. };
  116938. static long _huff_lengthlist_line_256x4_0sub1[] = {
  116939. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  116940. };
  116941. static static_codebook _huff_book_line_256x4_0sub1 = {
  116942. 1, 10,
  116943. _huff_lengthlist_line_256x4_0sub1,
  116944. 0, 0, 0, 0, 0,
  116945. NULL,
  116946. NULL,
  116947. NULL,
  116948. NULL,
  116949. 0
  116950. };
  116951. static long _huff_lengthlist_line_256x4_0sub2[] = {
  116952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  116953. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  116954. };
  116955. static static_codebook _huff_book_line_256x4_0sub2 = {
  116956. 1, 25,
  116957. _huff_lengthlist_line_256x4_0sub2,
  116958. 0, 0, 0, 0, 0,
  116959. NULL,
  116960. NULL,
  116961. NULL,
  116962. NULL,
  116963. 0
  116964. };
  116965. static long _huff_lengthlist_line_256x4_0sub3[] = {
  116966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116968. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  116969. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  116970. };
  116971. static static_codebook _huff_book_line_256x4_0sub3 = {
  116972. 1, 64,
  116973. _huff_lengthlist_line_256x4_0sub3,
  116974. 0, 0, 0, 0, 0,
  116975. NULL,
  116976. NULL,
  116977. NULL,
  116978. NULL,
  116979. 0
  116980. };
  116981. static long _huff_lengthlist_line_128x7_class0[] = {
  116982. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  116983. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  116984. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  116985. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  116986. };
  116987. static static_codebook _huff_book_line_128x7_class0 = {
  116988. 1, 64,
  116989. _huff_lengthlist_line_128x7_class0,
  116990. 0, 0, 0, 0, 0,
  116991. NULL,
  116992. NULL,
  116993. NULL,
  116994. NULL,
  116995. 0
  116996. };
  116997. static long _huff_lengthlist_line_128x7_class1[] = {
  116998. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  116999. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  117000. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  117001. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117002. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  117003. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  117004. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  117005. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  117006. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  117007. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  117008. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  117009. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  117010. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  117011. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  117012. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  117013. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  117014. };
  117015. static static_codebook _huff_book_line_128x7_class1 = {
  117016. 1, 256,
  117017. _huff_lengthlist_line_128x7_class1,
  117018. 0, 0, 0, 0, 0,
  117019. NULL,
  117020. NULL,
  117021. NULL,
  117022. NULL,
  117023. 0
  117024. };
  117025. static long _huff_lengthlist_line_128x7_0sub1[] = {
  117026. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  117027. };
  117028. static static_codebook _huff_book_line_128x7_0sub1 = {
  117029. 1, 9,
  117030. _huff_lengthlist_line_128x7_0sub1,
  117031. 0, 0, 0, 0, 0,
  117032. NULL,
  117033. NULL,
  117034. NULL,
  117035. NULL,
  117036. 0
  117037. };
  117038. static long _huff_lengthlist_line_128x7_0sub2[] = {
  117039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  117040. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  117041. };
  117042. static static_codebook _huff_book_line_128x7_0sub2 = {
  117043. 1, 25,
  117044. _huff_lengthlist_line_128x7_0sub2,
  117045. 0, 0, 0, 0, 0,
  117046. NULL,
  117047. NULL,
  117048. NULL,
  117049. NULL,
  117050. 0
  117051. };
  117052. static long _huff_lengthlist_line_128x7_0sub3[] = {
  117053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  117055. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117056. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  117057. };
  117058. static static_codebook _huff_book_line_128x7_0sub3 = {
  117059. 1, 64,
  117060. _huff_lengthlist_line_128x7_0sub3,
  117061. 0, 0, 0, 0, 0,
  117062. NULL,
  117063. NULL,
  117064. NULL,
  117065. NULL,
  117066. 0
  117067. };
  117068. static long _huff_lengthlist_line_128x7_1sub1[] = {
  117069. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  117070. };
  117071. static static_codebook _huff_book_line_128x7_1sub1 = {
  117072. 1, 9,
  117073. _huff_lengthlist_line_128x7_1sub1,
  117074. 0, 0, 0, 0, 0,
  117075. NULL,
  117076. NULL,
  117077. NULL,
  117078. NULL,
  117079. 0
  117080. };
  117081. static long _huff_lengthlist_line_128x7_1sub2[] = {
  117082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  117083. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  117084. };
  117085. static static_codebook _huff_book_line_128x7_1sub2 = {
  117086. 1, 25,
  117087. _huff_lengthlist_line_128x7_1sub2,
  117088. 0, 0, 0, 0, 0,
  117089. NULL,
  117090. NULL,
  117091. NULL,
  117092. NULL,
  117093. 0
  117094. };
  117095. static long _huff_lengthlist_line_128x7_1sub3[] = {
  117096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  117098. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  117099. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  117100. };
  117101. static static_codebook _huff_book_line_128x7_1sub3 = {
  117102. 1, 64,
  117103. _huff_lengthlist_line_128x7_1sub3,
  117104. 0, 0, 0, 0, 0,
  117105. NULL,
  117106. NULL,
  117107. NULL,
  117108. NULL,
  117109. 0
  117110. };
  117111. static long _huff_lengthlist_line_128x11_class1[] = {
  117112. 1, 6, 3, 7, 2, 4, 5, 7,
  117113. };
  117114. static static_codebook _huff_book_line_128x11_class1 = {
  117115. 1, 8,
  117116. _huff_lengthlist_line_128x11_class1,
  117117. 0, 0, 0, 0, 0,
  117118. NULL,
  117119. NULL,
  117120. NULL,
  117121. NULL,
  117122. 0
  117123. };
  117124. static long _huff_lengthlist_line_128x11_class2[] = {
  117125. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  117126. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  117127. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  117128. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  117129. };
  117130. static static_codebook _huff_book_line_128x11_class2 = {
  117131. 1, 64,
  117132. _huff_lengthlist_line_128x11_class2,
  117133. 0, 0, 0, 0, 0,
  117134. NULL,
  117135. NULL,
  117136. NULL,
  117137. NULL,
  117138. 0
  117139. };
  117140. static long _huff_lengthlist_line_128x11_class3[] = {
  117141. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  117142. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  117143. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  117144. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  117145. };
  117146. static static_codebook _huff_book_line_128x11_class3 = {
  117147. 1, 64,
  117148. _huff_lengthlist_line_128x11_class3,
  117149. 0, 0, 0, 0, 0,
  117150. NULL,
  117151. NULL,
  117152. NULL,
  117153. NULL,
  117154. 0
  117155. };
  117156. static long _huff_lengthlist_line_128x11_0sub0[] = {
  117157. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117158. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  117159. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  117160. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  117161. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  117162. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  117163. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  117164. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117165. };
  117166. static static_codebook _huff_book_line_128x11_0sub0 = {
  117167. 1, 128,
  117168. _huff_lengthlist_line_128x11_0sub0,
  117169. 0, 0, 0, 0, 0,
  117170. NULL,
  117171. NULL,
  117172. NULL,
  117173. NULL,
  117174. 0
  117175. };
  117176. static long _huff_lengthlist_line_128x11_1sub0[] = {
  117177. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117178. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  117179. };
  117180. static static_codebook _huff_book_line_128x11_1sub0 = {
  117181. 1, 32,
  117182. _huff_lengthlist_line_128x11_1sub0,
  117183. 0, 0, 0, 0, 0,
  117184. NULL,
  117185. NULL,
  117186. NULL,
  117187. NULL,
  117188. 0
  117189. };
  117190. static long _huff_lengthlist_line_128x11_1sub1[] = {
  117191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117193. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117194. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  117195. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  117196. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  117197. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  117198. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  117199. };
  117200. static static_codebook _huff_book_line_128x11_1sub1 = {
  117201. 1, 128,
  117202. _huff_lengthlist_line_128x11_1sub1,
  117203. 0, 0, 0, 0, 0,
  117204. NULL,
  117205. NULL,
  117206. NULL,
  117207. NULL,
  117208. 0
  117209. };
  117210. static long _huff_lengthlist_line_128x11_2sub1[] = {
  117211. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  117212. 5, 5,
  117213. };
  117214. static static_codebook _huff_book_line_128x11_2sub1 = {
  117215. 1, 18,
  117216. _huff_lengthlist_line_128x11_2sub1,
  117217. 0, 0, 0, 0, 0,
  117218. NULL,
  117219. NULL,
  117220. NULL,
  117221. NULL,
  117222. 0
  117223. };
  117224. static long _huff_lengthlist_line_128x11_2sub2[] = {
  117225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117226. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  117227. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  117228. 8,11,
  117229. };
  117230. static static_codebook _huff_book_line_128x11_2sub2 = {
  117231. 1, 50,
  117232. _huff_lengthlist_line_128x11_2sub2,
  117233. 0, 0, 0, 0, 0,
  117234. NULL,
  117235. NULL,
  117236. NULL,
  117237. NULL,
  117238. 0
  117239. };
  117240. static long _huff_lengthlist_line_128x11_2sub3[] = {
  117241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117244. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  117245. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117246. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117247. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117248. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117249. };
  117250. static static_codebook _huff_book_line_128x11_2sub3 = {
  117251. 1, 128,
  117252. _huff_lengthlist_line_128x11_2sub3,
  117253. 0, 0, 0, 0, 0,
  117254. NULL,
  117255. NULL,
  117256. NULL,
  117257. NULL,
  117258. 0
  117259. };
  117260. static long _huff_lengthlist_line_128x11_3sub1[] = {
  117261. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  117262. 5, 4,
  117263. };
  117264. static static_codebook _huff_book_line_128x11_3sub1 = {
  117265. 1, 18,
  117266. _huff_lengthlist_line_128x11_3sub1,
  117267. 0, 0, 0, 0, 0,
  117268. NULL,
  117269. NULL,
  117270. NULL,
  117271. NULL,
  117272. 0
  117273. };
  117274. static long _huff_lengthlist_line_128x11_3sub2[] = {
  117275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117276. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  117277. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  117278. 12, 6,
  117279. };
  117280. static static_codebook _huff_book_line_128x11_3sub2 = {
  117281. 1, 50,
  117282. _huff_lengthlist_line_128x11_3sub2,
  117283. 0, 0, 0, 0, 0,
  117284. NULL,
  117285. NULL,
  117286. NULL,
  117287. NULL,
  117288. 0
  117289. };
  117290. static long _huff_lengthlist_line_128x11_3sub3[] = {
  117291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117294. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  117295. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  117296. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117297. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117298. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  117299. };
  117300. static static_codebook _huff_book_line_128x11_3sub3 = {
  117301. 1, 128,
  117302. _huff_lengthlist_line_128x11_3sub3,
  117303. 0, 0, 0, 0, 0,
  117304. NULL,
  117305. NULL,
  117306. NULL,
  117307. NULL,
  117308. 0
  117309. };
  117310. static long _huff_lengthlist_line_128x17_class1[] = {
  117311. 1, 3, 4, 7, 2, 5, 6, 7,
  117312. };
  117313. static static_codebook _huff_book_line_128x17_class1 = {
  117314. 1, 8,
  117315. _huff_lengthlist_line_128x17_class1,
  117316. 0, 0, 0, 0, 0,
  117317. NULL,
  117318. NULL,
  117319. NULL,
  117320. NULL,
  117321. 0
  117322. };
  117323. static long _huff_lengthlist_line_128x17_class2[] = {
  117324. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  117325. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  117326. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  117327. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117328. };
  117329. static static_codebook _huff_book_line_128x17_class2 = {
  117330. 1, 64,
  117331. _huff_lengthlist_line_128x17_class2,
  117332. 0, 0, 0, 0, 0,
  117333. NULL,
  117334. NULL,
  117335. NULL,
  117336. NULL,
  117337. 0
  117338. };
  117339. static long _huff_lengthlist_line_128x17_class3[] = {
  117340. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  117341. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  117342. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  117343. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  117344. };
  117345. static static_codebook _huff_book_line_128x17_class3 = {
  117346. 1, 64,
  117347. _huff_lengthlist_line_128x17_class3,
  117348. 0, 0, 0, 0, 0,
  117349. NULL,
  117350. NULL,
  117351. NULL,
  117352. NULL,
  117353. 0
  117354. };
  117355. static long _huff_lengthlist_line_128x17_0sub0[] = {
  117356. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117357. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  117358. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  117359. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  117360. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  117361. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  117362. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  117363. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117364. };
  117365. static static_codebook _huff_book_line_128x17_0sub0 = {
  117366. 1, 128,
  117367. _huff_lengthlist_line_128x17_0sub0,
  117368. 0, 0, 0, 0, 0,
  117369. NULL,
  117370. NULL,
  117371. NULL,
  117372. NULL,
  117373. 0
  117374. };
  117375. static long _huff_lengthlist_line_128x17_1sub0[] = {
  117376. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117377. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  117378. };
  117379. static static_codebook _huff_book_line_128x17_1sub0 = {
  117380. 1, 32,
  117381. _huff_lengthlist_line_128x17_1sub0,
  117382. 0, 0, 0, 0, 0,
  117383. NULL,
  117384. NULL,
  117385. NULL,
  117386. NULL,
  117387. 0
  117388. };
  117389. static long _huff_lengthlist_line_128x17_1sub1[] = {
  117390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117392. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  117393. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  117394. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  117395. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  117396. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  117397. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  117398. };
  117399. static static_codebook _huff_book_line_128x17_1sub1 = {
  117400. 1, 128,
  117401. _huff_lengthlist_line_128x17_1sub1,
  117402. 0, 0, 0, 0, 0,
  117403. NULL,
  117404. NULL,
  117405. NULL,
  117406. NULL,
  117407. 0
  117408. };
  117409. static long _huff_lengthlist_line_128x17_2sub1[] = {
  117410. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  117411. 9, 4,
  117412. };
  117413. static static_codebook _huff_book_line_128x17_2sub1 = {
  117414. 1, 18,
  117415. _huff_lengthlist_line_128x17_2sub1,
  117416. 0, 0, 0, 0, 0,
  117417. NULL,
  117418. NULL,
  117419. NULL,
  117420. NULL,
  117421. 0
  117422. };
  117423. static long _huff_lengthlist_line_128x17_2sub2[] = {
  117424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117425. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  117426. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  117427. 13,13,
  117428. };
  117429. static static_codebook _huff_book_line_128x17_2sub2 = {
  117430. 1, 50,
  117431. _huff_lengthlist_line_128x17_2sub2,
  117432. 0, 0, 0, 0, 0,
  117433. NULL,
  117434. NULL,
  117435. NULL,
  117436. NULL,
  117437. 0
  117438. };
  117439. static long _huff_lengthlist_line_128x17_2sub3[] = {
  117440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117443. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117444. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  117445. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117446. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117447. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117448. };
  117449. static static_codebook _huff_book_line_128x17_2sub3 = {
  117450. 1, 128,
  117451. _huff_lengthlist_line_128x17_2sub3,
  117452. 0, 0, 0, 0, 0,
  117453. NULL,
  117454. NULL,
  117455. NULL,
  117456. NULL,
  117457. 0
  117458. };
  117459. static long _huff_lengthlist_line_128x17_3sub1[] = {
  117460. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  117461. 6, 4,
  117462. };
  117463. static static_codebook _huff_book_line_128x17_3sub1 = {
  117464. 1, 18,
  117465. _huff_lengthlist_line_128x17_3sub1,
  117466. 0, 0, 0, 0, 0,
  117467. NULL,
  117468. NULL,
  117469. NULL,
  117470. NULL,
  117471. 0
  117472. };
  117473. static long _huff_lengthlist_line_128x17_3sub2[] = {
  117474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117475. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117476. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  117477. 10, 8,
  117478. };
  117479. static static_codebook _huff_book_line_128x17_3sub2 = {
  117480. 1, 50,
  117481. _huff_lengthlist_line_128x17_3sub2,
  117482. 0, 0, 0, 0, 0,
  117483. NULL,
  117484. NULL,
  117485. NULL,
  117486. NULL,
  117487. 0
  117488. };
  117489. static long _huff_lengthlist_line_128x17_3sub3[] = {
  117490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117493. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  117494. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  117495. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117498. };
  117499. static static_codebook _huff_book_line_128x17_3sub3 = {
  117500. 1, 128,
  117501. _huff_lengthlist_line_128x17_3sub3,
  117502. 0, 0, 0, 0, 0,
  117503. NULL,
  117504. NULL,
  117505. NULL,
  117506. NULL,
  117507. 0
  117508. };
  117509. static long _huff_lengthlist_line_1024x27_class1[] = {
  117510. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  117511. };
  117512. static static_codebook _huff_book_line_1024x27_class1 = {
  117513. 1, 16,
  117514. _huff_lengthlist_line_1024x27_class1,
  117515. 0, 0, 0, 0, 0,
  117516. NULL,
  117517. NULL,
  117518. NULL,
  117519. NULL,
  117520. 0
  117521. };
  117522. static long _huff_lengthlist_line_1024x27_class2[] = {
  117523. 1, 4, 2, 6, 3, 7, 5, 7,
  117524. };
  117525. static static_codebook _huff_book_line_1024x27_class2 = {
  117526. 1, 8,
  117527. _huff_lengthlist_line_1024x27_class2,
  117528. 0, 0, 0, 0, 0,
  117529. NULL,
  117530. NULL,
  117531. NULL,
  117532. NULL,
  117533. 0
  117534. };
  117535. static long _huff_lengthlist_line_1024x27_class3[] = {
  117536. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  117537. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  117538. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  117539. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  117540. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  117541. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  117542. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  117543. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  117544. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  117545. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  117546. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  117547. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117548. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  117549. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  117550. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  117551. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117552. };
  117553. static static_codebook _huff_book_line_1024x27_class3 = {
  117554. 1, 256,
  117555. _huff_lengthlist_line_1024x27_class3,
  117556. 0, 0, 0, 0, 0,
  117557. NULL,
  117558. NULL,
  117559. NULL,
  117560. NULL,
  117561. 0
  117562. };
  117563. static long _huff_lengthlist_line_1024x27_class4[] = {
  117564. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  117565. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  117566. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  117567. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  117568. };
  117569. static static_codebook _huff_book_line_1024x27_class4 = {
  117570. 1, 64,
  117571. _huff_lengthlist_line_1024x27_class4,
  117572. 0, 0, 0, 0, 0,
  117573. NULL,
  117574. NULL,
  117575. NULL,
  117576. NULL,
  117577. 0
  117578. };
  117579. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  117580. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117581. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  117582. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  117583. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  117584. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  117585. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  117586. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  117587. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  117588. };
  117589. static static_codebook _huff_book_line_1024x27_0sub0 = {
  117590. 1, 128,
  117591. _huff_lengthlist_line_1024x27_0sub0,
  117592. 0, 0, 0, 0, 0,
  117593. NULL,
  117594. NULL,
  117595. NULL,
  117596. NULL,
  117597. 0
  117598. };
  117599. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  117600. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  117601. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  117602. };
  117603. static static_codebook _huff_book_line_1024x27_1sub0 = {
  117604. 1, 32,
  117605. _huff_lengthlist_line_1024x27_1sub0,
  117606. 0, 0, 0, 0, 0,
  117607. NULL,
  117608. NULL,
  117609. NULL,
  117610. NULL,
  117611. 0
  117612. };
  117613. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  117614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117616. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  117617. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  117618. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  117619. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  117620. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  117621. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  117622. };
  117623. static static_codebook _huff_book_line_1024x27_1sub1 = {
  117624. 1, 128,
  117625. _huff_lengthlist_line_1024x27_1sub1,
  117626. 0, 0, 0, 0, 0,
  117627. NULL,
  117628. NULL,
  117629. NULL,
  117630. NULL,
  117631. 0
  117632. };
  117633. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  117634. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117635. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  117636. };
  117637. static static_codebook _huff_book_line_1024x27_2sub0 = {
  117638. 1, 32,
  117639. _huff_lengthlist_line_1024x27_2sub0,
  117640. 0, 0, 0, 0, 0,
  117641. NULL,
  117642. NULL,
  117643. NULL,
  117644. NULL,
  117645. 0
  117646. };
  117647. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  117648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117650. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  117651. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  117652. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  117653. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  117654. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  117655. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  117656. };
  117657. static static_codebook _huff_book_line_1024x27_2sub1 = {
  117658. 1, 128,
  117659. _huff_lengthlist_line_1024x27_2sub1,
  117660. 0, 0, 0, 0, 0,
  117661. NULL,
  117662. NULL,
  117663. NULL,
  117664. NULL,
  117665. 0
  117666. };
  117667. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  117668. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  117669. 5, 5,
  117670. };
  117671. static static_codebook _huff_book_line_1024x27_3sub1 = {
  117672. 1, 18,
  117673. _huff_lengthlist_line_1024x27_3sub1,
  117674. 0, 0, 0, 0, 0,
  117675. NULL,
  117676. NULL,
  117677. NULL,
  117678. NULL,
  117679. 0
  117680. };
  117681. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  117682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117683. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  117684. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  117685. 9,11,
  117686. };
  117687. static static_codebook _huff_book_line_1024x27_3sub2 = {
  117688. 1, 50,
  117689. _huff_lengthlist_line_1024x27_3sub2,
  117690. 0, 0, 0, 0, 0,
  117691. NULL,
  117692. NULL,
  117693. NULL,
  117694. NULL,
  117695. 0
  117696. };
  117697. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  117698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117701. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  117702. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  117703. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117704. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117705. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117706. };
  117707. static static_codebook _huff_book_line_1024x27_3sub3 = {
  117708. 1, 128,
  117709. _huff_lengthlist_line_1024x27_3sub3,
  117710. 0, 0, 0, 0, 0,
  117711. NULL,
  117712. NULL,
  117713. NULL,
  117714. NULL,
  117715. 0
  117716. };
  117717. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  117718. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  117719. 5, 4,
  117720. };
  117721. static static_codebook _huff_book_line_1024x27_4sub1 = {
  117722. 1, 18,
  117723. _huff_lengthlist_line_1024x27_4sub1,
  117724. 0, 0, 0, 0, 0,
  117725. NULL,
  117726. NULL,
  117727. NULL,
  117728. NULL,
  117729. 0
  117730. };
  117731. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  117732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117733. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  117734. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  117735. 9,12,
  117736. };
  117737. static static_codebook _huff_book_line_1024x27_4sub2 = {
  117738. 1, 50,
  117739. _huff_lengthlist_line_1024x27_4sub2,
  117740. 0, 0, 0, 0, 0,
  117741. NULL,
  117742. NULL,
  117743. NULL,
  117744. NULL,
  117745. 0
  117746. };
  117747. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  117748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117751. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  117752. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  117753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117755. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  117756. };
  117757. static static_codebook _huff_book_line_1024x27_4sub3 = {
  117758. 1, 128,
  117759. _huff_lengthlist_line_1024x27_4sub3,
  117760. 0, 0, 0, 0, 0,
  117761. NULL,
  117762. NULL,
  117763. NULL,
  117764. NULL,
  117765. 0
  117766. };
  117767. static long _huff_lengthlist_line_2048x27_class1[] = {
  117768. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  117769. };
  117770. static static_codebook _huff_book_line_2048x27_class1 = {
  117771. 1, 16,
  117772. _huff_lengthlist_line_2048x27_class1,
  117773. 0, 0, 0, 0, 0,
  117774. NULL,
  117775. NULL,
  117776. NULL,
  117777. NULL,
  117778. 0
  117779. };
  117780. static long _huff_lengthlist_line_2048x27_class2[] = {
  117781. 1, 2, 3, 6, 4, 7, 5, 7,
  117782. };
  117783. static static_codebook _huff_book_line_2048x27_class2 = {
  117784. 1, 8,
  117785. _huff_lengthlist_line_2048x27_class2,
  117786. 0, 0, 0, 0, 0,
  117787. NULL,
  117788. NULL,
  117789. NULL,
  117790. NULL,
  117791. 0
  117792. };
  117793. static long _huff_lengthlist_line_2048x27_class3[] = {
  117794. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  117795. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  117796. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  117797. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  117798. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  117799. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  117800. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  117801. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  117802. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  117803. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  117804. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  117805. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117806. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  117807. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  117808. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117809. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117810. };
  117811. static static_codebook _huff_book_line_2048x27_class3 = {
  117812. 1, 256,
  117813. _huff_lengthlist_line_2048x27_class3,
  117814. 0, 0, 0, 0, 0,
  117815. NULL,
  117816. NULL,
  117817. NULL,
  117818. NULL,
  117819. 0
  117820. };
  117821. static long _huff_lengthlist_line_2048x27_class4[] = {
  117822. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  117823. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  117824. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  117825. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  117826. };
  117827. static static_codebook _huff_book_line_2048x27_class4 = {
  117828. 1, 64,
  117829. _huff_lengthlist_line_2048x27_class4,
  117830. 0, 0, 0, 0, 0,
  117831. NULL,
  117832. NULL,
  117833. NULL,
  117834. NULL,
  117835. 0
  117836. };
  117837. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  117838. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117839. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  117840. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  117841. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  117842. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  117843. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  117844. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  117845. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  117846. };
  117847. static static_codebook _huff_book_line_2048x27_0sub0 = {
  117848. 1, 128,
  117849. _huff_lengthlist_line_2048x27_0sub0,
  117850. 0, 0, 0, 0, 0,
  117851. NULL,
  117852. NULL,
  117853. NULL,
  117854. NULL,
  117855. 0
  117856. };
  117857. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  117858. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117859. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  117860. };
  117861. static static_codebook _huff_book_line_2048x27_1sub0 = {
  117862. 1, 32,
  117863. _huff_lengthlist_line_2048x27_1sub0,
  117864. 0, 0, 0, 0, 0,
  117865. NULL,
  117866. NULL,
  117867. NULL,
  117868. NULL,
  117869. 0
  117870. };
  117871. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  117872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117874. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  117875. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  117876. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  117877. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  117878. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  117879. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  117880. };
  117881. static static_codebook _huff_book_line_2048x27_1sub1 = {
  117882. 1, 128,
  117883. _huff_lengthlist_line_2048x27_1sub1,
  117884. 0, 0, 0, 0, 0,
  117885. NULL,
  117886. NULL,
  117887. NULL,
  117888. NULL,
  117889. 0
  117890. };
  117891. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  117892. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117893. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  117894. };
  117895. static static_codebook _huff_book_line_2048x27_2sub0 = {
  117896. 1, 32,
  117897. _huff_lengthlist_line_2048x27_2sub0,
  117898. 0, 0, 0, 0, 0,
  117899. NULL,
  117900. NULL,
  117901. NULL,
  117902. NULL,
  117903. 0
  117904. };
  117905. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  117906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117908. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  117909. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  117910. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  117911. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  117912. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  117913. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117914. };
  117915. static static_codebook _huff_book_line_2048x27_2sub1 = {
  117916. 1, 128,
  117917. _huff_lengthlist_line_2048x27_2sub1,
  117918. 0, 0, 0, 0, 0,
  117919. NULL,
  117920. NULL,
  117921. NULL,
  117922. NULL,
  117923. 0
  117924. };
  117925. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  117926. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  117927. 5, 5,
  117928. };
  117929. static static_codebook _huff_book_line_2048x27_3sub1 = {
  117930. 1, 18,
  117931. _huff_lengthlist_line_2048x27_3sub1,
  117932. 0, 0, 0, 0, 0,
  117933. NULL,
  117934. NULL,
  117935. NULL,
  117936. NULL,
  117937. 0
  117938. };
  117939. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  117940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117941. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  117942. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  117943. 10,12,
  117944. };
  117945. static static_codebook _huff_book_line_2048x27_3sub2 = {
  117946. 1, 50,
  117947. _huff_lengthlist_line_2048x27_3sub2,
  117948. 0, 0, 0, 0, 0,
  117949. NULL,
  117950. NULL,
  117951. NULL,
  117952. NULL,
  117953. 0
  117954. };
  117955. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  117956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117959. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  117960. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117961. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117962. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117963. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117964. };
  117965. static static_codebook _huff_book_line_2048x27_3sub3 = {
  117966. 1, 128,
  117967. _huff_lengthlist_line_2048x27_3sub3,
  117968. 0, 0, 0, 0, 0,
  117969. NULL,
  117970. NULL,
  117971. NULL,
  117972. NULL,
  117973. 0
  117974. };
  117975. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  117976. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  117977. 4, 5,
  117978. };
  117979. static static_codebook _huff_book_line_2048x27_4sub1 = {
  117980. 1, 18,
  117981. _huff_lengthlist_line_2048x27_4sub1,
  117982. 0, 0, 0, 0, 0,
  117983. NULL,
  117984. NULL,
  117985. NULL,
  117986. NULL,
  117987. 0
  117988. };
  117989. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  117990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117991. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  117992. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  117993. 10,10,
  117994. };
  117995. static static_codebook _huff_book_line_2048x27_4sub2 = {
  117996. 1, 50,
  117997. _huff_lengthlist_line_2048x27_4sub2,
  117998. 0, 0, 0, 0, 0,
  117999. NULL,
  118000. NULL,
  118001. NULL,
  118002. NULL,
  118003. 0
  118004. };
  118005. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  118006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118009. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  118010. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  118011. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118012. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118013. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118014. };
  118015. static static_codebook _huff_book_line_2048x27_4sub3 = {
  118016. 1, 128,
  118017. _huff_lengthlist_line_2048x27_4sub3,
  118018. 0, 0, 0, 0, 0,
  118019. NULL,
  118020. NULL,
  118021. NULL,
  118022. NULL,
  118023. 0
  118024. };
  118025. static long _huff_lengthlist_line_256x4low_class0[] = {
  118026. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  118027. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  118028. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  118029. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  118030. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  118031. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  118032. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  118033. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  118034. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  118035. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  118036. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  118037. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  118038. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  118039. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  118040. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  118041. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  118042. };
  118043. static static_codebook _huff_book_line_256x4low_class0 = {
  118044. 1, 256,
  118045. _huff_lengthlist_line_256x4low_class0,
  118046. 0, 0, 0, 0, 0,
  118047. NULL,
  118048. NULL,
  118049. NULL,
  118050. NULL,
  118051. 0
  118052. };
  118053. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  118054. 1, 3, 2, 3,
  118055. };
  118056. static static_codebook _huff_book_line_256x4low_0sub0 = {
  118057. 1, 4,
  118058. _huff_lengthlist_line_256x4low_0sub0,
  118059. 0, 0, 0, 0, 0,
  118060. NULL,
  118061. NULL,
  118062. NULL,
  118063. NULL,
  118064. 0
  118065. };
  118066. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  118067. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  118068. };
  118069. static static_codebook _huff_book_line_256x4low_0sub1 = {
  118070. 1, 10,
  118071. _huff_lengthlist_line_256x4low_0sub1,
  118072. 0, 0, 0, 0, 0,
  118073. NULL,
  118074. NULL,
  118075. NULL,
  118076. NULL,
  118077. 0
  118078. };
  118079. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  118080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  118081. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  118082. };
  118083. static static_codebook _huff_book_line_256x4low_0sub2 = {
  118084. 1, 25,
  118085. _huff_lengthlist_line_256x4low_0sub2,
  118086. 0, 0, 0, 0, 0,
  118087. NULL,
  118088. NULL,
  118089. NULL,
  118090. NULL,
  118091. 0
  118092. };
  118093. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  118094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  118096. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  118097. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  118098. };
  118099. static static_codebook _huff_book_line_256x4low_0sub3 = {
  118100. 1, 64,
  118101. _huff_lengthlist_line_256x4low_0sub3,
  118102. 0, 0, 0, 0, 0,
  118103. NULL,
  118104. NULL,
  118105. NULL,
  118106. NULL,
  118107. 0
  118108. };
  118109. /********* End of inlined file: floor_books.h *********/
  118110. static static_codebook *_floor_128x4_books[]={
  118111. &_huff_book_line_128x4_class0,
  118112. &_huff_book_line_128x4_0sub0,
  118113. &_huff_book_line_128x4_0sub1,
  118114. &_huff_book_line_128x4_0sub2,
  118115. &_huff_book_line_128x4_0sub3,
  118116. };
  118117. static static_codebook *_floor_256x4_books[]={
  118118. &_huff_book_line_256x4_class0,
  118119. &_huff_book_line_256x4_0sub0,
  118120. &_huff_book_line_256x4_0sub1,
  118121. &_huff_book_line_256x4_0sub2,
  118122. &_huff_book_line_256x4_0sub3,
  118123. };
  118124. static static_codebook *_floor_128x7_books[]={
  118125. &_huff_book_line_128x7_class0,
  118126. &_huff_book_line_128x7_class1,
  118127. &_huff_book_line_128x7_0sub1,
  118128. &_huff_book_line_128x7_0sub2,
  118129. &_huff_book_line_128x7_0sub3,
  118130. &_huff_book_line_128x7_1sub1,
  118131. &_huff_book_line_128x7_1sub2,
  118132. &_huff_book_line_128x7_1sub3,
  118133. };
  118134. static static_codebook *_floor_256x7_books[]={
  118135. &_huff_book_line_256x7_class0,
  118136. &_huff_book_line_256x7_class1,
  118137. &_huff_book_line_256x7_0sub1,
  118138. &_huff_book_line_256x7_0sub2,
  118139. &_huff_book_line_256x7_0sub3,
  118140. &_huff_book_line_256x7_1sub1,
  118141. &_huff_book_line_256x7_1sub2,
  118142. &_huff_book_line_256x7_1sub3,
  118143. };
  118144. static static_codebook *_floor_128x11_books[]={
  118145. &_huff_book_line_128x11_class1,
  118146. &_huff_book_line_128x11_class2,
  118147. &_huff_book_line_128x11_class3,
  118148. &_huff_book_line_128x11_0sub0,
  118149. &_huff_book_line_128x11_1sub0,
  118150. &_huff_book_line_128x11_1sub1,
  118151. &_huff_book_line_128x11_2sub1,
  118152. &_huff_book_line_128x11_2sub2,
  118153. &_huff_book_line_128x11_2sub3,
  118154. &_huff_book_line_128x11_3sub1,
  118155. &_huff_book_line_128x11_3sub2,
  118156. &_huff_book_line_128x11_3sub3,
  118157. };
  118158. static static_codebook *_floor_128x17_books[]={
  118159. &_huff_book_line_128x17_class1,
  118160. &_huff_book_line_128x17_class2,
  118161. &_huff_book_line_128x17_class3,
  118162. &_huff_book_line_128x17_0sub0,
  118163. &_huff_book_line_128x17_1sub0,
  118164. &_huff_book_line_128x17_1sub1,
  118165. &_huff_book_line_128x17_2sub1,
  118166. &_huff_book_line_128x17_2sub2,
  118167. &_huff_book_line_128x17_2sub3,
  118168. &_huff_book_line_128x17_3sub1,
  118169. &_huff_book_line_128x17_3sub2,
  118170. &_huff_book_line_128x17_3sub3,
  118171. };
  118172. static static_codebook *_floor_256x4low_books[]={
  118173. &_huff_book_line_256x4low_class0,
  118174. &_huff_book_line_256x4low_0sub0,
  118175. &_huff_book_line_256x4low_0sub1,
  118176. &_huff_book_line_256x4low_0sub2,
  118177. &_huff_book_line_256x4low_0sub3,
  118178. };
  118179. static static_codebook *_floor_1024x27_books[]={
  118180. &_huff_book_line_1024x27_class1,
  118181. &_huff_book_line_1024x27_class2,
  118182. &_huff_book_line_1024x27_class3,
  118183. &_huff_book_line_1024x27_class4,
  118184. &_huff_book_line_1024x27_0sub0,
  118185. &_huff_book_line_1024x27_1sub0,
  118186. &_huff_book_line_1024x27_1sub1,
  118187. &_huff_book_line_1024x27_2sub0,
  118188. &_huff_book_line_1024x27_2sub1,
  118189. &_huff_book_line_1024x27_3sub1,
  118190. &_huff_book_line_1024x27_3sub2,
  118191. &_huff_book_line_1024x27_3sub3,
  118192. &_huff_book_line_1024x27_4sub1,
  118193. &_huff_book_line_1024x27_4sub2,
  118194. &_huff_book_line_1024x27_4sub3,
  118195. };
  118196. static static_codebook *_floor_2048x27_books[]={
  118197. &_huff_book_line_2048x27_class1,
  118198. &_huff_book_line_2048x27_class2,
  118199. &_huff_book_line_2048x27_class3,
  118200. &_huff_book_line_2048x27_class4,
  118201. &_huff_book_line_2048x27_0sub0,
  118202. &_huff_book_line_2048x27_1sub0,
  118203. &_huff_book_line_2048x27_1sub1,
  118204. &_huff_book_line_2048x27_2sub0,
  118205. &_huff_book_line_2048x27_2sub1,
  118206. &_huff_book_line_2048x27_3sub1,
  118207. &_huff_book_line_2048x27_3sub2,
  118208. &_huff_book_line_2048x27_3sub3,
  118209. &_huff_book_line_2048x27_4sub1,
  118210. &_huff_book_line_2048x27_4sub2,
  118211. &_huff_book_line_2048x27_4sub3,
  118212. };
  118213. static static_codebook *_floor_512x17_books[]={
  118214. &_huff_book_line_512x17_class1,
  118215. &_huff_book_line_512x17_class2,
  118216. &_huff_book_line_512x17_class3,
  118217. &_huff_book_line_512x17_0sub0,
  118218. &_huff_book_line_512x17_1sub0,
  118219. &_huff_book_line_512x17_1sub1,
  118220. &_huff_book_line_512x17_2sub1,
  118221. &_huff_book_line_512x17_2sub2,
  118222. &_huff_book_line_512x17_2sub3,
  118223. &_huff_book_line_512x17_3sub1,
  118224. &_huff_book_line_512x17_3sub2,
  118225. &_huff_book_line_512x17_3sub3,
  118226. };
  118227. static static_codebook **_floor_books[10]={
  118228. _floor_128x4_books,
  118229. _floor_256x4_books,
  118230. _floor_128x7_books,
  118231. _floor_256x7_books,
  118232. _floor_128x11_books,
  118233. _floor_128x17_books,
  118234. _floor_256x4low_books,
  118235. _floor_1024x27_books,
  118236. _floor_2048x27_books,
  118237. _floor_512x17_books,
  118238. };
  118239. static vorbis_info_floor1 _floor[10]={
  118240. /* 128 x 4 */
  118241. {
  118242. 1,{0},{4},{2},{0},
  118243. {{1,2,3,4}},
  118244. 4,{0,128, 33,8,16,70},
  118245. 60,30,500, 1.,18., -1
  118246. },
  118247. /* 256 x 4 */
  118248. {
  118249. 1,{0},{4},{2},{0},
  118250. {{1,2,3,4}},
  118251. 4,{0,256, 66,16,32,140},
  118252. 60,30,500, 1.,18., -1
  118253. },
  118254. /* 128 x 7 */
  118255. {
  118256. 2,{0,1},{3,4},{2,2},{0,1},
  118257. {{-1,2,3,4},{-1,5,6,7}},
  118258. 4,{0,128, 14,4,58, 2,8,28,90},
  118259. 60,30,500, 1.,18., -1
  118260. },
  118261. /* 256 x 7 */
  118262. {
  118263. 2,{0,1},{3,4},{2,2},{0,1},
  118264. {{-1,2,3,4},{-1,5,6,7}},
  118265. 4,{0,256, 28,8,116, 4,16,56,180},
  118266. 60,30,500, 1.,18., -1
  118267. },
  118268. /* 128 x 11 */
  118269. {
  118270. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118271. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118272. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  118273. 60,30,500, 1,18., -1
  118274. },
  118275. /* 128 x 17 */
  118276. {
  118277. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118278. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118279. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  118280. 60,30,500, 1,18., -1
  118281. },
  118282. /* 256 x 4 (low bitrate version) */
  118283. {
  118284. 1,{0},{4},{2},{0},
  118285. {{1,2,3,4}},
  118286. 4,{0,256, 66,16,32,140},
  118287. 60,30,500, 1.,18., -1
  118288. },
  118289. /* 1024 x 27 */
  118290. {
  118291. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118292. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118293. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  118294. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  118295. 60,30,500, 3,18., -1 /* lowpass */
  118296. },
  118297. /* 2048 x 27 */
  118298. {
  118299. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118300. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118301. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  118302. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  118303. 60,30,500, 3,18., -1 /* lowpass */
  118304. },
  118305. /* 512 x 17 */
  118306. {
  118307. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118308. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118309. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  118310. 7,23,39, 55,79,110, 156,232,360},
  118311. 60,30,500, 1,18., -1 /* lowpass! */
  118312. },
  118313. };
  118314. /********* End of inlined file: floor_all.h *********/
  118315. /********* Start of inlined file: residue_44.h *********/
  118316. /********* Start of inlined file: res_books_stereo.h *********/
  118317. static long _vq_quantlist__16c0_s_p1_0[] = {
  118318. 1,
  118319. 0,
  118320. 2,
  118321. };
  118322. static long _vq_lengthlist__16c0_s_p1_0[] = {
  118323. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  118324. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118328. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  118329. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118333. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118334. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  118369. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  118370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  118374. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  118375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  118379. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  118380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118414. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  118415. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118419. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  118420. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  118421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118424. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  118425. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  118426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118733. 0,
  118734. };
  118735. static float _vq_quantthresh__16c0_s_p1_0[] = {
  118736. -0.5, 0.5,
  118737. };
  118738. static long _vq_quantmap__16c0_s_p1_0[] = {
  118739. 1, 0, 2,
  118740. };
  118741. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  118742. _vq_quantthresh__16c0_s_p1_0,
  118743. _vq_quantmap__16c0_s_p1_0,
  118744. 3,
  118745. 3
  118746. };
  118747. static static_codebook _16c0_s_p1_0 = {
  118748. 8, 6561,
  118749. _vq_lengthlist__16c0_s_p1_0,
  118750. 1, -535822336, 1611661312, 2, 0,
  118751. _vq_quantlist__16c0_s_p1_0,
  118752. NULL,
  118753. &_vq_auxt__16c0_s_p1_0,
  118754. NULL,
  118755. 0
  118756. };
  118757. static long _vq_quantlist__16c0_s_p2_0[] = {
  118758. 2,
  118759. 1,
  118760. 3,
  118761. 0,
  118762. 4,
  118763. };
  118764. static long _vq_lengthlist__16c0_s_p2_0[] = {
  118765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118804. 0,
  118805. };
  118806. static float _vq_quantthresh__16c0_s_p2_0[] = {
  118807. -1.5, -0.5, 0.5, 1.5,
  118808. };
  118809. static long _vq_quantmap__16c0_s_p2_0[] = {
  118810. 3, 1, 0, 2, 4,
  118811. };
  118812. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  118813. _vq_quantthresh__16c0_s_p2_0,
  118814. _vq_quantmap__16c0_s_p2_0,
  118815. 5,
  118816. 5
  118817. };
  118818. static static_codebook _16c0_s_p2_0 = {
  118819. 4, 625,
  118820. _vq_lengthlist__16c0_s_p2_0,
  118821. 1, -533725184, 1611661312, 3, 0,
  118822. _vq_quantlist__16c0_s_p2_0,
  118823. NULL,
  118824. &_vq_auxt__16c0_s_p2_0,
  118825. NULL,
  118826. 0
  118827. };
  118828. static long _vq_quantlist__16c0_s_p3_0[] = {
  118829. 2,
  118830. 1,
  118831. 3,
  118832. 0,
  118833. 4,
  118834. };
  118835. static long _vq_lengthlist__16c0_s_p3_0[] = {
  118836. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  118838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118839. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  118841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118842. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118875. 0,
  118876. };
  118877. static float _vq_quantthresh__16c0_s_p3_0[] = {
  118878. -1.5, -0.5, 0.5, 1.5,
  118879. };
  118880. static long _vq_quantmap__16c0_s_p3_0[] = {
  118881. 3, 1, 0, 2, 4,
  118882. };
  118883. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  118884. _vq_quantthresh__16c0_s_p3_0,
  118885. _vq_quantmap__16c0_s_p3_0,
  118886. 5,
  118887. 5
  118888. };
  118889. static static_codebook _16c0_s_p3_0 = {
  118890. 4, 625,
  118891. _vq_lengthlist__16c0_s_p3_0,
  118892. 1, -533725184, 1611661312, 3, 0,
  118893. _vq_quantlist__16c0_s_p3_0,
  118894. NULL,
  118895. &_vq_auxt__16c0_s_p3_0,
  118896. NULL,
  118897. 0
  118898. };
  118899. static long _vq_quantlist__16c0_s_p4_0[] = {
  118900. 4,
  118901. 3,
  118902. 5,
  118903. 2,
  118904. 6,
  118905. 1,
  118906. 7,
  118907. 0,
  118908. 8,
  118909. };
  118910. static long _vq_lengthlist__16c0_s_p4_0[] = {
  118911. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118912. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118913. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118914. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  118915. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118916. 0,
  118917. };
  118918. static float _vq_quantthresh__16c0_s_p4_0[] = {
  118919. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118920. };
  118921. static long _vq_quantmap__16c0_s_p4_0[] = {
  118922. 7, 5, 3, 1, 0, 2, 4, 6,
  118923. 8,
  118924. };
  118925. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  118926. _vq_quantthresh__16c0_s_p4_0,
  118927. _vq_quantmap__16c0_s_p4_0,
  118928. 9,
  118929. 9
  118930. };
  118931. static static_codebook _16c0_s_p4_0 = {
  118932. 2, 81,
  118933. _vq_lengthlist__16c0_s_p4_0,
  118934. 1, -531628032, 1611661312, 4, 0,
  118935. _vq_quantlist__16c0_s_p4_0,
  118936. NULL,
  118937. &_vq_auxt__16c0_s_p4_0,
  118938. NULL,
  118939. 0
  118940. };
  118941. static long _vq_quantlist__16c0_s_p5_0[] = {
  118942. 4,
  118943. 3,
  118944. 5,
  118945. 2,
  118946. 6,
  118947. 1,
  118948. 7,
  118949. 0,
  118950. 8,
  118951. };
  118952. static long _vq_lengthlist__16c0_s_p5_0[] = {
  118953. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118954. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  118955. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  118956. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  118957. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118958. 10,
  118959. };
  118960. static float _vq_quantthresh__16c0_s_p5_0[] = {
  118961. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118962. };
  118963. static long _vq_quantmap__16c0_s_p5_0[] = {
  118964. 7, 5, 3, 1, 0, 2, 4, 6,
  118965. 8,
  118966. };
  118967. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  118968. _vq_quantthresh__16c0_s_p5_0,
  118969. _vq_quantmap__16c0_s_p5_0,
  118970. 9,
  118971. 9
  118972. };
  118973. static static_codebook _16c0_s_p5_0 = {
  118974. 2, 81,
  118975. _vq_lengthlist__16c0_s_p5_0,
  118976. 1, -531628032, 1611661312, 4, 0,
  118977. _vq_quantlist__16c0_s_p5_0,
  118978. NULL,
  118979. &_vq_auxt__16c0_s_p5_0,
  118980. NULL,
  118981. 0
  118982. };
  118983. static long _vq_quantlist__16c0_s_p6_0[] = {
  118984. 8,
  118985. 7,
  118986. 9,
  118987. 6,
  118988. 10,
  118989. 5,
  118990. 11,
  118991. 4,
  118992. 12,
  118993. 3,
  118994. 13,
  118995. 2,
  118996. 14,
  118997. 1,
  118998. 15,
  118999. 0,
  119000. 16,
  119001. };
  119002. static long _vq_lengthlist__16c0_s_p6_0[] = {
  119003. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  119004. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  119005. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  119006. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  119007. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  119008. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119009. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119010. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119011. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  119012. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119013. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  119014. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  119015. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  119016. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  119017. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  119018. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  119019. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  119020. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  119021. 14,
  119022. };
  119023. static float _vq_quantthresh__16c0_s_p6_0[] = {
  119024. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119025. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119026. };
  119027. static long _vq_quantmap__16c0_s_p6_0[] = {
  119028. 15, 13, 11, 9, 7, 5, 3, 1,
  119029. 0, 2, 4, 6, 8, 10, 12, 14,
  119030. 16,
  119031. };
  119032. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  119033. _vq_quantthresh__16c0_s_p6_0,
  119034. _vq_quantmap__16c0_s_p6_0,
  119035. 17,
  119036. 17
  119037. };
  119038. static static_codebook _16c0_s_p6_0 = {
  119039. 2, 289,
  119040. _vq_lengthlist__16c0_s_p6_0,
  119041. 1, -529530880, 1611661312, 5, 0,
  119042. _vq_quantlist__16c0_s_p6_0,
  119043. NULL,
  119044. &_vq_auxt__16c0_s_p6_0,
  119045. NULL,
  119046. 0
  119047. };
  119048. static long _vq_quantlist__16c0_s_p7_0[] = {
  119049. 1,
  119050. 0,
  119051. 2,
  119052. };
  119053. static long _vq_lengthlist__16c0_s_p7_0[] = {
  119054. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  119055. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  119056. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  119057. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  119058. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  119059. 13,
  119060. };
  119061. static float _vq_quantthresh__16c0_s_p7_0[] = {
  119062. -5.5, 5.5,
  119063. };
  119064. static long _vq_quantmap__16c0_s_p7_0[] = {
  119065. 1, 0, 2,
  119066. };
  119067. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  119068. _vq_quantthresh__16c0_s_p7_0,
  119069. _vq_quantmap__16c0_s_p7_0,
  119070. 3,
  119071. 3
  119072. };
  119073. static static_codebook _16c0_s_p7_0 = {
  119074. 4, 81,
  119075. _vq_lengthlist__16c0_s_p7_0,
  119076. 1, -529137664, 1618345984, 2, 0,
  119077. _vq_quantlist__16c0_s_p7_0,
  119078. NULL,
  119079. &_vq_auxt__16c0_s_p7_0,
  119080. NULL,
  119081. 0
  119082. };
  119083. static long _vq_quantlist__16c0_s_p7_1[] = {
  119084. 5,
  119085. 4,
  119086. 6,
  119087. 3,
  119088. 7,
  119089. 2,
  119090. 8,
  119091. 1,
  119092. 9,
  119093. 0,
  119094. 10,
  119095. };
  119096. static long _vq_lengthlist__16c0_s_p7_1[] = {
  119097. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  119098. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  119099. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  119100. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  119101. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  119102. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  119103. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  119104. 11,11,11, 9, 9, 9, 9,10,10,
  119105. };
  119106. static float _vq_quantthresh__16c0_s_p7_1[] = {
  119107. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119108. 3.5, 4.5,
  119109. };
  119110. static long _vq_quantmap__16c0_s_p7_1[] = {
  119111. 9, 7, 5, 3, 1, 0, 2, 4,
  119112. 6, 8, 10,
  119113. };
  119114. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  119115. _vq_quantthresh__16c0_s_p7_1,
  119116. _vq_quantmap__16c0_s_p7_1,
  119117. 11,
  119118. 11
  119119. };
  119120. static static_codebook _16c0_s_p7_1 = {
  119121. 2, 121,
  119122. _vq_lengthlist__16c0_s_p7_1,
  119123. 1, -531365888, 1611661312, 4, 0,
  119124. _vq_quantlist__16c0_s_p7_1,
  119125. NULL,
  119126. &_vq_auxt__16c0_s_p7_1,
  119127. NULL,
  119128. 0
  119129. };
  119130. static long _vq_quantlist__16c0_s_p8_0[] = {
  119131. 6,
  119132. 5,
  119133. 7,
  119134. 4,
  119135. 8,
  119136. 3,
  119137. 9,
  119138. 2,
  119139. 10,
  119140. 1,
  119141. 11,
  119142. 0,
  119143. 12,
  119144. };
  119145. static long _vq_lengthlist__16c0_s_p8_0[] = {
  119146. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  119147. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  119148. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  119149. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  119150. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  119151. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  119152. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  119153. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  119154. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  119155. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  119156. 0,12,13,13,12,13,14,14,14,
  119157. };
  119158. static float _vq_quantthresh__16c0_s_p8_0[] = {
  119159. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119160. 12.5, 17.5, 22.5, 27.5,
  119161. };
  119162. static long _vq_quantmap__16c0_s_p8_0[] = {
  119163. 11, 9, 7, 5, 3, 1, 0, 2,
  119164. 4, 6, 8, 10, 12,
  119165. };
  119166. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  119167. _vq_quantthresh__16c0_s_p8_0,
  119168. _vq_quantmap__16c0_s_p8_0,
  119169. 13,
  119170. 13
  119171. };
  119172. static static_codebook _16c0_s_p8_0 = {
  119173. 2, 169,
  119174. _vq_lengthlist__16c0_s_p8_0,
  119175. 1, -526516224, 1616117760, 4, 0,
  119176. _vq_quantlist__16c0_s_p8_0,
  119177. NULL,
  119178. &_vq_auxt__16c0_s_p8_0,
  119179. NULL,
  119180. 0
  119181. };
  119182. static long _vq_quantlist__16c0_s_p8_1[] = {
  119183. 2,
  119184. 1,
  119185. 3,
  119186. 0,
  119187. 4,
  119188. };
  119189. static long _vq_lengthlist__16c0_s_p8_1[] = {
  119190. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  119191. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119192. };
  119193. static float _vq_quantthresh__16c0_s_p8_1[] = {
  119194. -1.5, -0.5, 0.5, 1.5,
  119195. };
  119196. static long _vq_quantmap__16c0_s_p8_1[] = {
  119197. 3, 1, 0, 2, 4,
  119198. };
  119199. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  119200. _vq_quantthresh__16c0_s_p8_1,
  119201. _vq_quantmap__16c0_s_p8_1,
  119202. 5,
  119203. 5
  119204. };
  119205. static static_codebook _16c0_s_p8_1 = {
  119206. 2, 25,
  119207. _vq_lengthlist__16c0_s_p8_1,
  119208. 1, -533725184, 1611661312, 3, 0,
  119209. _vq_quantlist__16c0_s_p8_1,
  119210. NULL,
  119211. &_vq_auxt__16c0_s_p8_1,
  119212. NULL,
  119213. 0
  119214. };
  119215. static long _vq_quantlist__16c0_s_p9_0[] = {
  119216. 1,
  119217. 0,
  119218. 2,
  119219. };
  119220. static long _vq_lengthlist__16c0_s_p9_0[] = {
  119221. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119222. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119223. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119224. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119225. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119226. 7,
  119227. };
  119228. static float _vq_quantthresh__16c0_s_p9_0[] = {
  119229. -157.5, 157.5,
  119230. };
  119231. static long _vq_quantmap__16c0_s_p9_0[] = {
  119232. 1, 0, 2,
  119233. };
  119234. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  119235. _vq_quantthresh__16c0_s_p9_0,
  119236. _vq_quantmap__16c0_s_p9_0,
  119237. 3,
  119238. 3
  119239. };
  119240. static static_codebook _16c0_s_p9_0 = {
  119241. 4, 81,
  119242. _vq_lengthlist__16c0_s_p9_0,
  119243. 1, -518803456, 1628680192, 2, 0,
  119244. _vq_quantlist__16c0_s_p9_0,
  119245. NULL,
  119246. &_vq_auxt__16c0_s_p9_0,
  119247. NULL,
  119248. 0
  119249. };
  119250. static long _vq_quantlist__16c0_s_p9_1[] = {
  119251. 7,
  119252. 6,
  119253. 8,
  119254. 5,
  119255. 9,
  119256. 4,
  119257. 10,
  119258. 3,
  119259. 11,
  119260. 2,
  119261. 12,
  119262. 1,
  119263. 13,
  119264. 0,
  119265. 14,
  119266. };
  119267. static long _vq_lengthlist__16c0_s_p9_1[] = {
  119268. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  119269. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  119270. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  119271. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  119272. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119275. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119276. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119277. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119281. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119282. 10,
  119283. };
  119284. static float _vq_quantthresh__16c0_s_p9_1[] = {
  119285. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119286. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119287. };
  119288. static long _vq_quantmap__16c0_s_p9_1[] = {
  119289. 13, 11, 9, 7, 5, 3, 1, 0,
  119290. 2, 4, 6, 8, 10, 12, 14,
  119291. };
  119292. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  119293. _vq_quantthresh__16c0_s_p9_1,
  119294. _vq_quantmap__16c0_s_p9_1,
  119295. 15,
  119296. 15
  119297. };
  119298. static static_codebook _16c0_s_p9_1 = {
  119299. 2, 225,
  119300. _vq_lengthlist__16c0_s_p9_1,
  119301. 1, -520986624, 1620377600, 4, 0,
  119302. _vq_quantlist__16c0_s_p9_1,
  119303. NULL,
  119304. &_vq_auxt__16c0_s_p9_1,
  119305. NULL,
  119306. 0
  119307. };
  119308. static long _vq_quantlist__16c0_s_p9_2[] = {
  119309. 10,
  119310. 9,
  119311. 11,
  119312. 8,
  119313. 12,
  119314. 7,
  119315. 13,
  119316. 6,
  119317. 14,
  119318. 5,
  119319. 15,
  119320. 4,
  119321. 16,
  119322. 3,
  119323. 17,
  119324. 2,
  119325. 18,
  119326. 1,
  119327. 19,
  119328. 0,
  119329. 20,
  119330. };
  119331. static long _vq_lengthlist__16c0_s_p9_2[] = {
  119332. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  119333. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  119334. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  119335. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  119336. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  119337. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  119338. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  119339. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  119340. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  119341. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  119342. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  119343. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  119344. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  119345. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  119346. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  119347. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  119348. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  119349. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  119350. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  119351. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  119352. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  119353. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  119354. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  119355. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  119356. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  119357. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  119358. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  119359. 10,11,10,10,11, 9,10,10,10,
  119360. };
  119361. static float _vq_quantthresh__16c0_s_p9_2[] = {
  119362. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119363. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119364. 6.5, 7.5, 8.5, 9.5,
  119365. };
  119366. static long _vq_quantmap__16c0_s_p9_2[] = {
  119367. 19, 17, 15, 13, 11, 9, 7, 5,
  119368. 3, 1, 0, 2, 4, 6, 8, 10,
  119369. 12, 14, 16, 18, 20,
  119370. };
  119371. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  119372. _vq_quantthresh__16c0_s_p9_2,
  119373. _vq_quantmap__16c0_s_p9_2,
  119374. 21,
  119375. 21
  119376. };
  119377. static static_codebook _16c0_s_p9_2 = {
  119378. 2, 441,
  119379. _vq_lengthlist__16c0_s_p9_2,
  119380. 1, -529268736, 1611661312, 5, 0,
  119381. _vq_quantlist__16c0_s_p9_2,
  119382. NULL,
  119383. &_vq_auxt__16c0_s_p9_2,
  119384. NULL,
  119385. 0
  119386. };
  119387. static long _huff_lengthlist__16c0_s_single[] = {
  119388. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  119389. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  119390. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  119391. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  119392. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  119393. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  119394. 16,16,18,18,
  119395. };
  119396. static static_codebook _huff_book__16c0_s_single = {
  119397. 2, 100,
  119398. _huff_lengthlist__16c0_s_single,
  119399. 0, 0, 0, 0, 0,
  119400. NULL,
  119401. NULL,
  119402. NULL,
  119403. NULL,
  119404. 0
  119405. };
  119406. static long _huff_lengthlist__16c1_s_long[] = {
  119407. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  119408. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  119409. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  119410. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  119411. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  119412. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  119413. 12,11,11,13,
  119414. };
  119415. static static_codebook _huff_book__16c1_s_long = {
  119416. 2, 100,
  119417. _huff_lengthlist__16c1_s_long,
  119418. 0, 0, 0, 0, 0,
  119419. NULL,
  119420. NULL,
  119421. NULL,
  119422. NULL,
  119423. 0
  119424. };
  119425. static long _vq_quantlist__16c1_s_p1_0[] = {
  119426. 1,
  119427. 0,
  119428. 2,
  119429. };
  119430. static long _vq_lengthlist__16c1_s_p1_0[] = {
  119431. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119432. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119436. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119437. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119441. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  119442. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  119477. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119482. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  119483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119487. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  119488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119522. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119523. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119527. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  119528. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  119529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119532. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  119533. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  119534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119841. 0,
  119842. };
  119843. static float _vq_quantthresh__16c1_s_p1_0[] = {
  119844. -0.5, 0.5,
  119845. };
  119846. static long _vq_quantmap__16c1_s_p1_0[] = {
  119847. 1, 0, 2,
  119848. };
  119849. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  119850. _vq_quantthresh__16c1_s_p1_0,
  119851. _vq_quantmap__16c1_s_p1_0,
  119852. 3,
  119853. 3
  119854. };
  119855. static static_codebook _16c1_s_p1_0 = {
  119856. 8, 6561,
  119857. _vq_lengthlist__16c1_s_p1_0,
  119858. 1, -535822336, 1611661312, 2, 0,
  119859. _vq_quantlist__16c1_s_p1_0,
  119860. NULL,
  119861. &_vq_auxt__16c1_s_p1_0,
  119862. NULL,
  119863. 0
  119864. };
  119865. static long _vq_quantlist__16c1_s_p2_0[] = {
  119866. 2,
  119867. 1,
  119868. 3,
  119869. 0,
  119870. 4,
  119871. };
  119872. static long _vq_lengthlist__16c1_s_p2_0[] = {
  119873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119912. 0,
  119913. };
  119914. static float _vq_quantthresh__16c1_s_p2_0[] = {
  119915. -1.5, -0.5, 0.5, 1.5,
  119916. };
  119917. static long _vq_quantmap__16c1_s_p2_0[] = {
  119918. 3, 1, 0, 2, 4,
  119919. };
  119920. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  119921. _vq_quantthresh__16c1_s_p2_0,
  119922. _vq_quantmap__16c1_s_p2_0,
  119923. 5,
  119924. 5
  119925. };
  119926. static static_codebook _16c1_s_p2_0 = {
  119927. 4, 625,
  119928. _vq_lengthlist__16c1_s_p2_0,
  119929. 1, -533725184, 1611661312, 3, 0,
  119930. _vq_quantlist__16c1_s_p2_0,
  119931. NULL,
  119932. &_vq_auxt__16c1_s_p2_0,
  119933. NULL,
  119934. 0
  119935. };
  119936. static long _vq_quantlist__16c1_s_p3_0[] = {
  119937. 2,
  119938. 1,
  119939. 3,
  119940. 0,
  119941. 4,
  119942. };
  119943. static long _vq_lengthlist__16c1_s_p3_0[] = {
  119944. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  119946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119947. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  119949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119950. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119983. 0,
  119984. };
  119985. static float _vq_quantthresh__16c1_s_p3_0[] = {
  119986. -1.5, -0.5, 0.5, 1.5,
  119987. };
  119988. static long _vq_quantmap__16c1_s_p3_0[] = {
  119989. 3, 1, 0, 2, 4,
  119990. };
  119991. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  119992. _vq_quantthresh__16c1_s_p3_0,
  119993. _vq_quantmap__16c1_s_p3_0,
  119994. 5,
  119995. 5
  119996. };
  119997. static static_codebook _16c1_s_p3_0 = {
  119998. 4, 625,
  119999. _vq_lengthlist__16c1_s_p3_0,
  120000. 1, -533725184, 1611661312, 3, 0,
  120001. _vq_quantlist__16c1_s_p3_0,
  120002. NULL,
  120003. &_vq_auxt__16c1_s_p3_0,
  120004. NULL,
  120005. 0
  120006. };
  120007. static long _vq_quantlist__16c1_s_p4_0[] = {
  120008. 4,
  120009. 3,
  120010. 5,
  120011. 2,
  120012. 6,
  120013. 1,
  120014. 7,
  120015. 0,
  120016. 8,
  120017. };
  120018. static long _vq_lengthlist__16c1_s_p4_0[] = {
  120019. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120020. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120021. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120022. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  120023. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120024. 0,
  120025. };
  120026. static float _vq_quantthresh__16c1_s_p4_0[] = {
  120027. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120028. };
  120029. static long _vq_quantmap__16c1_s_p4_0[] = {
  120030. 7, 5, 3, 1, 0, 2, 4, 6,
  120031. 8,
  120032. };
  120033. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  120034. _vq_quantthresh__16c1_s_p4_0,
  120035. _vq_quantmap__16c1_s_p4_0,
  120036. 9,
  120037. 9
  120038. };
  120039. static static_codebook _16c1_s_p4_0 = {
  120040. 2, 81,
  120041. _vq_lengthlist__16c1_s_p4_0,
  120042. 1, -531628032, 1611661312, 4, 0,
  120043. _vq_quantlist__16c1_s_p4_0,
  120044. NULL,
  120045. &_vq_auxt__16c1_s_p4_0,
  120046. NULL,
  120047. 0
  120048. };
  120049. static long _vq_quantlist__16c1_s_p5_0[] = {
  120050. 4,
  120051. 3,
  120052. 5,
  120053. 2,
  120054. 6,
  120055. 1,
  120056. 7,
  120057. 0,
  120058. 8,
  120059. };
  120060. static long _vq_lengthlist__16c1_s_p5_0[] = {
  120061. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120062. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  120063. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  120064. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120065. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120066. 10,
  120067. };
  120068. static float _vq_quantthresh__16c1_s_p5_0[] = {
  120069. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120070. };
  120071. static long _vq_quantmap__16c1_s_p5_0[] = {
  120072. 7, 5, 3, 1, 0, 2, 4, 6,
  120073. 8,
  120074. };
  120075. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  120076. _vq_quantthresh__16c1_s_p5_0,
  120077. _vq_quantmap__16c1_s_p5_0,
  120078. 9,
  120079. 9
  120080. };
  120081. static static_codebook _16c1_s_p5_0 = {
  120082. 2, 81,
  120083. _vq_lengthlist__16c1_s_p5_0,
  120084. 1, -531628032, 1611661312, 4, 0,
  120085. _vq_quantlist__16c1_s_p5_0,
  120086. NULL,
  120087. &_vq_auxt__16c1_s_p5_0,
  120088. NULL,
  120089. 0
  120090. };
  120091. static long _vq_quantlist__16c1_s_p6_0[] = {
  120092. 8,
  120093. 7,
  120094. 9,
  120095. 6,
  120096. 10,
  120097. 5,
  120098. 11,
  120099. 4,
  120100. 12,
  120101. 3,
  120102. 13,
  120103. 2,
  120104. 14,
  120105. 1,
  120106. 15,
  120107. 0,
  120108. 16,
  120109. };
  120110. static long _vq_lengthlist__16c1_s_p6_0[] = {
  120111. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  120112. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120113. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120114. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  120115. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  120116. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  120117. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  120118. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  120119. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  120120. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120121. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  120122. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  120123. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  120124. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  120125. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  120126. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  120127. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  120128. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  120129. 14,
  120130. };
  120131. static float _vq_quantthresh__16c1_s_p6_0[] = {
  120132. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120133. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120134. };
  120135. static long _vq_quantmap__16c1_s_p6_0[] = {
  120136. 15, 13, 11, 9, 7, 5, 3, 1,
  120137. 0, 2, 4, 6, 8, 10, 12, 14,
  120138. 16,
  120139. };
  120140. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  120141. _vq_quantthresh__16c1_s_p6_0,
  120142. _vq_quantmap__16c1_s_p6_0,
  120143. 17,
  120144. 17
  120145. };
  120146. static static_codebook _16c1_s_p6_0 = {
  120147. 2, 289,
  120148. _vq_lengthlist__16c1_s_p6_0,
  120149. 1, -529530880, 1611661312, 5, 0,
  120150. _vq_quantlist__16c1_s_p6_0,
  120151. NULL,
  120152. &_vq_auxt__16c1_s_p6_0,
  120153. NULL,
  120154. 0
  120155. };
  120156. static long _vq_quantlist__16c1_s_p7_0[] = {
  120157. 1,
  120158. 0,
  120159. 2,
  120160. };
  120161. static long _vq_lengthlist__16c1_s_p7_0[] = {
  120162. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  120163. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120164. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  120165. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  120166. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  120167. 11,
  120168. };
  120169. static float _vq_quantthresh__16c1_s_p7_0[] = {
  120170. -5.5, 5.5,
  120171. };
  120172. static long _vq_quantmap__16c1_s_p7_0[] = {
  120173. 1, 0, 2,
  120174. };
  120175. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  120176. _vq_quantthresh__16c1_s_p7_0,
  120177. _vq_quantmap__16c1_s_p7_0,
  120178. 3,
  120179. 3
  120180. };
  120181. static static_codebook _16c1_s_p7_0 = {
  120182. 4, 81,
  120183. _vq_lengthlist__16c1_s_p7_0,
  120184. 1, -529137664, 1618345984, 2, 0,
  120185. _vq_quantlist__16c1_s_p7_0,
  120186. NULL,
  120187. &_vq_auxt__16c1_s_p7_0,
  120188. NULL,
  120189. 0
  120190. };
  120191. static long _vq_quantlist__16c1_s_p7_1[] = {
  120192. 5,
  120193. 4,
  120194. 6,
  120195. 3,
  120196. 7,
  120197. 2,
  120198. 8,
  120199. 1,
  120200. 9,
  120201. 0,
  120202. 10,
  120203. };
  120204. static long _vq_lengthlist__16c1_s_p7_1[] = {
  120205. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  120206. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  120207. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120208. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  120209. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  120210. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  120211. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  120212. 10,10,10, 8, 8, 8, 8, 9, 9,
  120213. };
  120214. static float _vq_quantthresh__16c1_s_p7_1[] = {
  120215. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120216. 3.5, 4.5,
  120217. };
  120218. static long _vq_quantmap__16c1_s_p7_1[] = {
  120219. 9, 7, 5, 3, 1, 0, 2, 4,
  120220. 6, 8, 10,
  120221. };
  120222. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  120223. _vq_quantthresh__16c1_s_p7_1,
  120224. _vq_quantmap__16c1_s_p7_1,
  120225. 11,
  120226. 11
  120227. };
  120228. static static_codebook _16c1_s_p7_1 = {
  120229. 2, 121,
  120230. _vq_lengthlist__16c1_s_p7_1,
  120231. 1, -531365888, 1611661312, 4, 0,
  120232. _vq_quantlist__16c1_s_p7_1,
  120233. NULL,
  120234. &_vq_auxt__16c1_s_p7_1,
  120235. NULL,
  120236. 0
  120237. };
  120238. static long _vq_quantlist__16c1_s_p8_0[] = {
  120239. 6,
  120240. 5,
  120241. 7,
  120242. 4,
  120243. 8,
  120244. 3,
  120245. 9,
  120246. 2,
  120247. 10,
  120248. 1,
  120249. 11,
  120250. 0,
  120251. 12,
  120252. };
  120253. static long _vq_lengthlist__16c1_s_p8_0[] = {
  120254. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  120255. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  120256. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  120257. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  120258. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  120259. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  120260. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  120261. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  120262. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  120263. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  120264. 0,12,12,12,12,13,13,14,15,
  120265. };
  120266. static float _vq_quantthresh__16c1_s_p8_0[] = {
  120267. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120268. 12.5, 17.5, 22.5, 27.5,
  120269. };
  120270. static long _vq_quantmap__16c1_s_p8_0[] = {
  120271. 11, 9, 7, 5, 3, 1, 0, 2,
  120272. 4, 6, 8, 10, 12,
  120273. };
  120274. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  120275. _vq_quantthresh__16c1_s_p8_0,
  120276. _vq_quantmap__16c1_s_p8_0,
  120277. 13,
  120278. 13
  120279. };
  120280. static static_codebook _16c1_s_p8_0 = {
  120281. 2, 169,
  120282. _vq_lengthlist__16c1_s_p8_0,
  120283. 1, -526516224, 1616117760, 4, 0,
  120284. _vq_quantlist__16c1_s_p8_0,
  120285. NULL,
  120286. &_vq_auxt__16c1_s_p8_0,
  120287. NULL,
  120288. 0
  120289. };
  120290. static long _vq_quantlist__16c1_s_p8_1[] = {
  120291. 2,
  120292. 1,
  120293. 3,
  120294. 0,
  120295. 4,
  120296. };
  120297. static long _vq_lengthlist__16c1_s_p8_1[] = {
  120298. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120299. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120300. };
  120301. static float _vq_quantthresh__16c1_s_p8_1[] = {
  120302. -1.5, -0.5, 0.5, 1.5,
  120303. };
  120304. static long _vq_quantmap__16c1_s_p8_1[] = {
  120305. 3, 1, 0, 2, 4,
  120306. };
  120307. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  120308. _vq_quantthresh__16c1_s_p8_1,
  120309. _vq_quantmap__16c1_s_p8_1,
  120310. 5,
  120311. 5
  120312. };
  120313. static static_codebook _16c1_s_p8_1 = {
  120314. 2, 25,
  120315. _vq_lengthlist__16c1_s_p8_1,
  120316. 1, -533725184, 1611661312, 3, 0,
  120317. _vq_quantlist__16c1_s_p8_1,
  120318. NULL,
  120319. &_vq_auxt__16c1_s_p8_1,
  120320. NULL,
  120321. 0
  120322. };
  120323. static long _vq_quantlist__16c1_s_p9_0[] = {
  120324. 6,
  120325. 5,
  120326. 7,
  120327. 4,
  120328. 8,
  120329. 3,
  120330. 9,
  120331. 2,
  120332. 10,
  120333. 1,
  120334. 11,
  120335. 0,
  120336. 12,
  120337. };
  120338. static long _vq_lengthlist__16c1_s_p9_0[] = {
  120339. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120340. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120341. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120342. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120343. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120344. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120345. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120346. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120347. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120348. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120349. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120350. };
  120351. static float _vq_quantthresh__16c1_s_p9_0[] = {
  120352. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  120353. 787.5, 1102.5, 1417.5, 1732.5,
  120354. };
  120355. static long _vq_quantmap__16c1_s_p9_0[] = {
  120356. 11, 9, 7, 5, 3, 1, 0, 2,
  120357. 4, 6, 8, 10, 12,
  120358. };
  120359. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  120360. _vq_quantthresh__16c1_s_p9_0,
  120361. _vq_quantmap__16c1_s_p9_0,
  120362. 13,
  120363. 13
  120364. };
  120365. static static_codebook _16c1_s_p9_0 = {
  120366. 2, 169,
  120367. _vq_lengthlist__16c1_s_p9_0,
  120368. 1, -513964032, 1628680192, 4, 0,
  120369. _vq_quantlist__16c1_s_p9_0,
  120370. NULL,
  120371. &_vq_auxt__16c1_s_p9_0,
  120372. NULL,
  120373. 0
  120374. };
  120375. static long _vq_quantlist__16c1_s_p9_1[] = {
  120376. 7,
  120377. 6,
  120378. 8,
  120379. 5,
  120380. 9,
  120381. 4,
  120382. 10,
  120383. 3,
  120384. 11,
  120385. 2,
  120386. 12,
  120387. 1,
  120388. 13,
  120389. 0,
  120390. 14,
  120391. };
  120392. static long _vq_lengthlist__16c1_s_p9_1[] = {
  120393. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  120394. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  120395. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  120396. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  120397. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  120398. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  120399. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  120400. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120401. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120402. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120403. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120404. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120405. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  120406. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120407. 13,
  120408. };
  120409. static float _vq_quantthresh__16c1_s_p9_1[] = {
  120410. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120411. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120412. };
  120413. static long _vq_quantmap__16c1_s_p9_1[] = {
  120414. 13, 11, 9, 7, 5, 3, 1, 0,
  120415. 2, 4, 6, 8, 10, 12, 14,
  120416. };
  120417. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  120418. _vq_quantthresh__16c1_s_p9_1,
  120419. _vq_quantmap__16c1_s_p9_1,
  120420. 15,
  120421. 15
  120422. };
  120423. static static_codebook _16c1_s_p9_1 = {
  120424. 2, 225,
  120425. _vq_lengthlist__16c1_s_p9_1,
  120426. 1, -520986624, 1620377600, 4, 0,
  120427. _vq_quantlist__16c1_s_p9_1,
  120428. NULL,
  120429. &_vq_auxt__16c1_s_p9_1,
  120430. NULL,
  120431. 0
  120432. };
  120433. static long _vq_quantlist__16c1_s_p9_2[] = {
  120434. 10,
  120435. 9,
  120436. 11,
  120437. 8,
  120438. 12,
  120439. 7,
  120440. 13,
  120441. 6,
  120442. 14,
  120443. 5,
  120444. 15,
  120445. 4,
  120446. 16,
  120447. 3,
  120448. 17,
  120449. 2,
  120450. 18,
  120451. 1,
  120452. 19,
  120453. 0,
  120454. 20,
  120455. };
  120456. static long _vq_lengthlist__16c1_s_p9_2[] = {
  120457. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  120458. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  120459. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  120460. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  120461. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  120462. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  120463. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  120464. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  120465. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  120466. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  120467. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  120468. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  120469. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  120470. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  120471. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  120472. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  120473. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  120474. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  120475. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  120476. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  120477. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  120478. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  120479. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  120480. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  120481. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  120482. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  120483. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  120484. 11,11,11,11,12,11,11,12,11,
  120485. };
  120486. static float _vq_quantthresh__16c1_s_p9_2[] = {
  120487. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120488. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120489. 6.5, 7.5, 8.5, 9.5,
  120490. };
  120491. static long _vq_quantmap__16c1_s_p9_2[] = {
  120492. 19, 17, 15, 13, 11, 9, 7, 5,
  120493. 3, 1, 0, 2, 4, 6, 8, 10,
  120494. 12, 14, 16, 18, 20,
  120495. };
  120496. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  120497. _vq_quantthresh__16c1_s_p9_2,
  120498. _vq_quantmap__16c1_s_p9_2,
  120499. 21,
  120500. 21
  120501. };
  120502. static static_codebook _16c1_s_p9_2 = {
  120503. 2, 441,
  120504. _vq_lengthlist__16c1_s_p9_2,
  120505. 1, -529268736, 1611661312, 5, 0,
  120506. _vq_quantlist__16c1_s_p9_2,
  120507. NULL,
  120508. &_vq_auxt__16c1_s_p9_2,
  120509. NULL,
  120510. 0
  120511. };
  120512. static long _huff_lengthlist__16c1_s_short[] = {
  120513. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  120514. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  120515. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  120516. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  120517. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  120518. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  120519. 9, 9,10,13,
  120520. };
  120521. static static_codebook _huff_book__16c1_s_short = {
  120522. 2, 100,
  120523. _huff_lengthlist__16c1_s_short,
  120524. 0, 0, 0, 0, 0,
  120525. NULL,
  120526. NULL,
  120527. NULL,
  120528. NULL,
  120529. 0
  120530. };
  120531. static long _huff_lengthlist__16c2_s_long[] = {
  120532. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  120533. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  120534. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  120535. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  120536. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  120537. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  120538. 14,14,16,18,
  120539. };
  120540. static static_codebook _huff_book__16c2_s_long = {
  120541. 2, 100,
  120542. _huff_lengthlist__16c2_s_long,
  120543. 0, 0, 0, 0, 0,
  120544. NULL,
  120545. NULL,
  120546. NULL,
  120547. NULL,
  120548. 0
  120549. };
  120550. static long _vq_quantlist__16c2_s_p1_0[] = {
  120551. 1,
  120552. 0,
  120553. 2,
  120554. };
  120555. static long _vq_lengthlist__16c2_s_p1_0[] = {
  120556. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  120557. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120561. 0,
  120562. };
  120563. static float _vq_quantthresh__16c2_s_p1_0[] = {
  120564. -0.5, 0.5,
  120565. };
  120566. static long _vq_quantmap__16c2_s_p1_0[] = {
  120567. 1, 0, 2,
  120568. };
  120569. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  120570. _vq_quantthresh__16c2_s_p1_0,
  120571. _vq_quantmap__16c2_s_p1_0,
  120572. 3,
  120573. 3
  120574. };
  120575. static static_codebook _16c2_s_p1_0 = {
  120576. 4, 81,
  120577. _vq_lengthlist__16c2_s_p1_0,
  120578. 1, -535822336, 1611661312, 2, 0,
  120579. _vq_quantlist__16c2_s_p1_0,
  120580. NULL,
  120581. &_vq_auxt__16c2_s_p1_0,
  120582. NULL,
  120583. 0
  120584. };
  120585. static long _vq_quantlist__16c2_s_p2_0[] = {
  120586. 2,
  120587. 1,
  120588. 3,
  120589. 0,
  120590. 4,
  120591. };
  120592. static long _vq_lengthlist__16c2_s_p2_0[] = {
  120593. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  120594. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  120595. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  120596. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  120597. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  120598. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  120599. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  120600. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  120601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120605. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  120606. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  120607. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  120608. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  120609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120613. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  120614. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  120615. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  120616. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120621. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  120622. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  120623. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  120624. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  120629. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  120630. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  120631. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  120632. 13,
  120633. };
  120634. static float _vq_quantthresh__16c2_s_p2_0[] = {
  120635. -1.5, -0.5, 0.5, 1.5,
  120636. };
  120637. static long _vq_quantmap__16c2_s_p2_0[] = {
  120638. 3, 1, 0, 2, 4,
  120639. };
  120640. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  120641. _vq_quantthresh__16c2_s_p2_0,
  120642. _vq_quantmap__16c2_s_p2_0,
  120643. 5,
  120644. 5
  120645. };
  120646. static static_codebook _16c2_s_p2_0 = {
  120647. 4, 625,
  120648. _vq_lengthlist__16c2_s_p2_0,
  120649. 1, -533725184, 1611661312, 3, 0,
  120650. _vq_quantlist__16c2_s_p2_0,
  120651. NULL,
  120652. &_vq_auxt__16c2_s_p2_0,
  120653. NULL,
  120654. 0
  120655. };
  120656. static long _vq_quantlist__16c2_s_p3_0[] = {
  120657. 4,
  120658. 3,
  120659. 5,
  120660. 2,
  120661. 6,
  120662. 1,
  120663. 7,
  120664. 0,
  120665. 8,
  120666. };
  120667. static long _vq_lengthlist__16c2_s_p3_0[] = {
  120668. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  120669. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  120670. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  120671. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  120672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120673. 0,
  120674. };
  120675. static float _vq_quantthresh__16c2_s_p3_0[] = {
  120676. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120677. };
  120678. static long _vq_quantmap__16c2_s_p3_0[] = {
  120679. 7, 5, 3, 1, 0, 2, 4, 6,
  120680. 8,
  120681. };
  120682. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  120683. _vq_quantthresh__16c2_s_p3_0,
  120684. _vq_quantmap__16c2_s_p3_0,
  120685. 9,
  120686. 9
  120687. };
  120688. static static_codebook _16c2_s_p3_0 = {
  120689. 2, 81,
  120690. _vq_lengthlist__16c2_s_p3_0,
  120691. 1, -531628032, 1611661312, 4, 0,
  120692. _vq_quantlist__16c2_s_p3_0,
  120693. NULL,
  120694. &_vq_auxt__16c2_s_p3_0,
  120695. NULL,
  120696. 0
  120697. };
  120698. static long _vq_quantlist__16c2_s_p4_0[] = {
  120699. 8,
  120700. 7,
  120701. 9,
  120702. 6,
  120703. 10,
  120704. 5,
  120705. 11,
  120706. 4,
  120707. 12,
  120708. 3,
  120709. 13,
  120710. 2,
  120711. 14,
  120712. 1,
  120713. 15,
  120714. 0,
  120715. 16,
  120716. };
  120717. static long _vq_lengthlist__16c2_s_p4_0[] = {
  120718. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  120719. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  120720. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  120721. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  120722. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  120723. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  120724. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  120725. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  120726. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  120727. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  120728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120736. 0,
  120737. };
  120738. static float _vq_quantthresh__16c2_s_p4_0[] = {
  120739. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120740. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120741. };
  120742. static long _vq_quantmap__16c2_s_p4_0[] = {
  120743. 15, 13, 11, 9, 7, 5, 3, 1,
  120744. 0, 2, 4, 6, 8, 10, 12, 14,
  120745. 16,
  120746. };
  120747. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  120748. _vq_quantthresh__16c2_s_p4_0,
  120749. _vq_quantmap__16c2_s_p4_0,
  120750. 17,
  120751. 17
  120752. };
  120753. static static_codebook _16c2_s_p4_0 = {
  120754. 2, 289,
  120755. _vq_lengthlist__16c2_s_p4_0,
  120756. 1, -529530880, 1611661312, 5, 0,
  120757. _vq_quantlist__16c2_s_p4_0,
  120758. NULL,
  120759. &_vq_auxt__16c2_s_p4_0,
  120760. NULL,
  120761. 0
  120762. };
  120763. static long _vq_quantlist__16c2_s_p5_0[] = {
  120764. 1,
  120765. 0,
  120766. 2,
  120767. };
  120768. static long _vq_lengthlist__16c2_s_p5_0[] = {
  120769. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  120770. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  120771. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  120772. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  120773. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  120774. 12,
  120775. };
  120776. static float _vq_quantthresh__16c2_s_p5_0[] = {
  120777. -5.5, 5.5,
  120778. };
  120779. static long _vq_quantmap__16c2_s_p5_0[] = {
  120780. 1, 0, 2,
  120781. };
  120782. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  120783. _vq_quantthresh__16c2_s_p5_0,
  120784. _vq_quantmap__16c2_s_p5_0,
  120785. 3,
  120786. 3
  120787. };
  120788. static static_codebook _16c2_s_p5_0 = {
  120789. 4, 81,
  120790. _vq_lengthlist__16c2_s_p5_0,
  120791. 1, -529137664, 1618345984, 2, 0,
  120792. _vq_quantlist__16c2_s_p5_0,
  120793. NULL,
  120794. &_vq_auxt__16c2_s_p5_0,
  120795. NULL,
  120796. 0
  120797. };
  120798. static long _vq_quantlist__16c2_s_p5_1[] = {
  120799. 5,
  120800. 4,
  120801. 6,
  120802. 3,
  120803. 7,
  120804. 2,
  120805. 8,
  120806. 1,
  120807. 9,
  120808. 0,
  120809. 10,
  120810. };
  120811. static long _vq_lengthlist__16c2_s_p5_1[] = {
  120812. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  120813. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  120814. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  120815. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  120816. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  120817. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  120818. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  120819. 11,11,11, 7, 7, 8, 8, 8, 8,
  120820. };
  120821. static float _vq_quantthresh__16c2_s_p5_1[] = {
  120822. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120823. 3.5, 4.5,
  120824. };
  120825. static long _vq_quantmap__16c2_s_p5_1[] = {
  120826. 9, 7, 5, 3, 1, 0, 2, 4,
  120827. 6, 8, 10,
  120828. };
  120829. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  120830. _vq_quantthresh__16c2_s_p5_1,
  120831. _vq_quantmap__16c2_s_p5_1,
  120832. 11,
  120833. 11
  120834. };
  120835. static static_codebook _16c2_s_p5_1 = {
  120836. 2, 121,
  120837. _vq_lengthlist__16c2_s_p5_1,
  120838. 1, -531365888, 1611661312, 4, 0,
  120839. _vq_quantlist__16c2_s_p5_1,
  120840. NULL,
  120841. &_vq_auxt__16c2_s_p5_1,
  120842. NULL,
  120843. 0
  120844. };
  120845. static long _vq_quantlist__16c2_s_p6_0[] = {
  120846. 6,
  120847. 5,
  120848. 7,
  120849. 4,
  120850. 8,
  120851. 3,
  120852. 9,
  120853. 2,
  120854. 10,
  120855. 1,
  120856. 11,
  120857. 0,
  120858. 12,
  120859. };
  120860. static long _vq_lengthlist__16c2_s_p6_0[] = {
  120861. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120862. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  120863. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  120864. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  120865. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  120866. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  120867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120872. };
  120873. static float _vq_quantthresh__16c2_s_p6_0[] = {
  120874. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120875. 12.5, 17.5, 22.5, 27.5,
  120876. };
  120877. static long _vq_quantmap__16c2_s_p6_0[] = {
  120878. 11, 9, 7, 5, 3, 1, 0, 2,
  120879. 4, 6, 8, 10, 12,
  120880. };
  120881. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  120882. _vq_quantthresh__16c2_s_p6_0,
  120883. _vq_quantmap__16c2_s_p6_0,
  120884. 13,
  120885. 13
  120886. };
  120887. static static_codebook _16c2_s_p6_0 = {
  120888. 2, 169,
  120889. _vq_lengthlist__16c2_s_p6_0,
  120890. 1, -526516224, 1616117760, 4, 0,
  120891. _vq_quantlist__16c2_s_p6_0,
  120892. NULL,
  120893. &_vq_auxt__16c2_s_p6_0,
  120894. NULL,
  120895. 0
  120896. };
  120897. static long _vq_quantlist__16c2_s_p6_1[] = {
  120898. 2,
  120899. 1,
  120900. 3,
  120901. 0,
  120902. 4,
  120903. };
  120904. static long _vq_lengthlist__16c2_s_p6_1[] = {
  120905. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120906. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120907. };
  120908. static float _vq_quantthresh__16c2_s_p6_1[] = {
  120909. -1.5, -0.5, 0.5, 1.5,
  120910. };
  120911. static long _vq_quantmap__16c2_s_p6_1[] = {
  120912. 3, 1, 0, 2, 4,
  120913. };
  120914. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  120915. _vq_quantthresh__16c2_s_p6_1,
  120916. _vq_quantmap__16c2_s_p6_1,
  120917. 5,
  120918. 5
  120919. };
  120920. static static_codebook _16c2_s_p6_1 = {
  120921. 2, 25,
  120922. _vq_lengthlist__16c2_s_p6_1,
  120923. 1, -533725184, 1611661312, 3, 0,
  120924. _vq_quantlist__16c2_s_p6_1,
  120925. NULL,
  120926. &_vq_auxt__16c2_s_p6_1,
  120927. NULL,
  120928. 0
  120929. };
  120930. static long _vq_quantlist__16c2_s_p7_0[] = {
  120931. 6,
  120932. 5,
  120933. 7,
  120934. 4,
  120935. 8,
  120936. 3,
  120937. 9,
  120938. 2,
  120939. 10,
  120940. 1,
  120941. 11,
  120942. 0,
  120943. 12,
  120944. };
  120945. static long _vq_lengthlist__16c2_s_p7_0[] = {
  120946. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120947. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  120948. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  120949. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  120950. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  120951. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  120952. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  120953. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  120954. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  120955. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  120956. 18,13,14,13,13,14,13,15,14,
  120957. };
  120958. static float _vq_quantthresh__16c2_s_p7_0[] = {
  120959. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  120960. 27.5, 38.5, 49.5, 60.5,
  120961. };
  120962. static long _vq_quantmap__16c2_s_p7_0[] = {
  120963. 11, 9, 7, 5, 3, 1, 0, 2,
  120964. 4, 6, 8, 10, 12,
  120965. };
  120966. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  120967. _vq_quantthresh__16c2_s_p7_0,
  120968. _vq_quantmap__16c2_s_p7_0,
  120969. 13,
  120970. 13
  120971. };
  120972. static static_codebook _16c2_s_p7_0 = {
  120973. 2, 169,
  120974. _vq_lengthlist__16c2_s_p7_0,
  120975. 1, -523206656, 1618345984, 4, 0,
  120976. _vq_quantlist__16c2_s_p7_0,
  120977. NULL,
  120978. &_vq_auxt__16c2_s_p7_0,
  120979. NULL,
  120980. 0
  120981. };
  120982. static long _vq_quantlist__16c2_s_p7_1[] = {
  120983. 5,
  120984. 4,
  120985. 6,
  120986. 3,
  120987. 7,
  120988. 2,
  120989. 8,
  120990. 1,
  120991. 9,
  120992. 0,
  120993. 10,
  120994. };
  120995. static long _vq_lengthlist__16c2_s_p7_1[] = {
  120996. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  120997. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  120998. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  120999. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121000. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  121001. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  121002. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  121003. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121004. };
  121005. static float _vq_quantthresh__16c2_s_p7_1[] = {
  121006. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121007. 3.5, 4.5,
  121008. };
  121009. static long _vq_quantmap__16c2_s_p7_1[] = {
  121010. 9, 7, 5, 3, 1, 0, 2, 4,
  121011. 6, 8, 10,
  121012. };
  121013. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  121014. _vq_quantthresh__16c2_s_p7_1,
  121015. _vq_quantmap__16c2_s_p7_1,
  121016. 11,
  121017. 11
  121018. };
  121019. static static_codebook _16c2_s_p7_1 = {
  121020. 2, 121,
  121021. _vq_lengthlist__16c2_s_p7_1,
  121022. 1, -531365888, 1611661312, 4, 0,
  121023. _vq_quantlist__16c2_s_p7_1,
  121024. NULL,
  121025. &_vq_auxt__16c2_s_p7_1,
  121026. NULL,
  121027. 0
  121028. };
  121029. static long _vq_quantlist__16c2_s_p8_0[] = {
  121030. 7,
  121031. 6,
  121032. 8,
  121033. 5,
  121034. 9,
  121035. 4,
  121036. 10,
  121037. 3,
  121038. 11,
  121039. 2,
  121040. 12,
  121041. 1,
  121042. 13,
  121043. 0,
  121044. 14,
  121045. };
  121046. static long _vq_lengthlist__16c2_s_p8_0[] = {
  121047. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  121048. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  121049. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  121050. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  121051. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  121052. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  121053. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  121054. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  121055. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  121056. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  121057. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  121058. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  121059. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  121060. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  121061. 13,
  121062. };
  121063. static float _vq_quantthresh__16c2_s_p8_0[] = {
  121064. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121065. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121066. };
  121067. static long _vq_quantmap__16c2_s_p8_0[] = {
  121068. 13, 11, 9, 7, 5, 3, 1, 0,
  121069. 2, 4, 6, 8, 10, 12, 14,
  121070. };
  121071. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  121072. _vq_quantthresh__16c2_s_p8_0,
  121073. _vq_quantmap__16c2_s_p8_0,
  121074. 15,
  121075. 15
  121076. };
  121077. static static_codebook _16c2_s_p8_0 = {
  121078. 2, 225,
  121079. _vq_lengthlist__16c2_s_p8_0,
  121080. 1, -520986624, 1620377600, 4, 0,
  121081. _vq_quantlist__16c2_s_p8_0,
  121082. NULL,
  121083. &_vq_auxt__16c2_s_p8_0,
  121084. NULL,
  121085. 0
  121086. };
  121087. static long _vq_quantlist__16c2_s_p8_1[] = {
  121088. 10,
  121089. 9,
  121090. 11,
  121091. 8,
  121092. 12,
  121093. 7,
  121094. 13,
  121095. 6,
  121096. 14,
  121097. 5,
  121098. 15,
  121099. 4,
  121100. 16,
  121101. 3,
  121102. 17,
  121103. 2,
  121104. 18,
  121105. 1,
  121106. 19,
  121107. 0,
  121108. 20,
  121109. };
  121110. static long _vq_lengthlist__16c2_s_p8_1[] = {
  121111. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  121112. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  121113. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  121114. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  121115. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  121116. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  121117. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  121118. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  121119. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  121120. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  121121. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  121122. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  121123. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  121124. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  121125. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  121126. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  121127. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  121128. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  121129. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  121130. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  121131. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  121132. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  121133. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  121134. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  121135. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  121136. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  121137. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  121138. 10,11,10,10,10,10,10,10,10,
  121139. };
  121140. static float _vq_quantthresh__16c2_s_p8_1[] = {
  121141. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121142. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121143. 6.5, 7.5, 8.5, 9.5,
  121144. };
  121145. static long _vq_quantmap__16c2_s_p8_1[] = {
  121146. 19, 17, 15, 13, 11, 9, 7, 5,
  121147. 3, 1, 0, 2, 4, 6, 8, 10,
  121148. 12, 14, 16, 18, 20,
  121149. };
  121150. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  121151. _vq_quantthresh__16c2_s_p8_1,
  121152. _vq_quantmap__16c2_s_p8_1,
  121153. 21,
  121154. 21
  121155. };
  121156. static static_codebook _16c2_s_p8_1 = {
  121157. 2, 441,
  121158. _vq_lengthlist__16c2_s_p8_1,
  121159. 1, -529268736, 1611661312, 5, 0,
  121160. _vq_quantlist__16c2_s_p8_1,
  121161. NULL,
  121162. &_vq_auxt__16c2_s_p8_1,
  121163. NULL,
  121164. 0
  121165. };
  121166. static long _vq_quantlist__16c2_s_p9_0[] = {
  121167. 6,
  121168. 5,
  121169. 7,
  121170. 4,
  121171. 8,
  121172. 3,
  121173. 9,
  121174. 2,
  121175. 10,
  121176. 1,
  121177. 11,
  121178. 0,
  121179. 12,
  121180. };
  121181. static long _vq_lengthlist__16c2_s_p9_0[] = {
  121182. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121183. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121184. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121185. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121186. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121187. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121188. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121189. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121190. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121191. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121192. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121193. };
  121194. static float _vq_quantthresh__16c2_s_p9_0[] = {
  121195. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  121196. 2327.5, 3258.5, 4189.5, 5120.5,
  121197. };
  121198. static long _vq_quantmap__16c2_s_p9_0[] = {
  121199. 11, 9, 7, 5, 3, 1, 0, 2,
  121200. 4, 6, 8, 10, 12,
  121201. };
  121202. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  121203. _vq_quantthresh__16c2_s_p9_0,
  121204. _vq_quantmap__16c2_s_p9_0,
  121205. 13,
  121206. 13
  121207. };
  121208. static static_codebook _16c2_s_p9_0 = {
  121209. 2, 169,
  121210. _vq_lengthlist__16c2_s_p9_0,
  121211. 1, -510275072, 1631393792, 4, 0,
  121212. _vq_quantlist__16c2_s_p9_0,
  121213. NULL,
  121214. &_vq_auxt__16c2_s_p9_0,
  121215. NULL,
  121216. 0
  121217. };
  121218. static long _vq_quantlist__16c2_s_p9_1[] = {
  121219. 8,
  121220. 7,
  121221. 9,
  121222. 6,
  121223. 10,
  121224. 5,
  121225. 11,
  121226. 4,
  121227. 12,
  121228. 3,
  121229. 13,
  121230. 2,
  121231. 14,
  121232. 1,
  121233. 15,
  121234. 0,
  121235. 16,
  121236. };
  121237. static long _vq_lengthlist__16c2_s_p9_1[] = {
  121238. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  121239. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  121240. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  121241. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  121242. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  121243. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  121244. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  121245. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  121246. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  121247. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  121248. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121249. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121250. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121251. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121252. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121253. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  121254. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  121255. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121256. 10,
  121257. };
  121258. static float _vq_quantthresh__16c2_s_p9_1[] = {
  121259. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  121260. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  121261. };
  121262. static long _vq_quantmap__16c2_s_p9_1[] = {
  121263. 15, 13, 11, 9, 7, 5, 3, 1,
  121264. 0, 2, 4, 6, 8, 10, 12, 14,
  121265. 16,
  121266. };
  121267. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  121268. _vq_quantthresh__16c2_s_p9_1,
  121269. _vq_quantmap__16c2_s_p9_1,
  121270. 17,
  121271. 17
  121272. };
  121273. static static_codebook _16c2_s_p9_1 = {
  121274. 2, 289,
  121275. _vq_lengthlist__16c2_s_p9_1,
  121276. 1, -518488064, 1622704128, 5, 0,
  121277. _vq_quantlist__16c2_s_p9_1,
  121278. NULL,
  121279. &_vq_auxt__16c2_s_p9_1,
  121280. NULL,
  121281. 0
  121282. };
  121283. static long _vq_quantlist__16c2_s_p9_2[] = {
  121284. 13,
  121285. 12,
  121286. 14,
  121287. 11,
  121288. 15,
  121289. 10,
  121290. 16,
  121291. 9,
  121292. 17,
  121293. 8,
  121294. 18,
  121295. 7,
  121296. 19,
  121297. 6,
  121298. 20,
  121299. 5,
  121300. 21,
  121301. 4,
  121302. 22,
  121303. 3,
  121304. 23,
  121305. 2,
  121306. 24,
  121307. 1,
  121308. 25,
  121309. 0,
  121310. 26,
  121311. };
  121312. static long _vq_lengthlist__16c2_s_p9_2[] = {
  121313. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  121314. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  121315. };
  121316. static float _vq_quantthresh__16c2_s_p9_2[] = {
  121317. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  121318. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121319. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  121320. 11.5, 12.5,
  121321. };
  121322. static long _vq_quantmap__16c2_s_p9_2[] = {
  121323. 25, 23, 21, 19, 17, 15, 13, 11,
  121324. 9, 7, 5, 3, 1, 0, 2, 4,
  121325. 6, 8, 10, 12, 14, 16, 18, 20,
  121326. 22, 24, 26,
  121327. };
  121328. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  121329. _vq_quantthresh__16c2_s_p9_2,
  121330. _vq_quantmap__16c2_s_p9_2,
  121331. 27,
  121332. 27
  121333. };
  121334. static static_codebook _16c2_s_p9_2 = {
  121335. 1, 27,
  121336. _vq_lengthlist__16c2_s_p9_2,
  121337. 1, -528875520, 1611661312, 5, 0,
  121338. _vq_quantlist__16c2_s_p9_2,
  121339. NULL,
  121340. &_vq_auxt__16c2_s_p9_2,
  121341. NULL,
  121342. 0
  121343. };
  121344. static long _huff_lengthlist__16c2_s_short[] = {
  121345. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  121346. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  121347. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  121348. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  121349. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  121350. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  121351. 15,12,14,14,
  121352. };
  121353. static static_codebook _huff_book__16c2_s_short = {
  121354. 2, 100,
  121355. _huff_lengthlist__16c2_s_short,
  121356. 0, 0, 0, 0, 0,
  121357. NULL,
  121358. NULL,
  121359. NULL,
  121360. NULL,
  121361. 0
  121362. };
  121363. static long _vq_quantlist__8c0_s_p1_0[] = {
  121364. 1,
  121365. 0,
  121366. 2,
  121367. };
  121368. static long _vq_lengthlist__8c0_s_p1_0[] = {
  121369. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121370. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  121375. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121380. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121415. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  121420. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  121425. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  121426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121460. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121461. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121465. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  121466. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  121467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121470. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  121471. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0,
  121780. };
  121781. static float _vq_quantthresh__8c0_s_p1_0[] = {
  121782. -0.5, 0.5,
  121783. };
  121784. static long _vq_quantmap__8c0_s_p1_0[] = {
  121785. 1, 0, 2,
  121786. };
  121787. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  121788. _vq_quantthresh__8c0_s_p1_0,
  121789. _vq_quantmap__8c0_s_p1_0,
  121790. 3,
  121791. 3
  121792. };
  121793. static static_codebook _8c0_s_p1_0 = {
  121794. 8, 6561,
  121795. _vq_lengthlist__8c0_s_p1_0,
  121796. 1, -535822336, 1611661312, 2, 0,
  121797. _vq_quantlist__8c0_s_p1_0,
  121798. NULL,
  121799. &_vq_auxt__8c0_s_p1_0,
  121800. NULL,
  121801. 0
  121802. };
  121803. static long _vq_quantlist__8c0_s_p2_0[] = {
  121804. 2,
  121805. 1,
  121806. 3,
  121807. 0,
  121808. 4,
  121809. };
  121810. static long _vq_lengthlist__8c0_s_p2_0[] = {
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121850. 0,
  121851. };
  121852. static float _vq_quantthresh__8c0_s_p2_0[] = {
  121853. -1.5, -0.5, 0.5, 1.5,
  121854. };
  121855. static long _vq_quantmap__8c0_s_p2_0[] = {
  121856. 3, 1, 0, 2, 4,
  121857. };
  121858. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  121859. _vq_quantthresh__8c0_s_p2_0,
  121860. _vq_quantmap__8c0_s_p2_0,
  121861. 5,
  121862. 5
  121863. };
  121864. static static_codebook _8c0_s_p2_0 = {
  121865. 4, 625,
  121866. _vq_lengthlist__8c0_s_p2_0,
  121867. 1, -533725184, 1611661312, 3, 0,
  121868. _vq_quantlist__8c0_s_p2_0,
  121869. NULL,
  121870. &_vq_auxt__8c0_s_p2_0,
  121871. NULL,
  121872. 0
  121873. };
  121874. static long _vq_quantlist__8c0_s_p3_0[] = {
  121875. 2,
  121876. 1,
  121877. 3,
  121878. 0,
  121879. 4,
  121880. };
  121881. static long _vq_lengthlist__8c0_s_p3_0[] = {
  121882. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  121889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121921. 0,
  121922. };
  121923. static float _vq_quantthresh__8c0_s_p3_0[] = {
  121924. -1.5, -0.5, 0.5, 1.5,
  121925. };
  121926. static long _vq_quantmap__8c0_s_p3_0[] = {
  121927. 3, 1, 0, 2, 4,
  121928. };
  121929. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  121930. _vq_quantthresh__8c0_s_p3_0,
  121931. _vq_quantmap__8c0_s_p3_0,
  121932. 5,
  121933. 5
  121934. };
  121935. static static_codebook _8c0_s_p3_0 = {
  121936. 4, 625,
  121937. _vq_lengthlist__8c0_s_p3_0,
  121938. 1, -533725184, 1611661312, 3, 0,
  121939. _vq_quantlist__8c0_s_p3_0,
  121940. NULL,
  121941. &_vq_auxt__8c0_s_p3_0,
  121942. NULL,
  121943. 0
  121944. };
  121945. static long _vq_quantlist__8c0_s_p4_0[] = {
  121946. 4,
  121947. 3,
  121948. 5,
  121949. 2,
  121950. 6,
  121951. 1,
  121952. 7,
  121953. 0,
  121954. 8,
  121955. };
  121956. static long _vq_lengthlist__8c0_s_p4_0[] = {
  121957. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121958. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121959. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121960. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121961. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0,
  121963. };
  121964. static float _vq_quantthresh__8c0_s_p4_0[] = {
  121965. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121966. };
  121967. static long _vq_quantmap__8c0_s_p4_0[] = {
  121968. 7, 5, 3, 1, 0, 2, 4, 6,
  121969. 8,
  121970. };
  121971. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  121972. _vq_quantthresh__8c0_s_p4_0,
  121973. _vq_quantmap__8c0_s_p4_0,
  121974. 9,
  121975. 9
  121976. };
  121977. static static_codebook _8c0_s_p4_0 = {
  121978. 2, 81,
  121979. _vq_lengthlist__8c0_s_p4_0,
  121980. 1, -531628032, 1611661312, 4, 0,
  121981. _vq_quantlist__8c0_s_p4_0,
  121982. NULL,
  121983. &_vq_auxt__8c0_s_p4_0,
  121984. NULL,
  121985. 0
  121986. };
  121987. static long _vq_quantlist__8c0_s_p5_0[] = {
  121988. 4,
  121989. 3,
  121990. 5,
  121991. 2,
  121992. 6,
  121993. 1,
  121994. 7,
  121995. 0,
  121996. 8,
  121997. };
  121998. static long _vq_lengthlist__8c0_s_p5_0[] = {
  121999. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122000. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  122001. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  122002. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122003. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122004. 10,
  122005. };
  122006. static float _vq_quantthresh__8c0_s_p5_0[] = {
  122007. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122008. };
  122009. static long _vq_quantmap__8c0_s_p5_0[] = {
  122010. 7, 5, 3, 1, 0, 2, 4, 6,
  122011. 8,
  122012. };
  122013. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  122014. _vq_quantthresh__8c0_s_p5_0,
  122015. _vq_quantmap__8c0_s_p5_0,
  122016. 9,
  122017. 9
  122018. };
  122019. static static_codebook _8c0_s_p5_0 = {
  122020. 2, 81,
  122021. _vq_lengthlist__8c0_s_p5_0,
  122022. 1, -531628032, 1611661312, 4, 0,
  122023. _vq_quantlist__8c0_s_p5_0,
  122024. NULL,
  122025. &_vq_auxt__8c0_s_p5_0,
  122026. NULL,
  122027. 0
  122028. };
  122029. static long _vq_quantlist__8c0_s_p6_0[] = {
  122030. 8,
  122031. 7,
  122032. 9,
  122033. 6,
  122034. 10,
  122035. 5,
  122036. 11,
  122037. 4,
  122038. 12,
  122039. 3,
  122040. 13,
  122041. 2,
  122042. 14,
  122043. 1,
  122044. 15,
  122045. 0,
  122046. 16,
  122047. };
  122048. static long _vq_lengthlist__8c0_s_p6_0[] = {
  122049. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  122050. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122051. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122052. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  122053. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  122054. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  122055. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  122056. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  122057. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  122058. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122059. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  122060. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  122061. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  122062. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  122063. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  122064. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  122065. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  122067. 14,
  122068. };
  122069. static float _vq_quantthresh__8c0_s_p6_0[] = {
  122070. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122071. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122072. };
  122073. static long _vq_quantmap__8c0_s_p6_0[] = {
  122074. 15, 13, 11, 9, 7, 5, 3, 1,
  122075. 0, 2, 4, 6, 8, 10, 12, 14,
  122076. 16,
  122077. };
  122078. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  122079. _vq_quantthresh__8c0_s_p6_0,
  122080. _vq_quantmap__8c0_s_p6_0,
  122081. 17,
  122082. 17
  122083. };
  122084. static static_codebook _8c0_s_p6_0 = {
  122085. 2, 289,
  122086. _vq_lengthlist__8c0_s_p6_0,
  122087. 1, -529530880, 1611661312, 5, 0,
  122088. _vq_quantlist__8c0_s_p6_0,
  122089. NULL,
  122090. &_vq_auxt__8c0_s_p6_0,
  122091. NULL,
  122092. 0
  122093. };
  122094. static long _vq_quantlist__8c0_s_p7_0[] = {
  122095. 1,
  122096. 0,
  122097. 2,
  122098. };
  122099. static long _vq_lengthlist__8c0_s_p7_0[] = {
  122100. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  122101. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  122102. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  122103. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  122104. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  122105. 10,
  122106. };
  122107. static float _vq_quantthresh__8c0_s_p7_0[] = {
  122108. -5.5, 5.5,
  122109. };
  122110. static long _vq_quantmap__8c0_s_p7_0[] = {
  122111. 1, 0, 2,
  122112. };
  122113. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  122114. _vq_quantthresh__8c0_s_p7_0,
  122115. _vq_quantmap__8c0_s_p7_0,
  122116. 3,
  122117. 3
  122118. };
  122119. static static_codebook _8c0_s_p7_0 = {
  122120. 4, 81,
  122121. _vq_lengthlist__8c0_s_p7_0,
  122122. 1, -529137664, 1618345984, 2, 0,
  122123. _vq_quantlist__8c0_s_p7_0,
  122124. NULL,
  122125. &_vq_auxt__8c0_s_p7_0,
  122126. NULL,
  122127. 0
  122128. };
  122129. static long _vq_quantlist__8c0_s_p7_1[] = {
  122130. 5,
  122131. 4,
  122132. 6,
  122133. 3,
  122134. 7,
  122135. 2,
  122136. 8,
  122137. 1,
  122138. 9,
  122139. 0,
  122140. 10,
  122141. };
  122142. static long _vq_lengthlist__8c0_s_p7_1[] = {
  122143. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  122144. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  122145. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  122146. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  122147. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  122148. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  122149. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  122150. 10,10,10, 9, 9, 9,10,10,10,
  122151. };
  122152. static float _vq_quantthresh__8c0_s_p7_1[] = {
  122153. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122154. 3.5, 4.5,
  122155. };
  122156. static long _vq_quantmap__8c0_s_p7_1[] = {
  122157. 9, 7, 5, 3, 1, 0, 2, 4,
  122158. 6, 8, 10,
  122159. };
  122160. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  122161. _vq_quantthresh__8c0_s_p7_1,
  122162. _vq_quantmap__8c0_s_p7_1,
  122163. 11,
  122164. 11
  122165. };
  122166. static static_codebook _8c0_s_p7_1 = {
  122167. 2, 121,
  122168. _vq_lengthlist__8c0_s_p7_1,
  122169. 1, -531365888, 1611661312, 4, 0,
  122170. _vq_quantlist__8c0_s_p7_1,
  122171. NULL,
  122172. &_vq_auxt__8c0_s_p7_1,
  122173. NULL,
  122174. 0
  122175. };
  122176. static long _vq_quantlist__8c0_s_p8_0[] = {
  122177. 6,
  122178. 5,
  122179. 7,
  122180. 4,
  122181. 8,
  122182. 3,
  122183. 9,
  122184. 2,
  122185. 10,
  122186. 1,
  122187. 11,
  122188. 0,
  122189. 12,
  122190. };
  122191. static long _vq_lengthlist__8c0_s_p8_0[] = {
  122192. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  122193. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  122194. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  122195. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  122196. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  122197. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  122198. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  122199. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  122200. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  122201. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  122202. 0, 0,13,13,11,13,13,11,12,
  122203. };
  122204. static float _vq_quantthresh__8c0_s_p8_0[] = {
  122205. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122206. 12.5, 17.5, 22.5, 27.5,
  122207. };
  122208. static long _vq_quantmap__8c0_s_p8_0[] = {
  122209. 11, 9, 7, 5, 3, 1, 0, 2,
  122210. 4, 6, 8, 10, 12,
  122211. };
  122212. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  122213. _vq_quantthresh__8c0_s_p8_0,
  122214. _vq_quantmap__8c0_s_p8_0,
  122215. 13,
  122216. 13
  122217. };
  122218. static static_codebook _8c0_s_p8_0 = {
  122219. 2, 169,
  122220. _vq_lengthlist__8c0_s_p8_0,
  122221. 1, -526516224, 1616117760, 4, 0,
  122222. _vq_quantlist__8c0_s_p8_0,
  122223. NULL,
  122224. &_vq_auxt__8c0_s_p8_0,
  122225. NULL,
  122226. 0
  122227. };
  122228. static long _vq_quantlist__8c0_s_p8_1[] = {
  122229. 2,
  122230. 1,
  122231. 3,
  122232. 0,
  122233. 4,
  122234. };
  122235. static long _vq_lengthlist__8c0_s_p8_1[] = {
  122236. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  122237. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122238. };
  122239. static float _vq_quantthresh__8c0_s_p8_1[] = {
  122240. -1.5, -0.5, 0.5, 1.5,
  122241. };
  122242. static long _vq_quantmap__8c0_s_p8_1[] = {
  122243. 3, 1, 0, 2, 4,
  122244. };
  122245. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  122246. _vq_quantthresh__8c0_s_p8_1,
  122247. _vq_quantmap__8c0_s_p8_1,
  122248. 5,
  122249. 5
  122250. };
  122251. static static_codebook _8c0_s_p8_1 = {
  122252. 2, 25,
  122253. _vq_lengthlist__8c0_s_p8_1,
  122254. 1, -533725184, 1611661312, 3, 0,
  122255. _vq_quantlist__8c0_s_p8_1,
  122256. NULL,
  122257. &_vq_auxt__8c0_s_p8_1,
  122258. NULL,
  122259. 0
  122260. };
  122261. static long _vq_quantlist__8c0_s_p9_0[] = {
  122262. 1,
  122263. 0,
  122264. 2,
  122265. };
  122266. static long _vq_lengthlist__8c0_s_p9_0[] = {
  122267. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122268. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122269. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122270. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122271. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122272. 7,
  122273. };
  122274. static float _vq_quantthresh__8c0_s_p9_0[] = {
  122275. -157.5, 157.5,
  122276. };
  122277. static long _vq_quantmap__8c0_s_p9_0[] = {
  122278. 1, 0, 2,
  122279. };
  122280. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  122281. _vq_quantthresh__8c0_s_p9_0,
  122282. _vq_quantmap__8c0_s_p9_0,
  122283. 3,
  122284. 3
  122285. };
  122286. static static_codebook _8c0_s_p9_0 = {
  122287. 4, 81,
  122288. _vq_lengthlist__8c0_s_p9_0,
  122289. 1, -518803456, 1628680192, 2, 0,
  122290. _vq_quantlist__8c0_s_p9_0,
  122291. NULL,
  122292. &_vq_auxt__8c0_s_p9_0,
  122293. NULL,
  122294. 0
  122295. };
  122296. static long _vq_quantlist__8c0_s_p9_1[] = {
  122297. 7,
  122298. 6,
  122299. 8,
  122300. 5,
  122301. 9,
  122302. 4,
  122303. 10,
  122304. 3,
  122305. 11,
  122306. 2,
  122307. 12,
  122308. 1,
  122309. 13,
  122310. 0,
  122311. 14,
  122312. };
  122313. static long _vq_lengthlist__8c0_s_p9_1[] = {
  122314. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  122315. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  122316. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  122317. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  122318. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122319. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122320. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122321. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122322. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122323. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122324. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122325. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122326. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122327. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122328. 11,
  122329. };
  122330. static float _vq_quantthresh__8c0_s_p9_1[] = {
  122331. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122332. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122333. };
  122334. static long _vq_quantmap__8c0_s_p9_1[] = {
  122335. 13, 11, 9, 7, 5, 3, 1, 0,
  122336. 2, 4, 6, 8, 10, 12, 14,
  122337. };
  122338. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  122339. _vq_quantthresh__8c0_s_p9_1,
  122340. _vq_quantmap__8c0_s_p9_1,
  122341. 15,
  122342. 15
  122343. };
  122344. static static_codebook _8c0_s_p9_1 = {
  122345. 2, 225,
  122346. _vq_lengthlist__8c0_s_p9_1,
  122347. 1, -520986624, 1620377600, 4, 0,
  122348. _vq_quantlist__8c0_s_p9_1,
  122349. NULL,
  122350. &_vq_auxt__8c0_s_p9_1,
  122351. NULL,
  122352. 0
  122353. };
  122354. static long _vq_quantlist__8c0_s_p9_2[] = {
  122355. 10,
  122356. 9,
  122357. 11,
  122358. 8,
  122359. 12,
  122360. 7,
  122361. 13,
  122362. 6,
  122363. 14,
  122364. 5,
  122365. 15,
  122366. 4,
  122367. 16,
  122368. 3,
  122369. 17,
  122370. 2,
  122371. 18,
  122372. 1,
  122373. 19,
  122374. 0,
  122375. 20,
  122376. };
  122377. static long _vq_lengthlist__8c0_s_p9_2[] = {
  122378. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  122379. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  122380. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  122381. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  122382. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  122383. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  122384. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  122385. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  122386. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  122387. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  122388. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  122389. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  122390. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  122391. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  122392. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  122393. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  122394. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  122395. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  122396. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  122397. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  122398. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  122399. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  122400. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  122401. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  122402. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  122403. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  122404. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  122405. 10,11, 9,11,10, 9,10, 9,10,
  122406. };
  122407. static float _vq_quantthresh__8c0_s_p9_2[] = {
  122408. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122409. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122410. 6.5, 7.5, 8.5, 9.5,
  122411. };
  122412. static long _vq_quantmap__8c0_s_p9_2[] = {
  122413. 19, 17, 15, 13, 11, 9, 7, 5,
  122414. 3, 1, 0, 2, 4, 6, 8, 10,
  122415. 12, 14, 16, 18, 20,
  122416. };
  122417. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  122418. _vq_quantthresh__8c0_s_p9_2,
  122419. _vq_quantmap__8c0_s_p9_2,
  122420. 21,
  122421. 21
  122422. };
  122423. static static_codebook _8c0_s_p9_2 = {
  122424. 2, 441,
  122425. _vq_lengthlist__8c0_s_p9_2,
  122426. 1, -529268736, 1611661312, 5, 0,
  122427. _vq_quantlist__8c0_s_p9_2,
  122428. NULL,
  122429. &_vq_auxt__8c0_s_p9_2,
  122430. NULL,
  122431. 0
  122432. };
  122433. static long _huff_lengthlist__8c0_s_single[] = {
  122434. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  122435. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  122436. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  122437. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  122438. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  122439. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  122440. 17,16,17,17,
  122441. };
  122442. static static_codebook _huff_book__8c0_s_single = {
  122443. 2, 100,
  122444. _huff_lengthlist__8c0_s_single,
  122445. 0, 0, 0, 0, 0,
  122446. NULL,
  122447. NULL,
  122448. NULL,
  122449. NULL,
  122450. 0
  122451. };
  122452. static long _vq_quantlist__8c1_s_p1_0[] = {
  122453. 1,
  122454. 0,
  122455. 2,
  122456. };
  122457. static long _vq_lengthlist__8c1_s_p1_0[] = {
  122458. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122459. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122464. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122469. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122504. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122509. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122514. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122550. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  122555. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  122560. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0,
  122869. };
  122870. static float _vq_quantthresh__8c1_s_p1_0[] = {
  122871. -0.5, 0.5,
  122872. };
  122873. static long _vq_quantmap__8c1_s_p1_0[] = {
  122874. 1, 0, 2,
  122875. };
  122876. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  122877. _vq_quantthresh__8c1_s_p1_0,
  122878. _vq_quantmap__8c1_s_p1_0,
  122879. 3,
  122880. 3
  122881. };
  122882. static static_codebook _8c1_s_p1_0 = {
  122883. 8, 6561,
  122884. _vq_lengthlist__8c1_s_p1_0,
  122885. 1, -535822336, 1611661312, 2, 0,
  122886. _vq_quantlist__8c1_s_p1_0,
  122887. NULL,
  122888. &_vq_auxt__8c1_s_p1_0,
  122889. NULL,
  122890. 0
  122891. };
  122892. static long _vq_quantlist__8c1_s_p2_0[] = {
  122893. 2,
  122894. 1,
  122895. 3,
  122896. 0,
  122897. 4,
  122898. };
  122899. static long _vq_lengthlist__8c1_s_p2_0[] = {
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0,
  122940. };
  122941. static float _vq_quantthresh__8c1_s_p2_0[] = {
  122942. -1.5, -0.5, 0.5, 1.5,
  122943. };
  122944. static long _vq_quantmap__8c1_s_p2_0[] = {
  122945. 3, 1, 0, 2, 4,
  122946. };
  122947. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  122948. _vq_quantthresh__8c1_s_p2_0,
  122949. _vq_quantmap__8c1_s_p2_0,
  122950. 5,
  122951. 5
  122952. };
  122953. static static_codebook _8c1_s_p2_0 = {
  122954. 4, 625,
  122955. _vq_lengthlist__8c1_s_p2_0,
  122956. 1, -533725184, 1611661312, 3, 0,
  122957. _vq_quantlist__8c1_s_p2_0,
  122958. NULL,
  122959. &_vq_auxt__8c1_s_p2_0,
  122960. NULL,
  122961. 0
  122962. };
  122963. static long _vq_quantlist__8c1_s_p3_0[] = {
  122964. 2,
  122965. 1,
  122966. 3,
  122967. 0,
  122968. 4,
  122969. };
  122970. static long _vq_lengthlist__8c1_s_p3_0[] = {
  122971. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0,
  123011. };
  123012. static float _vq_quantthresh__8c1_s_p3_0[] = {
  123013. -1.5, -0.5, 0.5, 1.5,
  123014. };
  123015. static long _vq_quantmap__8c1_s_p3_0[] = {
  123016. 3, 1, 0, 2, 4,
  123017. };
  123018. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  123019. _vq_quantthresh__8c1_s_p3_0,
  123020. _vq_quantmap__8c1_s_p3_0,
  123021. 5,
  123022. 5
  123023. };
  123024. static static_codebook _8c1_s_p3_0 = {
  123025. 4, 625,
  123026. _vq_lengthlist__8c1_s_p3_0,
  123027. 1, -533725184, 1611661312, 3, 0,
  123028. _vq_quantlist__8c1_s_p3_0,
  123029. NULL,
  123030. &_vq_auxt__8c1_s_p3_0,
  123031. NULL,
  123032. 0
  123033. };
  123034. static long _vq_quantlist__8c1_s_p4_0[] = {
  123035. 4,
  123036. 3,
  123037. 5,
  123038. 2,
  123039. 6,
  123040. 1,
  123041. 7,
  123042. 0,
  123043. 8,
  123044. };
  123045. static long _vq_lengthlist__8c1_s_p4_0[] = {
  123046. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123047. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123048. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123049. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  123050. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0,
  123052. };
  123053. static float _vq_quantthresh__8c1_s_p4_0[] = {
  123054. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123055. };
  123056. static long _vq_quantmap__8c1_s_p4_0[] = {
  123057. 7, 5, 3, 1, 0, 2, 4, 6,
  123058. 8,
  123059. };
  123060. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  123061. _vq_quantthresh__8c1_s_p4_0,
  123062. _vq_quantmap__8c1_s_p4_0,
  123063. 9,
  123064. 9
  123065. };
  123066. static static_codebook _8c1_s_p4_0 = {
  123067. 2, 81,
  123068. _vq_lengthlist__8c1_s_p4_0,
  123069. 1, -531628032, 1611661312, 4, 0,
  123070. _vq_quantlist__8c1_s_p4_0,
  123071. NULL,
  123072. &_vq_auxt__8c1_s_p4_0,
  123073. NULL,
  123074. 0
  123075. };
  123076. static long _vq_quantlist__8c1_s_p5_0[] = {
  123077. 4,
  123078. 3,
  123079. 5,
  123080. 2,
  123081. 6,
  123082. 1,
  123083. 7,
  123084. 0,
  123085. 8,
  123086. };
  123087. static long _vq_lengthlist__8c1_s_p5_0[] = {
  123088. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  123089. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  123090. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  123091. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  123092. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123093. 10,
  123094. };
  123095. static float _vq_quantthresh__8c1_s_p5_0[] = {
  123096. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123097. };
  123098. static long _vq_quantmap__8c1_s_p5_0[] = {
  123099. 7, 5, 3, 1, 0, 2, 4, 6,
  123100. 8,
  123101. };
  123102. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  123103. _vq_quantthresh__8c1_s_p5_0,
  123104. _vq_quantmap__8c1_s_p5_0,
  123105. 9,
  123106. 9
  123107. };
  123108. static static_codebook _8c1_s_p5_0 = {
  123109. 2, 81,
  123110. _vq_lengthlist__8c1_s_p5_0,
  123111. 1, -531628032, 1611661312, 4, 0,
  123112. _vq_quantlist__8c1_s_p5_0,
  123113. NULL,
  123114. &_vq_auxt__8c1_s_p5_0,
  123115. NULL,
  123116. 0
  123117. };
  123118. static long _vq_quantlist__8c1_s_p6_0[] = {
  123119. 8,
  123120. 7,
  123121. 9,
  123122. 6,
  123123. 10,
  123124. 5,
  123125. 11,
  123126. 4,
  123127. 12,
  123128. 3,
  123129. 13,
  123130. 2,
  123131. 14,
  123132. 1,
  123133. 15,
  123134. 0,
  123135. 16,
  123136. };
  123137. static long _vq_lengthlist__8c1_s_p6_0[] = {
  123138. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  123139. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123140. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123141. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  123142. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  123143. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  123144. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  123145. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  123146. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123147. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123148. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123149. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  123150. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123151. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123152. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123153. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  123154. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123156. 14,
  123157. };
  123158. static float _vq_quantthresh__8c1_s_p6_0[] = {
  123159. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123160. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123161. };
  123162. static long _vq_quantmap__8c1_s_p6_0[] = {
  123163. 15, 13, 11, 9, 7, 5, 3, 1,
  123164. 0, 2, 4, 6, 8, 10, 12, 14,
  123165. 16,
  123166. };
  123167. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  123168. _vq_quantthresh__8c1_s_p6_0,
  123169. _vq_quantmap__8c1_s_p6_0,
  123170. 17,
  123171. 17
  123172. };
  123173. static static_codebook _8c1_s_p6_0 = {
  123174. 2, 289,
  123175. _vq_lengthlist__8c1_s_p6_0,
  123176. 1, -529530880, 1611661312, 5, 0,
  123177. _vq_quantlist__8c1_s_p6_0,
  123178. NULL,
  123179. &_vq_auxt__8c1_s_p6_0,
  123180. NULL,
  123181. 0
  123182. };
  123183. static long _vq_quantlist__8c1_s_p7_0[] = {
  123184. 1,
  123185. 0,
  123186. 2,
  123187. };
  123188. static long _vq_lengthlist__8c1_s_p7_0[] = {
  123189. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  123190. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  123191. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  123192. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  123193. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  123194. 9,
  123195. };
  123196. static float _vq_quantthresh__8c1_s_p7_0[] = {
  123197. -5.5, 5.5,
  123198. };
  123199. static long _vq_quantmap__8c1_s_p7_0[] = {
  123200. 1, 0, 2,
  123201. };
  123202. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  123203. _vq_quantthresh__8c1_s_p7_0,
  123204. _vq_quantmap__8c1_s_p7_0,
  123205. 3,
  123206. 3
  123207. };
  123208. static static_codebook _8c1_s_p7_0 = {
  123209. 4, 81,
  123210. _vq_lengthlist__8c1_s_p7_0,
  123211. 1, -529137664, 1618345984, 2, 0,
  123212. _vq_quantlist__8c1_s_p7_0,
  123213. NULL,
  123214. &_vq_auxt__8c1_s_p7_0,
  123215. NULL,
  123216. 0
  123217. };
  123218. static long _vq_quantlist__8c1_s_p7_1[] = {
  123219. 5,
  123220. 4,
  123221. 6,
  123222. 3,
  123223. 7,
  123224. 2,
  123225. 8,
  123226. 1,
  123227. 9,
  123228. 0,
  123229. 10,
  123230. };
  123231. static long _vq_lengthlist__8c1_s_p7_1[] = {
  123232. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  123233. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  123234. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123235. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123236. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123237. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123238. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  123239. 10,10,10, 8, 8, 8, 8, 8, 8,
  123240. };
  123241. static float _vq_quantthresh__8c1_s_p7_1[] = {
  123242. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123243. 3.5, 4.5,
  123244. };
  123245. static long _vq_quantmap__8c1_s_p7_1[] = {
  123246. 9, 7, 5, 3, 1, 0, 2, 4,
  123247. 6, 8, 10,
  123248. };
  123249. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  123250. _vq_quantthresh__8c1_s_p7_1,
  123251. _vq_quantmap__8c1_s_p7_1,
  123252. 11,
  123253. 11
  123254. };
  123255. static static_codebook _8c1_s_p7_1 = {
  123256. 2, 121,
  123257. _vq_lengthlist__8c1_s_p7_1,
  123258. 1, -531365888, 1611661312, 4, 0,
  123259. _vq_quantlist__8c1_s_p7_1,
  123260. NULL,
  123261. &_vq_auxt__8c1_s_p7_1,
  123262. NULL,
  123263. 0
  123264. };
  123265. static long _vq_quantlist__8c1_s_p8_0[] = {
  123266. 6,
  123267. 5,
  123268. 7,
  123269. 4,
  123270. 8,
  123271. 3,
  123272. 9,
  123273. 2,
  123274. 10,
  123275. 1,
  123276. 11,
  123277. 0,
  123278. 12,
  123279. };
  123280. static long _vq_lengthlist__8c1_s_p8_0[] = {
  123281. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  123282. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  123283. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123284. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123285. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  123286. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  123287. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  123288. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  123289. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  123290. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  123291. 0,12,12,11,10,12,11,13,12,
  123292. };
  123293. static float _vq_quantthresh__8c1_s_p8_0[] = {
  123294. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123295. 12.5, 17.5, 22.5, 27.5,
  123296. };
  123297. static long _vq_quantmap__8c1_s_p8_0[] = {
  123298. 11, 9, 7, 5, 3, 1, 0, 2,
  123299. 4, 6, 8, 10, 12,
  123300. };
  123301. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  123302. _vq_quantthresh__8c1_s_p8_0,
  123303. _vq_quantmap__8c1_s_p8_0,
  123304. 13,
  123305. 13
  123306. };
  123307. static static_codebook _8c1_s_p8_0 = {
  123308. 2, 169,
  123309. _vq_lengthlist__8c1_s_p8_0,
  123310. 1, -526516224, 1616117760, 4, 0,
  123311. _vq_quantlist__8c1_s_p8_0,
  123312. NULL,
  123313. &_vq_auxt__8c1_s_p8_0,
  123314. NULL,
  123315. 0
  123316. };
  123317. static long _vq_quantlist__8c1_s_p8_1[] = {
  123318. 2,
  123319. 1,
  123320. 3,
  123321. 0,
  123322. 4,
  123323. };
  123324. static long _vq_lengthlist__8c1_s_p8_1[] = {
  123325. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123326. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123327. };
  123328. static float _vq_quantthresh__8c1_s_p8_1[] = {
  123329. -1.5, -0.5, 0.5, 1.5,
  123330. };
  123331. static long _vq_quantmap__8c1_s_p8_1[] = {
  123332. 3, 1, 0, 2, 4,
  123333. };
  123334. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  123335. _vq_quantthresh__8c1_s_p8_1,
  123336. _vq_quantmap__8c1_s_p8_1,
  123337. 5,
  123338. 5
  123339. };
  123340. static static_codebook _8c1_s_p8_1 = {
  123341. 2, 25,
  123342. _vq_lengthlist__8c1_s_p8_1,
  123343. 1, -533725184, 1611661312, 3, 0,
  123344. _vq_quantlist__8c1_s_p8_1,
  123345. NULL,
  123346. &_vq_auxt__8c1_s_p8_1,
  123347. NULL,
  123348. 0
  123349. };
  123350. static long _vq_quantlist__8c1_s_p9_0[] = {
  123351. 6,
  123352. 5,
  123353. 7,
  123354. 4,
  123355. 8,
  123356. 3,
  123357. 9,
  123358. 2,
  123359. 10,
  123360. 1,
  123361. 11,
  123362. 0,
  123363. 12,
  123364. };
  123365. static long _vq_lengthlist__8c1_s_p9_0[] = {
  123366. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  123367. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  123368. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123369. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123370. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123371. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123373. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123374. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123375. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123376. 10,10,10,10,10, 9, 9, 9, 9,
  123377. };
  123378. static float _vq_quantthresh__8c1_s_p9_0[] = {
  123379. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123380. 787.5, 1102.5, 1417.5, 1732.5,
  123381. };
  123382. static long _vq_quantmap__8c1_s_p9_0[] = {
  123383. 11, 9, 7, 5, 3, 1, 0, 2,
  123384. 4, 6, 8, 10, 12,
  123385. };
  123386. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  123387. _vq_quantthresh__8c1_s_p9_0,
  123388. _vq_quantmap__8c1_s_p9_0,
  123389. 13,
  123390. 13
  123391. };
  123392. static static_codebook _8c1_s_p9_0 = {
  123393. 2, 169,
  123394. _vq_lengthlist__8c1_s_p9_0,
  123395. 1, -513964032, 1628680192, 4, 0,
  123396. _vq_quantlist__8c1_s_p9_0,
  123397. NULL,
  123398. &_vq_auxt__8c1_s_p9_0,
  123399. NULL,
  123400. 0
  123401. };
  123402. static long _vq_quantlist__8c1_s_p9_1[] = {
  123403. 7,
  123404. 6,
  123405. 8,
  123406. 5,
  123407. 9,
  123408. 4,
  123409. 10,
  123410. 3,
  123411. 11,
  123412. 2,
  123413. 12,
  123414. 1,
  123415. 13,
  123416. 0,
  123417. 14,
  123418. };
  123419. static long _vq_lengthlist__8c1_s_p9_1[] = {
  123420. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  123421. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  123422. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  123423. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  123424. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  123425. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  123426. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  123427. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  123428. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  123429. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  123430. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  123431. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  123432. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  123433. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  123434. 15,
  123435. };
  123436. static float _vq_quantthresh__8c1_s_p9_1[] = {
  123437. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123438. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123439. };
  123440. static long _vq_quantmap__8c1_s_p9_1[] = {
  123441. 13, 11, 9, 7, 5, 3, 1, 0,
  123442. 2, 4, 6, 8, 10, 12, 14,
  123443. };
  123444. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  123445. _vq_quantthresh__8c1_s_p9_1,
  123446. _vq_quantmap__8c1_s_p9_1,
  123447. 15,
  123448. 15
  123449. };
  123450. static static_codebook _8c1_s_p9_1 = {
  123451. 2, 225,
  123452. _vq_lengthlist__8c1_s_p9_1,
  123453. 1, -520986624, 1620377600, 4, 0,
  123454. _vq_quantlist__8c1_s_p9_1,
  123455. NULL,
  123456. &_vq_auxt__8c1_s_p9_1,
  123457. NULL,
  123458. 0
  123459. };
  123460. static long _vq_quantlist__8c1_s_p9_2[] = {
  123461. 10,
  123462. 9,
  123463. 11,
  123464. 8,
  123465. 12,
  123466. 7,
  123467. 13,
  123468. 6,
  123469. 14,
  123470. 5,
  123471. 15,
  123472. 4,
  123473. 16,
  123474. 3,
  123475. 17,
  123476. 2,
  123477. 18,
  123478. 1,
  123479. 19,
  123480. 0,
  123481. 20,
  123482. };
  123483. static long _vq_lengthlist__8c1_s_p9_2[] = {
  123484. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  123485. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  123486. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  123487. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  123488. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123489. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  123490. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  123491. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  123492. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  123493. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  123494. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  123495. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  123496. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  123497. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  123498. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  123499. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  123500. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123501. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  123502. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  123503. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  123504. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123505. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  123506. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  123507. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  123508. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  123509. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  123510. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  123511. 10,10,10,10,10,10,10,10,10,
  123512. };
  123513. static float _vq_quantthresh__8c1_s_p9_2[] = {
  123514. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123515. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123516. 6.5, 7.5, 8.5, 9.5,
  123517. };
  123518. static long _vq_quantmap__8c1_s_p9_2[] = {
  123519. 19, 17, 15, 13, 11, 9, 7, 5,
  123520. 3, 1, 0, 2, 4, 6, 8, 10,
  123521. 12, 14, 16, 18, 20,
  123522. };
  123523. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  123524. _vq_quantthresh__8c1_s_p9_2,
  123525. _vq_quantmap__8c1_s_p9_2,
  123526. 21,
  123527. 21
  123528. };
  123529. static static_codebook _8c1_s_p9_2 = {
  123530. 2, 441,
  123531. _vq_lengthlist__8c1_s_p9_2,
  123532. 1, -529268736, 1611661312, 5, 0,
  123533. _vq_quantlist__8c1_s_p9_2,
  123534. NULL,
  123535. &_vq_auxt__8c1_s_p9_2,
  123536. NULL,
  123537. 0
  123538. };
  123539. static long _huff_lengthlist__8c1_s_single[] = {
  123540. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  123541. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  123542. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  123543. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  123544. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  123545. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  123546. 9, 7, 7, 8,
  123547. };
  123548. static static_codebook _huff_book__8c1_s_single = {
  123549. 2, 100,
  123550. _huff_lengthlist__8c1_s_single,
  123551. 0, 0, 0, 0, 0,
  123552. NULL,
  123553. NULL,
  123554. NULL,
  123555. NULL,
  123556. 0
  123557. };
  123558. static long _huff_lengthlist__44c2_s_long[] = {
  123559. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  123560. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  123561. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  123562. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  123563. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  123564. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  123565. 10, 8, 8, 9,
  123566. };
  123567. static static_codebook _huff_book__44c2_s_long = {
  123568. 2, 100,
  123569. _huff_lengthlist__44c2_s_long,
  123570. 0, 0, 0, 0, 0,
  123571. NULL,
  123572. NULL,
  123573. NULL,
  123574. NULL,
  123575. 0
  123576. };
  123577. static long _vq_quantlist__44c2_s_p1_0[] = {
  123578. 1,
  123579. 0,
  123580. 2,
  123581. };
  123582. static long _vq_lengthlist__44c2_s_p1_0[] = {
  123583. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123584. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123589. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123594. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123629. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123634. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123639. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123675. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123680. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123685. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0,
  123994. };
  123995. static float _vq_quantthresh__44c2_s_p1_0[] = {
  123996. -0.5, 0.5,
  123997. };
  123998. static long _vq_quantmap__44c2_s_p1_0[] = {
  123999. 1, 0, 2,
  124000. };
  124001. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  124002. _vq_quantthresh__44c2_s_p1_0,
  124003. _vq_quantmap__44c2_s_p1_0,
  124004. 3,
  124005. 3
  124006. };
  124007. static static_codebook _44c2_s_p1_0 = {
  124008. 8, 6561,
  124009. _vq_lengthlist__44c2_s_p1_0,
  124010. 1, -535822336, 1611661312, 2, 0,
  124011. _vq_quantlist__44c2_s_p1_0,
  124012. NULL,
  124013. &_vq_auxt__44c2_s_p1_0,
  124014. NULL,
  124015. 0
  124016. };
  124017. static long _vq_quantlist__44c2_s_p2_0[] = {
  124018. 2,
  124019. 1,
  124020. 3,
  124021. 0,
  124022. 4,
  124023. };
  124024. static long _vq_lengthlist__44c2_s_p2_0[] = {
  124025. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  124026. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  124027. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  124028. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  124029. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  124035. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  124036. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  124037. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  124043. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  124044. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  124051. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  124052. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0,
  124065. };
  124066. static float _vq_quantthresh__44c2_s_p2_0[] = {
  124067. -1.5, -0.5, 0.5, 1.5,
  124068. };
  124069. static long _vq_quantmap__44c2_s_p2_0[] = {
  124070. 3, 1, 0, 2, 4,
  124071. };
  124072. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  124073. _vq_quantthresh__44c2_s_p2_0,
  124074. _vq_quantmap__44c2_s_p2_0,
  124075. 5,
  124076. 5
  124077. };
  124078. static static_codebook _44c2_s_p2_0 = {
  124079. 4, 625,
  124080. _vq_lengthlist__44c2_s_p2_0,
  124081. 1, -533725184, 1611661312, 3, 0,
  124082. _vq_quantlist__44c2_s_p2_0,
  124083. NULL,
  124084. &_vq_auxt__44c2_s_p2_0,
  124085. NULL,
  124086. 0
  124087. };
  124088. static long _vq_quantlist__44c2_s_p3_0[] = {
  124089. 2,
  124090. 1,
  124091. 3,
  124092. 0,
  124093. 4,
  124094. };
  124095. static long _vq_lengthlist__44c2_s_p3_0[] = {
  124096. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0,
  124136. };
  124137. static float _vq_quantthresh__44c2_s_p3_0[] = {
  124138. -1.5, -0.5, 0.5, 1.5,
  124139. };
  124140. static long _vq_quantmap__44c2_s_p3_0[] = {
  124141. 3, 1, 0, 2, 4,
  124142. };
  124143. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  124144. _vq_quantthresh__44c2_s_p3_0,
  124145. _vq_quantmap__44c2_s_p3_0,
  124146. 5,
  124147. 5
  124148. };
  124149. static static_codebook _44c2_s_p3_0 = {
  124150. 4, 625,
  124151. _vq_lengthlist__44c2_s_p3_0,
  124152. 1, -533725184, 1611661312, 3, 0,
  124153. _vq_quantlist__44c2_s_p3_0,
  124154. NULL,
  124155. &_vq_auxt__44c2_s_p3_0,
  124156. NULL,
  124157. 0
  124158. };
  124159. static long _vq_quantlist__44c2_s_p4_0[] = {
  124160. 4,
  124161. 3,
  124162. 5,
  124163. 2,
  124164. 6,
  124165. 1,
  124166. 7,
  124167. 0,
  124168. 8,
  124169. };
  124170. static long _vq_lengthlist__44c2_s_p4_0[] = {
  124171. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  124172. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  124173. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  124174. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  124175. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0,
  124177. };
  124178. static float _vq_quantthresh__44c2_s_p4_0[] = {
  124179. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124180. };
  124181. static long _vq_quantmap__44c2_s_p4_0[] = {
  124182. 7, 5, 3, 1, 0, 2, 4, 6,
  124183. 8,
  124184. };
  124185. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  124186. _vq_quantthresh__44c2_s_p4_0,
  124187. _vq_quantmap__44c2_s_p4_0,
  124188. 9,
  124189. 9
  124190. };
  124191. static static_codebook _44c2_s_p4_0 = {
  124192. 2, 81,
  124193. _vq_lengthlist__44c2_s_p4_0,
  124194. 1, -531628032, 1611661312, 4, 0,
  124195. _vq_quantlist__44c2_s_p4_0,
  124196. NULL,
  124197. &_vq_auxt__44c2_s_p4_0,
  124198. NULL,
  124199. 0
  124200. };
  124201. static long _vq_quantlist__44c2_s_p5_0[] = {
  124202. 4,
  124203. 3,
  124204. 5,
  124205. 2,
  124206. 6,
  124207. 1,
  124208. 7,
  124209. 0,
  124210. 8,
  124211. };
  124212. static long _vq_lengthlist__44c2_s_p5_0[] = {
  124213. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  124214. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  124215. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124216. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124217. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  124218. 11,
  124219. };
  124220. static float _vq_quantthresh__44c2_s_p5_0[] = {
  124221. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124222. };
  124223. static long _vq_quantmap__44c2_s_p5_0[] = {
  124224. 7, 5, 3, 1, 0, 2, 4, 6,
  124225. 8,
  124226. };
  124227. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  124228. _vq_quantthresh__44c2_s_p5_0,
  124229. _vq_quantmap__44c2_s_p5_0,
  124230. 9,
  124231. 9
  124232. };
  124233. static static_codebook _44c2_s_p5_0 = {
  124234. 2, 81,
  124235. _vq_lengthlist__44c2_s_p5_0,
  124236. 1, -531628032, 1611661312, 4, 0,
  124237. _vq_quantlist__44c2_s_p5_0,
  124238. NULL,
  124239. &_vq_auxt__44c2_s_p5_0,
  124240. NULL,
  124241. 0
  124242. };
  124243. static long _vq_quantlist__44c2_s_p6_0[] = {
  124244. 8,
  124245. 7,
  124246. 9,
  124247. 6,
  124248. 10,
  124249. 5,
  124250. 11,
  124251. 4,
  124252. 12,
  124253. 3,
  124254. 13,
  124255. 2,
  124256. 14,
  124257. 1,
  124258. 15,
  124259. 0,
  124260. 16,
  124261. };
  124262. static long _vq_lengthlist__44c2_s_p6_0[] = {
  124263. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  124264. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124265. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124266. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  124267. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  124268. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124269. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124270. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124271. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124272. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124273. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124274. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124275. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  124276. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124277. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  124278. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  124279. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124281. 14,
  124282. };
  124283. static float _vq_quantthresh__44c2_s_p6_0[] = {
  124284. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124285. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124286. };
  124287. static long _vq_quantmap__44c2_s_p6_0[] = {
  124288. 15, 13, 11, 9, 7, 5, 3, 1,
  124289. 0, 2, 4, 6, 8, 10, 12, 14,
  124290. 16,
  124291. };
  124292. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  124293. _vq_quantthresh__44c2_s_p6_0,
  124294. _vq_quantmap__44c2_s_p6_0,
  124295. 17,
  124296. 17
  124297. };
  124298. static static_codebook _44c2_s_p6_0 = {
  124299. 2, 289,
  124300. _vq_lengthlist__44c2_s_p6_0,
  124301. 1, -529530880, 1611661312, 5, 0,
  124302. _vq_quantlist__44c2_s_p6_0,
  124303. NULL,
  124304. &_vq_auxt__44c2_s_p6_0,
  124305. NULL,
  124306. 0
  124307. };
  124308. static long _vq_quantlist__44c2_s_p7_0[] = {
  124309. 1,
  124310. 0,
  124311. 2,
  124312. };
  124313. static long _vq_lengthlist__44c2_s_p7_0[] = {
  124314. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124315. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  124316. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124317. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  124318. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  124319. 11,
  124320. };
  124321. static float _vq_quantthresh__44c2_s_p7_0[] = {
  124322. -5.5, 5.5,
  124323. };
  124324. static long _vq_quantmap__44c2_s_p7_0[] = {
  124325. 1, 0, 2,
  124326. };
  124327. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  124328. _vq_quantthresh__44c2_s_p7_0,
  124329. _vq_quantmap__44c2_s_p7_0,
  124330. 3,
  124331. 3
  124332. };
  124333. static static_codebook _44c2_s_p7_0 = {
  124334. 4, 81,
  124335. _vq_lengthlist__44c2_s_p7_0,
  124336. 1, -529137664, 1618345984, 2, 0,
  124337. _vq_quantlist__44c2_s_p7_0,
  124338. NULL,
  124339. &_vq_auxt__44c2_s_p7_0,
  124340. NULL,
  124341. 0
  124342. };
  124343. static long _vq_quantlist__44c2_s_p7_1[] = {
  124344. 5,
  124345. 4,
  124346. 6,
  124347. 3,
  124348. 7,
  124349. 2,
  124350. 8,
  124351. 1,
  124352. 9,
  124353. 0,
  124354. 10,
  124355. };
  124356. static long _vq_lengthlist__44c2_s_p7_1[] = {
  124357. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  124358. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  124359. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124360. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124361. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124362. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124363. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  124364. 10,10,10, 8, 8, 8, 8, 8, 8,
  124365. };
  124366. static float _vq_quantthresh__44c2_s_p7_1[] = {
  124367. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124368. 3.5, 4.5,
  124369. };
  124370. static long _vq_quantmap__44c2_s_p7_1[] = {
  124371. 9, 7, 5, 3, 1, 0, 2, 4,
  124372. 6, 8, 10,
  124373. };
  124374. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  124375. _vq_quantthresh__44c2_s_p7_1,
  124376. _vq_quantmap__44c2_s_p7_1,
  124377. 11,
  124378. 11
  124379. };
  124380. static static_codebook _44c2_s_p7_1 = {
  124381. 2, 121,
  124382. _vq_lengthlist__44c2_s_p7_1,
  124383. 1, -531365888, 1611661312, 4, 0,
  124384. _vq_quantlist__44c2_s_p7_1,
  124385. NULL,
  124386. &_vq_auxt__44c2_s_p7_1,
  124387. NULL,
  124388. 0
  124389. };
  124390. static long _vq_quantlist__44c2_s_p8_0[] = {
  124391. 6,
  124392. 5,
  124393. 7,
  124394. 4,
  124395. 8,
  124396. 3,
  124397. 9,
  124398. 2,
  124399. 10,
  124400. 1,
  124401. 11,
  124402. 0,
  124403. 12,
  124404. };
  124405. static long _vq_lengthlist__44c2_s_p8_0[] = {
  124406. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124407. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  124408. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124409. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124410. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  124411. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124412. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  124413. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  124414. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  124415. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  124416. 0,12,12,12,12,13,12,14,14,
  124417. };
  124418. static float _vq_quantthresh__44c2_s_p8_0[] = {
  124419. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124420. 12.5, 17.5, 22.5, 27.5,
  124421. };
  124422. static long _vq_quantmap__44c2_s_p8_0[] = {
  124423. 11, 9, 7, 5, 3, 1, 0, 2,
  124424. 4, 6, 8, 10, 12,
  124425. };
  124426. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  124427. _vq_quantthresh__44c2_s_p8_0,
  124428. _vq_quantmap__44c2_s_p8_0,
  124429. 13,
  124430. 13
  124431. };
  124432. static static_codebook _44c2_s_p8_0 = {
  124433. 2, 169,
  124434. _vq_lengthlist__44c2_s_p8_0,
  124435. 1, -526516224, 1616117760, 4, 0,
  124436. _vq_quantlist__44c2_s_p8_0,
  124437. NULL,
  124438. &_vq_auxt__44c2_s_p8_0,
  124439. NULL,
  124440. 0
  124441. };
  124442. static long _vq_quantlist__44c2_s_p8_1[] = {
  124443. 2,
  124444. 1,
  124445. 3,
  124446. 0,
  124447. 4,
  124448. };
  124449. static long _vq_lengthlist__44c2_s_p8_1[] = {
  124450. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  124451. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124452. };
  124453. static float _vq_quantthresh__44c2_s_p8_1[] = {
  124454. -1.5, -0.5, 0.5, 1.5,
  124455. };
  124456. static long _vq_quantmap__44c2_s_p8_1[] = {
  124457. 3, 1, 0, 2, 4,
  124458. };
  124459. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  124460. _vq_quantthresh__44c2_s_p8_1,
  124461. _vq_quantmap__44c2_s_p8_1,
  124462. 5,
  124463. 5
  124464. };
  124465. static static_codebook _44c2_s_p8_1 = {
  124466. 2, 25,
  124467. _vq_lengthlist__44c2_s_p8_1,
  124468. 1, -533725184, 1611661312, 3, 0,
  124469. _vq_quantlist__44c2_s_p8_1,
  124470. NULL,
  124471. &_vq_auxt__44c2_s_p8_1,
  124472. NULL,
  124473. 0
  124474. };
  124475. static long _vq_quantlist__44c2_s_p9_0[] = {
  124476. 6,
  124477. 5,
  124478. 7,
  124479. 4,
  124480. 8,
  124481. 3,
  124482. 9,
  124483. 2,
  124484. 10,
  124485. 1,
  124486. 11,
  124487. 0,
  124488. 12,
  124489. };
  124490. static long _vq_lengthlist__44c2_s_p9_0[] = {
  124491. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124492. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  124493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124494. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  124495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124501. 11,11,11,11,11,11,11,11,11,
  124502. };
  124503. static float _vq_quantthresh__44c2_s_p9_0[] = {
  124504. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  124505. 552.5, 773.5, 994.5, 1215.5,
  124506. };
  124507. static long _vq_quantmap__44c2_s_p9_0[] = {
  124508. 11, 9, 7, 5, 3, 1, 0, 2,
  124509. 4, 6, 8, 10, 12,
  124510. };
  124511. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  124512. _vq_quantthresh__44c2_s_p9_0,
  124513. _vq_quantmap__44c2_s_p9_0,
  124514. 13,
  124515. 13
  124516. };
  124517. static static_codebook _44c2_s_p9_0 = {
  124518. 2, 169,
  124519. _vq_lengthlist__44c2_s_p9_0,
  124520. 1, -514541568, 1627103232, 4, 0,
  124521. _vq_quantlist__44c2_s_p9_0,
  124522. NULL,
  124523. &_vq_auxt__44c2_s_p9_0,
  124524. NULL,
  124525. 0
  124526. };
  124527. static long _vq_quantlist__44c2_s_p9_1[] = {
  124528. 6,
  124529. 5,
  124530. 7,
  124531. 4,
  124532. 8,
  124533. 3,
  124534. 9,
  124535. 2,
  124536. 10,
  124537. 1,
  124538. 11,
  124539. 0,
  124540. 12,
  124541. };
  124542. static long _vq_lengthlist__44c2_s_p9_1[] = {
  124543. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  124544. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  124545. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  124546. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  124547. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  124548. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  124549. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  124550. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  124551. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  124552. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  124553. 17,13,12,12,10,13,11,14,14,
  124554. };
  124555. static float _vq_quantthresh__44c2_s_p9_1[] = {
  124556. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  124557. 42.5, 59.5, 76.5, 93.5,
  124558. };
  124559. static long _vq_quantmap__44c2_s_p9_1[] = {
  124560. 11, 9, 7, 5, 3, 1, 0, 2,
  124561. 4, 6, 8, 10, 12,
  124562. };
  124563. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  124564. _vq_quantthresh__44c2_s_p9_1,
  124565. _vq_quantmap__44c2_s_p9_1,
  124566. 13,
  124567. 13
  124568. };
  124569. static static_codebook _44c2_s_p9_1 = {
  124570. 2, 169,
  124571. _vq_lengthlist__44c2_s_p9_1,
  124572. 1, -522616832, 1620115456, 4, 0,
  124573. _vq_quantlist__44c2_s_p9_1,
  124574. NULL,
  124575. &_vq_auxt__44c2_s_p9_1,
  124576. NULL,
  124577. 0
  124578. };
  124579. static long _vq_quantlist__44c2_s_p9_2[] = {
  124580. 8,
  124581. 7,
  124582. 9,
  124583. 6,
  124584. 10,
  124585. 5,
  124586. 11,
  124587. 4,
  124588. 12,
  124589. 3,
  124590. 13,
  124591. 2,
  124592. 14,
  124593. 1,
  124594. 15,
  124595. 0,
  124596. 16,
  124597. };
  124598. static long _vq_lengthlist__44c2_s_p9_2[] = {
  124599. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124600. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124601. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  124602. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  124603. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  124604. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124605. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  124606. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  124607. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  124608. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  124609. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  124610. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  124611. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  124612. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  124613. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  124614. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  124615. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  124616. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  124617. 10,
  124618. };
  124619. static float _vq_quantthresh__44c2_s_p9_2[] = {
  124620. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124621. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124622. };
  124623. static long _vq_quantmap__44c2_s_p9_2[] = {
  124624. 15, 13, 11, 9, 7, 5, 3, 1,
  124625. 0, 2, 4, 6, 8, 10, 12, 14,
  124626. 16,
  124627. };
  124628. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  124629. _vq_quantthresh__44c2_s_p9_2,
  124630. _vq_quantmap__44c2_s_p9_2,
  124631. 17,
  124632. 17
  124633. };
  124634. static static_codebook _44c2_s_p9_2 = {
  124635. 2, 289,
  124636. _vq_lengthlist__44c2_s_p9_2,
  124637. 1, -529530880, 1611661312, 5, 0,
  124638. _vq_quantlist__44c2_s_p9_2,
  124639. NULL,
  124640. &_vq_auxt__44c2_s_p9_2,
  124641. NULL,
  124642. 0
  124643. };
  124644. static long _huff_lengthlist__44c2_s_short[] = {
  124645. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  124646. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  124647. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  124648. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  124649. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  124650. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  124651. 6, 8, 9,12,
  124652. };
  124653. static static_codebook _huff_book__44c2_s_short = {
  124654. 2, 100,
  124655. _huff_lengthlist__44c2_s_short,
  124656. 0, 0, 0, 0, 0,
  124657. NULL,
  124658. NULL,
  124659. NULL,
  124660. NULL,
  124661. 0
  124662. };
  124663. static long _huff_lengthlist__44c3_s_long[] = {
  124664. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  124665. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  124666. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  124667. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  124668. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  124669. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  124670. 9, 8, 8, 8,
  124671. };
  124672. static static_codebook _huff_book__44c3_s_long = {
  124673. 2, 100,
  124674. _huff_lengthlist__44c3_s_long,
  124675. 0, 0, 0, 0, 0,
  124676. NULL,
  124677. NULL,
  124678. NULL,
  124679. NULL,
  124680. 0
  124681. };
  124682. static long _vq_quantlist__44c3_s_p1_0[] = {
  124683. 1,
  124684. 0,
  124685. 2,
  124686. };
  124687. static long _vq_lengthlist__44c3_s_p1_0[] = {
  124688. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124689. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124694. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124699. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124734. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124739. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124744. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124780. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124785. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124790. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0,
  125099. };
  125100. static float _vq_quantthresh__44c3_s_p1_0[] = {
  125101. -0.5, 0.5,
  125102. };
  125103. static long _vq_quantmap__44c3_s_p1_0[] = {
  125104. 1, 0, 2,
  125105. };
  125106. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  125107. _vq_quantthresh__44c3_s_p1_0,
  125108. _vq_quantmap__44c3_s_p1_0,
  125109. 3,
  125110. 3
  125111. };
  125112. static static_codebook _44c3_s_p1_0 = {
  125113. 8, 6561,
  125114. _vq_lengthlist__44c3_s_p1_0,
  125115. 1, -535822336, 1611661312, 2, 0,
  125116. _vq_quantlist__44c3_s_p1_0,
  125117. NULL,
  125118. &_vq_auxt__44c3_s_p1_0,
  125119. NULL,
  125120. 0
  125121. };
  125122. static long _vq_quantlist__44c3_s_p2_0[] = {
  125123. 2,
  125124. 1,
  125125. 3,
  125126. 0,
  125127. 4,
  125128. };
  125129. static long _vq_lengthlist__44c3_s_p2_0[] = {
  125130. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125131. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125132. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125133. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125134. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  125140. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125141. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125142. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125148. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125149. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125156. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125157. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0,
  125170. };
  125171. static float _vq_quantthresh__44c3_s_p2_0[] = {
  125172. -1.5, -0.5, 0.5, 1.5,
  125173. };
  125174. static long _vq_quantmap__44c3_s_p2_0[] = {
  125175. 3, 1, 0, 2, 4,
  125176. };
  125177. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  125178. _vq_quantthresh__44c3_s_p2_0,
  125179. _vq_quantmap__44c3_s_p2_0,
  125180. 5,
  125181. 5
  125182. };
  125183. static static_codebook _44c3_s_p2_0 = {
  125184. 4, 625,
  125185. _vq_lengthlist__44c3_s_p2_0,
  125186. 1, -533725184, 1611661312, 3, 0,
  125187. _vq_quantlist__44c3_s_p2_0,
  125188. NULL,
  125189. &_vq_auxt__44c3_s_p2_0,
  125190. NULL,
  125191. 0
  125192. };
  125193. static long _vq_quantlist__44c3_s_p3_0[] = {
  125194. 2,
  125195. 1,
  125196. 3,
  125197. 0,
  125198. 4,
  125199. };
  125200. static long _vq_lengthlist__44c3_s_p3_0[] = {
  125201. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0,
  125241. };
  125242. static float _vq_quantthresh__44c3_s_p3_0[] = {
  125243. -1.5, -0.5, 0.5, 1.5,
  125244. };
  125245. static long _vq_quantmap__44c3_s_p3_0[] = {
  125246. 3, 1, 0, 2, 4,
  125247. };
  125248. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  125249. _vq_quantthresh__44c3_s_p3_0,
  125250. _vq_quantmap__44c3_s_p3_0,
  125251. 5,
  125252. 5
  125253. };
  125254. static static_codebook _44c3_s_p3_0 = {
  125255. 4, 625,
  125256. _vq_lengthlist__44c3_s_p3_0,
  125257. 1, -533725184, 1611661312, 3, 0,
  125258. _vq_quantlist__44c3_s_p3_0,
  125259. NULL,
  125260. &_vq_auxt__44c3_s_p3_0,
  125261. NULL,
  125262. 0
  125263. };
  125264. static long _vq_quantlist__44c3_s_p4_0[] = {
  125265. 4,
  125266. 3,
  125267. 5,
  125268. 2,
  125269. 6,
  125270. 1,
  125271. 7,
  125272. 0,
  125273. 8,
  125274. };
  125275. static long _vq_lengthlist__44c3_s_p4_0[] = {
  125276. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125277. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125278. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125279. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  125280. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0,
  125282. };
  125283. static float _vq_quantthresh__44c3_s_p4_0[] = {
  125284. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125285. };
  125286. static long _vq_quantmap__44c3_s_p4_0[] = {
  125287. 7, 5, 3, 1, 0, 2, 4, 6,
  125288. 8,
  125289. };
  125290. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  125291. _vq_quantthresh__44c3_s_p4_0,
  125292. _vq_quantmap__44c3_s_p4_0,
  125293. 9,
  125294. 9
  125295. };
  125296. static static_codebook _44c3_s_p4_0 = {
  125297. 2, 81,
  125298. _vq_lengthlist__44c3_s_p4_0,
  125299. 1, -531628032, 1611661312, 4, 0,
  125300. _vq_quantlist__44c3_s_p4_0,
  125301. NULL,
  125302. &_vq_auxt__44c3_s_p4_0,
  125303. NULL,
  125304. 0
  125305. };
  125306. static long _vq_quantlist__44c3_s_p5_0[] = {
  125307. 4,
  125308. 3,
  125309. 5,
  125310. 2,
  125311. 6,
  125312. 1,
  125313. 7,
  125314. 0,
  125315. 8,
  125316. };
  125317. static long _vq_lengthlist__44c3_s_p5_0[] = {
  125318. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  125319. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  125320. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  125321. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  125322. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  125323. 11,
  125324. };
  125325. static float _vq_quantthresh__44c3_s_p5_0[] = {
  125326. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125327. };
  125328. static long _vq_quantmap__44c3_s_p5_0[] = {
  125329. 7, 5, 3, 1, 0, 2, 4, 6,
  125330. 8,
  125331. };
  125332. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  125333. _vq_quantthresh__44c3_s_p5_0,
  125334. _vq_quantmap__44c3_s_p5_0,
  125335. 9,
  125336. 9
  125337. };
  125338. static static_codebook _44c3_s_p5_0 = {
  125339. 2, 81,
  125340. _vq_lengthlist__44c3_s_p5_0,
  125341. 1, -531628032, 1611661312, 4, 0,
  125342. _vq_quantlist__44c3_s_p5_0,
  125343. NULL,
  125344. &_vq_auxt__44c3_s_p5_0,
  125345. NULL,
  125346. 0
  125347. };
  125348. static long _vq_quantlist__44c3_s_p6_0[] = {
  125349. 8,
  125350. 7,
  125351. 9,
  125352. 6,
  125353. 10,
  125354. 5,
  125355. 11,
  125356. 4,
  125357. 12,
  125358. 3,
  125359. 13,
  125360. 2,
  125361. 14,
  125362. 1,
  125363. 15,
  125364. 0,
  125365. 16,
  125366. };
  125367. static long _vq_lengthlist__44c3_s_p6_0[] = {
  125368. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  125369. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  125370. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  125371. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125372. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125373. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125374. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  125375. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125376. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125377. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  125378. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  125379. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  125380. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  125381. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  125382. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  125383. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125384. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125386. 13,
  125387. };
  125388. static float _vq_quantthresh__44c3_s_p6_0[] = {
  125389. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125390. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125391. };
  125392. static long _vq_quantmap__44c3_s_p6_0[] = {
  125393. 15, 13, 11, 9, 7, 5, 3, 1,
  125394. 0, 2, 4, 6, 8, 10, 12, 14,
  125395. 16,
  125396. };
  125397. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  125398. _vq_quantthresh__44c3_s_p6_0,
  125399. _vq_quantmap__44c3_s_p6_0,
  125400. 17,
  125401. 17
  125402. };
  125403. static static_codebook _44c3_s_p6_0 = {
  125404. 2, 289,
  125405. _vq_lengthlist__44c3_s_p6_0,
  125406. 1, -529530880, 1611661312, 5, 0,
  125407. _vq_quantlist__44c3_s_p6_0,
  125408. NULL,
  125409. &_vq_auxt__44c3_s_p6_0,
  125410. NULL,
  125411. 0
  125412. };
  125413. static long _vq_quantlist__44c3_s_p7_0[] = {
  125414. 1,
  125415. 0,
  125416. 2,
  125417. };
  125418. static long _vq_lengthlist__44c3_s_p7_0[] = {
  125419. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125420. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125421. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125422. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  125423. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125424. 10,
  125425. };
  125426. static float _vq_quantthresh__44c3_s_p7_0[] = {
  125427. -5.5, 5.5,
  125428. };
  125429. static long _vq_quantmap__44c3_s_p7_0[] = {
  125430. 1, 0, 2,
  125431. };
  125432. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  125433. _vq_quantthresh__44c3_s_p7_0,
  125434. _vq_quantmap__44c3_s_p7_0,
  125435. 3,
  125436. 3
  125437. };
  125438. static static_codebook _44c3_s_p7_0 = {
  125439. 4, 81,
  125440. _vq_lengthlist__44c3_s_p7_0,
  125441. 1, -529137664, 1618345984, 2, 0,
  125442. _vq_quantlist__44c3_s_p7_0,
  125443. NULL,
  125444. &_vq_auxt__44c3_s_p7_0,
  125445. NULL,
  125446. 0
  125447. };
  125448. static long _vq_quantlist__44c3_s_p7_1[] = {
  125449. 5,
  125450. 4,
  125451. 6,
  125452. 3,
  125453. 7,
  125454. 2,
  125455. 8,
  125456. 1,
  125457. 9,
  125458. 0,
  125459. 10,
  125460. };
  125461. static long _vq_lengthlist__44c3_s_p7_1[] = {
  125462. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  125463. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125464. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125465. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  125466. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125467. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125468. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  125469. 10,10,10, 8, 8, 8, 8, 8, 8,
  125470. };
  125471. static float _vq_quantthresh__44c3_s_p7_1[] = {
  125472. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125473. 3.5, 4.5,
  125474. };
  125475. static long _vq_quantmap__44c3_s_p7_1[] = {
  125476. 9, 7, 5, 3, 1, 0, 2, 4,
  125477. 6, 8, 10,
  125478. };
  125479. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  125480. _vq_quantthresh__44c3_s_p7_1,
  125481. _vq_quantmap__44c3_s_p7_1,
  125482. 11,
  125483. 11
  125484. };
  125485. static static_codebook _44c3_s_p7_1 = {
  125486. 2, 121,
  125487. _vq_lengthlist__44c3_s_p7_1,
  125488. 1, -531365888, 1611661312, 4, 0,
  125489. _vq_quantlist__44c3_s_p7_1,
  125490. NULL,
  125491. &_vq_auxt__44c3_s_p7_1,
  125492. NULL,
  125493. 0
  125494. };
  125495. static long _vq_quantlist__44c3_s_p8_0[] = {
  125496. 6,
  125497. 5,
  125498. 7,
  125499. 4,
  125500. 8,
  125501. 3,
  125502. 9,
  125503. 2,
  125504. 10,
  125505. 1,
  125506. 11,
  125507. 0,
  125508. 12,
  125509. };
  125510. static long _vq_lengthlist__44c3_s_p8_0[] = {
  125511. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125512. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  125513. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125514. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125515. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  125516. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125517. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  125518. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125519. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  125520. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  125521. 0,13,13,12,12,13,12,14,13,
  125522. };
  125523. static float _vq_quantthresh__44c3_s_p8_0[] = {
  125524. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125525. 12.5, 17.5, 22.5, 27.5,
  125526. };
  125527. static long _vq_quantmap__44c3_s_p8_0[] = {
  125528. 11, 9, 7, 5, 3, 1, 0, 2,
  125529. 4, 6, 8, 10, 12,
  125530. };
  125531. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  125532. _vq_quantthresh__44c3_s_p8_0,
  125533. _vq_quantmap__44c3_s_p8_0,
  125534. 13,
  125535. 13
  125536. };
  125537. static static_codebook _44c3_s_p8_0 = {
  125538. 2, 169,
  125539. _vq_lengthlist__44c3_s_p8_0,
  125540. 1, -526516224, 1616117760, 4, 0,
  125541. _vq_quantlist__44c3_s_p8_0,
  125542. NULL,
  125543. &_vq_auxt__44c3_s_p8_0,
  125544. NULL,
  125545. 0
  125546. };
  125547. static long _vq_quantlist__44c3_s_p8_1[] = {
  125548. 2,
  125549. 1,
  125550. 3,
  125551. 0,
  125552. 4,
  125553. };
  125554. static long _vq_lengthlist__44c3_s_p8_1[] = {
  125555. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  125556. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125557. };
  125558. static float _vq_quantthresh__44c3_s_p8_1[] = {
  125559. -1.5, -0.5, 0.5, 1.5,
  125560. };
  125561. static long _vq_quantmap__44c3_s_p8_1[] = {
  125562. 3, 1, 0, 2, 4,
  125563. };
  125564. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  125565. _vq_quantthresh__44c3_s_p8_1,
  125566. _vq_quantmap__44c3_s_p8_1,
  125567. 5,
  125568. 5
  125569. };
  125570. static static_codebook _44c3_s_p8_1 = {
  125571. 2, 25,
  125572. _vq_lengthlist__44c3_s_p8_1,
  125573. 1, -533725184, 1611661312, 3, 0,
  125574. _vq_quantlist__44c3_s_p8_1,
  125575. NULL,
  125576. &_vq_auxt__44c3_s_p8_1,
  125577. NULL,
  125578. 0
  125579. };
  125580. static long _vq_quantlist__44c3_s_p9_0[] = {
  125581. 6,
  125582. 5,
  125583. 7,
  125584. 4,
  125585. 8,
  125586. 3,
  125587. 9,
  125588. 2,
  125589. 10,
  125590. 1,
  125591. 11,
  125592. 0,
  125593. 12,
  125594. };
  125595. static long _vq_lengthlist__44c3_s_p9_0[] = {
  125596. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125597. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  125598. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125599. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  125600. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125601. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125602. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125603. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125604. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  125605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125606. 11,11,11,11,11,11,11,11,11,
  125607. };
  125608. static float _vq_quantthresh__44c3_s_p9_0[] = {
  125609. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  125610. 637.5, 892.5, 1147.5, 1402.5,
  125611. };
  125612. static long _vq_quantmap__44c3_s_p9_0[] = {
  125613. 11, 9, 7, 5, 3, 1, 0, 2,
  125614. 4, 6, 8, 10, 12,
  125615. };
  125616. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  125617. _vq_quantthresh__44c3_s_p9_0,
  125618. _vq_quantmap__44c3_s_p9_0,
  125619. 13,
  125620. 13
  125621. };
  125622. static static_codebook _44c3_s_p9_0 = {
  125623. 2, 169,
  125624. _vq_lengthlist__44c3_s_p9_0,
  125625. 1, -514332672, 1627381760, 4, 0,
  125626. _vq_quantlist__44c3_s_p9_0,
  125627. NULL,
  125628. &_vq_auxt__44c3_s_p9_0,
  125629. NULL,
  125630. 0
  125631. };
  125632. static long _vq_quantlist__44c3_s_p9_1[] = {
  125633. 7,
  125634. 6,
  125635. 8,
  125636. 5,
  125637. 9,
  125638. 4,
  125639. 10,
  125640. 3,
  125641. 11,
  125642. 2,
  125643. 12,
  125644. 1,
  125645. 13,
  125646. 0,
  125647. 14,
  125648. };
  125649. static long _vq_lengthlist__44c3_s_p9_1[] = {
  125650. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  125651. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  125652. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  125653. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  125654. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  125655. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  125656. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  125657. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  125658. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  125659. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  125660. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  125661. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  125662. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  125663. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  125664. 15,
  125665. };
  125666. static float _vq_quantthresh__44c3_s_p9_1[] = {
  125667. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  125668. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  125669. };
  125670. static long _vq_quantmap__44c3_s_p9_1[] = {
  125671. 13, 11, 9, 7, 5, 3, 1, 0,
  125672. 2, 4, 6, 8, 10, 12, 14,
  125673. };
  125674. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  125675. _vq_quantthresh__44c3_s_p9_1,
  125676. _vq_quantmap__44c3_s_p9_1,
  125677. 15,
  125678. 15
  125679. };
  125680. static static_codebook _44c3_s_p9_1 = {
  125681. 2, 225,
  125682. _vq_lengthlist__44c3_s_p9_1,
  125683. 1, -522338304, 1620115456, 4, 0,
  125684. _vq_quantlist__44c3_s_p9_1,
  125685. NULL,
  125686. &_vq_auxt__44c3_s_p9_1,
  125687. NULL,
  125688. 0
  125689. };
  125690. static long _vq_quantlist__44c3_s_p9_2[] = {
  125691. 8,
  125692. 7,
  125693. 9,
  125694. 6,
  125695. 10,
  125696. 5,
  125697. 11,
  125698. 4,
  125699. 12,
  125700. 3,
  125701. 13,
  125702. 2,
  125703. 14,
  125704. 1,
  125705. 15,
  125706. 0,
  125707. 16,
  125708. };
  125709. static long _vq_lengthlist__44c3_s_p9_2[] = {
  125710. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125711. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  125712. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125713. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125714. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  125715. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125716. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  125717. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  125718. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  125719. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  125720. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  125721. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  125722. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  125723. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  125724. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  125725. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  125726. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  125727. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  125728. 10,
  125729. };
  125730. static float _vq_quantthresh__44c3_s_p9_2[] = {
  125731. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125732. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125733. };
  125734. static long _vq_quantmap__44c3_s_p9_2[] = {
  125735. 15, 13, 11, 9, 7, 5, 3, 1,
  125736. 0, 2, 4, 6, 8, 10, 12, 14,
  125737. 16,
  125738. };
  125739. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  125740. _vq_quantthresh__44c3_s_p9_2,
  125741. _vq_quantmap__44c3_s_p9_2,
  125742. 17,
  125743. 17
  125744. };
  125745. static static_codebook _44c3_s_p9_2 = {
  125746. 2, 289,
  125747. _vq_lengthlist__44c3_s_p9_2,
  125748. 1, -529530880, 1611661312, 5, 0,
  125749. _vq_quantlist__44c3_s_p9_2,
  125750. NULL,
  125751. &_vq_auxt__44c3_s_p9_2,
  125752. NULL,
  125753. 0
  125754. };
  125755. static long _huff_lengthlist__44c3_s_short[] = {
  125756. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  125757. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  125758. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  125759. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  125760. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  125761. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  125762. 6, 8, 9,11,
  125763. };
  125764. static static_codebook _huff_book__44c3_s_short = {
  125765. 2, 100,
  125766. _huff_lengthlist__44c3_s_short,
  125767. 0, 0, 0, 0, 0,
  125768. NULL,
  125769. NULL,
  125770. NULL,
  125771. NULL,
  125772. 0
  125773. };
  125774. static long _huff_lengthlist__44c4_s_long[] = {
  125775. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  125776. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  125777. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  125778. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  125779. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  125780. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  125781. 9, 8, 7, 7,
  125782. };
  125783. static static_codebook _huff_book__44c4_s_long = {
  125784. 2, 100,
  125785. _huff_lengthlist__44c4_s_long,
  125786. 0, 0, 0, 0, 0,
  125787. NULL,
  125788. NULL,
  125789. NULL,
  125790. NULL,
  125791. 0
  125792. };
  125793. static long _vq_quantlist__44c4_s_p1_0[] = {
  125794. 1,
  125795. 0,
  125796. 2,
  125797. };
  125798. static long _vq_lengthlist__44c4_s_p1_0[] = {
  125799. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125800. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125805. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125810. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125845. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125850. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  125855. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125891. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125896. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125901. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0,
  126210. };
  126211. static float _vq_quantthresh__44c4_s_p1_0[] = {
  126212. -0.5, 0.5,
  126213. };
  126214. static long _vq_quantmap__44c4_s_p1_0[] = {
  126215. 1, 0, 2,
  126216. };
  126217. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  126218. _vq_quantthresh__44c4_s_p1_0,
  126219. _vq_quantmap__44c4_s_p1_0,
  126220. 3,
  126221. 3
  126222. };
  126223. static static_codebook _44c4_s_p1_0 = {
  126224. 8, 6561,
  126225. _vq_lengthlist__44c4_s_p1_0,
  126226. 1, -535822336, 1611661312, 2, 0,
  126227. _vq_quantlist__44c4_s_p1_0,
  126228. NULL,
  126229. &_vq_auxt__44c4_s_p1_0,
  126230. NULL,
  126231. 0
  126232. };
  126233. static long _vq_quantlist__44c4_s_p2_0[] = {
  126234. 2,
  126235. 1,
  126236. 3,
  126237. 0,
  126238. 4,
  126239. };
  126240. static long _vq_lengthlist__44c4_s_p2_0[] = {
  126241. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126242. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126243. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126244. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126245. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  126251. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  126252. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  126253. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  126259. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  126260. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  126267. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  126268. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0,
  126281. };
  126282. static float _vq_quantthresh__44c4_s_p2_0[] = {
  126283. -1.5, -0.5, 0.5, 1.5,
  126284. };
  126285. static long _vq_quantmap__44c4_s_p2_0[] = {
  126286. 3, 1, 0, 2, 4,
  126287. };
  126288. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  126289. _vq_quantthresh__44c4_s_p2_0,
  126290. _vq_quantmap__44c4_s_p2_0,
  126291. 5,
  126292. 5
  126293. };
  126294. static static_codebook _44c4_s_p2_0 = {
  126295. 4, 625,
  126296. _vq_lengthlist__44c4_s_p2_0,
  126297. 1, -533725184, 1611661312, 3, 0,
  126298. _vq_quantlist__44c4_s_p2_0,
  126299. NULL,
  126300. &_vq_auxt__44c4_s_p2_0,
  126301. NULL,
  126302. 0
  126303. };
  126304. static long _vq_quantlist__44c4_s_p3_0[] = {
  126305. 2,
  126306. 1,
  126307. 3,
  126308. 0,
  126309. 4,
  126310. };
  126311. static long _vq_lengthlist__44c4_s_p3_0[] = {
  126312. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0,
  126352. };
  126353. static float _vq_quantthresh__44c4_s_p3_0[] = {
  126354. -1.5, -0.5, 0.5, 1.5,
  126355. };
  126356. static long _vq_quantmap__44c4_s_p3_0[] = {
  126357. 3, 1, 0, 2, 4,
  126358. };
  126359. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  126360. _vq_quantthresh__44c4_s_p3_0,
  126361. _vq_quantmap__44c4_s_p3_0,
  126362. 5,
  126363. 5
  126364. };
  126365. static static_codebook _44c4_s_p3_0 = {
  126366. 4, 625,
  126367. _vq_lengthlist__44c4_s_p3_0,
  126368. 1, -533725184, 1611661312, 3, 0,
  126369. _vq_quantlist__44c4_s_p3_0,
  126370. NULL,
  126371. &_vq_auxt__44c4_s_p3_0,
  126372. NULL,
  126373. 0
  126374. };
  126375. static long _vq_quantlist__44c4_s_p4_0[] = {
  126376. 4,
  126377. 3,
  126378. 5,
  126379. 2,
  126380. 6,
  126381. 1,
  126382. 7,
  126383. 0,
  126384. 8,
  126385. };
  126386. static long _vq_lengthlist__44c4_s_p4_0[] = {
  126387. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126388. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126389. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126390. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126391. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0,
  126393. };
  126394. static float _vq_quantthresh__44c4_s_p4_0[] = {
  126395. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126396. };
  126397. static long _vq_quantmap__44c4_s_p4_0[] = {
  126398. 7, 5, 3, 1, 0, 2, 4, 6,
  126399. 8,
  126400. };
  126401. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  126402. _vq_quantthresh__44c4_s_p4_0,
  126403. _vq_quantmap__44c4_s_p4_0,
  126404. 9,
  126405. 9
  126406. };
  126407. static static_codebook _44c4_s_p4_0 = {
  126408. 2, 81,
  126409. _vq_lengthlist__44c4_s_p4_0,
  126410. 1, -531628032, 1611661312, 4, 0,
  126411. _vq_quantlist__44c4_s_p4_0,
  126412. NULL,
  126413. &_vq_auxt__44c4_s_p4_0,
  126414. NULL,
  126415. 0
  126416. };
  126417. static long _vq_quantlist__44c4_s_p5_0[] = {
  126418. 4,
  126419. 3,
  126420. 5,
  126421. 2,
  126422. 6,
  126423. 1,
  126424. 7,
  126425. 0,
  126426. 8,
  126427. };
  126428. static long _vq_lengthlist__44c4_s_p5_0[] = {
  126429. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126430. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  126431. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  126432. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  126433. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  126434. 10,
  126435. };
  126436. static float _vq_quantthresh__44c4_s_p5_0[] = {
  126437. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126438. };
  126439. static long _vq_quantmap__44c4_s_p5_0[] = {
  126440. 7, 5, 3, 1, 0, 2, 4, 6,
  126441. 8,
  126442. };
  126443. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  126444. _vq_quantthresh__44c4_s_p5_0,
  126445. _vq_quantmap__44c4_s_p5_0,
  126446. 9,
  126447. 9
  126448. };
  126449. static static_codebook _44c4_s_p5_0 = {
  126450. 2, 81,
  126451. _vq_lengthlist__44c4_s_p5_0,
  126452. 1, -531628032, 1611661312, 4, 0,
  126453. _vq_quantlist__44c4_s_p5_0,
  126454. NULL,
  126455. &_vq_auxt__44c4_s_p5_0,
  126456. NULL,
  126457. 0
  126458. };
  126459. static long _vq_quantlist__44c4_s_p6_0[] = {
  126460. 8,
  126461. 7,
  126462. 9,
  126463. 6,
  126464. 10,
  126465. 5,
  126466. 11,
  126467. 4,
  126468. 12,
  126469. 3,
  126470. 13,
  126471. 2,
  126472. 14,
  126473. 1,
  126474. 15,
  126475. 0,
  126476. 16,
  126477. };
  126478. static long _vq_lengthlist__44c4_s_p6_0[] = {
  126479. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  126480. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126481. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126482. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126483. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126484. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126485. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126486. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126487. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126488. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  126489. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  126490. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  126491. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  126492. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  126493. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126494. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126495. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  126497. 13,
  126498. };
  126499. static float _vq_quantthresh__44c4_s_p6_0[] = {
  126500. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126501. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126502. };
  126503. static long _vq_quantmap__44c4_s_p6_0[] = {
  126504. 15, 13, 11, 9, 7, 5, 3, 1,
  126505. 0, 2, 4, 6, 8, 10, 12, 14,
  126506. 16,
  126507. };
  126508. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  126509. _vq_quantthresh__44c4_s_p6_0,
  126510. _vq_quantmap__44c4_s_p6_0,
  126511. 17,
  126512. 17
  126513. };
  126514. static static_codebook _44c4_s_p6_0 = {
  126515. 2, 289,
  126516. _vq_lengthlist__44c4_s_p6_0,
  126517. 1, -529530880, 1611661312, 5, 0,
  126518. _vq_quantlist__44c4_s_p6_0,
  126519. NULL,
  126520. &_vq_auxt__44c4_s_p6_0,
  126521. NULL,
  126522. 0
  126523. };
  126524. static long _vq_quantlist__44c4_s_p7_0[] = {
  126525. 1,
  126526. 0,
  126527. 2,
  126528. };
  126529. static long _vq_lengthlist__44c4_s_p7_0[] = {
  126530. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126531. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126532. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126533. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126534. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126535. 10,
  126536. };
  126537. static float _vq_quantthresh__44c4_s_p7_0[] = {
  126538. -5.5, 5.5,
  126539. };
  126540. static long _vq_quantmap__44c4_s_p7_0[] = {
  126541. 1, 0, 2,
  126542. };
  126543. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  126544. _vq_quantthresh__44c4_s_p7_0,
  126545. _vq_quantmap__44c4_s_p7_0,
  126546. 3,
  126547. 3
  126548. };
  126549. static static_codebook _44c4_s_p7_0 = {
  126550. 4, 81,
  126551. _vq_lengthlist__44c4_s_p7_0,
  126552. 1, -529137664, 1618345984, 2, 0,
  126553. _vq_quantlist__44c4_s_p7_0,
  126554. NULL,
  126555. &_vq_auxt__44c4_s_p7_0,
  126556. NULL,
  126557. 0
  126558. };
  126559. static long _vq_quantlist__44c4_s_p7_1[] = {
  126560. 5,
  126561. 4,
  126562. 6,
  126563. 3,
  126564. 7,
  126565. 2,
  126566. 8,
  126567. 1,
  126568. 9,
  126569. 0,
  126570. 10,
  126571. };
  126572. static long _vq_lengthlist__44c4_s_p7_1[] = {
  126573. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126574. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126575. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126576. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  126577. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126578. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126579. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126580. 10,10,10, 8, 8, 8, 8, 9, 9,
  126581. };
  126582. static float _vq_quantthresh__44c4_s_p7_1[] = {
  126583. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126584. 3.5, 4.5,
  126585. };
  126586. static long _vq_quantmap__44c4_s_p7_1[] = {
  126587. 9, 7, 5, 3, 1, 0, 2, 4,
  126588. 6, 8, 10,
  126589. };
  126590. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  126591. _vq_quantthresh__44c4_s_p7_1,
  126592. _vq_quantmap__44c4_s_p7_1,
  126593. 11,
  126594. 11
  126595. };
  126596. static static_codebook _44c4_s_p7_1 = {
  126597. 2, 121,
  126598. _vq_lengthlist__44c4_s_p7_1,
  126599. 1, -531365888, 1611661312, 4, 0,
  126600. _vq_quantlist__44c4_s_p7_1,
  126601. NULL,
  126602. &_vq_auxt__44c4_s_p7_1,
  126603. NULL,
  126604. 0
  126605. };
  126606. static long _vq_quantlist__44c4_s_p8_0[] = {
  126607. 6,
  126608. 5,
  126609. 7,
  126610. 4,
  126611. 8,
  126612. 3,
  126613. 9,
  126614. 2,
  126615. 10,
  126616. 1,
  126617. 11,
  126618. 0,
  126619. 12,
  126620. };
  126621. static long _vq_lengthlist__44c4_s_p8_0[] = {
  126622. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126623. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126624. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126625. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126626. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  126627. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  126628. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  126629. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126630. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  126631. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126632. 0,13,12,12,12,12,12,13,13,
  126633. };
  126634. static float _vq_quantthresh__44c4_s_p8_0[] = {
  126635. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126636. 12.5, 17.5, 22.5, 27.5,
  126637. };
  126638. static long _vq_quantmap__44c4_s_p8_0[] = {
  126639. 11, 9, 7, 5, 3, 1, 0, 2,
  126640. 4, 6, 8, 10, 12,
  126641. };
  126642. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  126643. _vq_quantthresh__44c4_s_p8_0,
  126644. _vq_quantmap__44c4_s_p8_0,
  126645. 13,
  126646. 13
  126647. };
  126648. static static_codebook _44c4_s_p8_0 = {
  126649. 2, 169,
  126650. _vq_lengthlist__44c4_s_p8_0,
  126651. 1, -526516224, 1616117760, 4, 0,
  126652. _vq_quantlist__44c4_s_p8_0,
  126653. NULL,
  126654. &_vq_auxt__44c4_s_p8_0,
  126655. NULL,
  126656. 0
  126657. };
  126658. static long _vq_quantlist__44c4_s_p8_1[] = {
  126659. 2,
  126660. 1,
  126661. 3,
  126662. 0,
  126663. 4,
  126664. };
  126665. static long _vq_lengthlist__44c4_s_p8_1[] = {
  126666. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  126667. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126668. };
  126669. static float _vq_quantthresh__44c4_s_p8_1[] = {
  126670. -1.5, -0.5, 0.5, 1.5,
  126671. };
  126672. static long _vq_quantmap__44c4_s_p8_1[] = {
  126673. 3, 1, 0, 2, 4,
  126674. };
  126675. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  126676. _vq_quantthresh__44c4_s_p8_1,
  126677. _vq_quantmap__44c4_s_p8_1,
  126678. 5,
  126679. 5
  126680. };
  126681. static static_codebook _44c4_s_p8_1 = {
  126682. 2, 25,
  126683. _vq_lengthlist__44c4_s_p8_1,
  126684. 1, -533725184, 1611661312, 3, 0,
  126685. _vq_quantlist__44c4_s_p8_1,
  126686. NULL,
  126687. &_vq_auxt__44c4_s_p8_1,
  126688. NULL,
  126689. 0
  126690. };
  126691. static long _vq_quantlist__44c4_s_p9_0[] = {
  126692. 6,
  126693. 5,
  126694. 7,
  126695. 4,
  126696. 8,
  126697. 3,
  126698. 9,
  126699. 2,
  126700. 10,
  126701. 1,
  126702. 11,
  126703. 0,
  126704. 12,
  126705. };
  126706. static long _vq_lengthlist__44c4_s_p9_0[] = {
  126707. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  126708. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  126709. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126710. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126711. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126712. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126713. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126714. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126715. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126716. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126717. 12,12,12,12,12,12,12,12,12,
  126718. };
  126719. static float _vq_quantthresh__44c4_s_p9_0[] = {
  126720. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126721. 787.5, 1102.5, 1417.5, 1732.5,
  126722. };
  126723. static long _vq_quantmap__44c4_s_p9_0[] = {
  126724. 11, 9, 7, 5, 3, 1, 0, 2,
  126725. 4, 6, 8, 10, 12,
  126726. };
  126727. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  126728. _vq_quantthresh__44c4_s_p9_0,
  126729. _vq_quantmap__44c4_s_p9_0,
  126730. 13,
  126731. 13
  126732. };
  126733. static static_codebook _44c4_s_p9_0 = {
  126734. 2, 169,
  126735. _vq_lengthlist__44c4_s_p9_0,
  126736. 1, -513964032, 1628680192, 4, 0,
  126737. _vq_quantlist__44c4_s_p9_0,
  126738. NULL,
  126739. &_vq_auxt__44c4_s_p9_0,
  126740. NULL,
  126741. 0
  126742. };
  126743. static long _vq_quantlist__44c4_s_p9_1[] = {
  126744. 7,
  126745. 6,
  126746. 8,
  126747. 5,
  126748. 9,
  126749. 4,
  126750. 10,
  126751. 3,
  126752. 11,
  126753. 2,
  126754. 12,
  126755. 1,
  126756. 13,
  126757. 0,
  126758. 14,
  126759. };
  126760. static long _vq_lengthlist__44c4_s_p9_1[] = {
  126761. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  126762. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  126763. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  126764. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  126765. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  126766. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  126767. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  126768. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  126769. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  126770. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  126771. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  126772. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  126773. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  126774. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  126775. 15,
  126776. };
  126777. static float _vq_quantthresh__44c4_s_p9_1[] = {
  126778. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126779. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126780. };
  126781. static long _vq_quantmap__44c4_s_p9_1[] = {
  126782. 13, 11, 9, 7, 5, 3, 1, 0,
  126783. 2, 4, 6, 8, 10, 12, 14,
  126784. };
  126785. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  126786. _vq_quantthresh__44c4_s_p9_1,
  126787. _vq_quantmap__44c4_s_p9_1,
  126788. 15,
  126789. 15
  126790. };
  126791. static static_codebook _44c4_s_p9_1 = {
  126792. 2, 225,
  126793. _vq_lengthlist__44c4_s_p9_1,
  126794. 1, -520986624, 1620377600, 4, 0,
  126795. _vq_quantlist__44c4_s_p9_1,
  126796. NULL,
  126797. &_vq_auxt__44c4_s_p9_1,
  126798. NULL,
  126799. 0
  126800. };
  126801. static long _vq_quantlist__44c4_s_p9_2[] = {
  126802. 10,
  126803. 9,
  126804. 11,
  126805. 8,
  126806. 12,
  126807. 7,
  126808. 13,
  126809. 6,
  126810. 14,
  126811. 5,
  126812. 15,
  126813. 4,
  126814. 16,
  126815. 3,
  126816. 17,
  126817. 2,
  126818. 18,
  126819. 1,
  126820. 19,
  126821. 0,
  126822. 20,
  126823. };
  126824. static long _vq_lengthlist__44c4_s_p9_2[] = {
  126825. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126826. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  126827. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  126828. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  126829. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  126830. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  126831. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  126832. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126833. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  126834. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  126835. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126836. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126837. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126838. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126839. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  126840. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  126841. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  126842. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126843. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  126844. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  126845. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126846. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126847. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  126848. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  126849. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  126850. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  126851. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  126852. 10,10,10,10,10,10,10,10,10,
  126853. };
  126854. static float _vq_quantthresh__44c4_s_p9_2[] = {
  126855. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126856. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126857. 6.5, 7.5, 8.5, 9.5,
  126858. };
  126859. static long _vq_quantmap__44c4_s_p9_2[] = {
  126860. 19, 17, 15, 13, 11, 9, 7, 5,
  126861. 3, 1, 0, 2, 4, 6, 8, 10,
  126862. 12, 14, 16, 18, 20,
  126863. };
  126864. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  126865. _vq_quantthresh__44c4_s_p9_2,
  126866. _vq_quantmap__44c4_s_p9_2,
  126867. 21,
  126868. 21
  126869. };
  126870. static static_codebook _44c4_s_p9_2 = {
  126871. 2, 441,
  126872. _vq_lengthlist__44c4_s_p9_2,
  126873. 1, -529268736, 1611661312, 5, 0,
  126874. _vq_quantlist__44c4_s_p9_2,
  126875. NULL,
  126876. &_vq_auxt__44c4_s_p9_2,
  126877. NULL,
  126878. 0
  126879. };
  126880. static long _huff_lengthlist__44c4_s_short[] = {
  126881. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  126882. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  126883. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  126884. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  126885. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  126886. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  126887. 7, 9,12,17,
  126888. };
  126889. static static_codebook _huff_book__44c4_s_short = {
  126890. 2, 100,
  126891. _huff_lengthlist__44c4_s_short,
  126892. 0, 0, 0, 0, 0,
  126893. NULL,
  126894. NULL,
  126895. NULL,
  126896. NULL,
  126897. 0
  126898. };
  126899. static long _huff_lengthlist__44c5_s_long[] = {
  126900. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  126901. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  126902. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  126903. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  126904. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  126905. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  126906. 9, 8, 7, 7,
  126907. };
  126908. static static_codebook _huff_book__44c5_s_long = {
  126909. 2, 100,
  126910. _huff_lengthlist__44c5_s_long,
  126911. 0, 0, 0, 0, 0,
  126912. NULL,
  126913. NULL,
  126914. NULL,
  126915. NULL,
  126916. 0
  126917. };
  126918. static long _vq_quantlist__44c5_s_p1_0[] = {
  126919. 1,
  126920. 0,
  126921. 2,
  126922. };
  126923. static long _vq_lengthlist__44c5_s_p1_0[] = {
  126924. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126925. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126930. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126935. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126970. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126975. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126980. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127016. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  127021. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127026. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0,
  127335. };
  127336. static float _vq_quantthresh__44c5_s_p1_0[] = {
  127337. -0.5, 0.5,
  127338. };
  127339. static long _vq_quantmap__44c5_s_p1_0[] = {
  127340. 1, 0, 2,
  127341. };
  127342. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  127343. _vq_quantthresh__44c5_s_p1_0,
  127344. _vq_quantmap__44c5_s_p1_0,
  127345. 3,
  127346. 3
  127347. };
  127348. static static_codebook _44c5_s_p1_0 = {
  127349. 8, 6561,
  127350. _vq_lengthlist__44c5_s_p1_0,
  127351. 1, -535822336, 1611661312, 2, 0,
  127352. _vq_quantlist__44c5_s_p1_0,
  127353. NULL,
  127354. &_vq_auxt__44c5_s_p1_0,
  127355. NULL,
  127356. 0
  127357. };
  127358. static long _vq_quantlist__44c5_s_p2_0[] = {
  127359. 2,
  127360. 1,
  127361. 3,
  127362. 0,
  127363. 4,
  127364. };
  127365. static long _vq_lengthlist__44c5_s_p2_0[] = {
  127366. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127367. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127368. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127369. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  127370. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  127376. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  127377. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  127378. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  127384. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  127385. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  127392. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  127393. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0,
  127406. };
  127407. static float _vq_quantthresh__44c5_s_p2_0[] = {
  127408. -1.5, -0.5, 0.5, 1.5,
  127409. };
  127410. static long _vq_quantmap__44c5_s_p2_0[] = {
  127411. 3, 1, 0, 2, 4,
  127412. };
  127413. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  127414. _vq_quantthresh__44c5_s_p2_0,
  127415. _vq_quantmap__44c5_s_p2_0,
  127416. 5,
  127417. 5
  127418. };
  127419. static static_codebook _44c5_s_p2_0 = {
  127420. 4, 625,
  127421. _vq_lengthlist__44c5_s_p2_0,
  127422. 1, -533725184, 1611661312, 3, 0,
  127423. _vq_quantlist__44c5_s_p2_0,
  127424. NULL,
  127425. &_vq_auxt__44c5_s_p2_0,
  127426. NULL,
  127427. 0
  127428. };
  127429. static long _vq_quantlist__44c5_s_p3_0[] = {
  127430. 2,
  127431. 1,
  127432. 3,
  127433. 0,
  127434. 4,
  127435. };
  127436. static long _vq_lengthlist__44c5_s_p3_0[] = {
  127437. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0,
  127477. };
  127478. static float _vq_quantthresh__44c5_s_p3_0[] = {
  127479. -1.5, -0.5, 0.5, 1.5,
  127480. };
  127481. static long _vq_quantmap__44c5_s_p3_0[] = {
  127482. 3, 1, 0, 2, 4,
  127483. };
  127484. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  127485. _vq_quantthresh__44c5_s_p3_0,
  127486. _vq_quantmap__44c5_s_p3_0,
  127487. 5,
  127488. 5
  127489. };
  127490. static static_codebook _44c5_s_p3_0 = {
  127491. 4, 625,
  127492. _vq_lengthlist__44c5_s_p3_0,
  127493. 1, -533725184, 1611661312, 3, 0,
  127494. _vq_quantlist__44c5_s_p3_0,
  127495. NULL,
  127496. &_vq_auxt__44c5_s_p3_0,
  127497. NULL,
  127498. 0
  127499. };
  127500. static long _vq_quantlist__44c5_s_p4_0[] = {
  127501. 4,
  127502. 3,
  127503. 5,
  127504. 2,
  127505. 6,
  127506. 1,
  127507. 7,
  127508. 0,
  127509. 8,
  127510. };
  127511. static long _vq_lengthlist__44c5_s_p4_0[] = {
  127512. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127513. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127514. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127515. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  127516. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0,
  127518. };
  127519. static float _vq_quantthresh__44c5_s_p4_0[] = {
  127520. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127521. };
  127522. static long _vq_quantmap__44c5_s_p4_0[] = {
  127523. 7, 5, 3, 1, 0, 2, 4, 6,
  127524. 8,
  127525. };
  127526. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  127527. _vq_quantthresh__44c5_s_p4_0,
  127528. _vq_quantmap__44c5_s_p4_0,
  127529. 9,
  127530. 9
  127531. };
  127532. static static_codebook _44c5_s_p4_0 = {
  127533. 2, 81,
  127534. _vq_lengthlist__44c5_s_p4_0,
  127535. 1, -531628032, 1611661312, 4, 0,
  127536. _vq_quantlist__44c5_s_p4_0,
  127537. NULL,
  127538. &_vq_auxt__44c5_s_p4_0,
  127539. NULL,
  127540. 0
  127541. };
  127542. static long _vq_quantlist__44c5_s_p5_0[] = {
  127543. 4,
  127544. 3,
  127545. 5,
  127546. 2,
  127547. 6,
  127548. 1,
  127549. 7,
  127550. 0,
  127551. 8,
  127552. };
  127553. static long _vq_lengthlist__44c5_s_p5_0[] = {
  127554. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127555. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127556. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  127557. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127558. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127559. 10,
  127560. };
  127561. static float _vq_quantthresh__44c5_s_p5_0[] = {
  127562. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127563. };
  127564. static long _vq_quantmap__44c5_s_p5_0[] = {
  127565. 7, 5, 3, 1, 0, 2, 4, 6,
  127566. 8,
  127567. };
  127568. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  127569. _vq_quantthresh__44c5_s_p5_0,
  127570. _vq_quantmap__44c5_s_p5_0,
  127571. 9,
  127572. 9
  127573. };
  127574. static static_codebook _44c5_s_p5_0 = {
  127575. 2, 81,
  127576. _vq_lengthlist__44c5_s_p5_0,
  127577. 1, -531628032, 1611661312, 4, 0,
  127578. _vq_quantlist__44c5_s_p5_0,
  127579. NULL,
  127580. &_vq_auxt__44c5_s_p5_0,
  127581. NULL,
  127582. 0
  127583. };
  127584. static long _vq_quantlist__44c5_s_p6_0[] = {
  127585. 8,
  127586. 7,
  127587. 9,
  127588. 6,
  127589. 10,
  127590. 5,
  127591. 11,
  127592. 4,
  127593. 12,
  127594. 3,
  127595. 13,
  127596. 2,
  127597. 14,
  127598. 1,
  127599. 15,
  127600. 0,
  127601. 16,
  127602. };
  127603. static long _vq_lengthlist__44c5_s_p6_0[] = {
  127604. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  127605. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127606. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127607. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127608. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127609. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  127610. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  127611. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  127612. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127613. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  127614. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  127615. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  127616. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  127617. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  127618. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  127619. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127620. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  127622. 13,
  127623. };
  127624. static float _vq_quantthresh__44c5_s_p6_0[] = {
  127625. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127626. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127627. };
  127628. static long _vq_quantmap__44c5_s_p6_0[] = {
  127629. 15, 13, 11, 9, 7, 5, 3, 1,
  127630. 0, 2, 4, 6, 8, 10, 12, 14,
  127631. 16,
  127632. };
  127633. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  127634. _vq_quantthresh__44c5_s_p6_0,
  127635. _vq_quantmap__44c5_s_p6_0,
  127636. 17,
  127637. 17
  127638. };
  127639. static static_codebook _44c5_s_p6_0 = {
  127640. 2, 289,
  127641. _vq_lengthlist__44c5_s_p6_0,
  127642. 1, -529530880, 1611661312, 5, 0,
  127643. _vq_quantlist__44c5_s_p6_0,
  127644. NULL,
  127645. &_vq_auxt__44c5_s_p6_0,
  127646. NULL,
  127647. 0
  127648. };
  127649. static long _vq_quantlist__44c5_s_p7_0[] = {
  127650. 1,
  127651. 0,
  127652. 2,
  127653. };
  127654. static long _vq_lengthlist__44c5_s_p7_0[] = {
  127655. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127656. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127657. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127658. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127659. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127660. 10,
  127661. };
  127662. static float _vq_quantthresh__44c5_s_p7_0[] = {
  127663. -5.5, 5.5,
  127664. };
  127665. static long _vq_quantmap__44c5_s_p7_0[] = {
  127666. 1, 0, 2,
  127667. };
  127668. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  127669. _vq_quantthresh__44c5_s_p7_0,
  127670. _vq_quantmap__44c5_s_p7_0,
  127671. 3,
  127672. 3
  127673. };
  127674. static static_codebook _44c5_s_p7_0 = {
  127675. 4, 81,
  127676. _vq_lengthlist__44c5_s_p7_0,
  127677. 1, -529137664, 1618345984, 2, 0,
  127678. _vq_quantlist__44c5_s_p7_0,
  127679. NULL,
  127680. &_vq_auxt__44c5_s_p7_0,
  127681. NULL,
  127682. 0
  127683. };
  127684. static long _vq_quantlist__44c5_s_p7_1[] = {
  127685. 5,
  127686. 4,
  127687. 6,
  127688. 3,
  127689. 7,
  127690. 2,
  127691. 8,
  127692. 1,
  127693. 9,
  127694. 0,
  127695. 10,
  127696. };
  127697. static long _vq_lengthlist__44c5_s_p7_1[] = {
  127698. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  127699. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127700. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127701. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127702. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127703. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  127704. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127705. 10,10,10, 8, 8, 8, 8, 8, 8,
  127706. };
  127707. static float _vq_quantthresh__44c5_s_p7_1[] = {
  127708. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127709. 3.5, 4.5,
  127710. };
  127711. static long _vq_quantmap__44c5_s_p7_1[] = {
  127712. 9, 7, 5, 3, 1, 0, 2, 4,
  127713. 6, 8, 10,
  127714. };
  127715. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  127716. _vq_quantthresh__44c5_s_p7_1,
  127717. _vq_quantmap__44c5_s_p7_1,
  127718. 11,
  127719. 11
  127720. };
  127721. static static_codebook _44c5_s_p7_1 = {
  127722. 2, 121,
  127723. _vq_lengthlist__44c5_s_p7_1,
  127724. 1, -531365888, 1611661312, 4, 0,
  127725. _vq_quantlist__44c5_s_p7_1,
  127726. NULL,
  127727. &_vq_auxt__44c5_s_p7_1,
  127728. NULL,
  127729. 0
  127730. };
  127731. static long _vq_quantlist__44c5_s_p8_0[] = {
  127732. 6,
  127733. 5,
  127734. 7,
  127735. 4,
  127736. 8,
  127737. 3,
  127738. 9,
  127739. 2,
  127740. 10,
  127741. 1,
  127742. 11,
  127743. 0,
  127744. 12,
  127745. };
  127746. static long _vq_lengthlist__44c5_s_p8_0[] = {
  127747. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127748. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  127749. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127750. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127751. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  127752. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  127753. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  127754. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127755. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  127756. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127757. 0,12,12,12,12,12,12,13,13,
  127758. };
  127759. static float _vq_quantthresh__44c5_s_p8_0[] = {
  127760. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127761. 12.5, 17.5, 22.5, 27.5,
  127762. };
  127763. static long _vq_quantmap__44c5_s_p8_0[] = {
  127764. 11, 9, 7, 5, 3, 1, 0, 2,
  127765. 4, 6, 8, 10, 12,
  127766. };
  127767. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  127768. _vq_quantthresh__44c5_s_p8_0,
  127769. _vq_quantmap__44c5_s_p8_0,
  127770. 13,
  127771. 13
  127772. };
  127773. static static_codebook _44c5_s_p8_0 = {
  127774. 2, 169,
  127775. _vq_lengthlist__44c5_s_p8_0,
  127776. 1, -526516224, 1616117760, 4, 0,
  127777. _vq_quantlist__44c5_s_p8_0,
  127778. NULL,
  127779. &_vq_auxt__44c5_s_p8_0,
  127780. NULL,
  127781. 0
  127782. };
  127783. static long _vq_quantlist__44c5_s_p8_1[] = {
  127784. 2,
  127785. 1,
  127786. 3,
  127787. 0,
  127788. 4,
  127789. };
  127790. static long _vq_lengthlist__44c5_s_p8_1[] = {
  127791. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  127792. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127793. };
  127794. static float _vq_quantthresh__44c5_s_p8_1[] = {
  127795. -1.5, -0.5, 0.5, 1.5,
  127796. };
  127797. static long _vq_quantmap__44c5_s_p8_1[] = {
  127798. 3, 1, 0, 2, 4,
  127799. };
  127800. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  127801. _vq_quantthresh__44c5_s_p8_1,
  127802. _vq_quantmap__44c5_s_p8_1,
  127803. 5,
  127804. 5
  127805. };
  127806. static static_codebook _44c5_s_p8_1 = {
  127807. 2, 25,
  127808. _vq_lengthlist__44c5_s_p8_1,
  127809. 1, -533725184, 1611661312, 3, 0,
  127810. _vq_quantlist__44c5_s_p8_1,
  127811. NULL,
  127812. &_vq_auxt__44c5_s_p8_1,
  127813. NULL,
  127814. 0
  127815. };
  127816. static long _vq_quantlist__44c5_s_p9_0[] = {
  127817. 7,
  127818. 6,
  127819. 8,
  127820. 5,
  127821. 9,
  127822. 4,
  127823. 10,
  127824. 3,
  127825. 11,
  127826. 2,
  127827. 12,
  127828. 1,
  127829. 13,
  127830. 0,
  127831. 14,
  127832. };
  127833. static long _vq_lengthlist__44c5_s_p9_0[] = {
  127834. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  127835. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  127836. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127837. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127838. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127839. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127840. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127841. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127842. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127843. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127844. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127845. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127846. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127847. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  127848. 12,
  127849. };
  127850. static float _vq_quantthresh__44c5_s_p9_0[] = {
  127851. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  127852. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  127853. };
  127854. static long _vq_quantmap__44c5_s_p9_0[] = {
  127855. 13, 11, 9, 7, 5, 3, 1, 0,
  127856. 2, 4, 6, 8, 10, 12, 14,
  127857. };
  127858. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  127859. _vq_quantthresh__44c5_s_p9_0,
  127860. _vq_quantmap__44c5_s_p9_0,
  127861. 15,
  127862. 15
  127863. };
  127864. static static_codebook _44c5_s_p9_0 = {
  127865. 2, 225,
  127866. _vq_lengthlist__44c5_s_p9_0,
  127867. 1, -512522752, 1628852224, 4, 0,
  127868. _vq_quantlist__44c5_s_p9_0,
  127869. NULL,
  127870. &_vq_auxt__44c5_s_p9_0,
  127871. NULL,
  127872. 0
  127873. };
  127874. static long _vq_quantlist__44c5_s_p9_1[] = {
  127875. 8,
  127876. 7,
  127877. 9,
  127878. 6,
  127879. 10,
  127880. 5,
  127881. 11,
  127882. 4,
  127883. 12,
  127884. 3,
  127885. 13,
  127886. 2,
  127887. 14,
  127888. 1,
  127889. 15,
  127890. 0,
  127891. 16,
  127892. };
  127893. static long _vq_lengthlist__44c5_s_p9_1[] = {
  127894. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  127895. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  127896. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  127897. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  127898. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  127899. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  127900. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  127901. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  127902. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  127903. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  127904. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  127905. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  127906. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  127907. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  127908. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  127909. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  127910. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  127911. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  127912. 15,
  127913. };
  127914. static float _vq_quantthresh__44c5_s_p9_1[] = {
  127915. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  127916. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  127917. };
  127918. static long _vq_quantmap__44c5_s_p9_1[] = {
  127919. 15, 13, 11, 9, 7, 5, 3, 1,
  127920. 0, 2, 4, 6, 8, 10, 12, 14,
  127921. 16,
  127922. };
  127923. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  127924. _vq_quantthresh__44c5_s_p9_1,
  127925. _vq_quantmap__44c5_s_p9_1,
  127926. 17,
  127927. 17
  127928. };
  127929. static static_codebook _44c5_s_p9_1 = {
  127930. 2, 289,
  127931. _vq_lengthlist__44c5_s_p9_1,
  127932. 1, -520814592, 1620377600, 5, 0,
  127933. _vq_quantlist__44c5_s_p9_1,
  127934. NULL,
  127935. &_vq_auxt__44c5_s_p9_1,
  127936. NULL,
  127937. 0
  127938. };
  127939. static long _vq_quantlist__44c5_s_p9_2[] = {
  127940. 10,
  127941. 9,
  127942. 11,
  127943. 8,
  127944. 12,
  127945. 7,
  127946. 13,
  127947. 6,
  127948. 14,
  127949. 5,
  127950. 15,
  127951. 4,
  127952. 16,
  127953. 3,
  127954. 17,
  127955. 2,
  127956. 18,
  127957. 1,
  127958. 19,
  127959. 0,
  127960. 20,
  127961. };
  127962. static long _vq_lengthlist__44c5_s_p9_2[] = {
  127963. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127964. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  127965. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  127966. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  127967. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  127968. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127969. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127970. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  127971. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127972. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127973. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127974. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  127975. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  127976. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  127977. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  127978. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  127979. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127980. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127981. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  127982. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  127983. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127984. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127985. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127986. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127987. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  127988. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127989. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  127990. 10,10,10,10,10,10,10,10,10,
  127991. };
  127992. static float _vq_quantthresh__44c5_s_p9_2[] = {
  127993. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127994. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127995. 6.5, 7.5, 8.5, 9.5,
  127996. };
  127997. static long _vq_quantmap__44c5_s_p9_2[] = {
  127998. 19, 17, 15, 13, 11, 9, 7, 5,
  127999. 3, 1, 0, 2, 4, 6, 8, 10,
  128000. 12, 14, 16, 18, 20,
  128001. };
  128002. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  128003. _vq_quantthresh__44c5_s_p9_2,
  128004. _vq_quantmap__44c5_s_p9_2,
  128005. 21,
  128006. 21
  128007. };
  128008. static static_codebook _44c5_s_p9_2 = {
  128009. 2, 441,
  128010. _vq_lengthlist__44c5_s_p9_2,
  128011. 1, -529268736, 1611661312, 5, 0,
  128012. _vq_quantlist__44c5_s_p9_2,
  128013. NULL,
  128014. &_vq_auxt__44c5_s_p9_2,
  128015. NULL,
  128016. 0
  128017. };
  128018. static long _huff_lengthlist__44c5_s_short[] = {
  128019. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  128020. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  128021. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  128022. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  128023. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  128024. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  128025. 6, 8,11,16,
  128026. };
  128027. static static_codebook _huff_book__44c5_s_short = {
  128028. 2, 100,
  128029. _huff_lengthlist__44c5_s_short,
  128030. 0, 0, 0, 0, 0,
  128031. NULL,
  128032. NULL,
  128033. NULL,
  128034. NULL,
  128035. 0
  128036. };
  128037. static long _huff_lengthlist__44c6_s_long[] = {
  128038. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  128039. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  128040. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  128041. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  128042. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  128043. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  128044. 11,10,10,12,
  128045. };
  128046. static static_codebook _huff_book__44c6_s_long = {
  128047. 2, 100,
  128048. _huff_lengthlist__44c6_s_long,
  128049. 0, 0, 0, 0, 0,
  128050. NULL,
  128051. NULL,
  128052. NULL,
  128053. NULL,
  128054. 0
  128055. };
  128056. static long _vq_quantlist__44c6_s_p1_0[] = {
  128057. 1,
  128058. 0,
  128059. 2,
  128060. };
  128061. static long _vq_lengthlist__44c6_s_p1_0[] = {
  128062. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128063. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128065. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128066. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  128067. 8,
  128068. };
  128069. static float _vq_quantthresh__44c6_s_p1_0[] = {
  128070. -0.5, 0.5,
  128071. };
  128072. static long _vq_quantmap__44c6_s_p1_0[] = {
  128073. 1, 0, 2,
  128074. };
  128075. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  128076. _vq_quantthresh__44c6_s_p1_0,
  128077. _vq_quantmap__44c6_s_p1_0,
  128078. 3,
  128079. 3
  128080. };
  128081. static static_codebook _44c6_s_p1_0 = {
  128082. 4, 81,
  128083. _vq_lengthlist__44c6_s_p1_0,
  128084. 1, -535822336, 1611661312, 2, 0,
  128085. _vq_quantlist__44c6_s_p1_0,
  128086. NULL,
  128087. &_vq_auxt__44c6_s_p1_0,
  128088. NULL,
  128089. 0
  128090. };
  128091. static long _vq_quantlist__44c6_s_p2_0[] = {
  128092. 2,
  128093. 1,
  128094. 3,
  128095. 0,
  128096. 4,
  128097. };
  128098. static long _vq_lengthlist__44c6_s_p2_0[] = {
  128099. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128100. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128101. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128102. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128103. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  128104. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128105. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  128106. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128109. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128110. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128111. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128112. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128113. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  128114. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128117. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  128118. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  128119. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  128120. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  128121. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128122. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  128125. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128126. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128127. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  128128. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128129. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  128130. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128135. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  128136. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  128137. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128138. 13,
  128139. };
  128140. static float _vq_quantthresh__44c6_s_p2_0[] = {
  128141. -1.5, -0.5, 0.5, 1.5,
  128142. };
  128143. static long _vq_quantmap__44c6_s_p2_0[] = {
  128144. 3, 1, 0, 2, 4,
  128145. };
  128146. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  128147. _vq_quantthresh__44c6_s_p2_0,
  128148. _vq_quantmap__44c6_s_p2_0,
  128149. 5,
  128150. 5
  128151. };
  128152. static static_codebook _44c6_s_p2_0 = {
  128153. 4, 625,
  128154. _vq_lengthlist__44c6_s_p2_0,
  128155. 1, -533725184, 1611661312, 3, 0,
  128156. _vq_quantlist__44c6_s_p2_0,
  128157. NULL,
  128158. &_vq_auxt__44c6_s_p2_0,
  128159. NULL,
  128160. 0
  128161. };
  128162. static long _vq_quantlist__44c6_s_p3_0[] = {
  128163. 4,
  128164. 3,
  128165. 5,
  128166. 2,
  128167. 6,
  128168. 1,
  128169. 7,
  128170. 0,
  128171. 8,
  128172. };
  128173. static long _vq_lengthlist__44c6_s_p3_0[] = {
  128174. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128175. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  128176. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  128177. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0,
  128180. };
  128181. static float _vq_quantthresh__44c6_s_p3_0[] = {
  128182. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128183. };
  128184. static long _vq_quantmap__44c6_s_p3_0[] = {
  128185. 7, 5, 3, 1, 0, 2, 4, 6,
  128186. 8,
  128187. };
  128188. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  128189. _vq_quantthresh__44c6_s_p3_0,
  128190. _vq_quantmap__44c6_s_p3_0,
  128191. 9,
  128192. 9
  128193. };
  128194. static static_codebook _44c6_s_p3_0 = {
  128195. 2, 81,
  128196. _vq_lengthlist__44c6_s_p3_0,
  128197. 1, -531628032, 1611661312, 4, 0,
  128198. _vq_quantlist__44c6_s_p3_0,
  128199. NULL,
  128200. &_vq_auxt__44c6_s_p3_0,
  128201. NULL,
  128202. 0
  128203. };
  128204. static long _vq_quantlist__44c6_s_p4_0[] = {
  128205. 8,
  128206. 7,
  128207. 9,
  128208. 6,
  128209. 10,
  128210. 5,
  128211. 11,
  128212. 4,
  128213. 12,
  128214. 3,
  128215. 13,
  128216. 2,
  128217. 14,
  128218. 1,
  128219. 15,
  128220. 0,
  128221. 16,
  128222. };
  128223. static long _vq_lengthlist__44c6_s_p4_0[] = {
  128224. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  128225. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128226. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  128227. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128228. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128229. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128230. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  128231. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128232. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  128233. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0,
  128243. };
  128244. static float _vq_quantthresh__44c6_s_p4_0[] = {
  128245. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128246. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128247. };
  128248. static long _vq_quantmap__44c6_s_p4_0[] = {
  128249. 15, 13, 11, 9, 7, 5, 3, 1,
  128250. 0, 2, 4, 6, 8, 10, 12, 14,
  128251. 16,
  128252. };
  128253. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  128254. _vq_quantthresh__44c6_s_p4_0,
  128255. _vq_quantmap__44c6_s_p4_0,
  128256. 17,
  128257. 17
  128258. };
  128259. static static_codebook _44c6_s_p4_0 = {
  128260. 2, 289,
  128261. _vq_lengthlist__44c6_s_p4_0,
  128262. 1, -529530880, 1611661312, 5, 0,
  128263. _vq_quantlist__44c6_s_p4_0,
  128264. NULL,
  128265. &_vq_auxt__44c6_s_p4_0,
  128266. NULL,
  128267. 0
  128268. };
  128269. static long _vq_quantlist__44c6_s_p5_0[] = {
  128270. 1,
  128271. 0,
  128272. 2,
  128273. };
  128274. static long _vq_lengthlist__44c6_s_p5_0[] = {
  128275. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  128276. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  128277. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  128278. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128279. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  128280. 12,
  128281. };
  128282. static float _vq_quantthresh__44c6_s_p5_0[] = {
  128283. -5.5, 5.5,
  128284. };
  128285. static long _vq_quantmap__44c6_s_p5_0[] = {
  128286. 1, 0, 2,
  128287. };
  128288. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  128289. _vq_quantthresh__44c6_s_p5_0,
  128290. _vq_quantmap__44c6_s_p5_0,
  128291. 3,
  128292. 3
  128293. };
  128294. static static_codebook _44c6_s_p5_0 = {
  128295. 4, 81,
  128296. _vq_lengthlist__44c6_s_p5_0,
  128297. 1, -529137664, 1618345984, 2, 0,
  128298. _vq_quantlist__44c6_s_p5_0,
  128299. NULL,
  128300. &_vq_auxt__44c6_s_p5_0,
  128301. NULL,
  128302. 0
  128303. };
  128304. static long _vq_quantlist__44c6_s_p5_1[] = {
  128305. 5,
  128306. 4,
  128307. 6,
  128308. 3,
  128309. 7,
  128310. 2,
  128311. 8,
  128312. 1,
  128313. 9,
  128314. 0,
  128315. 10,
  128316. };
  128317. static long _vq_lengthlist__44c6_s_p5_1[] = {
  128318. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  128319. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  128320. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  128321. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  128322. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  128323. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  128324. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  128325. 11,10,10, 7, 7, 8, 8, 8, 8,
  128326. };
  128327. static float _vq_quantthresh__44c6_s_p5_1[] = {
  128328. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128329. 3.5, 4.5,
  128330. };
  128331. static long _vq_quantmap__44c6_s_p5_1[] = {
  128332. 9, 7, 5, 3, 1, 0, 2, 4,
  128333. 6, 8, 10,
  128334. };
  128335. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  128336. _vq_quantthresh__44c6_s_p5_1,
  128337. _vq_quantmap__44c6_s_p5_1,
  128338. 11,
  128339. 11
  128340. };
  128341. static static_codebook _44c6_s_p5_1 = {
  128342. 2, 121,
  128343. _vq_lengthlist__44c6_s_p5_1,
  128344. 1, -531365888, 1611661312, 4, 0,
  128345. _vq_quantlist__44c6_s_p5_1,
  128346. NULL,
  128347. &_vq_auxt__44c6_s_p5_1,
  128348. NULL,
  128349. 0
  128350. };
  128351. static long _vq_quantlist__44c6_s_p6_0[] = {
  128352. 6,
  128353. 5,
  128354. 7,
  128355. 4,
  128356. 8,
  128357. 3,
  128358. 9,
  128359. 2,
  128360. 10,
  128361. 1,
  128362. 11,
  128363. 0,
  128364. 12,
  128365. };
  128366. static long _vq_lengthlist__44c6_s_p6_0[] = {
  128367. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  128368. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  128369. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  128370. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128371. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  128372. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. };
  128379. static float _vq_quantthresh__44c6_s_p6_0[] = {
  128380. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128381. 12.5, 17.5, 22.5, 27.5,
  128382. };
  128383. static long _vq_quantmap__44c6_s_p6_0[] = {
  128384. 11, 9, 7, 5, 3, 1, 0, 2,
  128385. 4, 6, 8, 10, 12,
  128386. };
  128387. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  128388. _vq_quantthresh__44c6_s_p6_0,
  128389. _vq_quantmap__44c6_s_p6_0,
  128390. 13,
  128391. 13
  128392. };
  128393. static static_codebook _44c6_s_p6_0 = {
  128394. 2, 169,
  128395. _vq_lengthlist__44c6_s_p6_0,
  128396. 1, -526516224, 1616117760, 4, 0,
  128397. _vq_quantlist__44c6_s_p6_0,
  128398. NULL,
  128399. &_vq_auxt__44c6_s_p6_0,
  128400. NULL,
  128401. 0
  128402. };
  128403. static long _vq_quantlist__44c6_s_p6_1[] = {
  128404. 2,
  128405. 1,
  128406. 3,
  128407. 0,
  128408. 4,
  128409. };
  128410. static long _vq_lengthlist__44c6_s_p6_1[] = {
  128411. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128412. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128413. };
  128414. static float _vq_quantthresh__44c6_s_p6_1[] = {
  128415. -1.5, -0.5, 0.5, 1.5,
  128416. };
  128417. static long _vq_quantmap__44c6_s_p6_1[] = {
  128418. 3, 1, 0, 2, 4,
  128419. };
  128420. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  128421. _vq_quantthresh__44c6_s_p6_1,
  128422. _vq_quantmap__44c6_s_p6_1,
  128423. 5,
  128424. 5
  128425. };
  128426. static static_codebook _44c6_s_p6_1 = {
  128427. 2, 25,
  128428. _vq_lengthlist__44c6_s_p6_1,
  128429. 1, -533725184, 1611661312, 3, 0,
  128430. _vq_quantlist__44c6_s_p6_1,
  128431. NULL,
  128432. &_vq_auxt__44c6_s_p6_1,
  128433. NULL,
  128434. 0
  128435. };
  128436. static long _vq_quantlist__44c6_s_p7_0[] = {
  128437. 6,
  128438. 5,
  128439. 7,
  128440. 4,
  128441. 8,
  128442. 3,
  128443. 9,
  128444. 2,
  128445. 10,
  128446. 1,
  128447. 11,
  128448. 0,
  128449. 12,
  128450. };
  128451. static long _vq_lengthlist__44c6_s_p7_0[] = {
  128452. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  128453. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  128454. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  128455. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128456. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  128457. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  128458. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  128459. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  128460. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  128461. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  128462. 20,13,13,13,13,13,13,14,14,
  128463. };
  128464. static float _vq_quantthresh__44c6_s_p7_0[] = {
  128465. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128466. 27.5, 38.5, 49.5, 60.5,
  128467. };
  128468. static long _vq_quantmap__44c6_s_p7_0[] = {
  128469. 11, 9, 7, 5, 3, 1, 0, 2,
  128470. 4, 6, 8, 10, 12,
  128471. };
  128472. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  128473. _vq_quantthresh__44c6_s_p7_0,
  128474. _vq_quantmap__44c6_s_p7_0,
  128475. 13,
  128476. 13
  128477. };
  128478. static static_codebook _44c6_s_p7_0 = {
  128479. 2, 169,
  128480. _vq_lengthlist__44c6_s_p7_0,
  128481. 1, -523206656, 1618345984, 4, 0,
  128482. _vq_quantlist__44c6_s_p7_0,
  128483. NULL,
  128484. &_vq_auxt__44c6_s_p7_0,
  128485. NULL,
  128486. 0
  128487. };
  128488. static long _vq_quantlist__44c6_s_p7_1[] = {
  128489. 5,
  128490. 4,
  128491. 6,
  128492. 3,
  128493. 7,
  128494. 2,
  128495. 8,
  128496. 1,
  128497. 9,
  128498. 0,
  128499. 10,
  128500. };
  128501. static long _vq_lengthlist__44c6_s_p7_1[] = {
  128502. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  128503. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  128504. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  128505. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  128506. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  128507. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  128508. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  128509. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  128510. };
  128511. static float _vq_quantthresh__44c6_s_p7_1[] = {
  128512. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128513. 3.5, 4.5,
  128514. };
  128515. static long _vq_quantmap__44c6_s_p7_1[] = {
  128516. 9, 7, 5, 3, 1, 0, 2, 4,
  128517. 6, 8, 10,
  128518. };
  128519. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  128520. _vq_quantthresh__44c6_s_p7_1,
  128521. _vq_quantmap__44c6_s_p7_1,
  128522. 11,
  128523. 11
  128524. };
  128525. static static_codebook _44c6_s_p7_1 = {
  128526. 2, 121,
  128527. _vq_lengthlist__44c6_s_p7_1,
  128528. 1, -531365888, 1611661312, 4, 0,
  128529. _vq_quantlist__44c6_s_p7_1,
  128530. NULL,
  128531. &_vq_auxt__44c6_s_p7_1,
  128532. NULL,
  128533. 0
  128534. };
  128535. static long _vq_quantlist__44c6_s_p8_0[] = {
  128536. 7,
  128537. 6,
  128538. 8,
  128539. 5,
  128540. 9,
  128541. 4,
  128542. 10,
  128543. 3,
  128544. 11,
  128545. 2,
  128546. 12,
  128547. 1,
  128548. 13,
  128549. 0,
  128550. 14,
  128551. };
  128552. static long _vq_lengthlist__44c6_s_p8_0[] = {
  128553. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  128554. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  128555. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  128556. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  128557. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  128558. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  128559. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  128560. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  128561. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  128562. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  128563. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  128564. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  128565. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  128566. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  128567. 14,
  128568. };
  128569. static float _vq_quantthresh__44c6_s_p8_0[] = {
  128570. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128571. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128572. };
  128573. static long _vq_quantmap__44c6_s_p8_0[] = {
  128574. 13, 11, 9, 7, 5, 3, 1, 0,
  128575. 2, 4, 6, 8, 10, 12, 14,
  128576. };
  128577. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  128578. _vq_quantthresh__44c6_s_p8_0,
  128579. _vq_quantmap__44c6_s_p8_0,
  128580. 15,
  128581. 15
  128582. };
  128583. static static_codebook _44c6_s_p8_0 = {
  128584. 2, 225,
  128585. _vq_lengthlist__44c6_s_p8_0,
  128586. 1, -520986624, 1620377600, 4, 0,
  128587. _vq_quantlist__44c6_s_p8_0,
  128588. NULL,
  128589. &_vq_auxt__44c6_s_p8_0,
  128590. NULL,
  128591. 0
  128592. };
  128593. static long _vq_quantlist__44c6_s_p8_1[] = {
  128594. 10,
  128595. 9,
  128596. 11,
  128597. 8,
  128598. 12,
  128599. 7,
  128600. 13,
  128601. 6,
  128602. 14,
  128603. 5,
  128604. 15,
  128605. 4,
  128606. 16,
  128607. 3,
  128608. 17,
  128609. 2,
  128610. 18,
  128611. 1,
  128612. 19,
  128613. 0,
  128614. 20,
  128615. };
  128616. static long _vq_lengthlist__44c6_s_p8_1[] = {
  128617. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  128618. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  128619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128620. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128621. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128622. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  128623. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  128624. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  128625. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128626. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128627. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  128628. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  128629. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  128630. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  128631. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  128632. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  128633. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  128634. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  128635. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  128636. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  128637. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  128638. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128639. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128640. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128641. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  128642. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  128643. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  128644. 10,10,10,10,10,10,10,10,10,
  128645. };
  128646. static float _vq_quantthresh__44c6_s_p8_1[] = {
  128647. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128648. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128649. 6.5, 7.5, 8.5, 9.5,
  128650. };
  128651. static long _vq_quantmap__44c6_s_p8_1[] = {
  128652. 19, 17, 15, 13, 11, 9, 7, 5,
  128653. 3, 1, 0, 2, 4, 6, 8, 10,
  128654. 12, 14, 16, 18, 20,
  128655. };
  128656. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  128657. _vq_quantthresh__44c6_s_p8_1,
  128658. _vq_quantmap__44c6_s_p8_1,
  128659. 21,
  128660. 21
  128661. };
  128662. static static_codebook _44c6_s_p8_1 = {
  128663. 2, 441,
  128664. _vq_lengthlist__44c6_s_p8_1,
  128665. 1, -529268736, 1611661312, 5, 0,
  128666. _vq_quantlist__44c6_s_p8_1,
  128667. NULL,
  128668. &_vq_auxt__44c6_s_p8_1,
  128669. NULL,
  128670. 0
  128671. };
  128672. static long _vq_quantlist__44c6_s_p9_0[] = {
  128673. 6,
  128674. 5,
  128675. 7,
  128676. 4,
  128677. 8,
  128678. 3,
  128679. 9,
  128680. 2,
  128681. 10,
  128682. 1,
  128683. 11,
  128684. 0,
  128685. 12,
  128686. };
  128687. static long _vq_lengthlist__44c6_s_p9_0[] = {
  128688. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  128689. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  128690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128691. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128697. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128698. 10,10,10,10,10,10,10,10,10,
  128699. };
  128700. static float _vq_quantthresh__44c6_s_p9_0[] = {
  128701. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128702. 1592.5, 2229.5, 2866.5, 3503.5,
  128703. };
  128704. static long _vq_quantmap__44c6_s_p9_0[] = {
  128705. 11, 9, 7, 5, 3, 1, 0, 2,
  128706. 4, 6, 8, 10, 12,
  128707. };
  128708. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  128709. _vq_quantthresh__44c6_s_p9_0,
  128710. _vq_quantmap__44c6_s_p9_0,
  128711. 13,
  128712. 13
  128713. };
  128714. static static_codebook _44c6_s_p9_0 = {
  128715. 2, 169,
  128716. _vq_lengthlist__44c6_s_p9_0,
  128717. 1, -511845376, 1630791680, 4, 0,
  128718. _vq_quantlist__44c6_s_p9_0,
  128719. NULL,
  128720. &_vq_auxt__44c6_s_p9_0,
  128721. NULL,
  128722. 0
  128723. };
  128724. static long _vq_quantlist__44c6_s_p9_1[] = {
  128725. 6,
  128726. 5,
  128727. 7,
  128728. 4,
  128729. 8,
  128730. 3,
  128731. 9,
  128732. 2,
  128733. 10,
  128734. 1,
  128735. 11,
  128736. 0,
  128737. 12,
  128738. };
  128739. static long _vq_lengthlist__44c6_s_p9_1[] = {
  128740. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128741. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  128742. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  128743. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  128744. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  128745. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  128746. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  128747. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  128748. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  128749. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  128750. 15,12,10,11,11,13,11,12,13,
  128751. };
  128752. static float _vq_quantthresh__44c6_s_p9_1[] = {
  128753. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128754. 122.5, 171.5, 220.5, 269.5,
  128755. };
  128756. static long _vq_quantmap__44c6_s_p9_1[] = {
  128757. 11, 9, 7, 5, 3, 1, 0, 2,
  128758. 4, 6, 8, 10, 12,
  128759. };
  128760. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  128761. _vq_quantthresh__44c6_s_p9_1,
  128762. _vq_quantmap__44c6_s_p9_1,
  128763. 13,
  128764. 13
  128765. };
  128766. static static_codebook _44c6_s_p9_1 = {
  128767. 2, 169,
  128768. _vq_lengthlist__44c6_s_p9_1,
  128769. 1, -518889472, 1622704128, 4, 0,
  128770. _vq_quantlist__44c6_s_p9_1,
  128771. NULL,
  128772. &_vq_auxt__44c6_s_p9_1,
  128773. NULL,
  128774. 0
  128775. };
  128776. static long _vq_quantlist__44c6_s_p9_2[] = {
  128777. 24,
  128778. 23,
  128779. 25,
  128780. 22,
  128781. 26,
  128782. 21,
  128783. 27,
  128784. 20,
  128785. 28,
  128786. 19,
  128787. 29,
  128788. 18,
  128789. 30,
  128790. 17,
  128791. 31,
  128792. 16,
  128793. 32,
  128794. 15,
  128795. 33,
  128796. 14,
  128797. 34,
  128798. 13,
  128799. 35,
  128800. 12,
  128801. 36,
  128802. 11,
  128803. 37,
  128804. 10,
  128805. 38,
  128806. 9,
  128807. 39,
  128808. 8,
  128809. 40,
  128810. 7,
  128811. 41,
  128812. 6,
  128813. 42,
  128814. 5,
  128815. 43,
  128816. 4,
  128817. 44,
  128818. 3,
  128819. 45,
  128820. 2,
  128821. 46,
  128822. 1,
  128823. 47,
  128824. 0,
  128825. 48,
  128826. };
  128827. static long _vq_lengthlist__44c6_s_p9_2[] = {
  128828. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128829. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128830. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128831. 7,
  128832. };
  128833. static float _vq_quantthresh__44c6_s_p9_2[] = {
  128834. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128835. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128836. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128837. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128838. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128839. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128840. };
  128841. static long _vq_quantmap__44c6_s_p9_2[] = {
  128842. 47, 45, 43, 41, 39, 37, 35, 33,
  128843. 31, 29, 27, 25, 23, 21, 19, 17,
  128844. 15, 13, 11, 9, 7, 5, 3, 1,
  128845. 0, 2, 4, 6, 8, 10, 12, 14,
  128846. 16, 18, 20, 22, 24, 26, 28, 30,
  128847. 32, 34, 36, 38, 40, 42, 44, 46,
  128848. 48,
  128849. };
  128850. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  128851. _vq_quantthresh__44c6_s_p9_2,
  128852. _vq_quantmap__44c6_s_p9_2,
  128853. 49,
  128854. 49
  128855. };
  128856. static static_codebook _44c6_s_p9_2 = {
  128857. 1, 49,
  128858. _vq_lengthlist__44c6_s_p9_2,
  128859. 1, -526909440, 1611661312, 6, 0,
  128860. _vq_quantlist__44c6_s_p9_2,
  128861. NULL,
  128862. &_vq_auxt__44c6_s_p9_2,
  128863. NULL,
  128864. 0
  128865. };
  128866. static long _huff_lengthlist__44c6_s_short[] = {
  128867. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  128868. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  128869. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  128870. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  128871. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  128872. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  128873. 9,10,17,18,
  128874. };
  128875. static static_codebook _huff_book__44c6_s_short = {
  128876. 2, 100,
  128877. _huff_lengthlist__44c6_s_short,
  128878. 0, 0, 0, 0, 0,
  128879. NULL,
  128880. NULL,
  128881. NULL,
  128882. NULL,
  128883. 0
  128884. };
  128885. static long _huff_lengthlist__44c7_s_long[] = {
  128886. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  128887. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  128888. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  128889. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  128890. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  128891. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  128892. 11,10,10,12,
  128893. };
  128894. static static_codebook _huff_book__44c7_s_long = {
  128895. 2, 100,
  128896. _huff_lengthlist__44c7_s_long,
  128897. 0, 0, 0, 0, 0,
  128898. NULL,
  128899. NULL,
  128900. NULL,
  128901. NULL,
  128902. 0
  128903. };
  128904. static long _vq_quantlist__44c7_s_p1_0[] = {
  128905. 1,
  128906. 0,
  128907. 2,
  128908. };
  128909. static long _vq_lengthlist__44c7_s_p1_0[] = {
  128910. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128911. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128913. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128914. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128915. 8,
  128916. };
  128917. static float _vq_quantthresh__44c7_s_p1_0[] = {
  128918. -0.5, 0.5,
  128919. };
  128920. static long _vq_quantmap__44c7_s_p1_0[] = {
  128921. 1, 0, 2,
  128922. };
  128923. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  128924. _vq_quantthresh__44c7_s_p1_0,
  128925. _vq_quantmap__44c7_s_p1_0,
  128926. 3,
  128927. 3
  128928. };
  128929. static static_codebook _44c7_s_p1_0 = {
  128930. 4, 81,
  128931. _vq_lengthlist__44c7_s_p1_0,
  128932. 1, -535822336, 1611661312, 2, 0,
  128933. _vq_quantlist__44c7_s_p1_0,
  128934. NULL,
  128935. &_vq_auxt__44c7_s_p1_0,
  128936. NULL,
  128937. 0
  128938. };
  128939. static long _vq_quantlist__44c7_s_p2_0[] = {
  128940. 2,
  128941. 1,
  128942. 3,
  128943. 0,
  128944. 4,
  128945. };
  128946. static long _vq_lengthlist__44c7_s_p2_0[] = {
  128947. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128948. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128949. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128950. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128951. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128952. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128953. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  128954. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128957. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128958. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128959. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128960. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128961. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  128962. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128965. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  128966. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  128967. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  128968. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  128969. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128970. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128973. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128974. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128975. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  128976. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128977. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  128978. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128983. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  128984. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128985. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128986. 13,
  128987. };
  128988. static float _vq_quantthresh__44c7_s_p2_0[] = {
  128989. -1.5, -0.5, 0.5, 1.5,
  128990. };
  128991. static long _vq_quantmap__44c7_s_p2_0[] = {
  128992. 3, 1, 0, 2, 4,
  128993. };
  128994. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  128995. _vq_quantthresh__44c7_s_p2_0,
  128996. _vq_quantmap__44c7_s_p2_0,
  128997. 5,
  128998. 5
  128999. };
  129000. static static_codebook _44c7_s_p2_0 = {
  129001. 4, 625,
  129002. _vq_lengthlist__44c7_s_p2_0,
  129003. 1, -533725184, 1611661312, 3, 0,
  129004. _vq_quantlist__44c7_s_p2_0,
  129005. NULL,
  129006. &_vq_auxt__44c7_s_p2_0,
  129007. NULL,
  129008. 0
  129009. };
  129010. static long _vq_quantlist__44c7_s_p3_0[] = {
  129011. 4,
  129012. 3,
  129013. 5,
  129014. 2,
  129015. 6,
  129016. 1,
  129017. 7,
  129018. 0,
  129019. 8,
  129020. };
  129021. static long _vq_lengthlist__44c7_s_p3_0[] = {
  129022. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129023. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129024. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129025. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0,
  129028. };
  129029. static float _vq_quantthresh__44c7_s_p3_0[] = {
  129030. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129031. };
  129032. static long _vq_quantmap__44c7_s_p3_0[] = {
  129033. 7, 5, 3, 1, 0, 2, 4, 6,
  129034. 8,
  129035. };
  129036. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  129037. _vq_quantthresh__44c7_s_p3_0,
  129038. _vq_quantmap__44c7_s_p3_0,
  129039. 9,
  129040. 9
  129041. };
  129042. static static_codebook _44c7_s_p3_0 = {
  129043. 2, 81,
  129044. _vq_lengthlist__44c7_s_p3_0,
  129045. 1, -531628032, 1611661312, 4, 0,
  129046. _vq_quantlist__44c7_s_p3_0,
  129047. NULL,
  129048. &_vq_auxt__44c7_s_p3_0,
  129049. NULL,
  129050. 0
  129051. };
  129052. static long _vq_quantlist__44c7_s_p4_0[] = {
  129053. 8,
  129054. 7,
  129055. 9,
  129056. 6,
  129057. 10,
  129058. 5,
  129059. 11,
  129060. 4,
  129061. 12,
  129062. 3,
  129063. 13,
  129064. 2,
  129065. 14,
  129066. 1,
  129067. 15,
  129068. 0,
  129069. 16,
  129070. };
  129071. static long _vq_lengthlist__44c7_s_p4_0[] = {
  129072. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129073. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  129074. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129075. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  129076. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  129077. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129078. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129079. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129080. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129081. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0,
  129091. };
  129092. static float _vq_quantthresh__44c7_s_p4_0[] = {
  129093. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129094. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129095. };
  129096. static long _vq_quantmap__44c7_s_p4_0[] = {
  129097. 15, 13, 11, 9, 7, 5, 3, 1,
  129098. 0, 2, 4, 6, 8, 10, 12, 14,
  129099. 16,
  129100. };
  129101. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  129102. _vq_quantthresh__44c7_s_p4_0,
  129103. _vq_quantmap__44c7_s_p4_0,
  129104. 17,
  129105. 17
  129106. };
  129107. static static_codebook _44c7_s_p4_0 = {
  129108. 2, 289,
  129109. _vq_lengthlist__44c7_s_p4_0,
  129110. 1, -529530880, 1611661312, 5, 0,
  129111. _vq_quantlist__44c7_s_p4_0,
  129112. NULL,
  129113. &_vq_auxt__44c7_s_p4_0,
  129114. NULL,
  129115. 0
  129116. };
  129117. static long _vq_quantlist__44c7_s_p5_0[] = {
  129118. 1,
  129119. 0,
  129120. 2,
  129121. };
  129122. static long _vq_lengthlist__44c7_s_p5_0[] = {
  129123. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  129124. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129125. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129126. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129127. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  129128. 12,
  129129. };
  129130. static float _vq_quantthresh__44c7_s_p5_0[] = {
  129131. -5.5, 5.5,
  129132. };
  129133. static long _vq_quantmap__44c7_s_p5_0[] = {
  129134. 1, 0, 2,
  129135. };
  129136. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  129137. _vq_quantthresh__44c7_s_p5_0,
  129138. _vq_quantmap__44c7_s_p5_0,
  129139. 3,
  129140. 3
  129141. };
  129142. static static_codebook _44c7_s_p5_0 = {
  129143. 4, 81,
  129144. _vq_lengthlist__44c7_s_p5_0,
  129145. 1, -529137664, 1618345984, 2, 0,
  129146. _vq_quantlist__44c7_s_p5_0,
  129147. NULL,
  129148. &_vq_auxt__44c7_s_p5_0,
  129149. NULL,
  129150. 0
  129151. };
  129152. static long _vq_quantlist__44c7_s_p5_1[] = {
  129153. 5,
  129154. 4,
  129155. 6,
  129156. 3,
  129157. 7,
  129158. 2,
  129159. 8,
  129160. 1,
  129161. 9,
  129162. 0,
  129163. 10,
  129164. };
  129165. static long _vq_lengthlist__44c7_s_p5_1[] = {
  129166. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129167. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  129168. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  129169. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  129170. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  129171. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  129172. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  129173. 11,11,11, 7, 7, 8, 8, 8, 8,
  129174. };
  129175. static float _vq_quantthresh__44c7_s_p5_1[] = {
  129176. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129177. 3.5, 4.5,
  129178. };
  129179. static long _vq_quantmap__44c7_s_p5_1[] = {
  129180. 9, 7, 5, 3, 1, 0, 2, 4,
  129181. 6, 8, 10,
  129182. };
  129183. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  129184. _vq_quantthresh__44c7_s_p5_1,
  129185. _vq_quantmap__44c7_s_p5_1,
  129186. 11,
  129187. 11
  129188. };
  129189. static static_codebook _44c7_s_p5_1 = {
  129190. 2, 121,
  129191. _vq_lengthlist__44c7_s_p5_1,
  129192. 1, -531365888, 1611661312, 4, 0,
  129193. _vq_quantlist__44c7_s_p5_1,
  129194. NULL,
  129195. &_vq_auxt__44c7_s_p5_1,
  129196. NULL,
  129197. 0
  129198. };
  129199. static long _vq_quantlist__44c7_s_p6_0[] = {
  129200. 6,
  129201. 5,
  129202. 7,
  129203. 4,
  129204. 8,
  129205. 3,
  129206. 9,
  129207. 2,
  129208. 10,
  129209. 1,
  129210. 11,
  129211. 0,
  129212. 12,
  129213. };
  129214. static long _vq_lengthlist__44c7_s_p6_0[] = {
  129215. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  129216. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129217. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  129218. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  129219. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  129220. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. };
  129227. static float _vq_quantthresh__44c7_s_p6_0[] = {
  129228. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129229. 12.5, 17.5, 22.5, 27.5,
  129230. };
  129231. static long _vq_quantmap__44c7_s_p6_0[] = {
  129232. 11, 9, 7, 5, 3, 1, 0, 2,
  129233. 4, 6, 8, 10, 12,
  129234. };
  129235. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  129236. _vq_quantthresh__44c7_s_p6_0,
  129237. _vq_quantmap__44c7_s_p6_0,
  129238. 13,
  129239. 13
  129240. };
  129241. static static_codebook _44c7_s_p6_0 = {
  129242. 2, 169,
  129243. _vq_lengthlist__44c7_s_p6_0,
  129244. 1, -526516224, 1616117760, 4, 0,
  129245. _vq_quantlist__44c7_s_p6_0,
  129246. NULL,
  129247. &_vq_auxt__44c7_s_p6_0,
  129248. NULL,
  129249. 0
  129250. };
  129251. static long _vq_quantlist__44c7_s_p6_1[] = {
  129252. 2,
  129253. 1,
  129254. 3,
  129255. 0,
  129256. 4,
  129257. };
  129258. static long _vq_lengthlist__44c7_s_p6_1[] = {
  129259. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129260. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129261. };
  129262. static float _vq_quantthresh__44c7_s_p6_1[] = {
  129263. -1.5, -0.5, 0.5, 1.5,
  129264. };
  129265. static long _vq_quantmap__44c7_s_p6_1[] = {
  129266. 3, 1, 0, 2, 4,
  129267. };
  129268. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  129269. _vq_quantthresh__44c7_s_p6_1,
  129270. _vq_quantmap__44c7_s_p6_1,
  129271. 5,
  129272. 5
  129273. };
  129274. static static_codebook _44c7_s_p6_1 = {
  129275. 2, 25,
  129276. _vq_lengthlist__44c7_s_p6_1,
  129277. 1, -533725184, 1611661312, 3, 0,
  129278. _vq_quantlist__44c7_s_p6_1,
  129279. NULL,
  129280. &_vq_auxt__44c7_s_p6_1,
  129281. NULL,
  129282. 0
  129283. };
  129284. static long _vq_quantlist__44c7_s_p7_0[] = {
  129285. 6,
  129286. 5,
  129287. 7,
  129288. 4,
  129289. 8,
  129290. 3,
  129291. 9,
  129292. 2,
  129293. 10,
  129294. 1,
  129295. 11,
  129296. 0,
  129297. 12,
  129298. };
  129299. static long _vq_lengthlist__44c7_s_p7_0[] = {
  129300. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  129301. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129302. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  129303. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  129304. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  129305. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  129306. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  129307. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  129308. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  129309. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  129310. 19,13,13,13,13,14,14,15,15,
  129311. };
  129312. static float _vq_quantthresh__44c7_s_p7_0[] = {
  129313. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129314. 27.5, 38.5, 49.5, 60.5,
  129315. };
  129316. static long _vq_quantmap__44c7_s_p7_0[] = {
  129317. 11, 9, 7, 5, 3, 1, 0, 2,
  129318. 4, 6, 8, 10, 12,
  129319. };
  129320. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  129321. _vq_quantthresh__44c7_s_p7_0,
  129322. _vq_quantmap__44c7_s_p7_0,
  129323. 13,
  129324. 13
  129325. };
  129326. static static_codebook _44c7_s_p7_0 = {
  129327. 2, 169,
  129328. _vq_lengthlist__44c7_s_p7_0,
  129329. 1, -523206656, 1618345984, 4, 0,
  129330. _vq_quantlist__44c7_s_p7_0,
  129331. NULL,
  129332. &_vq_auxt__44c7_s_p7_0,
  129333. NULL,
  129334. 0
  129335. };
  129336. static long _vq_quantlist__44c7_s_p7_1[] = {
  129337. 5,
  129338. 4,
  129339. 6,
  129340. 3,
  129341. 7,
  129342. 2,
  129343. 8,
  129344. 1,
  129345. 9,
  129346. 0,
  129347. 10,
  129348. };
  129349. static long _vq_lengthlist__44c7_s_p7_1[] = {
  129350. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  129351. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  129352. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  129353. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129354. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129355. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129356. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129357. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129358. };
  129359. static float _vq_quantthresh__44c7_s_p7_1[] = {
  129360. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129361. 3.5, 4.5,
  129362. };
  129363. static long _vq_quantmap__44c7_s_p7_1[] = {
  129364. 9, 7, 5, 3, 1, 0, 2, 4,
  129365. 6, 8, 10,
  129366. };
  129367. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  129368. _vq_quantthresh__44c7_s_p7_1,
  129369. _vq_quantmap__44c7_s_p7_1,
  129370. 11,
  129371. 11
  129372. };
  129373. static static_codebook _44c7_s_p7_1 = {
  129374. 2, 121,
  129375. _vq_lengthlist__44c7_s_p7_1,
  129376. 1, -531365888, 1611661312, 4, 0,
  129377. _vq_quantlist__44c7_s_p7_1,
  129378. NULL,
  129379. &_vq_auxt__44c7_s_p7_1,
  129380. NULL,
  129381. 0
  129382. };
  129383. static long _vq_quantlist__44c7_s_p8_0[] = {
  129384. 7,
  129385. 6,
  129386. 8,
  129387. 5,
  129388. 9,
  129389. 4,
  129390. 10,
  129391. 3,
  129392. 11,
  129393. 2,
  129394. 12,
  129395. 1,
  129396. 13,
  129397. 0,
  129398. 14,
  129399. };
  129400. static long _vq_lengthlist__44c7_s_p8_0[] = {
  129401. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  129402. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  129403. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  129404. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  129405. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  129406. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  129407. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  129408. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  129409. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  129410. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  129411. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  129412. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  129413. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  129414. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  129415. 14,
  129416. };
  129417. static float _vq_quantthresh__44c7_s_p8_0[] = {
  129418. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129419. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129420. };
  129421. static long _vq_quantmap__44c7_s_p8_0[] = {
  129422. 13, 11, 9, 7, 5, 3, 1, 0,
  129423. 2, 4, 6, 8, 10, 12, 14,
  129424. };
  129425. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  129426. _vq_quantthresh__44c7_s_p8_0,
  129427. _vq_quantmap__44c7_s_p8_0,
  129428. 15,
  129429. 15
  129430. };
  129431. static static_codebook _44c7_s_p8_0 = {
  129432. 2, 225,
  129433. _vq_lengthlist__44c7_s_p8_0,
  129434. 1, -520986624, 1620377600, 4, 0,
  129435. _vq_quantlist__44c7_s_p8_0,
  129436. NULL,
  129437. &_vq_auxt__44c7_s_p8_0,
  129438. NULL,
  129439. 0
  129440. };
  129441. static long _vq_quantlist__44c7_s_p8_1[] = {
  129442. 10,
  129443. 9,
  129444. 11,
  129445. 8,
  129446. 12,
  129447. 7,
  129448. 13,
  129449. 6,
  129450. 14,
  129451. 5,
  129452. 15,
  129453. 4,
  129454. 16,
  129455. 3,
  129456. 17,
  129457. 2,
  129458. 18,
  129459. 1,
  129460. 19,
  129461. 0,
  129462. 20,
  129463. };
  129464. static long _vq_lengthlist__44c7_s_p8_1[] = {
  129465. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129466. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129467. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129468. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129469. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129470. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129471. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  129472. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129473. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129474. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129475. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  129476. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  129477. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  129478. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  129479. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  129480. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  129481. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  129482. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129483. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  129484. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  129485. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  129486. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  129487. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  129488. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  129489. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  129490. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  129491. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  129492. 10,10,10,10,10,10,10,10,10,
  129493. };
  129494. static float _vq_quantthresh__44c7_s_p8_1[] = {
  129495. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129496. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129497. 6.5, 7.5, 8.5, 9.5,
  129498. };
  129499. static long _vq_quantmap__44c7_s_p8_1[] = {
  129500. 19, 17, 15, 13, 11, 9, 7, 5,
  129501. 3, 1, 0, 2, 4, 6, 8, 10,
  129502. 12, 14, 16, 18, 20,
  129503. };
  129504. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  129505. _vq_quantthresh__44c7_s_p8_1,
  129506. _vq_quantmap__44c7_s_p8_1,
  129507. 21,
  129508. 21
  129509. };
  129510. static static_codebook _44c7_s_p8_1 = {
  129511. 2, 441,
  129512. _vq_lengthlist__44c7_s_p8_1,
  129513. 1, -529268736, 1611661312, 5, 0,
  129514. _vq_quantlist__44c7_s_p8_1,
  129515. NULL,
  129516. &_vq_auxt__44c7_s_p8_1,
  129517. NULL,
  129518. 0
  129519. };
  129520. static long _vq_quantlist__44c7_s_p9_0[] = {
  129521. 6,
  129522. 5,
  129523. 7,
  129524. 4,
  129525. 8,
  129526. 3,
  129527. 9,
  129528. 2,
  129529. 10,
  129530. 1,
  129531. 11,
  129532. 0,
  129533. 12,
  129534. };
  129535. static long _vq_lengthlist__44c7_s_p9_0[] = {
  129536. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  129537. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  129538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129546. 11,11,11,11,11,11,11,11,11,
  129547. };
  129548. static float _vq_quantthresh__44c7_s_p9_0[] = {
  129549. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129550. 1592.5, 2229.5, 2866.5, 3503.5,
  129551. };
  129552. static long _vq_quantmap__44c7_s_p9_0[] = {
  129553. 11, 9, 7, 5, 3, 1, 0, 2,
  129554. 4, 6, 8, 10, 12,
  129555. };
  129556. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  129557. _vq_quantthresh__44c7_s_p9_0,
  129558. _vq_quantmap__44c7_s_p9_0,
  129559. 13,
  129560. 13
  129561. };
  129562. static static_codebook _44c7_s_p9_0 = {
  129563. 2, 169,
  129564. _vq_lengthlist__44c7_s_p9_0,
  129565. 1, -511845376, 1630791680, 4, 0,
  129566. _vq_quantlist__44c7_s_p9_0,
  129567. NULL,
  129568. &_vq_auxt__44c7_s_p9_0,
  129569. NULL,
  129570. 0
  129571. };
  129572. static long _vq_quantlist__44c7_s_p9_1[] = {
  129573. 6,
  129574. 5,
  129575. 7,
  129576. 4,
  129577. 8,
  129578. 3,
  129579. 9,
  129580. 2,
  129581. 10,
  129582. 1,
  129583. 11,
  129584. 0,
  129585. 12,
  129586. };
  129587. static long _vq_lengthlist__44c7_s_p9_1[] = {
  129588. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  129589. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  129590. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  129591. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  129592. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  129593. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  129594. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  129595. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  129596. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  129597. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  129598. 15,11,11,10,10,12,12,12,12,
  129599. };
  129600. static float _vq_quantthresh__44c7_s_p9_1[] = {
  129601. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  129602. 122.5, 171.5, 220.5, 269.5,
  129603. };
  129604. static long _vq_quantmap__44c7_s_p9_1[] = {
  129605. 11, 9, 7, 5, 3, 1, 0, 2,
  129606. 4, 6, 8, 10, 12,
  129607. };
  129608. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  129609. _vq_quantthresh__44c7_s_p9_1,
  129610. _vq_quantmap__44c7_s_p9_1,
  129611. 13,
  129612. 13
  129613. };
  129614. static static_codebook _44c7_s_p9_1 = {
  129615. 2, 169,
  129616. _vq_lengthlist__44c7_s_p9_1,
  129617. 1, -518889472, 1622704128, 4, 0,
  129618. _vq_quantlist__44c7_s_p9_1,
  129619. NULL,
  129620. &_vq_auxt__44c7_s_p9_1,
  129621. NULL,
  129622. 0
  129623. };
  129624. static long _vq_quantlist__44c7_s_p9_2[] = {
  129625. 24,
  129626. 23,
  129627. 25,
  129628. 22,
  129629. 26,
  129630. 21,
  129631. 27,
  129632. 20,
  129633. 28,
  129634. 19,
  129635. 29,
  129636. 18,
  129637. 30,
  129638. 17,
  129639. 31,
  129640. 16,
  129641. 32,
  129642. 15,
  129643. 33,
  129644. 14,
  129645. 34,
  129646. 13,
  129647. 35,
  129648. 12,
  129649. 36,
  129650. 11,
  129651. 37,
  129652. 10,
  129653. 38,
  129654. 9,
  129655. 39,
  129656. 8,
  129657. 40,
  129658. 7,
  129659. 41,
  129660. 6,
  129661. 42,
  129662. 5,
  129663. 43,
  129664. 4,
  129665. 44,
  129666. 3,
  129667. 45,
  129668. 2,
  129669. 46,
  129670. 1,
  129671. 47,
  129672. 0,
  129673. 48,
  129674. };
  129675. static long _vq_lengthlist__44c7_s_p9_2[] = {
  129676. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129677. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129678. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129679. 7,
  129680. };
  129681. static float _vq_quantthresh__44c7_s_p9_2[] = {
  129682. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129683. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129684. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129685. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129686. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129687. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129688. };
  129689. static long _vq_quantmap__44c7_s_p9_2[] = {
  129690. 47, 45, 43, 41, 39, 37, 35, 33,
  129691. 31, 29, 27, 25, 23, 21, 19, 17,
  129692. 15, 13, 11, 9, 7, 5, 3, 1,
  129693. 0, 2, 4, 6, 8, 10, 12, 14,
  129694. 16, 18, 20, 22, 24, 26, 28, 30,
  129695. 32, 34, 36, 38, 40, 42, 44, 46,
  129696. 48,
  129697. };
  129698. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  129699. _vq_quantthresh__44c7_s_p9_2,
  129700. _vq_quantmap__44c7_s_p9_2,
  129701. 49,
  129702. 49
  129703. };
  129704. static static_codebook _44c7_s_p9_2 = {
  129705. 1, 49,
  129706. _vq_lengthlist__44c7_s_p9_2,
  129707. 1, -526909440, 1611661312, 6, 0,
  129708. _vq_quantlist__44c7_s_p9_2,
  129709. NULL,
  129710. &_vq_auxt__44c7_s_p9_2,
  129711. NULL,
  129712. 0
  129713. };
  129714. static long _huff_lengthlist__44c7_s_short[] = {
  129715. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  129716. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  129717. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  129718. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  129719. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  129720. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  129721. 10, 9,11,14,
  129722. };
  129723. static static_codebook _huff_book__44c7_s_short = {
  129724. 2, 100,
  129725. _huff_lengthlist__44c7_s_short,
  129726. 0, 0, 0, 0, 0,
  129727. NULL,
  129728. NULL,
  129729. NULL,
  129730. NULL,
  129731. 0
  129732. };
  129733. static long _huff_lengthlist__44c8_s_long[] = {
  129734. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  129735. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  129736. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  129737. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  129738. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  129739. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  129740. 11, 9, 9,10,
  129741. };
  129742. static static_codebook _huff_book__44c8_s_long = {
  129743. 2, 100,
  129744. _huff_lengthlist__44c8_s_long,
  129745. 0, 0, 0, 0, 0,
  129746. NULL,
  129747. NULL,
  129748. NULL,
  129749. NULL,
  129750. 0
  129751. };
  129752. static long _vq_quantlist__44c8_s_p1_0[] = {
  129753. 1,
  129754. 0,
  129755. 2,
  129756. };
  129757. static long _vq_lengthlist__44c8_s_p1_0[] = {
  129758. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  129759. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129761. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129762. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129763. 8,
  129764. };
  129765. static float _vq_quantthresh__44c8_s_p1_0[] = {
  129766. -0.5, 0.5,
  129767. };
  129768. static long _vq_quantmap__44c8_s_p1_0[] = {
  129769. 1, 0, 2,
  129770. };
  129771. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  129772. _vq_quantthresh__44c8_s_p1_0,
  129773. _vq_quantmap__44c8_s_p1_0,
  129774. 3,
  129775. 3
  129776. };
  129777. static static_codebook _44c8_s_p1_0 = {
  129778. 4, 81,
  129779. _vq_lengthlist__44c8_s_p1_0,
  129780. 1, -535822336, 1611661312, 2, 0,
  129781. _vq_quantlist__44c8_s_p1_0,
  129782. NULL,
  129783. &_vq_auxt__44c8_s_p1_0,
  129784. NULL,
  129785. 0
  129786. };
  129787. static long _vq_quantlist__44c8_s_p2_0[] = {
  129788. 2,
  129789. 1,
  129790. 3,
  129791. 0,
  129792. 4,
  129793. };
  129794. static long _vq_lengthlist__44c8_s_p2_0[] = {
  129795. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129796. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129797. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129798. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  129799. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129800. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  129801. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  129802. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129805. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  129806. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129807. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  129808. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  129809. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  129810. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  129813. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  129814. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  129815. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  129816. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  129817. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  129818. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129821. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  129822. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129823. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  129824. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  129825. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  129826. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129831. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  129832. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129833. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  129834. 13,
  129835. };
  129836. static float _vq_quantthresh__44c8_s_p2_0[] = {
  129837. -1.5, -0.5, 0.5, 1.5,
  129838. };
  129839. static long _vq_quantmap__44c8_s_p2_0[] = {
  129840. 3, 1, 0, 2, 4,
  129841. };
  129842. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  129843. _vq_quantthresh__44c8_s_p2_0,
  129844. _vq_quantmap__44c8_s_p2_0,
  129845. 5,
  129846. 5
  129847. };
  129848. static static_codebook _44c8_s_p2_0 = {
  129849. 4, 625,
  129850. _vq_lengthlist__44c8_s_p2_0,
  129851. 1, -533725184, 1611661312, 3, 0,
  129852. _vq_quantlist__44c8_s_p2_0,
  129853. NULL,
  129854. &_vq_auxt__44c8_s_p2_0,
  129855. NULL,
  129856. 0
  129857. };
  129858. static long _vq_quantlist__44c8_s_p3_0[] = {
  129859. 4,
  129860. 3,
  129861. 5,
  129862. 2,
  129863. 6,
  129864. 1,
  129865. 7,
  129866. 0,
  129867. 8,
  129868. };
  129869. static long _vq_lengthlist__44c8_s_p3_0[] = {
  129870. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129871. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129872. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129873. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0,
  129876. };
  129877. static float _vq_quantthresh__44c8_s_p3_0[] = {
  129878. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129879. };
  129880. static long _vq_quantmap__44c8_s_p3_0[] = {
  129881. 7, 5, 3, 1, 0, 2, 4, 6,
  129882. 8,
  129883. };
  129884. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  129885. _vq_quantthresh__44c8_s_p3_0,
  129886. _vq_quantmap__44c8_s_p3_0,
  129887. 9,
  129888. 9
  129889. };
  129890. static static_codebook _44c8_s_p3_0 = {
  129891. 2, 81,
  129892. _vq_lengthlist__44c8_s_p3_0,
  129893. 1, -531628032, 1611661312, 4, 0,
  129894. _vq_quantlist__44c8_s_p3_0,
  129895. NULL,
  129896. &_vq_auxt__44c8_s_p3_0,
  129897. NULL,
  129898. 0
  129899. };
  129900. static long _vq_quantlist__44c8_s_p4_0[] = {
  129901. 8,
  129902. 7,
  129903. 9,
  129904. 6,
  129905. 10,
  129906. 5,
  129907. 11,
  129908. 4,
  129909. 12,
  129910. 3,
  129911. 13,
  129912. 2,
  129913. 14,
  129914. 1,
  129915. 15,
  129916. 0,
  129917. 16,
  129918. };
  129919. static long _vq_lengthlist__44c8_s_p4_0[] = {
  129920. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129921. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  129922. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129923. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  129924. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  129925. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129926. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129927. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129928. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129929. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0,
  129939. };
  129940. static float _vq_quantthresh__44c8_s_p4_0[] = {
  129941. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129942. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129943. };
  129944. static long _vq_quantmap__44c8_s_p4_0[] = {
  129945. 15, 13, 11, 9, 7, 5, 3, 1,
  129946. 0, 2, 4, 6, 8, 10, 12, 14,
  129947. 16,
  129948. };
  129949. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  129950. _vq_quantthresh__44c8_s_p4_0,
  129951. _vq_quantmap__44c8_s_p4_0,
  129952. 17,
  129953. 17
  129954. };
  129955. static static_codebook _44c8_s_p4_0 = {
  129956. 2, 289,
  129957. _vq_lengthlist__44c8_s_p4_0,
  129958. 1, -529530880, 1611661312, 5, 0,
  129959. _vq_quantlist__44c8_s_p4_0,
  129960. NULL,
  129961. &_vq_auxt__44c8_s_p4_0,
  129962. NULL,
  129963. 0
  129964. };
  129965. static long _vq_quantlist__44c8_s_p5_0[] = {
  129966. 1,
  129967. 0,
  129968. 2,
  129969. };
  129970. static long _vq_lengthlist__44c8_s_p5_0[] = {
  129971. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  129972. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129973. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129974. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  129975. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  129976. 12,
  129977. };
  129978. static float _vq_quantthresh__44c8_s_p5_0[] = {
  129979. -5.5, 5.5,
  129980. };
  129981. static long _vq_quantmap__44c8_s_p5_0[] = {
  129982. 1, 0, 2,
  129983. };
  129984. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  129985. _vq_quantthresh__44c8_s_p5_0,
  129986. _vq_quantmap__44c8_s_p5_0,
  129987. 3,
  129988. 3
  129989. };
  129990. static static_codebook _44c8_s_p5_0 = {
  129991. 4, 81,
  129992. _vq_lengthlist__44c8_s_p5_0,
  129993. 1, -529137664, 1618345984, 2, 0,
  129994. _vq_quantlist__44c8_s_p5_0,
  129995. NULL,
  129996. &_vq_auxt__44c8_s_p5_0,
  129997. NULL,
  129998. 0
  129999. };
  130000. static long _vq_quantlist__44c8_s_p5_1[] = {
  130001. 5,
  130002. 4,
  130003. 6,
  130004. 3,
  130005. 7,
  130006. 2,
  130007. 8,
  130008. 1,
  130009. 9,
  130010. 0,
  130011. 10,
  130012. };
  130013. static long _vq_lengthlist__44c8_s_p5_1[] = {
  130014. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  130015. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130016. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  130017. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  130018. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  130019. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  130020. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  130021. 11,11,11, 7, 7, 7, 7, 8, 8,
  130022. };
  130023. static float _vq_quantthresh__44c8_s_p5_1[] = {
  130024. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130025. 3.5, 4.5,
  130026. };
  130027. static long _vq_quantmap__44c8_s_p5_1[] = {
  130028. 9, 7, 5, 3, 1, 0, 2, 4,
  130029. 6, 8, 10,
  130030. };
  130031. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  130032. _vq_quantthresh__44c8_s_p5_1,
  130033. _vq_quantmap__44c8_s_p5_1,
  130034. 11,
  130035. 11
  130036. };
  130037. static static_codebook _44c8_s_p5_1 = {
  130038. 2, 121,
  130039. _vq_lengthlist__44c8_s_p5_1,
  130040. 1, -531365888, 1611661312, 4, 0,
  130041. _vq_quantlist__44c8_s_p5_1,
  130042. NULL,
  130043. &_vq_auxt__44c8_s_p5_1,
  130044. NULL,
  130045. 0
  130046. };
  130047. static long _vq_quantlist__44c8_s_p6_0[] = {
  130048. 6,
  130049. 5,
  130050. 7,
  130051. 4,
  130052. 8,
  130053. 3,
  130054. 9,
  130055. 2,
  130056. 10,
  130057. 1,
  130058. 11,
  130059. 0,
  130060. 12,
  130061. };
  130062. static long _vq_lengthlist__44c8_s_p6_0[] = {
  130063. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130064. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  130065. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  130066. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  130067. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  130068. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. };
  130075. static float _vq_quantthresh__44c8_s_p6_0[] = {
  130076. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130077. 12.5, 17.5, 22.5, 27.5,
  130078. };
  130079. static long _vq_quantmap__44c8_s_p6_0[] = {
  130080. 11, 9, 7, 5, 3, 1, 0, 2,
  130081. 4, 6, 8, 10, 12,
  130082. };
  130083. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  130084. _vq_quantthresh__44c8_s_p6_0,
  130085. _vq_quantmap__44c8_s_p6_0,
  130086. 13,
  130087. 13
  130088. };
  130089. static static_codebook _44c8_s_p6_0 = {
  130090. 2, 169,
  130091. _vq_lengthlist__44c8_s_p6_0,
  130092. 1, -526516224, 1616117760, 4, 0,
  130093. _vq_quantlist__44c8_s_p6_0,
  130094. NULL,
  130095. &_vq_auxt__44c8_s_p6_0,
  130096. NULL,
  130097. 0
  130098. };
  130099. static long _vq_quantlist__44c8_s_p6_1[] = {
  130100. 2,
  130101. 1,
  130102. 3,
  130103. 0,
  130104. 4,
  130105. };
  130106. static long _vq_lengthlist__44c8_s_p6_1[] = {
  130107. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130108. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130109. };
  130110. static float _vq_quantthresh__44c8_s_p6_1[] = {
  130111. -1.5, -0.5, 0.5, 1.5,
  130112. };
  130113. static long _vq_quantmap__44c8_s_p6_1[] = {
  130114. 3, 1, 0, 2, 4,
  130115. };
  130116. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  130117. _vq_quantthresh__44c8_s_p6_1,
  130118. _vq_quantmap__44c8_s_p6_1,
  130119. 5,
  130120. 5
  130121. };
  130122. static static_codebook _44c8_s_p6_1 = {
  130123. 2, 25,
  130124. _vq_lengthlist__44c8_s_p6_1,
  130125. 1, -533725184, 1611661312, 3, 0,
  130126. _vq_quantlist__44c8_s_p6_1,
  130127. NULL,
  130128. &_vq_auxt__44c8_s_p6_1,
  130129. NULL,
  130130. 0
  130131. };
  130132. static long _vq_quantlist__44c8_s_p7_0[] = {
  130133. 6,
  130134. 5,
  130135. 7,
  130136. 4,
  130137. 8,
  130138. 3,
  130139. 9,
  130140. 2,
  130141. 10,
  130142. 1,
  130143. 11,
  130144. 0,
  130145. 12,
  130146. };
  130147. static long _vq_lengthlist__44c8_s_p7_0[] = {
  130148. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  130149. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130150. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  130151. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  130152. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  130153. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  130154. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  130155. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  130156. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  130157. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  130158. 20,13,13,13,13,14,13,15,15,
  130159. };
  130160. static float _vq_quantthresh__44c8_s_p7_0[] = {
  130161. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130162. 27.5, 38.5, 49.5, 60.5,
  130163. };
  130164. static long _vq_quantmap__44c8_s_p7_0[] = {
  130165. 11, 9, 7, 5, 3, 1, 0, 2,
  130166. 4, 6, 8, 10, 12,
  130167. };
  130168. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  130169. _vq_quantthresh__44c8_s_p7_0,
  130170. _vq_quantmap__44c8_s_p7_0,
  130171. 13,
  130172. 13
  130173. };
  130174. static static_codebook _44c8_s_p7_0 = {
  130175. 2, 169,
  130176. _vq_lengthlist__44c8_s_p7_0,
  130177. 1, -523206656, 1618345984, 4, 0,
  130178. _vq_quantlist__44c8_s_p7_0,
  130179. NULL,
  130180. &_vq_auxt__44c8_s_p7_0,
  130181. NULL,
  130182. 0
  130183. };
  130184. static long _vq_quantlist__44c8_s_p7_1[] = {
  130185. 5,
  130186. 4,
  130187. 6,
  130188. 3,
  130189. 7,
  130190. 2,
  130191. 8,
  130192. 1,
  130193. 9,
  130194. 0,
  130195. 10,
  130196. };
  130197. static long _vq_lengthlist__44c8_s_p7_1[] = {
  130198. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  130199. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130200. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130201. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130202. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130203. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130204. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130205. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130206. };
  130207. static float _vq_quantthresh__44c8_s_p7_1[] = {
  130208. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130209. 3.5, 4.5,
  130210. };
  130211. static long _vq_quantmap__44c8_s_p7_1[] = {
  130212. 9, 7, 5, 3, 1, 0, 2, 4,
  130213. 6, 8, 10,
  130214. };
  130215. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  130216. _vq_quantthresh__44c8_s_p7_1,
  130217. _vq_quantmap__44c8_s_p7_1,
  130218. 11,
  130219. 11
  130220. };
  130221. static static_codebook _44c8_s_p7_1 = {
  130222. 2, 121,
  130223. _vq_lengthlist__44c8_s_p7_1,
  130224. 1, -531365888, 1611661312, 4, 0,
  130225. _vq_quantlist__44c8_s_p7_1,
  130226. NULL,
  130227. &_vq_auxt__44c8_s_p7_1,
  130228. NULL,
  130229. 0
  130230. };
  130231. static long _vq_quantlist__44c8_s_p8_0[] = {
  130232. 7,
  130233. 6,
  130234. 8,
  130235. 5,
  130236. 9,
  130237. 4,
  130238. 10,
  130239. 3,
  130240. 11,
  130241. 2,
  130242. 12,
  130243. 1,
  130244. 13,
  130245. 0,
  130246. 14,
  130247. };
  130248. static long _vq_lengthlist__44c8_s_p8_0[] = {
  130249. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  130250. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  130251. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  130252. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  130253. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  130254. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  130255. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  130256. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  130257. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  130258. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  130259. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  130260. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130261. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  130262. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  130263. 15,
  130264. };
  130265. static float _vq_quantthresh__44c8_s_p8_0[] = {
  130266. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130267. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130268. };
  130269. static long _vq_quantmap__44c8_s_p8_0[] = {
  130270. 13, 11, 9, 7, 5, 3, 1, 0,
  130271. 2, 4, 6, 8, 10, 12, 14,
  130272. };
  130273. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  130274. _vq_quantthresh__44c8_s_p8_0,
  130275. _vq_quantmap__44c8_s_p8_0,
  130276. 15,
  130277. 15
  130278. };
  130279. static static_codebook _44c8_s_p8_0 = {
  130280. 2, 225,
  130281. _vq_lengthlist__44c8_s_p8_0,
  130282. 1, -520986624, 1620377600, 4, 0,
  130283. _vq_quantlist__44c8_s_p8_0,
  130284. NULL,
  130285. &_vq_auxt__44c8_s_p8_0,
  130286. NULL,
  130287. 0
  130288. };
  130289. static long _vq_quantlist__44c8_s_p8_1[] = {
  130290. 10,
  130291. 9,
  130292. 11,
  130293. 8,
  130294. 12,
  130295. 7,
  130296. 13,
  130297. 6,
  130298. 14,
  130299. 5,
  130300. 15,
  130301. 4,
  130302. 16,
  130303. 3,
  130304. 17,
  130305. 2,
  130306. 18,
  130307. 1,
  130308. 19,
  130309. 0,
  130310. 20,
  130311. };
  130312. static long _vq_lengthlist__44c8_s_p8_1[] = {
  130313. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130314. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130315. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130316. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130317. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130318. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130319. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130320. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130321. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130322. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130323. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  130324. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130325. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  130326. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130327. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  130328. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  130329. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  130330. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  130331. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  130332. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  130333. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  130334. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  130335. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130336. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  130337. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  130338. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  130339. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130340. 10, 9, 9,10,10, 9,10, 9, 9,
  130341. };
  130342. static float _vq_quantthresh__44c8_s_p8_1[] = {
  130343. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130344. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130345. 6.5, 7.5, 8.5, 9.5,
  130346. };
  130347. static long _vq_quantmap__44c8_s_p8_1[] = {
  130348. 19, 17, 15, 13, 11, 9, 7, 5,
  130349. 3, 1, 0, 2, 4, 6, 8, 10,
  130350. 12, 14, 16, 18, 20,
  130351. };
  130352. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  130353. _vq_quantthresh__44c8_s_p8_1,
  130354. _vq_quantmap__44c8_s_p8_1,
  130355. 21,
  130356. 21
  130357. };
  130358. static static_codebook _44c8_s_p8_1 = {
  130359. 2, 441,
  130360. _vq_lengthlist__44c8_s_p8_1,
  130361. 1, -529268736, 1611661312, 5, 0,
  130362. _vq_quantlist__44c8_s_p8_1,
  130363. NULL,
  130364. &_vq_auxt__44c8_s_p8_1,
  130365. NULL,
  130366. 0
  130367. };
  130368. static long _vq_quantlist__44c8_s_p9_0[] = {
  130369. 8,
  130370. 7,
  130371. 9,
  130372. 6,
  130373. 10,
  130374. 5,
  130375. 11,
  130376. 4,
  130377. 12,
  130378. 3,
  130379. 13,
  130380. 2,
  130381. 14,
  130382. 1,
  130383. 15,
  130384. 0,
  130385. 16,
  130386. };
  130387. static long _vq_lengthlist__44c8_s_p9_0[] = {
  130388. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130389. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  130390. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  130391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130395. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130398. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130399. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130401. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130402. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130403. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130404. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130405. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130406. 10,
  130407. };
  130408. static float _vq_quantthresh__44c8_s_p9_0[] = {
  130409. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  130410. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  130411. };
  130412. static long _vq_quantmap__44c8_s_p9_0[] = {
  130413. 15, 13, 11, 9, 7, 5, 3, 1,
  130414. 0, 2, 4, 6, 8, 10, 12, 14,
  130415. 16,
  130416. };
  130417. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  130418. _vq_quantthresh__44c8_s_p9_0,
  130419. _vq_quantmap__44c8_s_p9_0,
  130420. 17,
  130421. 17
  130422. };
  130423. static static_codebook _44c8_s_p9_0 = {
  130424. 2, 289,
  130425. _vq_lengthlist__44c8_s_p9_0,
  130426. 1, -509798400, 1631393792, 5, 0,
  130427. _vq_quantlist__44c8_s_p9_0,
  130428. NULL,
  130429. &_vq_auxt__44c8_s_p9_0,
  130430. NULL,
  130431. 0
  130432. };
  130433. static long _vq_quantlist__44c8_s_p9_1[] = {
  130434. 9,
  130435. 8,
  130436. 10,
  130437. 7,
  130438. 11,
  130439. 6,
  130440. 12,
  130441. 5,
  130442. 13,
  130443. 4,
  130444. 14,
  130445. 3,
  130446. 15,
  130447. 2,
  130448. 16,
  130449. 1,
  130450. 17,
  130451. 0,
  130452. 18,
  130453. };
  130454. static long _vq_lengthlist__44c8_s_p9_1[] = {
  130455. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  130456. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  130457. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  130458. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  130459. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  130460. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  130461. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  130462. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  130463. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  130464. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  130465. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  130466. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  130467. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  130468. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  130469. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  130470. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  130471. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  130472. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  130473. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  130474. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  130475. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  130476. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  130477. 14,13,13,14,14,15,14,15,14,
  130478. };
  130479. static float _vq_quantthresh__44c8_s_p9_1[] = {
  130480. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  130481. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  130482. 367.5, 416.5,
  130483. };
  130484. static long _vq_quantmap__44c8_s_p9_1[] = {
  130485. 17, 15, 13, 11, 9, 7, 5, 3,
  130486. 1, 0, 2, 4, 6, 8, 10, 12,
  130487. 14, 16, 18,
  130488. };
  130489. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  130490. _vq_quantthresh__44c8_s_p9_1,
  130491. _vq_quantmap__44c8_s_p9_1,
  130492. 19,
  130493. 19
  130494. };
  130495. static static_codebook _44c8_s_p9_1 = {
  130496. 2, 361,
  130497. _vq_lengthlist__44c8_s_p9_1,
  130498. 1, -518287360, 1622704128, 5, 0,
  130499. _vq_quantlist__44c8_s_p9_1,
  130500. NULL,
  130501. &_vq_auxt__44c8_s_p9_1,
  130502. NULL,
  130503. 0
  130504. };
  130505. static long _vq_quantlist__44c8_s_p9_2[] = {
  130506. 24,
  130507. 23,
  130508. 25,
  130509. 22,
  130510. 26,
  130511. 21,
  130512. 27,
  130513. 20,
  130514. 28,
  130515. 19,
  130516. 29,
  130517. 18,
  130518. 30,
  130519. 17,
  130520. 31,
  130521. 16,
  130522. 32,
  130523. 15,
  130524. 33,
  130525. 14,
  130526. 34,
  130527. 13,
  130528. 35,
  130529. 12,
  130530. 36,
  130531. 11,
  130532. 37,
  130533. 10,
  130534. 38,
  130535. 9,
  130536. 39,
  130537. 8,
  130538. 40,
  130539. 7,
  130540. 41,
  130541. 6,
  130542. 42,
  130543. 5,
  130544. 43,
  130545. 4,
  130546. 44,
  130547. 3,
  130548. 45,
  130549. 2,
  130550. 46,
  130551. 1,
  130552. 47,
  130553. 0,
  130554. 48,
  130555. };
  130556. static long _vq_lengthlist__44c8_s_p9_2[] = {
  130557. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  130558. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130559. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130560. 7,
  130561. };
  130562. static float _vq_quantthresh__44c8_s_p9_2[] = {
  130563. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130564. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130565. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130566. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130567. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130568. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130569. };
  130570. static long _vq_quantmap__44c8_s_p9_2[] = {
  130571. 47, 45, 43, 41, 39, 37, 35, 33,
  130572. 31, 29, 27, 25, 23, 21, 19, 17,
  130573. 15, 13, 11, 9, 7, 5, 3, 1,
  130574. 0, 2, 4, 6, 8, 10, 12, 14,
  130575. 16, 18, 20, 22, 24, 26, 28, 30,
  130576. 32, 34, 36, 38, 40, 42, 44, 46,
  130577. 48,
  130578. };
  130579. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  130580. _vq_quantthresh__44c8_s_p9_2,
  130581. _vq_quantmap__44c8_s_p9_2,
  130582. 49,
  130583. 49
  130584. };
  130585. static static_codebook _44c8_s_p9_2 = {
  130586. 1, 49,
  130587. _vq_lengthlist__44c8_s_p9_2,
  130588. 1, -526909440, 1611661312, 6, 0,
  130589. _vq_quantlist__44c8_s_p9_2,
  130590. NULL,
  130591. &_vq_auxt__44c8_s_p9_2,
  130592. NULL,
  130593. 0
  130594. };
  130595. static long _huff_lengthlist__44c8_s_short[] = {
  130596. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  130597. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  130598. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  130599. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  130600. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  130601. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  130602. 10, 9,11,14,
  130603. };
  130604. static static_codebook _huff_book__44c8_s_short = {
  130605. 2, 100,
  130606. _huff_lengthlist__44c8_s_short,
  130607. 0, 0, 0, 0, 0,
  130608. NULL,
  130609. NULL,
  130610. NULL,
  130611. NULL,
  130612. 0
  130613. };
  130614. static long _huff_lengthlist__44c9_s_long[] = {
  130615. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  130616. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  130617. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  130618. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  130619. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  130620. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  130621. 10, 9, 8, 9,
  130622. };
  130623. static static_codebook _huff_book__44c9_s_long = {
  130624. 2, 100,
  130625. _huff_lengthlist__44c9_s_long,
  130626. 0, 0, 0, 0, 0,
  130627. NULL,
  130628. NULL,
  130629. NULL,
  130630. NULL,
  130631. 0
  130632. };
  130633. static long _vq_quantlist__44c9_s_p1_0[] = {
  130634. 1,
  130635. 0,
  130636. 2,
  130637. };
  130638. static long _vq_lengthlist__44c9_s_p1_0[] = {
  130639. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  130640. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  130642. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130643. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  130644. 7,
  130645. };
  130646. static float _vq_quantthresh__44c9_s_p1_0[] = {
  130647. -0.5, 0.5,
  130648. };
  130649. static long _vq_quantmap__44c9_s_p1_0[] = {
  130650. 1, 0, 2,
  130651. };
  130652. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  130653. _vq_quantthresh__44c9_s_p1_0,
  130654. _vq_quantmap__44c9_s_p1_0,
  130655. 3,
  130656. 3
  130657. };
  130658. static static_codebook _44c9_s_p1_0 = {
  130659. 4, 81,
  130660. _vq_lengthlist__44c9_s_p1_0,
  130661. 1, -535822336, 1611661312, 2, 0,
  130662. _vq_quantlist__44c9_s_p1_0,
  130663. NULL,
  130664. &_vq_auxt__44c9_s_p1_0,
  130665. NULL,
  130666. 0
  130667. };
  130668. static long _vq_quantlist__44c9_s_p2_0[] = {
  130669. 2,
  130670. 1,
  130671. 3,
  130672. 0,
  130673. 4,
  130674. };
  130675. static long _vq_lengthlist__44c9_s_p2_0[] = {
  130676. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130677. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  130678. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  130679. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  130680. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  130681. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  130682. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  130683. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  130686. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  130687. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  130688. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  130689. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  130690. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  130691. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  130694. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  130695. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  130696. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  130697. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  130698. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  130699. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  130702. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  130703. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  130704. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  130705. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  130706. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  130707. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130712. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  130713. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  130714. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  130715. 12,
  130716. };
  130717. static float _vq_quantthresh__44c9_s_p2_0[] = {
  130718. -1.5, -0.5, 0.5, 1.5,
  130719. };
  130720. static long _vq_quantmap__44c9_s_p2_0[] = {
  130721. 3, 1, 0, 2, 4,
  130722. };
  130723. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  130724. _vq_quantthresh__44c9_s_p2_0,
  130725. _vq_quantmap__44c9_s_p2_0,
  130726. 5,
  130727. 5
  130728. };
  130729. static static_codebook _44c9_s_p2_0 = {
  130730. 4, 625,
  130731. _vq_lengthlist__44c9_s_p2_0,
  130732. 1, -533725184, 1611661312, 3, 0,
  130733. _vq_quantlist__44c9_s_p2_0,
  130734. NULL,
  130735. &_vq_auxt__44c9_s_p2_0,
  130736. NULL,
  130737. 0
  130738. };
  130739. static long _vq_quantlist__44c9_s_p3_0[] = {
  130740. 4,
  130741. 3,
  130742. 5,
  130743. 2,
  130744. 6,
  130745. 1,
  130746. 7,
  130747. 0,
  130748. 8,
  130749. };
  130750. static long _vq_lengthlist__44c9_s_p3_0[] = {
  130751. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  130752. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  130753. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  130754. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0,
  130757. };
  130758. static float _vq_quantthresh__44c9_s_p3_0[] = {
  130759. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130760. };
  130761. static long _vq_quantmap__44c9_s_p3_0[] = {
  130762. 7, 5, 3, 1, 0, 2, 4, 6,
  130763. 8,
  130764. };
  130765. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  130766. _vq_quantthresh__44c9_s_p3_0,
  130767. _vq_quantmap__44c9_s_p3_0,
  130768. 9,
  130769. 9
  130770. };
  130771. static static_codebook _44c9_s_p3_0 = {
  130772. 2, 81,
  130773. _vq_lengthlist__44c9_s_p3_0,
  130774. 1, -531628032, 1611661312, 4, 0,
  130775. _vq_quantlist__44c9_s_p3_0,
  130776. NULL,
  130777. &_vq_auxt__44c9_s_p3_0,
  130778. NULL,
  130779. 0
  130780. };
  130781. static long _vq_quantlist__44c9_s_p4_0[] = {
  130782. 8,
  130783. 7,
  130784. 9,
  130785. 6,
  130786. 10,
  130787. 5,
  130788. 11,
  130789. 4,
  130790. 12,
  130791. 3,
  130792. 13,
  130793. 2,
  130794. 14,
  130795. 1,
  130796. 15,
  130797. 0,
  130798. 16,
  130799. };
  130800. static long _vq_lengthlist__44c9_s_p4_0[] = {
  130801. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  130802. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  130803. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  130804. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  130805. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  130806. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  130807. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  130808. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130809. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130810. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0,
  130820. };
  130821. static float _vq_quantthresh__44c9_s_p4_0[] = {
  130822. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130823. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130824. };
  130825. static long _vq_quantmap__44c9_s_p4_0[] = {
  130826. 15, 13, 11, 9, 7, 5, 3, 1,
  130827. 0, 2, 4, 6, 8, 10, 12, 14,
  130828. 16,
  130829. };
  130830. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  130831. _vq_quantthresh__44c9_s_p4_0,
  130832. _vq_quantmap__44c9_s_p4_0,
  130833. 17,
  130834. 17
  130835. };
  130836. static static_codebook _44c9_s_p4_0 = {
  130837. 2, 289,
  130838. _vq_lengthlist__44c9_s_p4_0,
  130839. 1, -529530880, 1611661312, 5, 0,
  130840. _vq_quantlist__44c9_s_p4_0,
  130841. NULL,
  130842. &_vq_auxt__44c9_s_p4_0,
  130843. NULL,
  130844. 0
  130845. };
  130846. static long _vq_quantlist__44c9_s_p5_0[] = {
  130847. 1,
  130848. 0,
  130849. 2,
  130850. };
  130851. static long _vq_lengthlist__44c9_s_p5_0[] = {
  130852. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  130853. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  130854. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  130855. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  130856. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  130857. 12,
  130858. };
  130859. static float _vq_quantthresh__44c9_s_p5_0[] = {
  130860. -5.5, 5.5,
  130861. };
  130862. static long _vq_quantmap__44c9_s_p5_0[] = {
  130863. 1, 0, 2,
  130864. };
  130865. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  130866. _vq_quantthresh__44c9_s_p5_0,
  130867. _vq_quantmap__44c9_s_p5_0,
  130868. 3,
  130869. 3
  130870. };
  130871. static static_codebook _44c9_s_p5_0 = {
  130872. 4, 81,
  130873. _vq_lengthlist__44c9_s_p5_0,
  130874. 1, -529137664, 1618345984, 2, 0,
  130875. _vq_quantlist__44c9_s_p5_0,
  130876. NULL,
  130877. &_vq_auxt__44c9_s_p5_0,
  130878. NULL,
  130879. 0
  130880. };
  130881. static long _vq_quantlist__44c9_s_p5_1[] = {
  130882. 5,
  130883. 4,
  130884. 6,
  130885. 3,
  130886. 7,
  130887. 2,
  130888. 8,
  130889. 1,
  130890. 9,
  130891. 0,
  130892. 10,
  130893. };
  130894. static long _vq_lengthlist__44c9_s_p5_1[] = {
  130895. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  130896. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  130897. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  130898. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  130899. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  130900. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  130901. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  130902. 11,11,11, 7, 7, 7, 7, 7, 7,
  130903. };
  130904. static float _vq_quantthresh__44c9_s_p5_1[] = {
  130905. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130906. 3.5, 4.5,
  130907. };
  130908. static long _vq_quantmap__44c9_s_p5_1[] = {
  130909. 9, 7, 5, 3, 1, 0, 2, 4,
  130910. 6, 8, 10,
  130911. };
  130912. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  130913. _vq_quantthresh__44c9_s_p5_1,
  130914. _vq_quantmap__44c9_s_p5_1,
  130915. 11,
  130916. 11
  130917. };
  130918. static static_codebook _44c9_s_p5_1 = {
  130919. 2, 121,
  130920. _vq_lengthlist__44c9_s_p5_1,
  130921. 1, -531365888, 1611661312, 4, 0,
  130922. _vq_quantlist__44c9_s_p5_1,
  130923. NULL,
  130924. &_vq_auxt__44c9_s_p5_1,
  130925. NULL,
  130926. 0
  130927. };
  130928. static long _vq_quantlist__44c9_s_p6_0[] = {
  130929. 6,
  130930. 5,
  130931. 7,
  130932. 4,
  130933. 8,
  130934. 3,
  130935. 9,
  130936. 2,
  130937. 10,
  130938. 1,
  130939. 11,
  130940. 0,
  130941. 12,
  130942. };
  130943. static long _vq_lengthlist__44c9_s_p6_0[] = {
  130944. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  130945. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  130946. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  130947. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130948. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  130949. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. };
  130956. static float _vq_quantthresh__44c9_s_p6_0[] = {
  130957. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130958. 12.5, 17.5, 22.5, 27.5,
  130959. };
  130960. static long _vq_quantmap__44c9_s_p6_0[] = {
  130961. 11, 9, 7, 5, 3, 1, 0, 2,
  130962. 4, 6, 8, 10, 12,
  130963. };
  130964. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  130965. _vq_quantthresh__44c9_s_p6_0,
  130966. _vq_quantmap__44c9_s_p6_0,
  130967. 13,
  130968. 13
  130969. };
  130970. static static_codebook _44c9_s_p6_0 = {
  130971. 2, 169,
  130972. _vq_lengthlist__44c9_s_p6_0,
  130973. 1, -526516224, 1616117760, 4, 0,
  130974. _vq_quantlist__44c9_s_p6_0,
  130975. NULL,
  130976. &_vq_auxt__44c9_s_p6_0,
  130977. NULL,
  130978. 0
  130979. };
  130980. static long _vq_quantlist__44c9_s_p6_1[] = {
  130981. 2,
  130982. 1,
  130983. 3,
  130984. 0,
  130985. 4,
  130986. };
  130987. static long _vq_lengthlist__44c9_s_p6_1[] = {
  130988. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  130989. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  130990. };
  130991. static float _vq_quantthresh__44c9_s_p6_1[] = {
  130992. -1.5, -0.5, 0.5, 1.5,
  130993. };
  130994. static long _vq_quantmap__44c9_s_p6_1[] = {
  130995. 3, 1, 0, 2, 4,
  130996. };
  130997. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  130998. _vq_quantthresh__44c9_s_p6_1,
  130999. _vq_quantmap__44c9_s_p6_1,
  131000. 5,
  131001. 5
  131002. };
  131003. static static_codebook _44c9_s_p6_1 = {
  131004. 2, 25,
  131005. _vq_lengthlist__44c9_s_p6_1,
  131006. 1, -533725184, 1611661312, 3, 0,
  131007. _vq_quantlist__44c9_s_p6_1,
  131008. NULL,
  131009. &_vq_auxt__44c9_s_p6_1,
  131010. NULL,
  131011. 0
  131012. };
  131013. static long _vq_quantlist__44c9_s_p7_0[] = {
  131014. 6,
  131015. 5,
  131016. 7,
  131017. 4,
  131018. 8,
  131019. 3,
  131020. 9,
  131021. 2,
  131022. 10,
  131023. 1,
  131024. 11,
  131025. 0,
  131026. 12,
  131027. };
  131028. static long _vq_lengthlist__44c9_s_p7_0[] = {
  131029. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  131030. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  131031. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  131032. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  131033. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  131034. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  131035. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  131036. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  131037. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  131038. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  131039. 19,12,12,12,12,13,13,14,14,
  131040. };
  131041. static float _vq_quantthresh__44c9_s_p7_0[] = {
  131042. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131043. 27.5, 38.5, 49.5, 60.5,
  131044. };
  131045. static long _vq_quantmap__44c9_s_p7_0[] = {
  131046. 11, 9, 7, 5, 3, 1, 0, 2,
  131047. 4, 6, 8, 10, 12,
  131048. };
  131049. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  131050. _vq_quantthresh__44c9_s_p7_0,
  131051. _vq_quantmap__44c9_s_p7_0,
  131052. 13,
  131053. 13
  131054. };
  131055. static static_codebook _44c9_s_p7_0 = {
  131056. 2, 169,
  131057. _vq_lengthlist__44c9_s_p7_0,
  131058. 1, -523206656, 1618345984, 4, 0,
  131059. _vq_quantlist__44c9_s_p7_0,
  131060. NULL,
  131061. &_vq_auxt__44c9_s_p7_0,
  131062. NULL,
  131063. 0
  131064. };
  131065. static long _vq_quantlist__44c9_s_p7_1[] = {
  131066. 5,
  131067. 4,
  131068. 6,
  131069. 3,
  131070. 7,
  131071. 2,
  131072. 8,
  131073. 1,
  131074. 9,
  131075. 0,
  131076. 10,
  131077. };
  131078. static long _vq_lengthlist__44c9_s_p7_1[] = {
  131079. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  131080. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131081. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  131082. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131083. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  131084. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  131085. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  131086. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131087. };
  131088. static float _vq_quantthresh__44c9_s_p7_1[] = {
  131089. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131090. 3.5, 4.5,
  131091. };
  131092. static long _vq_quantmap__44c9_s_p7_1[] = {
  131093. 9, 7, 5, 3, 1, 0, 2, 4,
  131094. 6, 8, 10,
  131095. };
  131096. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  131097. _vq_quantthresh__44c9_s_p7_1,
  131098. _vq_quantmap__44c9_s_p7_1,
  131099. 11,
  131100. 11
  131101. };
  131102. static static_codebook _44c9_s_p7_1 = {
  131103. 2, 121,
  131104. _vq_lengthlist__44c9_s_p7_1,
  131105. 1, -531365888, 1611661312, 4, 0,
  131106. _vq_quantlist__44c9_s_p7_1,
  131107. NULL,
  131108. &_vq_auxt__44c9_s_p7_1,
  131109. NULL,
  131110. 0
  131111. };
  131112. static long _vq_quantlist__44c9_s_p8_0[] = {
  131113. 7,
  131114. 6,
  131115. 8,
  131116. 5,
  131117. 9,
  131118. 4,
  131119. 10,
  131120. 3,
  131121. 11,
  131122. 2,
  131123. 12,
  131124. 1,
  131125. 13,
  131126. 0,
  131127. 14,
  131128. };
  131129. static long _vq_lengthlist__44c9_s_p8_0[] = {
  131130. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  131131. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  131132. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  131133. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  131134. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  131135. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  131136. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  131137. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  131138. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  131139. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  131140. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  131141. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  131142. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  131143. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  131144. 14,
  131145. };
  131146. static float _vq_quantthresh__44c9_s_p8_0[] = {
  131147. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131148. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131149. };
  131150. static long _vq_quantmap__44c9_s_p8_0[] = {
  131151. 13, 11, 9, 7, 5, 3, 1, 0,
  131152. 2, 4, 6, 8, 10, 12, 14,
  131153. };
  131154. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  131155. _vq_quantthresh__44c9_s_p8_0,
  131156. _vq_quantmap__44c9_s_p8_0,
  131157. 15,
  131158. 15
  131159. };
  131160. static static_codebook _44c9_s_p8_0 = {
  131161. 2, 225,
  131162. _vq_lengthlist__44c9_s_p8_0,
  131163. 1, -520986624, 1620377600, 4, 0,
  131164. _vq_quantlist__44c9_s_p8_0,
  131165. NULL,
  131166. &_vq_auxt__44c9_s_p8_0,
  131167. NULL,
  131168. 0
  131169. };
  131170. static long _vq_quantlist__44c9_s_p8_1[] = {
  131171. 10,
  131172. 9,
  131173. 11,
  131174. 8,
  131175. 12,
  131176. 7,
  131177. 13,
  131178. 6,
  131179. 14,
  131180. 5,
  131181. 15,
  131182. 4,
  131183. 16,
  131184. 3,
  131185. 17,
  131186. 2,
  131187. 18,
  131188. 1,
  131189. 19,
  131190. 0,
  131191. 20,
  131192. };
  131193. static long _vq_lengthlist__44c9_s_p8_1[] = {
  131194. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131195. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131196. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131197. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131198. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131199. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131200. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  131201. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131202. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131203. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131204. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131205. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131206. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131207. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131208. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131209. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  131210. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  131211. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  131212. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  131213. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131214. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131215. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  131216. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131217. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131218. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  131219. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  131220. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  131221. 9, 9, 9,10, 9, 9, 9, 9, 9,
  131222. };
  131223. static float _vq_quantthresh__44c9_s_p8_1[] = {
  131224. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131225. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131226. 6.5, 7.5, 8.5, 9.5,
  131227. };
  131228. static long _vq_quantmap__44c9_s_p8_1[] = {
  131229. 19, 17, 15, 13, 11, 9, 7, 5,
  131230. 3, 1, 0, 2, 4, 6, 8, 10,
  131231. 12, 14, 16, 18, 20,
  131232. };
  131233. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  131234. _vq_quantthresh__44c9_s_p8_1,
  131235. _vq_quantmap__44c9_s_p8_1,
  131236. 21,
  131237. 21
  131238. };
  131239. static static_codebook _44c9_s_p8_1 = {
  131240. 2, 441,
  131241. _vq_lengthlist__44c9_s_p8_1,
  131242. 1, -529268736, 1611661312, 5, 0,
  131243. _vq_quantlist__44c9_s_p8_1,
  131244. NULL,
  131245. &_vq_auxt__44c9_s_p8_1,
  131246. NULL,
  131247. 0
  131248. };
  131249. static long _vq_quantlist__44c9_s_p9_0[] = {
  131250. 9,
  131251. 8,
  131252. 10,
  131253. 7,
  131254. 11,
  131255. 6,
  131256. 12,
  131257. 5,
  131258. 13,
  131259. 4,
  131260. 14,
  131261. 3,
  131262. 15,
  131263. 2,
  131264. 16,
  131265. 1,
  131266. 17,
  131267. 0,
  131268. 18,
  131269. };
  131270. static long _vq_lengthlist__44c9_s_p9_0[] = {
  131271. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131272. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  131273. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  131274. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  131275. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131276. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131277. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131278. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131279. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131280. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131281. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131282. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131283. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131284. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131285. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131286. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131287. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  131288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131293. 11,11,11,11,11,11,11,11,11,
  131294. };
  131295. static float _vq_quantthresh__44c9_s_p9_0[] = {
  131296. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  131297. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  131298. 6982.5, 7913.5,
  131299. };
  131300. static long _vq_quantmap__44c9_s_p9_0[] = {
  131301. 17, 15, 13, 11, 9, 7, 5, 3,
  131302. 1, 0, 2, 4, 6, 8, 10, 12,
  131303. 14, 16, 18,
  131304. };
  131305. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  131306. _vq_quantthresh__44c9_s_p9_0,
  131307. _vq_quantmap__44c9_s_p9_0,
  131308. 19,
  131309. 19
  131310. };
  131311. static static_codebook _44c9_s_p9_0 = {
  131312. 2, 361,
  131313. _vq_lengthlist__44c9_s_p9_0,
  131314. 1, -508535424, 1631393792, 5, 0,
  131315. _vq_quantlist__44c9_s_p9_0,
  131316. NULL,
  131317. &_vq_auxt__44c9_s_p9_0,
  131318. NULL,
  131319. 0
  131320. };
  131321. static long _vq_quantlist__44c9_s_p9_1[] = {
  131322. 9,
  131323. 8,
  131324. 10,
  131325. 7,
  131326. 11,
  131327. 6,
  131328. 12,
  131329. 5,
  131330. 13,
  131331. 4,
  131332. 14,
  131333. 3,
  131334. 15,
  131335. 2,
  131336. 16,
  131337. 1,
  131338. 17,
  131339. 0,
  131340. 18,
  131341. };
  131342. static long _vq_lengthlist__44c9_s_p9_1[] = {
  131343. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  131344. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  131345. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  131346. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  131347. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  131348. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  131349. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  131350. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  131351. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  131352. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  131353. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  131354. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  131355. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  131356. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  131357. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  131358. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  131359. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  131360. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  131361. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  131362. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  131363. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  131364. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  131365. 13,13,13,14,13,14,15,15,15,
  131366. };
  131367. static float _vq_quantthresh__44c9_s_p9_1[] = {
  131368. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131369. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131370. 367.5, 416.5,
  131371. };
  131372. static long _vq_quantmap__44c9_s_p9_1[] = {
  131373. 17, 15, 13, 11, 9, 7, 5, 3,
  131374. 1, 0, 2, 4, 6, 8, 10, 12,
  131375. 14, 16, 18,
  131376. };
  131377. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  131378. _vq_quantthresh__44c9_s_p9_1,
  131379. _vq_quantmap__44c9_s_p9_1,
  131380. 19,
  131381. 19
  131382. };
  131383. static static_codebook _44c9_s_p9_1 = {
  131384. 2, 361,
  131385. _vq_lengthlist__44c9_s_p9_1,
  131386. 1, -518287360, 1622704128, 5, 0,
  131387. _vq_quantlist__44c9_s_p9_1,
  131388. NULL,
  131389. &_vq_auxt__44c9_s_p9_1,
  131390. NULL,
  131391. 0
  131392. };
  131393. static long _vq_quantlist__44c9_s_p9_2[] = {
  131394. 24,
  131395. 23,
  131396. 25,
  131397. 22,
  131398. 26,
  131399. 21,
  131400. 27,
  131401. 20,
  131402. 28,
  131403. 19,
  131404. 29,
  131405. 18,
  131406. 30,
  131407. 17,
  131408. 31,
  131409. 16,
  131410. 32,
  131411. 15,
  131412. 33,
  131413. 14,
  131414. 34,
  131415. 13,
  131416. 35,
  131417. 12,
  131418. 36,
  131419. 11,
  131420. 37,
  131421. 10,
  131422. 38,
  131423. 9,
  131424. 39,
  131425. 8,
  131426. 40,
  131427. 7,
  131428. 41,
  131429. 6,
  131430. 42,
  131431. 5,
  131432. 43,
  131433. 4,
  131434. 44,
  131435. 3,
  131436. 45,
  131437. 2,
  131438. 46,
  131439. 1,
  131440. 47,
  131441. 0,
  131442. 48,
  131443. };
  131444. static long _vq_lengthlist__44c9_s_p9_2[] = {
  131445. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131446. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131447. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131448. 7,
  131449. };
  131450. static float _vq_quantthresh__44c9_s_p9_2[] = {
  131451. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131452. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131453. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131454. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131455. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131456. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131457. };
  131458. static long _vq_quantmap__44c9_s_p9_2[] = {
  131459. 47, 45, 43, 41, 39, 37, 35, 33,
  131460. 31, 29, 27, 25, 23, 21, 19, 17,
  131461. 15, 13, 11, 9, 7, 5, 3, 1,
  131462. 0, 2, 4, 6, 8, 10, 12, 14,
  131463. 16, 18, 20, 22, 24, 26, 28, 30,
  131464. 32, 34, 36, 38, 40, 42, 44, 46,
  131465. 48,
  131466. };
  131467. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  131468. _vq_quantthresh__44c9_s_p9_2,
  131469. _vq_quantmap__44c9_s_p9_2,
  131470. 49,
  131471. 49
  131472. };
  131473. static static_codebook _44c9_s_p9_2 = {
  131474. 1, 49,
  131475. _vq_lengthlist__44c9_s_p9_2,
  131476. 1, -526909440, 1611661312, 6, 0,
  131477. _vq_quantlist__44c9_s_p9_2,
  131478. NULL,
  131479. &_vq_auxt__44c9_s_p9_2,
  131480. NULL,
  131481. 0
  131482. };
  131483. static long _huff_lengthlist__44c9_s_short[] = {
  131484. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  131485. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  131486. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  131487. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  131488. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  131489. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  131490. 9, 8,10,13,
  131491. };
  131492. static static_codebook _huff_book__44c9_s_short = {
  131493. 2, 100,
  131494. _huff_lengthlist__44c9_s_short,
  131495. 0, 0, 0, 0, 0,
  131496. NULL,
  131497. NULL,
  131498. NULL,
  131499. NULL,
  131500. 0
  131501. };
  131502. static long _huff_lengthlist__44c0_s_long[] = {
  131503. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  131504. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  131505. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  131506. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  131507. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  131508. 12,
  131509. };
  131510. static static_codebook _huff_book__44c0_s_long = {
  131511. 2, 81,
  131512. _huff_lengthlist__44c0_s_long,
  131513. 0, 0, 0, 0, 0,
  131514. NULL,
  131515. NULL,
  131516. NULL,
  131517. NULL,
  131518. 0
  131519. };
  131520. static long _vq_quantlist__44c0_s_p1_0[] = {
  131521. 1,
  131522. 0,
  131523. 2,
  131524. };
  131525. static long _vq_lengthlist__44c0_s_p1_0[] = {
  131526. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131527. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131532. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131537. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131572. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131577. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131582. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131618. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131623. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  131628. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0,
  131937. };
  131938. static float _vq_quantthresh__44c0_s_p1_0[] = {
  131939. -0.5, 0.5,
  131940. };
  131941. static long _vq_quantmap__44c0_s_p1_0[] = {
  131942. 1, 0, 2,
  131943. };
  131944. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  131945. _vq_quantthresh__44c0_s_p1_0,
  131946. _vq_quantmap__44c0_s_p1_0,
  131947. 3,
  131948. 3
  131949. };
  131950. static static_codebook _44c0_s_p1_0 = {
  131951. 8, 6561,
  131952. _vq_lengthlist__44c0_s_p1_0,
  131953. 1, -535822336, 1611661312, 2, 0,
  131954. _vq_quantlist__44c0_s_p1_0,
  131955. NULL,
  131956. &_vq_auxt__44c0_s_p1_0,
  131957. NULL,
  131958. 0
  131959. };
  131960. static long _vq_quantlist__44c0_s_p2_0[] = {
  131961. 2,
  131962. 1,
  131963. 3,
  131964. 0,
  131965. 4,
  131966. };
  131967. static long _vq_lengthlist__44c0_s_p2_0[] = {
  131968. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0,
  132008. };
  132009. static float _vq_quantthresh__44c0_s_p2_0[] = {
  132010. -1.5, -0.5, 0.5, 1.5,
  132011. };
  132012. static long _vq_quantmap__44c0_s_p2_0[] = {
  132013. 3, 1, 0, 2, 4,
  132014. };
  132015. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  132016. _vq_quantthresh__44c0_s_p2_0,
  132017. _vq_quantmap__44c0_s_p2_0,
  132018. 5,
  132019. 5
  132020. };
  132021. static static_codebook _44c0_s_p2_0 = {
  132022. 4, 625,
  132023. _vq_lengthlist__44c0_s_p2_0,
  132024. 1, -533725184, 1611661312, 3, 0,
  132025. _vq_quantlist__44c0_s_p2_0,
  132026. NULL,
  132027. &_vq_auxt__44c0_s_p2_0,
  132028. NULL,
  132029. 0
  132030. };
  132031. static long _vq_quantlist__44c0_s_p3_0[] = {
  132032. 4,
  132033. 3,
  132034. 5,
  132035. 2,
  132036. 6,
  132037. 1,
  132038. 7,
  132039. 0,
  132040. 8,
  132041. };
  132042. static long _vq_lengthlist__44c0_s_p3_0[] = {
  132043. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  132044. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132045. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132046. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132047. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0,
  132049. };
  132050. static float _vq_quantthresh__44c0_s_p3_0[] = {
  132051. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132052. };
  132053. static long _vq_quantmap__44c0_s_p3_0[] = {
  132054. 7, 5, 3, 1, 0, 2, 4, 6,
  132055. 8,
  132056. };
  132057. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  132058. _vq_quantthresh__44c0_s_p3_0,
  132059. _vq_quantmap__44c0_s_p3_0,
  132060. 9,
  132061. 9
  132062. };
  132063. static static_codebook _44c0_s_p3_0 = {
  132064. 2, 81,
  132065. _vq_lengthlist__44c0_s_p3_0,
  132066. 1, -531628032, 1611661312, 4, 0,
  132067. _vq_quantlist__44c0_s_p3_0,
  132068. NULL,
  132069. &_vq_auxt__44c0_s_p3_0,
  132070. NULL,
  132071. 0
  132072. };
  132073. static long _vq_quantlist__44c0_s_p4_0[] = {
  132074. 4,
  132075. 3,
  132076. 5,
  132077. 2,
  132078. 6,
  132079. 1,
  132080. 7,
  132081. 0,
  132082. 8,
  132083. };
  132084. static long _vq_lengthlist__44c0_s_p4_0[] = {
  132085. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132086. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132087. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  132088. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  132089. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132090. 10,
  132091. };
  132092. static float _vq_quantthresh__44c0_s_p4_0[] = {
  132093. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132094. };
  132095. static long _vq_quantmap__44c0_s_p4_0[] = {
  132096. 7, 5, 3, 1, 0, 2, 4, 6,
  132097. 8,
  132098. };
  132099. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  132100. _vq_quantthresh__44c0_s_p4_0,
  132101. _vq_quantmap__44c0_s_p4_0,
  132102. 9,
  132103. 9
  132104. };
  132105. static static_codebook _44c0_s_p4_0 = {
  132106. 2, 81,
  132107. _vq_lengthlist__44c0_s_p4_0,
  132108. 1, -531628032, 1611661312, 4, 0,
  132109. _vq_quantlist__44c0_s_p4_0,
  132110. NULL,
  132111. &_vq_auxt__44c0_s_p4_0,
  132112. NULL,
  132113. 0
  132114. };
  132115. static long _vq_quantlist__44c0_s_p5_0[] = {
  132116. 8,
  132117. 7,
  132118. 9,
  132119. 6,
  132120. 10,
  132121. 5,
  132122. 11,
  132123. 4,
  132124. 12,
  132125. 3,
  132126. 13,
  132127. 2,
  132128. 14,
  132129. 1,
  132130. 15,
  132131. 0,
  132132. 16,
  132133. };
  132134. static long _vq_lengthlist__44c0_s_p5_0[] = {
  132135. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132136. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  132137. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132138. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132139. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132140. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  132141. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  132142. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132143. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132144. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  132145. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132146. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132147. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132148. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132149. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  132150. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  132151. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  132152. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132153. 14,
  132154. };
  132155. static float _vq_quantthresh__44c0_s_p5_0[] = {
  132156. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132157. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132158. };
  132159. static long _vq_quantmap__44c0_s_p5_0[] = {
  132160. 15, 13, 11, 9, 7, 5, 3, 1,
  132161. 0, 2, 4, 6, 8, 10, 12, 14,
  132162. 16,
  132163. };
  132164. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  132165. _vq_quantthresh__44c0_s_p5_0,
  132166. _vq_quantmap__44c0_s_p5_0,
  132167. 17,
  132168. 17
  132169. };
  132170. static static_codebook _44c0_s_p5_0 = {
  132171. 2, 289,
  132172. _vq_lengthlist__44c0_s_p5_0,
  132173. 1, -529530880, 1611661312, 5, 0,
  132174. _vq_quantlist__44c0_s_p5_0,
  132175. NULL,
  132176. &_vq_auxt__44c0_s_p5_0,
  132177. NULL,
  132178. 0
  132179. };
  132180. static long _vq_quantlist__44c0_s_p6_0[] = {
  132181. 1,
  132182. 0,
  132183. 2,
  132184. };
  132185. static long _vq_lengthlist__44c0_s_p6_0[] = {
  132186. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  132187. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132188. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  132189. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  132190. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132191. 10,
  132192. };
  132193. static float _vq_quantthresh__44c0_s_p6_0[] = {
  132194. -5.5, 5.5,
  132195. };
  132196. static long _vq_quantmap__44c0_s_p6_0[] = {
  132197. 1, 0, 2,
  132198. };
  132199. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  132200. _vq_quantthresh__44c0_s_p6_0,
  132201. _vq_quantmap__44c0_s_p6_0,
  132202. 3,
  132203. 3
  132204. };
  132205. static static_codebook _44c0_s_p6_0 = {
  132206. 4, 81,
  132207. _vq_lengthlist__44c0_s_p6_0,
  132208. 1, -529137664, 1618345984, 2, 0,
  132209. _vq_quantlist__44c0_s_p6_0,
  132210. NULL,
  132211. &_vq_auxt__44c0_s_p6_0,
  132212. NULL,
  132213. 0
  132214. };
  132215. static long _vq_quantlist__44c0_s_p6_1[] = {
  132216. 5,
  132217. 4,
  132218. 6,
  132219. 3,
  132220. 7,
  132221. 2,
  132222. 8,
  132223. 1,
  132224. 9,
  132225. 0,
  132226. 10,
  132227. };
  132228. static long _vq_lengthlist__44c0_s_p6_1[] = {
  132229. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  132230. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132231. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132232. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  132233. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132234. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132235. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132236. 10,10,10, 8, 8, 8, 8, 8, 8,
  132237. };
  132238. static float _vq_quantthresh__44c0_s_p6_1[] = {
  132239. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132240. 3.5, 4.5,
  132241. };
  132242. static long _vq_quantmap__44c0_s_p6_1[] = {
  132243. 9, 7, 5, 3, 1, 0, 2, 4,
  132244. 6, 8, 10,
  132245. };
  132246. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  132247. _vq_quantthresh__44c0_s_p6_1,
  132248. _vq_quantmap__44c0_s_p6_1,
  132249. 11,
  132250. 11
  132251. };
  132252. static static_codebook _44c0_s_p6_1 = {
  132253. 2, 121,
  132254. _vq_lengthlist__44c0_s_p6_1,
  132255. 1, -531365888, 1611661312, 4, 0,
  132256. _vq_quantlist__44c0_s_p6_1,
  132257. NULL,
  132258. &_vq_auxt__44c0_s_p6_1,
  132259. NULL,
  132260. 0
  132261. };
  132262. static long _vq_quantlist__44c0_s_p7_0[] = {
  132263. 6,
  132264. 5,
  132265. 7,
  132266. 4,
  132267. 8,
  132268. 3,
  132269. 9,
  132270. 2,
  132271. 10,
  132272. 1,
  132273. 11,
  132274. 0,
  132275. 12,
  132276. };
  132277. static long _vq_lengthlist__44c0_s_p7_0[] = {
  132278. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  132279. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  132280. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132281. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132282. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  132283. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  132284. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  132285. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132286. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132287. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  132288. 0,12,12,11,11,12,12,13,13,
  132289. };
  132290. static float _vq_quantthresh__44c0_s_p7_0[] = {
  132291. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132292. 12.5, 17.5, 22.5, 27.5,
  132293. };
  132294. static long _vq_quantmap__44c0_s_p7_0[] = {
  132295. 11, 9, 7, 5, 3, 1, 0, 2,
  132296. 4, 6, 8, 10, 12,
  132297. };
  132298. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  132299. _vq_quantthresh__44c0_s_p7_0,
  132300. _vq_quantmap__44c0_s_p7_0,
  132301. 13,
  132302. 13
  132303. };
  132304. static static_codebook _44c0_s_p7_0 = {
  132305. 2, 169,
  132306. _vq_lengthlist__44c0_s_p7_0,
  132307. 1, -526516224, 1616117760, 4, 0,
  132308. _vq_quantlist__44c0_s_p7_0,
  132309. NULL,
  132310. &_vq_auxt__44c0_s_p7_0,
  132311. NULL,
  132312. 0
  132313. };
  132314. static long _vq_quantlist__44c0_s_p7_1[] = {
  132315. 2,
  132316. 1,
  132317. 3,
  132318. 0,
  132319. 4,
  132320. };
  132321. static long _vq_lengthlist__44c0_s_p7_1[] = {
  132322. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132323. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132324. };
  132325. static float _vq_quantthresh__44c0_s_p7_1[] = {
  132326. -1.5, -0.5, 0.5, 1.5,
  132327. };
  132328. static long _vq_quantmap__44c0_s_p7_1[] = {
  132329. 3, 1, 0, 2, 4,
  132330. };
  132331. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  132332. _vq_quantthresh__44c0_s_p7_1,
  132333. _vq_quantmap__44c0_s_p7_1,
  132334. 5,
  132335. 5
  132336. };
  132337. static static_codebook _44c0_s_p7_1 = {
  132338. 2, 25,
  132339. _vq_lengthlist__44c0_s_p7_1,
  132340. 1, -533725184, 1611661312, 3, 0,
  132341. _vq_quantlist__44c0_s_p7_1,
  132342. NULL,
  132343. &_vq_auxt__44c0_s_p7_1,
  132344. NULL,
  132345. 0
  132346. };
  132347. static long _vq_quantlist__44c0_s_p8_0[] = {
  132348. 2,
  132349. 1,
  132350. 3,
  132351. 0,
  132352. 4,
  132353. };
  132354. static long _vq_lengthlist__44c0_s_p8_0[] = {
  132355. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  132356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132357. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132359. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132360. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132361. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132362. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  132363. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132364. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132365. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132366. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132367. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  132368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132370. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  132371. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132376. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132382. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132383. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132394. 11,
  132395. };
  132396. static float _vq_quantthresh__44c0_s_p8_0[] = {
  132397. -331.5, -110.5, 110.5, 331.5,
  132398. };
  132399. static long _vq_quantmap__44c0_s_p8_0[] = {
  132400. 3, 1, 0, 2, 4,
  132401. };
  132402. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  132403. _vq_quantthresh__44c0_s_p8_0,
  132404. _vq_quantmap__44c0_s_p8_0,
  132405. 5,
  132406. 5
  132407. };
  132408. static static_codebook _44c0_s_p8_0 = {
  132409. 4, 625,
  132410. _vq_lengthlist__44c0_s_p8_0,
  132411. 1, -518283264, 1627103232, 3, 0,
  132412. _vq_quantlist__44c0_s_p8_0,
  132413. NULL,
  132414. &_vq_auxt__44c0_s_p8_0,
  132415. NULL,
  132416. 0
  132417. };
  132418. static long _vq_quantlist__44c0_s_p8_1[] = {
  132419. 6,
  132420. 5,
  132421. 7,
  132422. 4,
  132423. 8,
  132424. 3,
  132425. 9,
  132426. 2,
  132427. 10,
  132428. 1,
  132429. 11,
  132430. 0,
  132431. 12,
  132432. };
  132433. static long _vq_lengthlist__44c0_s_p8_1[] = {
  132434. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  132435. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  132436. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  132437. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  132438. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  132439. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  132440. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  132441. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  132442. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  132443. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  132444. 16,13,13,12,12,14,14,15,13,
  132445. };
  132446. static float _vq_quantthresh__44c0_s_p8_1[] = {
  132447. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132448. 42.5, 59.5, 76.5, 93.5,
  132449. };
  132450. static long _vq_quantmap__44c0_s_p8_1[] = {
  132451. 11, 9, 7, 5, 3, 1, 0, 2,
  132452. 4, 6, 8, 10, 12,
  132453. };
  132454. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  132455. _vq_quantthresh__44c0_s_p8_1,
  132456. _vq_quantmap__44c0_s_p8_1,
  132457. 13,
  132458. 13
  132459. };
  132460. static static_codebook _44c0_s_p8_1 = {
  132461. 2, 169,
  132462. _vq_lengthlist__44c0_s_p8_1,
  132463. 1, -522616832, 1620115456, 4, 0,
  132464. _vq_quantlist__44c0_s_p8_1,
  132465. NULL,
  132466. &_vq_auxt__44c0_s_p8_1,
  132467. NULL,
  132468. 0
  132469. };
  132470. static long _vq_quantlist__44c0_s_p8_2[] = {
  132471. 8,
  132472. 7,
  132473. 9,
  132474. 6,
  132475. 10,
  132476. 5,
  132477. 11,
  132478. 4,
  132479. 12,
  132480. 3,
  132481. 13,
  132482. 2,
  132483. 14,
  132484. 1,
  132485. 15,
  132486. 0,
  132487. 16,
  132488. };
  132489. static long _vq_lengthlist__44c0_s_p8_2[] = {
  132490. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132491. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  132492. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  132493. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  132494. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132495. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  132496. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  132497. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  132498. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  132499. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  132500. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  132501. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  132502. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  132503. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  132504. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  132505. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  132506. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  132507. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  132508. 10,
  132509. };
  132510. static float _vq_quantthresh__44c0_s_p8_2[] = {
  132511. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132512. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132513. };
  132514. static long _vq_quantmap__44c0_s_p8_2[] = {
  132515. 15, 13, 11, 9, 7, 5, 3, 1,
  132516. 0, 2, 4, 6, 8, 10, 12, 14,
  132517. 16,
  132518. };
  132519. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  132520. _vq_quantthresh__44c0_s_p8_2,
  132521. _vq_quantmap__44c0_s_p8_2,
  132522. 17,
  132523. 17
  132524. };
  132525. static static_codebook _44c0_s_p8_2 = {
  132526. 2, 289,
  132527. _vq_lengthlist__44c0_s_p8_2,
  132528. 1, -529530880, 1611661312, 5, 0,
  132529. _vq_quantlist__44c0_s_p8_2,
  132530. NULL,
  132531. &_vq_auxt__44c0_s_p8_2,
  132532. NULL,
  132533. 0
  132534. };
  132535. static long _huff_lengthlist__44c0_s_short[] = {
  132536. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  132537. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  132538. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  132539. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  132540. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  132541. 12,
  132542. };
  132543. static static_codebook _huff_book__44c0_s_short = {
  132544. 2, 81,
  132545. _huff_lengthlist__44c0_s_short,
  132546. 0, 0, 0, 0, 0,
  132547. NULL,
  132548. NULL,
  132549. NULL,
  132550. NULL,
  132551. 0
  132552. };
  132553. static long _huff_lengthlist__44c0_sm_long[] = {
  132554. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  132555. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  132556. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  132557. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  132558. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  132559. 13,
  132560. };
  132561. static static_codebook _huff_book__44c0_sm_long = {
  132562. 2, 81,
  132563. _huff_lengthlist__44c0_sm_long,
  132564. 0, 0, 0, 0, 0,
  132565. NULL,
  132566. NULL,
  132567. NULL,
  132568. NULL,
  132569. 0
  132570. };
  132571. static long _vq_quantlist__44c0_sm_p1_0[] = {
  132572. 1,
  132573. 0,
  132574. 2,
  132575. };
  132576. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  132577. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132578. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132582. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132583. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132587. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132588. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  132623. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  132624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132628. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132633. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132668. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132669. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132673. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132674. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  132675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132678. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132679. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  132680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132987. 0,
  132988. };
  132989. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  132990. -0.5, 0.5,
  132991. };
  132992. static long _vq_quantmap__44c0_sm_p1_0[] = {
  132993. 1, 0, 2,
  132994. };
  132995. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  132996. _vq_quantthresh__44c0_sm_p1_0,
  132997. _vq_quantmap__44c0_sm_p1_0,
  132998. 3,
  132999. 3
  133000. };
  133001. static static_codebook _44c0_sm_p1_0 = {
  133002. 8, 6561,
  133003. _vq_lengthlist__44c0_sm_p1_0,
  133004. 1, -535822336, 1611661312, 2, 0,
  133005. _vq_quantlist__44c0_sm_p1_0,
  133006. NULL,
  133007. &_vq_auxt__44c0_sm_p1_0,
  133008. NULL,
  133009. 0
  133010. };
  133011. static long _vq_quantlist__44c0_sm_p2_0[] = {
  133012. 2,
  133013. 1,
  133014. 3,
  133015. 0,
  133016. 4,
  133017. };
  133018. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  133019. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0,
  133059. };
  133060. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  133061. -1.5, -0.5, 0.5, 1.5,
  133062. };
  133063. static long _vq_quantmap__44c0_sm_p2_0[] = {
  133064. 3, 1, 0, 2, 4,
  133065. };
  133066. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  133067. _vq_quantthresh__44c0_sm_p2_0,
  133068. _vq_quantmap__44c0_sm_p2_0,
  133069. 5,
  133070. 5
  133071. };
  133072. static static_codebook _44c0_sm_p2_0 = {
  133073. 4, 625,
  133074. _vq_lengthlist__44c0_sm_p2_0,
  133075. 1, -533725184, 1611661312, 3, 0,
  133076. _vq_quantlist__44c0_sm_p2_0,
  133077. NULL,
  133078. &_vq_auxt__44c0_sm_p2_0,
  133079. NULL,
  133080. 0
  133081. };
  133082. static long _vq_quantlist__44c0_sm_p3_0[] = {
  133083. 4,
  133084. 3,
  133085. 5,
  133086. 2,
  133087. 6,
  133088. 1,
  133089. 7,
  133090. 0,
  133091. 8,
  133092. };
  133093. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  133094. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  133095. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  133096. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133097. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  133098. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0,
  133100. };
  133101. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  133102. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133103. };
  133104. static long _vq_quantmap__44c0_sm_p3_0[] = {
  133105. 7, 5, 3, 1, 0, 2, 4, 6,
  133106. 8,
  133107. };
  133108. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  133109. _vq_quantthresh__44c0_sm_p3_0,
  133110. _vq_quantmap__44c0_sm_p3_0,
  133111. 9,
  133112. 9
  133113. };
  133114. static static_codebook _44c0_sm_p3_0 = {
  133115. 2, 81,
  133116. _vq_lengthlist__44c0_sm_p3_0,
  133117. 1, -531628032, 1611661312, 4, 0,
  133118. _vq_quantlist__44c0_sm_p3_0,
  133119. NULL,
  133120. &_vq_auxt__44c0_sm_p3_0,
  133121. NULL,
  133122. 0
  133123. };
  133124. static long _vq_quantlist__44c0_sm_p4_0[] = {
  133125. 4,
  133126. 3,
  133127. 5,
  133128. 2,
  133129. 6,
  133130. 1,
  133131. 7,
  133132. 0,
  133133. 8,
  133134. };
  133135. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  133136. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  133137. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133138. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133139. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133140. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133141. 11,
  133142. };
  133143. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  133144. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133145. };
  133146. static long _vq_quantmap__44c0_sm_p4_0[] = {
  133147. 7, 5, 3, 1, 0, 2, 4, 6,
  133148. 8,
  133149. };
  133150. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  133151. _vq_quantthresh__44c0_sm_p4_0,
  133152. _vq_quantmap__44c0_sm_p4_0,
  133153. 9,
  133154. 9
  133155. };
  133156. static static_codebook _44c0_sm_p4_0 = {
  133157. 2, 81,
  133158. _vq_lengthlist__44c0_sm_p4_0,
  133159. 1, -531628032, 1611661312, 4, 0,
  133160. _vq_quantlist__44c0_sm_p4_0,
  133161. NULL,
  133162. &_vq_auxt__44c0_sm_p4_0,
  133163. NULL,
  133164. 0
  133165. };
  133166. static long _vq_quantlist__44c0_sm_p5_0[] = {
  133167. 8,
  133168. 7,
  133169. 9,
  133170. 6,
  133171. 10,
  133172. 5,
  133173. 11,
  133174. 4,
  133175. 12,
  133176. 3,
  133177. 13,
  133178. 2,
  133179. 14,
  133180. 1,
  133181. 15,
  133182. 0,
  133183. 16,
  133184. };
  133185. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  133186. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  133187. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  133188. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133189. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  133190. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  133191. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  133192. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  133193. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133194. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  133195. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133196. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133197. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133198. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  133199. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  133200. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  133201. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  133202. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  133203. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133204. 14,
  133205. };
  133206. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  133207. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133208. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133209. };
  133210. static long _vq_quantmap__44c0_sm_p5_0[] = {
  133211. 15, 13, 11, 9, 7, 5, 3, 1,
  133212. 0, 2, 4, 6, 8, 10, 12, 14,
  133213. 16,
  133214. };
  133215. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  133216. _vq_quantthresh__44c0_sm_p5_0,
  133217. _vq_quantmap__44c0_sm_p5_0,
  133218. 17,
  133219. 17
  133220. };
  133221. static static_codebook _44c0_sm_p5_0 = {
  133222. 2, 289,
  133223. _vq_lengthlist__44c0_sm_p5_0,
  133224. 1, -529530880, 1611661312, 5, 0,
  133225. _vq_quantlist__44c0_sm_p5_0,
  133226. NULL,
  133227. &_vq_auxt__44c0_sm_p5_0,
  133228. NULL,
  133229. 0
  133230. };
  133231. static long _vq_quantlist__44c0_sm_p6_0[] = {
  133232. 1,
  133233. 0,
  133234. 2,
  133235. };
  133236. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  133237. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133238. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133239. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133240. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  133241. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133242. 11,
  133243. };
  133244. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  133245. -5.5, 5.5,
  133246. };
  133247. static long _vq_quantmap__44c0_sm_p6_0[] = {
  133248. 1, 0, 2,
  133249. };
  133250. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  133251. _vq_quantthresh__44c0_sm_p6_0,
  133252. _vq_quantmap__44c0_sm_p6_0,
  133253. 3,
  133254. 3
  133255. };
  133256. static static_codebook _44c0_sm_p6_0 = {
  133257. 4, 81,
  133258. _vq_lengthlist__44c0_sm_p6_0,
  133259. 1, -529137664, 1618345984, 2, 0,
  133260. _vq_quantlist__44c0_sm_p6_0,
  133261. NULL,
  133262. &_vq_auxt__44c0_sm_p6_0,
  133263. NULL,
  133264. 0
  133265. };
  133266. static long _vq_quantlist__44c0_sm_p6_1[] = {
  133267. 5,
  133268. 4,
  133269. 6,
  133270. 3,
  133271. 7,
  133272. 2,
  133273. 8,
  133274. 1,
  133275. 9,
  133276. 0,
  133277. 10,
  133278. };
  133279. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  133280. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  133281. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133282. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133283. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  133284. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  133285. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133286. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133287. 10,10,10, 8, 8, 8, 8, 8, 8,
  133288. };
  133289. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  133290. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133291. 3.5, 4.5,
  133292. };
  133293. static long _vq_quantmap__44c0_sm_p6_1[] = {
  133294. 9, 7, 5, 3, 1, 0, 2, 4,
  133295. 6, 8, 10,
  133296. };
  133297. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  133298. _vq_quantthresh__44c0_sm_p6_1,
  133299. _vq_quantmap__44c0_sm_p6_1,
  133300. 11,
  133301. 11
  133302. };
  133303. static static_codebook _44c0_sm_p6_1 = {
  133304. 2, 121,
  133305. _vq_lengthlist__44c0_sm_p6_1,
  133306. 1, -531365888, 1611661312, 4, 0,
  133307. _vq_quantlist__44c0_sm_p6_1,
  133308. NULL,
  133309. &_vq_auxt__44c0_sm_p6_1,
  133310. NULL,
  133311. 0
  133312. };
  133313. static long _vq_quantlist__44c0_sm_p7_0[] = {
  133314. 6,
  133315. 5,
  133316. 7,
  133317. 4,
  133318. 8,
  133319. 3,
  133320. 9,
  133321. 2,
  133322. 10,
  133323. 1,
  133324. 11,
  133325. 0,
  133326. 12,
  133327. };
  133328. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  133329. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133330. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  133331. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133332. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133333. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133334. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  133335. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133336. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133337. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133338. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  133339. 0,12,12,11,11,13,12,14,14,
  133340. };
  133341. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  133342. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133343. 12.5, 17.5, 22.5, 27.5,
  133344. };
  133345. static long _vq_quantmap__44c0_sm_p7_0[] = {
  133346. 11, 9, 7, 5, 3, 1, 0, 2,
  133347. 4, 6, 8, 10, 12,
  133348. };
  133349. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  133350. _vq_quantthresh__44c0_sm_p7_0,
  133351. _vq_quantmap__44c0_sm_p7_0,
  133352. 13,
  133353. 13
  133354. };
  133355. static static_codebook _44c0_sm_p7_0 = {
  133356. 2, 169,
  133357. _vq_lengthlist__44c0_sm_p7_0,
  133358. 1, -526516224, 1616117760, 4, 0,
  133359. _vq_quantlist__44c0_sm_p7_0,
  133360. NULL,
  133361. &_vq_auxt__44c0_sm_p7_0,
  133362. NULL,
  133363. 0
  133364. };
  133365. static long _vq_quantlist__44c0_sm_p7_1[] = {
  133366. 2,
  133367. 1,
  133368. 3,
  133369. 0,
  133370. 4,
  133371. };
  133372. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  133373. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133374. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133375. };
  133376. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  133377. -1.5, -0.5, 0.5, 1.5,
  133378. };
  133379. static long _vq_quantmap__44c0_sm_p7_1[] = {
  133380. 3, 1, 0, 2, 4,
  133381. };
  133382. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  133383. _vq_quantthresh__44c0_sm_p7_1,
  133384. _vq_quantmap__44c0_sm_p7_1,
  133385. 5,
  133386. 5
  133387. };
  133388. static static_codebook _44c0_sm_p7_1 = {
  133389. 2, 25,
  133390. _vq_lengthlist__44c0_sm_p7_1,
  133391. 1, -533725184, 1611661312, 3, 0,
  133392. _vq_quantlist__44c0_sm_p7_1,
  133393. NULL,
  133394. &_vq_auxt__44c0_sm_p7_1,
  133395. NULL,
  133396. 0
  133397. };
  133398. static long _vq_quantlist__44c0_sm_p8_0[] = {
  133399. 4,
  133400. 3,
  133401. 5,
  133402. 2,
  133403. 6,
  133404. 1,
  133405. 7,
  133406. 0,
  133407. 8,
  133408. };
  133409. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  133410. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  133411. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  133412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133413. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133414. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133415. 12,
  133416. };
  133417. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  133418. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  133419. };
  133420. static long _vq_quantmap__44c0_sm_p8_0[] = {
  133421. 7, 5, 3, 1, 0, 2, 4, 6,
  133422. 8,
  133423. };
  133424. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  133425. _vq_quantthresh__44c0_sm_p8_0,
  133426. _vq_quantmap__44c0_sm_p8_0,
  133427. 9,
  133428. 9
  133429. };
  133430. static static_codebook _44c0_sm_p8_0 = {
  133431. 2, 81,
  133432. _vq_lengthlist__44c0_sm_p8_0,
  133433. 1, -516186112, 1627103232, 4, 0,
  133434. _vq_quantlist__44c0_sm_p8_0,
  133435. NULL,
  133436. &_vq_auxt__44c0_sm_p8_0,
  133437. NULL,
  133438. 0
  133439. };
  133440. static long _vq_quantlist__44c0_sm_p8_1[] = {
  133441. 6,
  133442. 5,
  133443. 7,
  133444. 4,
  133445. 8,
  133446. 3,
  133447. 9,
  133448. 2,
  133449. 10,
  133450. 1,
  133451. 11,
  133452. 0,
  133453. 12,
  133454. };
  133455. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  133456. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133457. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  133458. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  133459. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  133460. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  133461. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  133462. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  133463. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  133464. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  133465. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  133466. 20,13,13,12,12,16,13,15,13,
  133467. };
  133468. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  133469. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133470. 42.5, 59.5, 76.5, 93.5,
  133471. };
  133472. static long _vq_quantmap__44c0_sm_p8_1[] = {
  133473. 11, 9, 7, 5, 3, 1, 0, 2,
  133474. 4, 6, 8, 10, 12,
  133475. };
  133476. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  133477. _vq_quantthresh__44c0_sm_p8_1,
  133478. _vq_quantmap__44c0_sm_p8_1,
  133479. 13,
  133480. 13
  133481. };
  133482. static static_codebook _44c0_sm_p8_1 = {
  133483. 2, 169,
  133484. _vq_lengthlist__44c0_sm_p8_1,
  133485. 1, -522616832, 1620115456, 4, 0,
  133486. _vq_quantlist__44c0_sm_p8_1,
  133487. NULL,
  133488. &_vq_auxt__44c0_sm_p8_1,
  133489. NULL,
  133490. 0
  133491. };
  133492. static long _vq_quantlist__44c0_sm_p8_2[] = {
  133493. 8,
  133494. 7,
  133495. 9,
  133496. 6,
  133497. 10,
  133498. 5,
  133499. 11,
  133500. 4,
  133501. 12,
  133502. 3,
  133503. 13,
  133504. 2,
  133505. 14,
  133506. 1,
  133507. 15,
  133508. 0,
  133509. 16,
  133510. };
  133511. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  133512. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133513. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133514. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  133515. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133516. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133517. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133518. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133519. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133520. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  133521. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  133522. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  133523. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133524. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  133525. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  133526. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133527. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  133528. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  133529. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  133530. 9,
  133531. };
  133532. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  133533. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133534. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133535. };
  133536. static long _vq_quantmap__44c0_sm_p8_2[] = {
  133537. 15, 13, 11, 9, 7, 5, 3, 1,
  133538. 0, 2, 4, 6, 8, 10, 12, 14,
  133539. 16,
  133540. };
  133541. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  133542. _vq_quantthresh__44c0_sm_p8_2,
  133543. _vq_quantmap__44c0_sm_p8_2,
  133544. 17,
  133545. 17
  133546. };
  133547. static static_codebook _44c0_sm_p8_2 = {
  133548. 2, 289,
  133549. _vq_lengthlist__44c0_sm_p8_2,
  133550. 1, -529530880, 1611661312, 5, 0,
  133551. _vq_quantlist__44c0_sm_p8_2,
  133552. NULL,
  133553. &_vq_auxt__44c0_sm_p8_2,
  133554. NULL,
  133555. 0
  133556. };
  133557. static long _huff_lengthlist__44c0_sm_short[] = {
  133558. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  133559. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  133560. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  133561. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  133562. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  133563. 12,
  133564. };
  133565. static static_codebook _huff_book__44c0_sm_short = {
  133566. 2, 81,
  133567. _huff_lengthlist__44c0_sm_short,
  133568. 0, 0, 0, 0, 0,
  133569. NULL,
  133570. NULL,
  133571. NULL,
  133572. NULL,
  133573. 0
  133574. };
  133575. static long _huff_lengthlist__44c1_s_long[] = {
  133576. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  133577. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  133578. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  133579. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  133580. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  133581. 11,
  133582. };
  133583. static static_codebook _huff_book__44c1_s_long = {
  133584. 2, 81,
  133585. _huff_lengthlist__44c1_s_long,
  133586. 0, 0, 0, 0, 0,
  133587. NULL,
  133588. NULL,
  133589. NULL,
  133590. NULL,
  133591. 0
  133592. };
  133593. static long _vq_quantlist__44c1_s_p1_0[] = {
  133594. 1,
  133595. 0,
  133596. 2,
  133597. };
  133598. static long _vq_lengthlist__44c1_s_p1_0[] = {
  133599. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  133600. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133604. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133605. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133609. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133610. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  133645. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133650. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  133651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  133655. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133690. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133691. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133695. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  133696. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  133697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133700. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133701. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134009. 0,
  134010. };
  134011. static float _vq_quantthresh__44c1_s_p1_0[] = {
  134012. -0.5, 0.5,
  134013. };
  134014. static long _vq_quantmap__44c1_s_p1_0[] = {
  134015. 1, 0, 2,
  134016. };
  134017. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  134018. _vq_quantthresh__44c1_s_p1_0,
  134019. _vq_quantmap__44c1_s_p1_0,
  134020. 3,
  134021. 3
  134022. };
  134023. static static_codebook _44c1_s_p1_0 = {
  134024. 8, 6561,
  134025. _vq_lengthlist__44c1_s_p1_0,
  134026. 1, -535822336, 1611661312, 2, 0,
  134027. _vq_quantlist__44c1_s_p1_0,
  134028. NULL,
  134029. &_vq_auxt__44c1_s_p1_0,
  134030. NULL,
  134031. 0
  134032. };
  134033. static long _vq_quantlist__44c1_s_p2_0[] = {
  134034. 2,
  134035. 1,
  134036. 3,
  134037. 0,
  134038. 4,
  134039. };
  134040. static long _vq_lengthlist__44c1_s_p2_0[] = {
  134041. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134047. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134080. 0,
  134081. };
  134082. static float _vq_quantthresh__44c1_s_p2_0[] = {
  134083. -1.5, -0.5, 0.5, 1.5,
  134084. };
  134085. static long _vq_quantmap__44c1_s_p2_0[] = {
  134086. 3, 1, 0, 2, 4,
  134087. };
  134088. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  134089. _vq_quantthresh__44c1_s_p2_0,
  134090. _vq_quantmap__44c1_s_p2_0,
  134091. 5,
  134092. 5
  134093. };
  134094. static static_codebook _44c1_s_p2_0 = {
  134095. 4, 625,
  134096. _vq_lengthlist__44c1_s_p2_0,
  134097. 1, -533725184, 1611661312, 3, 0,
  134098. _vq_quantlist__44c1_s_p2_0,
  134099. NULL,
  134100. &_vq_auxt__44c1_s_p2_0,
  134101. NULL,
  134102. 0
  134103. };
  134104. static long _vq_quantlist__44c1_s_p3_0[] = {
  134105. 4,
  134106. 3,
  134107. 5,
  134108. 2,
  134109. 6,
  134110. 1,
  134111. 7,
  134112. 0,
  134113. 8,
  134114. };
  134115. static long _vq_lengthlist__44c1_s_p3_0[] = {
  134116. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  134117. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134118. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134119. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134120. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0,
  134122. };
  134123. static float _vq_quantthresh__44c1_s_p3_0[] = {
  134124. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134125. };
  134126. static long _vq_quantmap__44c1_s_p3_0[] = {
  134127. 7, 5, 3, 1, 0, 2, 4, 6,
  134128. 8,
  134129. };
  134130. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  134131. _vq_quantthresh__44c1_s_p3_0,
  134132. _vq_quantmap__44c1_s_p3_0,
  134133. 9,
  134134. 9
  134135. };
  134136. static static_codebook _44c1_s_p3_0 = {
  134137. 2, 81,
  134138. _vq_lengthlist__44c1_s_p3_0,
  134139. 1, -531628032, 1611661312, 4, 0,
  134140. _vq_quantlist__44c1_s_p3_0,
  134141. NULL,
  134142. &_vq_auxt__44c1_s_p3_0,
  134143. NULL,
  134144. 0
  134145. };
  134146. static long _vq_quantlist__44c1_s_p4_0[] = {
  134147. 4,
  134148. 3,
  134149. 5,
  134150. 2,
  134151. 6,
  134152. 1,
  134153. 7,
  134154. 0,
  134155. 8,
  134156. };
  134157. static long _vq_lengthlist__44c1_s_p4_0[] = {
  134158. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  134159. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134160. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134161. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  134162. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134163. 11,
  134164. };
  134165. static float _vq_quantthresh__44c1_s_p4_0[] = {
  134166. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134167. };
  134168. static long _vq_quantmap__44c1_s_p4_0[] = {
  134169. 7, 5, 3, 1, 0, 2, 4, 6,
  134170. 8,
  134171. };
  134172. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  134173. _vq_quantthresh__44c1_s_p4_0,
  134174. _vq_quantmap__44c1_s_p4_0,
  134175. 9,
  134176. 9
  134177. };
  134178. static static_codebook _44c1_s_p4_0 = {
  134179. 2, 81,
  134180. _vq_lengthlist__44c1_s_p4_0,
  134181. 1, -531628032, 1611661312, 4, 0,
  134182. _vq_quantlist__44c1_s_p4_0,
  134183. NULL,
  134184. &_vq_auxt__44c1_s_p4_0,
  134185. NULL,
  134186. 0
  134187. };
  134188. static long _vq_quantlist__44c1_s_p5_0[] = {
  134189. 8,
  134190. 7,
  134191. 9,
  134192. 6,
  134193. 10,
  134194. 5,
  134195. 11,
  134196. 4,
  134197. 12,
  134198. 3,
  134199. 13,
  134200. 2,
  134201. 14,
  134202. 1,
  134203. 15,
  134204. 0,
  134205. 16,
  134206. };
  134207. static long _vq_lengthlist__44c1_s_p5_0[] = {
  134208. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134209. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134210. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134211. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134212. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134213. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  134214. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  134215. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134216. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134217. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134218. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134219. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134220. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134221. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134222. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  134223. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134224. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134226. 14,
  134227. };
  134228. static float _vq_quantthresh__44c1_s_p5_0[] = {
  134229. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134230. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134231. };
  134232. static long _vq_quantmap__44c1_s_p5_0[] = {
  134233. 15, 13, 11, 9, 7, 5, 3, 1,
  134234. 0, 2, 4, 6, 8, 10, 12, 14,
  134235. 16,
  134236. };
  134237. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  134238. _vq_quantthresh__44c1_s_p5_0,
  134239. _vq_quantmap__44c1_s_p5_0,
  134240. 17,
  134241. 17
  134242. };
  134243. static static_codebook _44c1_s_p5_0 = {
  134244. 2, 289,
  134245. _vq_lengthlist__44c1_s_p5_0,
  134246. 1, -529530880, 1611661312, 5, 0,
  134247. _vq_quantlist__44c1_s_p5_0,
  134248. NULL,
  134249. &_vq_auxt__44c1_s_p5_0,
  134250. NULL,
  134251. 0
  134252. };
  134253. static long _vq_quantlist__44c1_s_p6_0[] = {
  134254. 1,
  134255. 0,
  134256. 2,
  134257. };
  134258. static long _vq_lengthlist__44c1_s_p6_0[] = {
  134259. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134260. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  134261. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  134262. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  134263. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  134264. 11,
  134265. };
  134266. static float _vq_quantthresh__44c1_s_p6_0[] = {
  134267. -5.5, 5.5,
  134268. };
  134269. static long _vq_quantmap__44c1_s_p6_0[] = {
  134270. 1, 0, 2,
  134271. };
  134272. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  134273. _vq_quantthresh__44c1_s_p6_0,
  134274. _vq_quantmap__44c1_s_p6_0,
  134275. 3,
  134276. 3
  134277. };
  134278. static static_codebook _44c1_s_p6_0 = {
  134279. 4, 81,
  134280. _vq_lengthlist__44c1_s_p6_0,
  134281. 1, -529137664, 1618345984, 2, 0,
  134282. _vq_quantlist__44c1_s_p6_0,
  134283. NULL,
  134284. &_vq_auxt__44c1_s_p6_0,
  134285. NULL,
  134286. 0
  134287. };
  134288. static long _vq_quantlist__44c1_s_p6_1[] = {
  134289. 5,
  134290. 4,
  134291. 6,
  134292. 3,
  134293. 7,
  134294. 2,
  134295. 8,
  134296. 1,
  134297. 9,
  134298. 0,
  134299. 10,
  134300. };
  134301. static long _vq_lengthlist__44c1_s_p6_1[] = {
  134302. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  134303. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  134304. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134305. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  134306. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  134307. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134308. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134309. 10,10,10, 8, 8, 8, 8, 8, 8,
  134310. };
  134311. static float _vq_quantthresh__44c1_s_p6_1[] = {
  134312. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134313. 3.5, 4.5,
  134314. };
  134315. static long _vq_quantmap__44c1_s_p6_1[] = {
  134316. 9, 7, 5, 3, 1, 0, 2, 4,
  134317. 6, 8, 10,
  134318. };
  134319. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  134320. _vq_quantthresh__44c1_s_p6_1,
  134321. _vq_quantmap__44c1_s_p6_1,
  134322. 11,
  134323. 11
  134324. };
  134325. static static_codebook _44c1_s_p6_1 = {
  134326. 2, 121,
  134327. _vq_lengthlist__44c1_s_p6_1,
  134328. 1, -531365888, 1611661312, 4, 0,
  134329. _vq_quantlist__44c1_s_p6_1,
  134330. NULL,
  134331. &_vq_auxt__44c1_s_p6_1,
  134332. NULL,
  134333. 0
  134334. };
  134335. static long _vq_quantlist__44c1_s_p7_0[] = {
  134336. 6,
  134337. 5,
  134338. 7,
  134339. 4,
  134340. 8,
  134341. 3,
  134342. 9,
  134343. 2,
  134344. 10,
  134345. 1,
  134346. 11,
  134347. 0,
  134348. 12,
  134349. };
  134350. static long _vq_lengthlist__44c1_s_p7_0[] = {
  134351. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  134352. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  134353. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134354. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134355. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  134356. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  134357. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  134358. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134359. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134360. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  134361. 0,12,11,11,11,13,10,14,13,
  134362. };
  134363. static float _vq_quantthresh__44c1_s_p7_0[] = {
  134364. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134365. 12.5, 17.5, 22.5, 27.5,
  134366. };
  134367. static long _vq_quantmap__44c1_s_p7_0[] = {
  134368. 11, 9, 7, 5, 3, 1, 0, 2,
  134369. 4, 6, 8, 10, 12,
  134370. };
  134371. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  134372. _vq_quantthresh__44c1_s_p7_0,
  134373. _vq_quantmap__44c1_s_p7_0,
  134374. 13,
  134375. 13
  134376. };
  134377. static static_codebook _44c1_s_p7_0 = {
  134378. 2, 169,
  134379. _vq_lengthlist__44c1_s_p7_0,
  134380. 1, -526516224, 1616117760, 4, 0,
  134381. _vq_quantlist__44c1_s_p7_0,
  134382. NULL,
  134383. &_vq_auxt__44c1_s_p7_0,
  134384. NULL,
  134385. 0
  134386. };
  134387. static long _vq_quantlist__44c1_s_p7_1[] = {
  134388. 2,
  134389. 1,
  134390. 3,
  134391. 0,
  134392. 4,
  134393. };
  134394. static long _vq_lengthlist__44c1_s_p7_1[] = {
  134395. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134396. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134397. };
  134398. static float _vq_quantthresh__44c1_s_p7_1[] = {
  134399. -1.5, -0.5, 0.5, 1.5,
  134400. };
  134401. static long _vq_quantmap__44c1_s_p7_1[] = {
  134402. 3, 1, 0, 2, 4,
  134403. };
  134404. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  134405. _vq_quantthresh__44c1_s_p7_1,
  134406. _vq_quantmap__44c1_s_p7_1,
  134407. 5,
  134408. 5
  134409. };
  134410. static static_codebook _44c1_s_p7_1 = {
  134411. 2, 25,
  134412. _vq_lengthlist__44c1_s_p7_1,
  134413. 1, -533725184, 1611661312, 3, 0,
  134414. _vq_quantlist__44c1_s_p7_1,
  134415. NULL,
  134416. &_vq_auxt__44c1_s_p7_1,
  134417. NULL,
  134418. 0
  134419. };
  134420. static long _vq_quantlist__44c1_s_p8_0[] = {
  134421. 6,
  134422. 5,
  134423. 7,
  134424. 4,
  134425. 8,
  134426. 3,
  134427. 9,
  134428. 2,
  134429. 10,
  134430. 1,
  134431. 11,
  134432. 0,
  134433. 12,
  134434. };
  134435. static long _vq_lengthlist__44c1_s_p8_0[] = {
  134436. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  134437. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  134438. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134441. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134442. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134444. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134446. 10,10,10,10,10,10,10,10,10,
  134447. };
  134448. static float _vq_quantthresh__44c1_s_p8_0[] = {
  134449. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  134450. 552.5, 773.5, 994.5, 1215.5,
  134451. };
  134452. static long _vq_quantmap__44c1_s_p8_0[] = {
  134453. 11, 9, 7, 5, 3, 1, 0, 2,
  134454. 4, 6, 8, 10, 12,
  134455. };
  134456. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  134457. _vq_quantthresh__44c1_s_p8_0,
  134458. _vq_quantmap__44c1_s_p8_0,
  134459. 13,
  134460. 13
  134461. };
  134462. static static_codebook _44c1_s_p8_0 = {
  134463. 2, 169,
  134464. _vq_lengthlist__44c1_s_p8_0,
  134465. 1, -514541568, 1627103232, 4, 0,
  134466. _vq_quantlist__44c1_s_p8_0,
  134467. NULL,
  134468. &_vq_auxt__44c1_s_p8_0,
  134469. NULL,
  134470. 0
  134471. };
  134472. static long _vq_quantlist__44c1_s_p8_1[] = {
  134473. 6,
  134474. 5,
  134475. 7,
  134476. 4,
  134477. 8,
  134478. 3,
  134479. 9,
  134480. 2,
  134481. 10,
  134482. 1,
  134483. 11,
  134484. 0,
  134485. 12,
  134486. };
  134487. static long _vq_lengthlist__44c1_s_p8_1[] = {
  134488. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134489. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134490. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  134491. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  134492. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  134493. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  134494. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  134495. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  134496. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  134497. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  134498. 16,13,12,12,11,14,12,15,13,
  134499. };
  134500. static float _vq_quantthresh__44c1_s_p8_1[] = {
  134501. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134502. 42.5, 59.5, 76.5, 93.5,
  134503. };
  134504. static long _vq_quantmap__44c1_s_p8_1[] = {
  134505. 11, 9, 7, 5, 3, 1, 0, 2,
  134506. 4, 6, 8, 10, 12,
  134507. };
  134508. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  134509. _vq_quantthresh__44c1_s_p8_1,
  134510. _vq_quantmap__44c1_s_p8_1,
  134511. 13,
  134512. 13
  134513. };
  134514. static static_codebook _44c1_s_p8_1 = {
  134515. 2, 169,
  134516. _vq_lengthlist__44c1_s_p8_1,
  134517. 1, -522616832, 1620115456, 4, 0,
  134518. _vq_quantlist__44c1_s_p8_1,
  134519. NULL,
  134520. &_vq_auxt__44c1_s_p8_1,
  134521. NULL,
  134522. 0
  134523. };
  134524. static long _vq_quantlist__44c1_s_p8_2[] = {
  134525. 8,
  134526. 7,
  134527. 9,
  134528. 6,
  134529. 10,
  134530. 5,
  134531. 11,
  134532. 4,
  134533. 12,
  134534. 3,
  134535. 13,
  134536. 2,
  134537. 14,
  134538. 1,
  134539. 15,
  134540. 0,
  134541. 16,
  134542. };
  134543. static long _vq_lengthlist__44c1_s_p8_2[] = {
  134544. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134545. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134546. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134547. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134548. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134549. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134550. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134551. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  134552. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  134553. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134554. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  134555. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134556. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  134557. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  134558. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134559. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  134560. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134561. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  134562. 9,
  134563. };
  134564. static float _vq_quantthresh__44c1_s_p8_2[] = {
  134565. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134566. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134567. };
  134568. static long _vq_quantmap__44c1_s_p8_2[] = {
  134569. 15, 13, 11, 9, 7, 5, 3, 1,
  134570. 0, 2, 4, 6, 8, 10, 12, 14,
  134571. 16,
  134572. };
  134573. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  134574. _vq_quantthresh__44c1_s_p8_2,
  134575. _vq_quantmap__44c1_s_p8_2,
  134576. 17,
  134577. 17
  134578. };
  134579. static static_codebook _44c1_s_p8_2 = {
  134580. 2, 289,
  134581. _vq_lengthlist__44c1_s_p8_2,
  134582. 1, -529530880, 1611661312, 5, 0,
  134583. _vq_quantlist__44c1_s_p8_2,
  134584. NULL,
  134585. &_vq_auxt__44c1_s_p8_2,
  134586. NULL,
  134587. 0
  134588. };
  134589. static long _huff_lengthlist__44c1_s_short[] = {
  134590. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  134591. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  134592. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  134593. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  134594. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  134595. 11,
  134596. };
  134597. static static_codebook _huff_book__44c1_s_short = {
  134598. 2, 81,
  134599. _huff_lengthlist__44c1_s_short,
  134600. 0, 0, 0, 0, 0,
  134601. NULL,
  134602. NULL,
  134603. NULL,
  134604. NULL,
  134605. 0
  134606. };
  134607. static long _huff_lengthlist__44c1_sm_long[] = {
  134608. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  134609. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  134610. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  134611. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  134612. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  134613. 11,
  134614. };
  134615. static static_codebook _huff_book__44c1_sm_long = {
  134616. 2, 81,
  134617. _huff_lengthlist__44c1_sm_long,
  134618. 0, 0, 0, 0, 0,
  134619. NULL,
  134620. NULL,
  134621. NULL,
  134622. NULL,
  134623. 0
  134624. };
  134625. static long _vq_quantlist__44c1_sm_p1_0[] = {
  134626. 1,
  134627. 0,
  134628. 2,
  134629. };
  134630. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  134631. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134632. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134636. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134637. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134641. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134642. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  134677. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134682. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134687. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134722. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134723. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134727. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134728. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  134729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134732. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134733. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  134734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0,
  135042. };
  135043. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  135044. -0.5, 0.5,
  135045. };
  135046. static long _vq_quantmap__44c1_sm_p1_0[] = {
  135047. 1, 0, 2,
  135048. };
  135049. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  135050. _vq_quantthresh__44c1_sm_p1_0,
  135051. _vq_quantmap__44c1_sm_p1_0,
  135052. 3,
  135053. 3
  135054. };
  135055. static static_codebook _44c1_sm_p1_0 = {
  135056. 8, 6561,
  135057. _vq_lengthlist__44c1_sm_p1_0,
  135058. 1, -535822336, 1611661312, 2, 0,
  135059. _vq_quantlist__44c1_sm_p1_0,
  135060. NULL,
  135061. &_vq_auxt__44c1_sm_p1_0,
  135062. NULL,
  135063. 0
  135064. };
  135065. static long _vq_quantlist__44c1_sm_p2_0[] = {
  135066. 2,
  135067. 1,
  135068. 3,
  135069. 0,
  135070. 4,
  135071. };
  135072. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  135073. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0,
  135113. };
  135114. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  135115. -1.5, -0.5, 0.5, 1.5,
  135116. };
  135117. static long _vq_quantmap__44c1_sm_p2_0[] = {
  135118. 3, 1, 0, 2, 4,
  135119. };
  135120. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  135121. _vq_quantthresh__44c1_sm_p2_0,
  135122. _vq_quantmap__44c1_sm_p2_0,
  135123. 5,
  135124. 5
  135125. };
  135126. static static_codebook _44c1_sm_p2_0 = {
  135127. 4, 625,
  135128. _vq_lengthlist__44c1_sm_p2_0,
  135129. 1, -533725184, 1611661312, 3, 0,
  135130. _vq_quantlist__44c1_sm_p2_0,
  135131. NULL,
  135132. &_vq_auxt__44c1_sm_p2_0,
  135133. NULL,
  135134. 0
  135135. };
  135136. static long _vq_quantlist__44c1_sm_p3_0[] = {
  135137. 4,
  135138. 3,
  135139. 5,
  135140. 2,
  135141. 6,
  135142. 1,
  135143. 7,
  135144. 0,
  135145. 8,
  135146. };
  135147. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  135148. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  135149. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  135150. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135151. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135152. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0,
  135154. };
  135155. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  135156. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135157. };
  135158. static long _vq_quantmap__44c1_sm_p3_0[] = {
  135159. 7, 5, 3, 1, 0, 2, 4, 6,
  135160. 8,
  135161. };
  135162. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  135163. _vq_quantthresh__44c1_sm_p3_0,
  135164. _vq_quantmap__44c1_sm_p3_0,
  135165. 9,
  135166. 9
  135167. };
  135168. static static_codebook _44c1_sm_p3_0 = {
  135169. 2, 81,
  135170. _vq_lengthlist__44c1_sm_p3_0,
  135171. 1, -531628032, 1611661312, 4, 0,
  135172. _vq_quantlist__44c1_sm_p3_0,
  135173. NULL,
  135174. &_vq_auxt__44c1_sm_p3_0,
  135175. NULL,
  135176. 0
  135177. };
  135178. static long _vq_quantlist__44c1_sm_p4_0[] = {
  135179. 4,
  135180. 3,
  135181. 5,
  135182. 2,
  135183. 6,
  135184. 1,
  135185. 7,
  135186. 0,
  135187. 8,
  135188. };
  135189. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  135190. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  135191. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135192. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135193. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  135194. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135195. 11,
  135196. };
  135197. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  135198. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135199. };
  135200. static long _vq_quantmap__44c1_sm_p4_0[] = {
  135201. 7, 5, 3, 1, 0, 2, 4, 6,
  135202. 8,
  135203. };
  135204. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  135205. _vq_quantthresh__44c1_sm_p4_0,
  135206. _vq_quantmap__44c1_sm_p4_0,
  135207. 9,
  135208. 9
  135209. };
  135210. static static_codebook _44c1_sm_p4_0 = {
  135211. 2, 81,
  135212. _vq_lengthlist__44c1_sm_p4_0,
  135213. 1, -531628032, 1611661312, 4, 0,
  135214. _vq_quantlist__44c1_sm_p4_0,
  135215. NULL,
  135216. &_vq_auxt__44c1_sm_p4_0,
  135217. NULL,
  135218. 0
  135219. };
  135220. static long _vq_quantlist__44c1_sm_p5_0[] = {
  135221. 8,
  135222. 7,
  135223. 9,
  135224. 6,
  135225. 10,
  135226. 5,
  135227. 11,
  135228. 4,
  135229. 12,
  135230. 3,
  135231. 13,
  135232. 2,
  135233. 14,
  135234. 1,
  135235. 15,
  135236. 0,
  135237. 16,
  135238. };
  135239. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  135240. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135241. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135242. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  135243. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135244. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135245. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  135246. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  135247. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135248. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135249. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135250. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135251. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135252. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  135253. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135254. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  135255. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  135256. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135258. 14,
  135259. };
  135260. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  135261. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135262. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135263. };
  135264. static long _vq_quantmap__44c1_sm_p5_0[] = {
  135265. 15, 13, 11, 9, 7, 5, 3, 1,
  135266. 0, 2, 4, 6, 8, 10, 12, 14,
  135267. 16,
  135268. };
  135269. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  135270. _vq_quantthresh__44c1_sm_p5_0,
  135271. _vq_quantmap__44c1_sm_p5_0,
  135272. 17,
  135273. 17
  135274. };
  135275. static static_codebook _44c1_sm_p5_0 = {
  135276. 2, 289,
  135277. _vq_lengthlist__44c1_sm_p5_0,
  135278. 1, -529530880, 1611661312, 5, 0,
  135279. _vq_quantlist__44c1_sm_p5_0,
  135280. NULL,
  135281. &_vq_auxt__44c1_sm_p5_0,
  135282. NULL,
  135283. 0
  135284. };
  135285. static long _vq_quantlist__44c1_sm_p6_0[] = {
  135286. 1,
  135287. 0,
  135288. 2,
  135289. };
  135290. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  135291. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135292. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135293. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  135294. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  135295. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  135296. 11,
  135297. };
  135298. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  135299. -5.5, 5.5,
  135300. };
  135301. static long _vq_quantmap__44c1_sm_p6_0[] = {
  135302. 1, 0, 2,
  135303. };
  135304. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  135305. _vq_quantthresh__44c1_sm_p6_0,
  135306. _vq_quantmap__44c1_sm_p6_0,
  135307. 3,
  135308. 3
  135309. };
  135310. static static_codebook _44c1_sm_p6_0 = {
  135311. 4, 81,
  135312. _vq_lengthlist__44c1_sm_p6_0,
  135313. 1, -529137664, 1618345984, 2, 0,
  135314. _vq_quantlist__44c1_sm_p6_0,
  135315. NULL,
  135316. &_vq_auxt__44c1_sm_p6_0,
  135317. NULL,
  135318. 0
  135319. };
  135320. static long _vq_quantlist__44c1_sm_p6_1[] = {
  135321. 5,
  135322. 4,
  135323. 6,
  135324. 3,
  135325. 7,
  135326. 2,
  135327. 8,
  135328. 1,
  135329. 9,
  135330. 0,
  135331. 10,
  135332. };
  135333. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  135334. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135335. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135336. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135337. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135338. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135339. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  135340. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135341. 10,10,10, 8, 8, 8, 8, 8, 8,
  135342. };
  135343. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  135344. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135345. 3.5, 4.5,
  135346. };
  135347. static long _vq_quantmap__44c1_sm_p6_1[] = {
  135348. 9, 7, 5, 3, 1, 0, 2, 4,
  135349. 6, 8, 10,
  135350. };
  135351. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  135352. _vq_quantthresh__44c1_sm_p6_1,
  135353. _vq_quantmap__44c1_sm_p6_1,
  135354. 11,
  135355. 11
  135356. };
  135357. static static_codebook _44c1_sm_p6_1 = {
  135358. 2, 121,
  135359. _vq_lengthlist__44c1_sm_p6_1,
  135360. 1, -531365888, 1611661312, 4, 0,
  135361. _vq_quantlist__44c1_sm_p6_1,
  135362. NULL,
  135363. &_vq_auxt__44c1_sm_p6_1,
  135364. NULL,
  135365. 0
  135366. };
  135367. static long _vq_quantlist__44c1_sm_p7_0[] = {
  135368. 6,
  135369. 5,
  135370. 7,
  135371. 4,
  135372. 8,
  135373. 3,
  135374. 9,
  135375. 2,
  135376. 10,
  135377. 1,
  135378. 11,
  135379. 0,
  135380. 12,
  135381. };
  135382. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  135383. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135384. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135385. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135386. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135387. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135388. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  135389. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  135390. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135391. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135392. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  135393. 0,12,12,11,11,13,12,14,13,
  135394. };
  135395. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  135396. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135397. 12.5, 17.5, 22.5, 27.5,
  135398. };
  135399. static long _vq_quantmap__44c1_sm_p7_0[] = {
  135400. 11, 9, 7, 5, 3, 1, 0, 2,
  135401. 4, 6, 8, 10, 12,
  135402. };
  135403. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  135404. _vq_quantthresh__44c1_sm_p7_0,
  135405. _vq_quantmap__44c1_sm_p7_0,
  135406. 13,
  135407. 13
  135408. };
  135409. static static_codebook _44c1_sm_p7_0 = {
  135410. 2, 169,
  135411. _vq_lengthlist__44c1_sm_p7_0,
  135412. 1, -526516224, 1616117760, 4, 0,
  135413. _vq_quantlist__44c1_sm_p7_0,
  135414. NULL,
  135415. &_vq_auxt__44c1_sm_p7_0,
  135416. NULL,
  135417. 0
  135418. };
  135419. static long _vq_quantlist__44c1_sm_p7_1[] = {
  135420. 2,
  135421. 1,
  135422. 3,
  135423. 0,
  135424. 4,
  135425. };
  135426. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  135427. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135428. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135429. };
  135430. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  135431. -1.5, -0.5, 0.5, 1.5,
  135432. };
  135433. static long _vq_quantmap__44c1_sm_p7_1[] = {
  135434. 3, 1, 0, 2, 4,
  135435. };
  135436. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  135437. _vq_quantthresh__44c1_sm_p7_1,
  135438. _vq_quantmap__44c1_sm_p7_1,
  135439. 5,
  135440. 5
  135441. };
  135442. static static_codebook _44c1_sm_p7_1 = {
  135443. 2, 25,
  135444. _vq_lengthlist__44c1_sm_p7_1,
  135445. 1, -533725184, 1611661312, 3, 0,
  135446. _vq_quantlist__44c1_sm_p7_1,
  135447. NULL,
  135448. &_vq_auxt__44c1_sm_p7_1,
  135449. NULL,
  135450. 0
  135451. };
  135452. static long _vq_quantlist__44c1_sm_p8_0[] = {
  135453. 6,
  135454. 5,
  135455. 7,
  135456. 4,
  135457. 8,
  135458. 3,
  135459. 9,
  135460. 2,
  135461. 10,
  135462. 1,
  135463. 11,
  135464. 0,
  135465. 12,
  135466. };
  135467. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  135468. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  135469. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  135470. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135471. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135472. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135473. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135474. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135475. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135476. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135477. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135478. 13,13,13,13,13,13,13,13,13,
  135479. };
  135480. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  135481. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135482. 552.5, 773.5, 994.5, 1215.5,
  135483. };
  135484. static long _vq_quantmap__44c1_sm_p8_0[] = {
  135485. 11, 9, 7, 5, 3, 1, 0, 2,
  135486. 4, 6, 8, 10, 12,
  135487. };
  135488. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  135489. _vq_quantthresh__44c1_sm_p8_0,
  135490. _vq_quantmap__44c1_sm_p8_0,
  135491. 13,
  135492. 13
  135493. };
  135494. static static_codebook _44c1_sm_p8_0 = {
  135495. 2, 169,
  135496. _vq_lengthlist__44c1_sm_p8_0,
  135497. 1, -514541568, 1627103232, 4, 0,
  135498. _vq_quantlist__44c1_sm_p8_0,
  135499. NULL,
  135500. &_vq_auxt__44c1_sm_p8_0,
  135501. NULL,
  135502. 0
  135503. };
  135504. static long _vq_quantlist__44c1_sm_p8_1[] = {
  135505. 6,
  135506. 5,
  135507. 7,
  135508. 4,
  135509. 8,
  135510. 3,
  135511. 9,
  135512. 2,
  135513. 10,
  135514. 1,
  135515. 11,
  135516. 0,
  135517. 12,
  135518. };
  135519. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  135520. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  135521. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  135522. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  135523. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  135524. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  135525. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  135526. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  135527. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  135528. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  135529. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  135530. 20,13,12,12,12,14,12,14,13,
  135531. };
  135532. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  135533. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135534. 42.5, 59.5, 76.5, 93.5,
  135535. };
  135536. static long _vq_quantmap__44c1_sm_p8_1[] = {
  135537. 11, 9, 7, 5, 3, 1, 0, 2,
  135538. 4, 6, 8, 10, 12,
  135539. };
  135540. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  135541. _vq_quantthresh__44c1_sm_p8_1,
  135542. _vq_quantmap__44c1_sm_p8_1,
  135543. 13,
  135544. 13
  135545. };
  135546. static static_codebook _44c1_sm_p8_1 = {
  135547. 2, 169,
  135548. _vq_lengthlist__44c1_sm_p8_1,
  135549. 1, -522616832, 1620115456, 4, 0,
  135550. _vq_quantlist__44c1_sm_p8_1,
  135551. NULL,
  135552. &_vq_auxt__44c1_sm_p8_1,
  135553. NULL,
  135554. 0
  135555. };
  135556. static long _vq_quantlist__44c1_sm_p8_2[] = {
  135557. 8,
  135558. 7,
  135559. 9,
  135560. 6,
  135561. 10,
  135562. 5,
  135563. 11,
  135564. 4,
  135565. 12,
  135566. 3,
  135567. 13,
  135568. 2,
  135569. 14,
  135570. 1,
  135571. 15,
  135572. 0,
  135573. 16,
  135574. };
  135575. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  135576. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135577. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135578. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135579. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135580. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135581. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135582. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135583. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  135584. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  135585. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135586. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  135587. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  135588. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  135589. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  135590. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135591. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  135592. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135593. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  135594. 9,
  135595. };
  135596. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  135597. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135598. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135599. };
  135600. static long _vq_quantmap__44c1_sm_p8_2[] = {
  135601. 15, 13, 11, 9, 7, 5, 3, 1,
  135602. 0, 2, 4, 6, 8, 10, 12, 14,
  135603. 16,
  135604. };
  135605. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  135606. _vq_quantthresh__44c1_sm_p8_2,
  135607. _vq_quantmap__44c1_sm_p8_2,
  135608. 17,
  135609. 17
  135610. };
  135611. static static_codebook _44c1_sm_p8_2 = {
  135612. 2, 289,
  135613. _vq_lengthlist__44c1_sm_p8_2,
  135614. 1, -529530880, 1611661312, 5, 0,
  135615. _vq_quantlist__44c1_sm_p8_2,
  135616. NULL,
  135617. &_vq_auxt__44c1_sm_p8_2,
  135618. NULL,
  135619. 0
  135620. };
  135621. static long _huff_lengthlist__44c1_sm_short[] = {
  135622. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  135623. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  135624. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  135625. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  135626. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  135627. 11,
  135628. };
  135629. static static_codebook _huff_book__44c1_sm_short = {
  135630. 2, 81,
  135631. _huff_lengthlist__44c1_sm_short,
  135632. 0, 0, 0, 0, 0,
  135633. NULL,
  135634. NULL,
  135635. NULL,
  135636. NULL,
  135637. 0
  135638. };
  135639. static long _huff_lengthlist__44cn1_s_long[] = {
  135640. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  135641. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  135642. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  135643. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  135644. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  135645. 20,
  135646. };
  135647. static static_codebook _huff_book__44cn1_s_long = {
  135648. 2, 81,
  135649. _huff_lengthlist__44cn1_s_long,
  135650. 0, 0, 0, 0, 0,
  135651. NULL,
  135652. NULL,
  135653. NULL,
  135654. NULL,
  135655. 0
  135656. };
  135657. static long _vq_quantlist__44cn1_s_p1_0[] = {
  135658. 1,
  135659. 0,
  135660. 2,
  135661. };
  135662. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  135663. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135664. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135669. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  135674. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  135709. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  135714. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  135719. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  135755. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135760. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  135765. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0,
  136074. };
  136075. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  136076. -0.5, 0.5,
  136077. };
  136078. static long _vq_quantmap__44cn1_s_p1_0[] = {
  136079. 1, 0, 2,
  136080. };
  136081. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  136082. _vq_quantthresh__44cn1_s_p1_0,
  136083. _vq_quantmap__44cn1_s_p1_0,
  136084. 3,
  136085. 3
  136086. };
  136087. static static_codebook _44cn1_s_p1_0 = {
  136088. 8, 6561,
  136089. _vq_lengthlist__44cn1_s_p1_0,
  136090. 1, -535822336, 1611661312, 2, 0,
  136091. _vq_quantlist__44cn1_s_p1_0,
  136092. NULL,
  136093. &_vq_auxt__44cn1_s_p1_0,
  136094. NULL,
  136095. 0
  136096. };
  136097. static long _vq_quantlist__44cn1_s_p2_0[] = {
  136098. 2,
  136099. 1,
  136100. 3,
  136101. 0,
  136102. 4,
  136103. };
  136104. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  136105. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0,
  136145. };
  136146. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  136147. -1.5, -0.5, 0.5, 1.5,
  136148. };
  136149. static long _vq_quantmap__44cn1_s_p2_0[] = {
  136150. 3, 1, 0, 2, 4,
  136151. };
  136152. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  136153. _vq_quantthresh__44cn1_s_p2_0,
  136154. _vq_quantmap__44cn1_s_p2_0,
  136155. 5,
  136156. 5
  136157. };
  136158. static static_codebook _44cn1_s_p2_0 = {
  136159. 4, 625,
  136160. _vq_lengthlist__44cn1_s_p2_0,
  136161. 1, -533725184, 1611661312, 3, 0,
  136162. _vq_quantlist__44cn1_s_p2_0,
  136163. NULL,
  136164. &_vq_auxt__44cn1_s_p2_0,
  136165. NULL,
  136166. 0
  136167. };
  136168. static long _vq_quantlist__44cn1_s_p3_0[] = {
  136169. 4,
  136170. 3,
  136171. 5,
  136172. 2,
  136173. 6,
  136174. 1,
  136175. 7,
  136176. 0,
  136177. 8,
  136178. };
  136179. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  136180. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136181. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136182. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136183. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136184. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0,
  136186. };
  136187. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  136188. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136189. };
  136190. static long _vq_quantmap__44cn1_s_p3_0[] = {
  136191. 7, 5, 3, 1, 0, 2, 4, 6,
  136192. 8,
  136193. };
  136194. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  136195. _vq_quantthresh__44cn1_s_p3_0,
  136196. _vq_quantmap__44cn1_s_p3_0,
  136197. 9,
  136198. 9
  136199. };
  136200. static static_codebook _44cn1_s_p3_0 = {
  136201. 2, 81,
  136202. _vq_lengthlist__44cn1_s_p3_0,
  136203. 1, -531628032, 1611661312, 4, 0,
  136204. _vq_quantlist__44cn1_s_p3_0,
  136205. NULL,
  136206. &_vq_auxt__44cn1_s_p3_0,
  136207. NULL,
  136208. 0
  136209. };
  136210. static long _vq_quantlist__44cn1_s_p4_0[] = {
  136211. 4,
  136212. 3,
  136213. 5,
  136214. 2,
  136215. 6,
  136216. 1,
  136217. 7,
  136218. 0,
  136219. 8,
  136220. };
  136221. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  136222. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  136223. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136224. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  136225. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136226. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136227. 11,
  136228. };
  136229. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  136230. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136231. };
  136232. static long _vq_quantmap__44cn1_s_p4_0[] = {
  136233. 7, 5, 3, 1, 0, 2, 4, 6,
  136234. 8,
  136235. };
  136236. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  136237. _vq_quantthresh__44cn1_s_p4_0,
  136238. _vq_quantmap__44cn1_s_p4_0,
  136239. 9,
  136240. 9
  136241. };
  136242. static static_codebook _44cn1_s_p4_0 = {
  136243. 2, 81,
  136244. _vq_lengthlist__44cn1_s_p4_0,
  136245. 1, -531628032, 1611661312, 4, 0,
  136246. _vq_quantlist__44cn1_s_p4_0,
  136247. NULL,
  136248. &_vq_auxt__44cn1_s_p4_0,
  136249. NULL,
  136250. 0
  136251. };
  136252. static long _vq_quantlist__44cn1_s_p5_0[] = {
  136253. 8,
  136254. 7,
  136255. 9,
  136256. 6,
  136257. 10,
  136258. 5,
  136259. 11,
  136260. 4,
  136261. 12,
  136262. 3,
  136263. 13,
  136264. 2,
  136265. 14,
  136266. 1,
  136267. 15,
  136268. 0,
  136269. 16,
  136270. };
  136271. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  136272. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  136273. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136274. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136275. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136276. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136277. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136278. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136279. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  136280. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136281. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  136282. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136283. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136284. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  136285. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136286. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  136287. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  136288. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  136290. 14,
  136291. };
  136292. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  136293. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136294. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136295. };
  136296. static long _vq_quantmap__44cn1_s_p5_0[] = {
  136297. 15, 13, 11, 9, 7, 5, 3, 1,
  136298. 0, 2, 4, 6, 8, 10, 12, 14,
  136299. 16,
  136300. };
  136301. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  136302. _vq_quantthresh__44cn1_s_p5_0,
  136303. _vq_quantmap__44cn1_s_p5_0,
  136304. 17,
  136305. 17
  136306. };
  136307. static static_codebook _44cn1_s_p5_0 = {
  136308. 2, 289,
  136309. _vq_lengthlist__44cn1_s_p5_0,
  136310. 1, -529530880, 1611661312, 5, 0,
  136311. _vq_quantlist__44cn1_s_p5_0,
  136312. NULL,
  136313. &_vq_auxt__44cn1_s_p5_0,
  136314. NULL,
  136315. 0
  136316. };
  136317. static long _vq_quantlist__44cn1_s_p6_0[] = {
  136318. 1,
  136319. 0,
  136320. 2,
  136321. };
  136322. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  136323. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  136324. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  136325. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  136326. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  136327. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  136328. 10,
  136329. };
  136330. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  136331. -5.5, 5.5,
  136332. };
  136333. static long _vq_quantmap__44cn1_s_p6_0[] = {
  136334. 1, 0, 2,
  136335. };
  136336. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  136337. _vq_quantthresh__44cn1_s_p6_0,
  136338. _vq_quantmap__44cn1_s_p6_0,
  136339. 3,
  136340. 3
  136341. };
  136342. static static_codebook _44cn1_s_p6_0 = {
  136343. 4, 81,
  136344. _vq_lengthlist__44cn1_s_p6_0,
  136345. 1, -529137664, 1618345984, 2, 0,
  136346. _vq_quantlist__44cn1_s_p6_0,
  136347. NULL,
  136348. &_vq_auxt__44cn1_s_p6_0,
  136349. NULL,
  136350. 0
  136351. };
  136352. static long _vq_quantlist__44cn1_s_p6_1[] = {
  136353. 5,
  136354. 4,
  136355. 6,
  136356. 3,
  136357. 7,
  136358. 2,
  136359. 8,
  136360. 1,
  136361. 9,
  136362. 0,
  136363. 10,
  136364. };
  136365. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  136366. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  136367. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  136368. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136369. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  136370. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  136371. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  136372. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  136373. 10,10,10, 9, 9, 9, 9, 9, 9,
  136374. };
  136375. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  136376. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136377. 3.5, 4.5,
  136378. };
  136379. static long _vq_quantmap__44cn1_s_p6_1[] = {
  136380. 9, 7, 5, 3, 1, 0, 2, 4,
  136381. 6, 8, 10,
  136382. };
  136383. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  136384. _vq_quantthresh__44cn1_s_p6_1,
  136385. _vq_quantmap__44cn1_s_p6_1,
  136386. 11,
  136387. 11
  136388. };
  136389. static static_codebook _44cn1_s_p6_1 = {
  136390. 2, 121,
  136391. _vq_lengthlist__44cn1_s_p6_1,
  136392. 1, -531365888, 1611661312, 4, 0,
  136393. _vq_quantlist__44cn1_s_p6_1,
  136394. NULL,
  136395. &_vq_auxt__44cn1_s_p6_1,
  136396. NULL,
  136397. 0
  136398. };
  136399. static long _vq_quantlist__44cn1_s_p7_0[] = {
  136400. 6,
  136401. 5,
  136402. 7,
  136403. 4,
  136404. 8,
  136405. 3,
  136406. 9,
  136407. 2,
  136408. 10,
  136409. 1,
  136410. 11,
  136411. 0,
  136412. 12,
  136413. };
  136414. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  136415. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  136416. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  136417. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136418. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136419. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  136420. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136421. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  136422. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  136423. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  136424. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  136425. 0,13,13,12,12,13,13,13,14,
  136426. };
  136427. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  136428. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136429. 12.5, 17.5, 22.5, 27.5,
  136430. };
  136431. static long _vq_quantmap__44cn1_s_p7_0[] = {
  136432. 11, 9, 7, 5, 3, 1, 0, 2,
  136433. 4, 6, 8, 10, 12,
  136434. };
  136435. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  136436. _vq_quantthresh__44cn1_s_p7_0,
  136437. _vq_quantmap__44cn1_s_p7_0,
  136438. 13,
  136439. 13
  136440. };
  136441. static static_codebook _44cn1_s_p7_0 = {
  136442. 2, 169,
  136443. _vq_lengthlist__44cn1_s_p7_0,
  136444. 1, -526516224, 1616117760, 4, 0,
  136445. _vq_quantlist__44cn1_s_p7_0,
  136446. NULL,
  136447. &_vq_auxt__44cn1_s_p7_0,
  136448. NULL,
  136449. 0
  136450. };
  136451. static long _vq_quantlist__44cn1_s_p7_1[] = {
  136452. 2,
  136453. 1,
  136454. 3,
  136455. 0,
  136456. 4,
  136457. };
  136458. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  136459. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136460. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136461. };
  136462. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  136463. -1.5, -0.5, 0.5, 1.5,
  136464. };
  136465. static long _vq_quantmap__44cn1_s_p7_1[] = {
  136466. 3, 1, 0, 2, 4,
  136467. };
  136468. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  136469. _vq_quantthresh__44cn1_s_p7_1,
  136470. _vq_quantmap__44cn1_s_p7_1,
  136471. 5,
  136472. 5
  136473. };
  136474. static static_codebook _44cn1_s_p7_1 = {
  136475. 2, 25,
  136476. _vq_lengthlist__44cn1_s_p7_1,
  136477. 1, -533725184, 1611661312, 3, 0,
  136478. _vq_quantlist__44cn1_s_p7_1,
  136479. NULL,
  136480. &_vq_auxt__44cn1_s_p7_1,
  136481. NULL,
  136482. 0
  136483. };
  136484. static long _vq_quantlist__44cn1_s_p8_0[] = {
  136485. 2,
  136486. 1,
  136487. 3,
  136488. 0,
  136489. 4,
  136490. };
  136491. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  136492. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  136493. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  136494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136495. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  136496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136499. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  136500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136501. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  136502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  136503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136507. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  136508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136524. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136525. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  136526. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136527. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136528. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136529. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136530. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136531. 12,
  136532. };
  136533. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  136534. -331.5, -110.5, 110.5, 331.5,
  136535. };
  136536. static long _vq_quantmap__44cn1_s_p8_0[] = {
  136537. 3, 1, 0, 2, 4,
  136538. };
  136539. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  136540. _vq_quantthresh__44cn1_s_p8_0,
  136541. _vq_quantmap__44cn1_s_p8_0,
  136542. 5,
  136543. 5
  136544. };
  136545. static static_codebook _44cn1_s_p8_0 = {
  136546. 4, 625,
  136547. _vq_lengthlist__44cn1_s_p8_0,
  136548. 1, -518283264, 1627103232, 3, 0,
  136549. _vq_quantlist__44cn1_s_p8_0,
  136550. NULL,
  136551. &_vq_auxt__44cn1_s_p8_0,
  136552. NULL,
  136553. 0
  136554. };
  136555. static long _vq_quantlist__44cn1_s_p8_1[] = {
  136556. 6,
  136557. 5,
  136558. 7,
  136559. 4,
  136560. 8,
  136561. 3,
  136562. 9,
  136563. 2,
  136564. 10,
  136565. 1,
  136566. 11,
  136567. 0,
  136568. 12,
  136569. };
  136570. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  136571. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  136572. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  136573. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  136574. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  136575. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  136576. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  136577. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  136578. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  136579. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  136580. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  136581. 15,12,12,11,11,14,12,13,14,
  136582. };
  136583. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  136584. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136585. 42.5, 59.5, 76.5, 93.5,
  136586. };
  136587. static long _vq_quantmap__44cn1_s_p8_1[] = {
  136588. 11, 9, 7, 5, 3, 1, 0, 2,
  136589. 4, 6, 8, 10, 12,
  136590. };
  136591. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  136592. _vq_quantthresh__44cn1_s_p8_1,
  136593. _vq_quantmap__44cn1_s_p8_1,
  136594. 13,
  136595. 13
  136596. };
  136597. static static_codebook _44cn1_s_p8_1 = {
  136598. 2, 169,
  136599. _vq_lengthlist__44cn1_s_p8_1,
  136600. 1, -522616832, 1620115456, 4, 0,
  136601. _vq_quantlist__44cn1_s_p8_1,
  136602. NULL,
  136603. &_vq_auxt__44cn1_s_p8_1,
  136604. NULL,
  136605. 0
  136606. };
  136607. static long _vq_quantlist__44cn1_s_p8_2[] = {
  136608. 8,
  136609. 7,
  136610. 9,
  136611. 6,
  136612. 10,
  136613. 5,
  136614. 11,
  136615. 4,
  136616. 12,
  136617. 3,
  136618. 13,
  136619. 2,
  136620. 14,
  136621. 1,
  136622. 15,
  136623. 0,
  136624. 16,
  136625. };
  136626. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  136627. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  136628. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136629. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136630. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  136631. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  136632. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  136633. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  136634. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  136635. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  136636. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  136637. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  136638. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  136639. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  136640. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  136641. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  136642. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136643. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136644. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  136645. 9,
  136646. };
  136647. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  136648. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136649. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136650. };
  136651. static long _vq_quantmap__44cn1_s_p8_2[] = {
  136652. 15, 13, 11, 9, 7, 5, 3, 1,
  136653. 0, 2, 4, 6, 8, 10, 12, 14,
  136654. 16,
  136655. };
  136656. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  136657. _vq_quantthresh__44cn1_s_p8_2,
  136658. _vq_quantmap__44cn1_s_p8_2,
  136659. 17,
  136660. 17
  136661. };
  136662. static static_codebook _44cn1_s_p8_2 = {
  136663. 2, 289,
  136664. _vq_lengthlist__44cn1_s_p8_2,
  136665. 1, -529530880, 1611661312, 5, 0,
  136666. _vq_quantlist__44cn1_s_p8_2,
  136667. NULL,
  136668. &_vq_auxt__44cn1_s_p8_2,
  136669. NULL,
  136670. 0
  136671. };
  136672. static long _huff_lengthlist__44cn1_s_short[] = {
  136673. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  136674. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  136675. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  136676. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  136677. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  136678. 10,
  136679. };
  136680. static static_codebook _huff_book__44cn1_s_short = {
  136681. 2, 81,
  136682. _huff_lengthlist__44cn1_s_short,
  136683. 0, 0, 0, 0, 0,
  136684. NULL,
  136685. NULL,
  136686. NULL,
  136687. NULL,
  136688. 0
  136689. };
  136690. static long _huff_lengthlist__44cn1_sm_long[] = {
  136691. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  136692. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  136693. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  136694. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  136695. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  136696. 17,
  136697. };
  136698. static static_codebook _huff_book__44cn1_sm_long = {
  136699. 2, 81,
  136700. _huff_lengthlist__44cn1_sm_long,
  136701. 0, 0, 0, 0, 0,
  136702. NULL,
  136703. NULL,
  136704. NULL,
  136705. NULL,
  136706. 0
  136707. };
  136708. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  136709. 1,
  136710. 0,
  136711. 2,
  136712. };
  136713. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  136714. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136715. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136720. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136725. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  136760. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  136765. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136770. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136806. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136811. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  136816. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0,
  137125. };
  137126. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  137127. -0.5, 0.5,
  137128. };
  137129. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  137130. 1, 0, 2,
  137131. };
  137132. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  137133. _vq_quantthresh__44cn1_sm_p1_0,
  137134. _vq_quantmap__44cn1_sm_p1_0,
  137135. 3,
  137136. 3
  137137. };
  137138. static static_codebook _44cn1_sm_p1_0 = {
  137139. 8, 6561,
  137140. _vq_lengthlist__44cn1_sm_p1_0,
  137141. 1, -535822336, 1611661312, 2, 0,
  137142. _vq_quantlist__44cn1_sm_p1_0,
  137143. NULL,
  137144. &_vq_auxt__44cn1_sm_p1_0,
  137145. NULL,
  137146. 0
  137147. };
  137148. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  137149. 2,
  137150. 1,
  137151. 3,
  137152. 0,
  137153. 4,
  137154. };
  137155. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  137156. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0,
  137196. };
  137197. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  137198. -1.5, -0.5, 0.5, 1.5,
  137199. };
  137200. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  137201. 3, 1, 0, 2, 4,
  137202. };
  137203. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  137204. _vq_quantthresh__44cn1_sm_p2_0,
  137205. _vq_quantmap__44cn1_sm_p2_0,
  137206. 5,
  137207. 5
  137208. };
  137209. static static_codebook _44cn1_sm_p2_0 = {
  137210. 4, 625,
  137211. _vq_lengthlist__44cn1_sm_p2_0,
  137212. 1, -533725184, 1611661312, 3, 0,
  137213. _vq_quantlist__44cn1_sm_p2_0,
  137214. NULL,
  137215. &_vq_auxt__44cn1_sm_p2_0,
  137216. NULL,
  137217. 0
  137218. };
  137219. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  137220. 4,
  137221. 3,
  137222. 5,
  137223. 2,
  137224. 6,
  137225. 1,
  137226. 7,
  137227. 0,
  137228. 8,
  137229. };
  137230. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  137231. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  137232. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137233. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137234. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  137235. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0,
  137237. };
  137238. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  137239. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137240. };
  137241. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  137242. 7, 5, 3, 1, 0, 2, 4, 6,
  137243. 8,
  137244. };
  137245. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  137246. _vq_quantthresh__44cn1_sm_p3_0,
  137247. _vq_quantmap__44cn1_sm_p3_0,
  137248. 9,
  137249. 9
  137250. };
  137251. static static_codebook _44cn1_sm_p3_0 = {
  137252. 2, 81,
  137253. _vq_lengthlist__44cn1_sm_p3_0,
  137254. 1, -531628032, 1611661312, 4, 0,
  137255. _vq_quantlist__44cn1_sm_p3_0,
  137256. NULL,
  137257. &_vq_auxt__44cn1_sm_p3_0,
  137258. NULL,
  137259. 0
  137260. };
  137261. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  137262. 4,
  137263. 3,
  137264. 5,
  137265. 2,
  137266. 6,
  137267. 1,
  137268. 7,
  137269. 0,
  137270. 8,
  137271. };
  137272. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  137273. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137274. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137275. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137276. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  137277. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  137278. 11,
  137279. };
  137280. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  137281. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137282. };
  137283. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  137284. 7, 5, 3, 1, 0, 2, 4, 6,
  137285. 8,
  137286. };
  137287. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  137288. _vq_quantthresh__44cn1_sm_p4_0,
  137289. _vq_quantmap__44cn1_sm_p4_0,
  137290. 9,
  137291. 9
  137292. };
  137293. static static_codebook _44cn1_sm_p4_0 = {
  137294. 2, 81,
  137295. _vq_lengthlist__44cn1_sm_p4_0,
  137296. 1, -531628032, 1611661312, 4, 0,
  137297. _vq_quantlist__44cn1_sm_p4_0,
  137298. NULL,
  137299. &_vq_auxt__44cn1_sm_p4_0,
  137300. NULL,
  137301. 0
  137302. };
  137303. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  137304. 8,
  137305. 7,
  137306. 9,
  137307. 6,
  137308. 10,
  137309. 5,
  137310. 11,
  137311. 4,
  137312. 12,
  137313. 3,
  137314. 13,
  137315. 2,
  137316. 14,
  137317. 1,
  137318. 15,
  137319. 0,
  137320. 16,
  137321. };
  137322. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  137323. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  137324. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  137325. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  137326. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137327. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  137328. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137329. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137330. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137331. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  137332. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137333. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  137334. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  137335. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  137336. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  137337. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  137338. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  137339. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  137341. 14,
  137342. };
  137343. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  137344. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137345. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137346. };
  137347. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  137348. 15, 13, 11, 9, 7, 5, 3, 1,
  137349. 0, 2, 4, 6, 8, 10, 12, 14,
  137350. 16,
  137351. };
  137352. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  137353. _vq_quantthresh__44cn1_sm_p5_0,
  137354. _vq_quantmap__44cn1_sm_p5_0,
  137355. 17,
  137356. 17
  137357. };
  137358. static static_codebook _44cn1_sm_p5_0 = {
  137359. 2, 289,
  137360. _vq_lengthlist__44cn1_sm_p5_0,
  137361. 1, -529530880, 1611661312, 5, 0,
  137362. _vq_quantlist__44cn1_sm_p5_0,
  137363. NULL,
  137364. &_vq_auxt__44cn1_sm_p5_0,
  137365. NULL,
  137366. 0
  137367. };
  137368. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  137369. 1,
  137370. 0,
  137371. 2,
  137372. };
  137373. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  137374. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  137375. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137376. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137377. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  137378. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  137379. 10,
  137380. };
  137381. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  137382. -5.5, 5.5,
  137383. };
  137384. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  137385. 1, 0, 2,
  137386. };
  137387. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  137388. _vq_quantthresh__44cn1_sm_p6_0,
  137389. _vq_quantmap__44cn1_sm_p6_0,
  137390. 3,
  137391. 3
  137392. };
  137393. static static_codebook _44cn1_sm_p6_0 = {
  137394. 4, 81,
  137395. _vq_lengthlist__44cn1_sm_p6_0,
  137396. 1, -529137664, 1618345984, 2, 0,
  137397. _vq_quantlist__44cn1_sm_p6_0,
  137398. NULL,
  137399. &_vq_auxt__44cn1_sm_p6_0,
  137400. NULL,
  137401. 0
  137402. };
  137403. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  137404. 5,
  137405. 4,
  137406. 6,
  137407. 3,
  137408. 7,
  137409. 2,
  137410. 8,
  137411. 1,
  137412. 9,
  137413. 0,
  137414. 10,
  137415. };
  137416. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  137417. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  137418. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137419. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137420. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137421. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137422. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  137423. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  137424. 10,10,10, 8, 9, 8, 8, 9, 8,
  137425. };
  137426. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  137427. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137428. 3.5, 4.5,
  137429. };
  137430. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  137431. 9, 7, 5, 3, 1, 0, 2, 4,
  137432. 6, 8, 10,
  137433. };
  137434. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  137435. _vq_quantthresh__44cn1_sm_p6_1,
  137436. _vq_quantmap__44cn1_sm_p6_1,
  137437. 11,
  137438. 11
  137439. };
  137440. static static_codebook _44cn1_sm_p6_1 = {
  137441. 2, 121,
  137442. _vq_lengthlist__44cn1_sm_p6_1,
  137443. 1, -531365888, 1611661312, 4, 0,
  137444. _vq_quantlist__44cn1_sm_p6_1,
  137445. NULL,
  137446. &_vq_auxt__44cn1_sm_p6_1,
  137447. NULL,
  137448. 0
  137449. };
  137450. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  137451. 6,
  137452. 5,
  137453. 7,
  137454. 4,
  137455. 8,
  137456. 3,
  137457. 9,
  137458. 2,
  137459. 10,
  137460. 1,
  137461. 11,
  137462. 0,
  137463. 12,
  137464. };
  137465. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  137466. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  137467. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  137468. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137469. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137470. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  137471. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  137472. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137473. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  137474. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  137475. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  137476. 0,13,12,12,12,13,13,13,14,
  137477. };
  137478. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  137479. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137480. 12.5, 17.5, 22.5, 27.5,
  137481. };
  137482. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  137483. 11, 9, 7, 5, 3, 1, 0, 2,
  137484. 4, 6, 8, 10, 12,
  137485. };
  137486. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  137487. _vq_quantthresh__44cn1_sm_p7_0,
  137488. _vq_quantmap__44cn1_sm_p7_0,
  137489. 13,
  137490. 13
  137491. };
  137492. static static_codebook _44cn1_sm_p7_0 = {
  137493. 2, 169,
  137494. _vq_lengthlist__44cn1_sm_p7_0,
  137495. 1, -526516224, 1616117760, 4, 0,
  137496. _vq_quantlist__44cn1_sm_p7_0,
  137497. NULL,
  137498. &_vq_auxt__44cn1_sm_p7_0,
  137499. NULL,
  137500. 0
  137501. };
  137502. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  137503. 2,
  137504. 1,
  137505. 3,
  137506. 0,
  137507. 4,
  137508. };
  137509. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  137510. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137511. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  137512. };
  137513. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  137514. -1.5, -0.5, 0.5, 1.5,
  137515. };
  137516. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  137517. 3, 1, 0, 2, 4,
  137518. };
  137519. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  137520. _vq_quantthresh__44cn1_sm_p7_1,
  137521. _vq_quantmap__44cn1_sm_p7_1,
  137522. 5,
  137523. 5
  137524. };
  137525. static static_codebook _44cn1_sm_p7_1 = {
  137526. 2, 25,
  137527. _vq_lengthlist__44cn1_sm_p7_1,
  137528. 1, -533725184, 1611661312, 3, 0,
  137529. _vq_quantlist__44cn1_sm_p7_1,
  137530. NULL,
  137531. &_vq_auxt__44cn1_sm_p7_1,
  137532. NULL,
  137533. 0
  137534. };
  137535. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  137536. 4,
  137537. 3,
  137538. 5,
  137539. 2,
  137540. 6,
  137541. 1,
  137542. 7,
  137543. 0,
  137544. 8,
  137545. };
  137546. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  137547. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  137548. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  137549. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  137550. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  137551. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  137552. 14,
  137553. };
  137554. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  137555. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137556. };
  137557. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  137558. 7, 5, 3, 1, 0, 2, 4, 6,
  137559. 8,
  137560. };
  137561. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  137562. _vq_quantthresh__44cn1_sm_p8_0,
  137563. _vq_quantmap__44cn1_sm_p8_0,
  137564. 9,
  137565. 9
  137566. };
  137567. static static_codebook _44cn1_sm_p8_0 = {
  137568. 2, 81,
  137569. _vq_lengthlist__44cn1_sm_p8_0,
  137570. 1, -516186112, 1627103232, 4, 0,
  137571. _vq_quantlist__44cn1_sm_p8_0,
  137572. NULL,
  137573. &_vq_auxt__44cn1_sm_p8_0,
  137574. NULL,
  137575. 0
  137576. };
  137577. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  137578. 6,
  137579. 5,
  137580. 7,
  137581. 4,
  137582. 8,
  137583. 3,
  137584. 9,
  137585. 2,
  137586. 10,
  137587. 1,
  137588. 11,
  137589. 0,
  137590. 12,
  137591. };
  137592. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  137593. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  137594. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  137595. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  137596. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  137597. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  137598. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  137599. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  137600. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  137601. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  137602. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  137603. 17,12,12,11,10,13,11,13,13,
  137604. };
  137605. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  137606. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137607. 42.5, 59.5, 76.5, 93.5,
  137608. };
  137609. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  137610. 11, 9, 7, 5, 3, 1, 0, 2,
  137611. 4, 6, 8, 10, 12,
  137612. };
  137613. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  137614. _vq_quantthresh__44cn1_sm_p8_1,
  137615. _vq_quantmap__44cn1_sm_p8_1,
  137616. 13,
  137617. 13
  137618. };
  137619. static static_codebook _44cn1_sm_p8_1 = {
  137620. 2, 169,
  137621. _vq_lengthlist__44cn1_sm_p8_1,
  137622. 1, -522616832, 1620115456, 4, 0,
  137623. _vq_quantlist__44cn1_sm_p8_1,
  137624. NULL,
  137625. &_vq_auxt__44cn1_sm_p8_1,
  137626. NULL,
  137627. 0
  137628. };
  137629. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  137630. 8,
  137631. 7,
  137632. 9,
  137633. 6,
  137634. 10,
  137635. 5,
  137636. 11,
  137637. 4,
  137638. 12,
  137639. 3,
  137640. 13,
  137641. 2,
  137642. 14,
  137643. 1,
  137644. 15,
  137645. 0,
  137646. 16,
  137647. };
  137648. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  137649. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  137650. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137651. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  137652. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137653. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  137654. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  137655. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  137656. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  137657. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  137658. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  137659. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  137660. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  137661. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  137662. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  137663. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  137664. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137665. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137666. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137667. 9,
  137668. };
  137669. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  137670. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137671. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137672. };
  137673. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  137674. 15, 13, 11, 9, 7, 5, 3, 1,
  137675. 0, 2, 4, 6, 8, 10, 12, 14,
  137676. 16,
  137677. };
  137678. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  137679. _vq_quantthresh__44cn1_sm_p8_2,
  137680. _vq_quantmap__44cn1_sm_p8_2,
  137681. 17,
  137682. 17
  137683. };
  137684. static static_codebook _44cn1_sm_p8_2 = {
  137685. 2, 289,
  137686. _vq_lengthlist__44cn1_sm_p8_2,
  137687. 1, -529530880, 1611661312, 5, 0,
  137688. _vq_quantlist__44cn1_sm_p8_2,
  137689. NULL,
  137690. &_vq_auxt__44cn1_sm_p8_2,
  137691. NULL,
  137692. 0
  137693. };
  137694. static long _huff_lengthlist__44cn1_sm_short[] = {
  137695. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  137696. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  137697. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  137698. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  137699. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  137700. 9,
  137701. };
  137702. static static_codebook _huff_book__44cn1_sm_short = {
  137703. 2, 81,
  137704. _huff_lengthlist__44cn1_sm_short,
  137705. 0, 0, 0, 0, 0,
  137706. NULL,
  137707. NULL,
  137708. NULL,
  137709. NULL,
  137710. 0
  137711. };
  137712. /********* End of inlined file: res_books_stereo.h *********/
  137713. /***** residue backends *********************************************/
  137714. static vorbis_info_residue0 _residue_44_low={
  137715. 0,-1, -1, 9,-1,
  137716. /* 0 1 2 3 4 5 6 7 */
  137717. {0},
  137718. {-1},
  137719. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137720. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  137721. };
  137722. static vorbis_info_residue0 _residue_44_mid={
  137723. 0,-1, -1, 10,-1,
  137724. /* 0 1 2 3 4 5 6 7 8 */
  137725. {0},
  137726. {-1},
  137727. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137728. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  137729. };
  137730. static vorbis_info_residue0 _residue_44_high={
  137731. 0,-1, -1, 10,-1,
  137732. /* 0 1 2 3 4 5 6 7 8 */
  137733. {0},
  137734. {-1},
  137735. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  137736. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  137737. };
  137738. static static_bookblock _resbook_44s_n1={
  137739. {
  137740. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  137741. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  137742. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  137743. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  137744. }
  137745. };
  137746. static static_bookblock _resbook_44sm_n1={
  137747. {
  137748. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  137749. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  137750. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  137751. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  137752. }
  137753. };
  137754. static static_bookblock _resbook_44s_0={
  137755. {
  137756. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  137757. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  137758. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  137759. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  137760. }
  137761. };
  137762. static static_bookblock _resbook_44sm_0={
  137763. {
  137764. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  137765. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  137766. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  137767. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  137768. }
  137769. };
  137770. static static_bookblock _resbook_44s_1={
  137771. {
  137772. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  137773. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  137774. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  137775. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  137776. }
  137777. };
  137778. static static_bookblock _resbook_44sm_1={
  137779. {
  137780. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  137781. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  137782. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  137783. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  137784. }
  137785. };
  137786. static static_bookblock _resbook_44s_2={
  137787. {
  137788. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  137789. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  137790. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  137791. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  137792. }
  137793. };
  137794. static static_bookblock _resbook_44s_3={
  137795. {
  137796. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  137797. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  137798. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  137799. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  137800. }
  137801. };
  137802. static static_bookblock _resbook_44s_4={
  137803. {
  137804. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  137805. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  137806. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  137807. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  137808. }
  137809. };
  137810. static static_bookblock _resbook_44s_5={
  137811. {
  137812. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  137813. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  137814. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  137815. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  137816. }
  137817. };
  137818. static static_bookblock _resbook_44s_6={
  137819. {
  137820. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  137821. {0,0,&_44c6_s_p4_0},
  137822. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  137823. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  137824. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  137825. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  137826. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  137827. }
  137828. };
  137829. static static_bookblock _resbook_44s_7={
  137830. {
  137831. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  137832. {0,0,&_44c7_s_p4_0},
  137833. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  137834. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  137835. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  137836. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  137837. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  137838. }
  137839. };
  137840. static static_bookblock _resbook_44s_8={
  137841. {
  137842. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  137843. {0,0,&_44c8_s_p4_0},
  137844. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  137845. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  137846. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  137847. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  137848. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  137849. }
  137850. };
  137851. static static_bookblock _resbook_44s_9={
  137852. {
  137853. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  137854. {0,0,&_44c9_s_p4_0},
  137855. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  137856. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  137857. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  137858. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  137859. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  137860. }
  137861. };
  137862. static vorbis_residue_template _res_44s_n1[]={
  137863. {2,0, &_residue_44_low,
  137864. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  137865. &_resbook_44s_n1,&_resbook_44sm_n1},
  137866. {2,0, &_residue_44_low,
  137867. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  137868. &_resbook_44s_n1,&_resbook_44sm_n1}
  137869. };
  137870. static vorbis_residue_template _res_44s_0[]={
  137871. {2,0, &_residue_44_low,
  137872. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  137873. &_resbook_44s_0,&_resbook_44sm_0},
  137874. {2,0, &_residue_44_low,
  137875. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  137876. &_resbook_44s_0,&_resbook_44sm_0}
  137877. };
  137878. static vorbis_residue_template _res_44s_1[]={
  137879. {2,0, &_residue_44_low,
  137880. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  137881. &_resbook_44s_1,&_resbook_44sm_1},
  137882. {2,0, &_residue_44_low,
  137883. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  137884. &_resbook_44s_1,&_resbook_44sm_1}
  137885. };
  137886. static vorbis_residue_template _res_44s_2[]={
  137887. {2,0, &_residue_44_mid,
  137888. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  137889. &_resbook_44s_2,&_resbook_44s_2},
  137890. {2,0, &_residue_44_mid,
  137891. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  137892. &_resbook_44s_2,&_resbook_44s_2}
  137893. };
  137894. static vorbis_residue_template _res_44s_3[]={
  137895. {2,0, &_residue_44_mid,
  137896. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  137897. &_resbook_44s_3,&_resbook_44s_3},
  137898. {2,0, &_residue_44_mid,
  137899. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  137900. &_resbook_44s_3,&_resbook_44s_3}
  137901. };
  137902. static vorbis_residue_template _res_44s_4[]={
  137903. {2,0, &_residue_44_mid,
  137904. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  137905. &_resbook_44s_4,&_resbook_44s_4},
  137906. {2,0, &_residue_44_mid,
  137907. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  137908. &_resbook_44s_4,&_resbook_44s_4}
  137909. };
  137910. static vorbis_residue_template _res_44s_5[]={
  137911. {2,0, &_residue_44_mid,
  137912. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  137913. &_resbook_44s_5,&_resbook_44s_5},
  137914. {2,0, &_residue_44_mid,
  137915. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  137916. &_resbook_44s_5,&_resbook_44s_5}
  137917. };
  137918. static vorbis_residue_template _res_44s_6[]={
  137919. {2,0, &_residue_44_high,
  137920. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  137921. &_resbook_44s_6,&_resbook_44s_6},
  137922. {2,0, &_residue_44_high,
  137923. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  137924. &_resbook_44s_6,&_resbook_44s_6}
  137925. };
  137926. static vorbis_residue_template _res_44s_7[]={
  137927. {2,0, &_residue_44_high,
  137928. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  137929. &_resbook_44s_7,&_resbook_44s_7},
  137930. {2,0, &_residue_44_high,
  137931. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  137932. &_resbook_44s_7,&_resbook_44s_7}
  137933. };
  137934. static vorbis_residue_template _res_44s_8[]={
  137935. {2,0, &_residue_44_high,
  137936. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  137937. &_resbook_44s_8,&_resbook_44s_8},
  137938. {2,0, &_residue_44_high,
  137939. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  137940. &_resbook_44s_8,&_resbook_44s_8}
  137941. };
  137942. static vorbis_residue_template _res_44s_9[]={
  137943. {2,0, &_residue_44_high,
  137944. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  137945. &_resbook_44s_9,&_resbook_44s_9},
  137946. {2,0, &_residue_44_high,
  137947. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  137948. &_resbook_44s_9,&_resbook_44s_9}
  137949. };
  137950. static vorbis_mapping_template _mapres_template_44_stereo[]={
  137951. { _map_nominal, _res_44s_n1 }, /* -1 */
  137952. { _map_nominal, _res_44s_0 }, /* 0 */
  137953. { _map_nominal, _res_44s_1 }, /* 1 */
  137954. { _map_nominal, _res_44s_2 }, /* 2 */
  137955. { _map_nominal, _res_44s_3 }, /* 3 */
  137956. { _map_nominal, _res_44s_4 }, /* 4 */
  137957. { _map_nominal, _res_44s_5 }, /* 5 */
  137958. { _map_nominal, _res_44s_6 }, /* 6 */
  137959. { _map_nominal, _res_44s_7 }, /* 7 */
  137960. { _map_nominal, _res_44s_8 }, /* 8 */
  137961. { _map_nominal, _res_44s_9 }, /* 9 */
  137962. };
  137963. /********* End of inlined file: residue_44.h *********/
  137964. /********* Start of inlined file: psych_44.h *********/
  137965. /* preecho trigger settings *****************************************/
  137966. static vorbis_info_psy_global _psy_global_44[5]={
  137967. {8, /* lines per eighth octave */
  137968. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  137969. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  137970. -6.f,
  137971. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137972. },
  137973. {8, /* lines per eighth octave */
  137974. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137975. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  137976. -6.f,
  137977. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137978. },
  137979. {8, /* lines per eighth octave */
  137980. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137981. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  137982. -6.f,
  137983. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137984. },
  137985. {8, /* lines per eighth octave */
  137986. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  137987. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  137988. -6.f,
  137989. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137990. },
  137991. {8, /* lines per eighth octave */
  137992. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  137993. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  137994. -6.f,
  137995. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137996. },
  137997. };
  137998. /* noise compander lookups * low, mid, high quality ****************/
  137999. static compandblock _psy_compand_44[6]={
  138000. /* sub-mode Z short */
  138001. {{
  138002. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138003. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138004. 16,17,18,19,20,21,22, 23, /* 23dB */
  138005. 24,25,26,27,28,29,30, 31, /* 31dB */
  138006. 32,33,34,35,36,37,38, 39, /* 39dB */
  138007. }},
  138008. /* mode_Z nominal short */
  138009. {{
  138010. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  138011. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  138012. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  138013. 15,16,17,17,17,18,18, 19, /* 31dB */
  138014. 19,19,20,21,22,23,24, 25, /* 39dB */
  138015. }},
  138016. /* mode A short */
  138017. {{
  138018. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  138019. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  138020. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138021. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138022. 11,12,13,14,15,16,17, 18, /* 39dB */
  138023. }},
  138024. /* sub-mode Z long */
  138025. {{
  138026. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138027. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138028. 16,17,18,19,20,21,22, 23, /* 23dB */
  138029. 24,25,26,27,28,29,30, 31, /* 31dB */
  138030. 32,33,34,35,36,37,38, 39, /* 39dB */
  138031. }},
  138032. /* mode_Z nominal long */
  138033. {{
  138034. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138035. 8, 9,10,11,12,12,13, 13, /* 15dB */
  138036. 13,14,14,14,15,15,15, 15, /* 23dB */
  138037. 16,16,17,17,17,18,18, 19, /* 31dB */
  138038. 19,19,20,21,22,23,24, 25, /* 39dB */
  138039. }},
  138040. /* mode A long */
  138041. {{
  138042. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138043. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  138044. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138045. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138046. 11,12,13,14,15,16,17, 18, /* 39dB */
  138047. }}
  138048. };
  138049. /* tonal masking curve level adjustments *************************/
  138050. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  138051. /* 63 125 250 500 1 2 4 8 16 */
  138052. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  138053. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138054. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  138055. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138056. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  138057. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138058. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  138059. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138060. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  138061. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  138062. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138063. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138064. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138065. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138066. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138067. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138068. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138069. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138070. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138071. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138072. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138073. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138074. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138075. };
  138076. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  138077. /* 63 125 250 500 1 2 4 8 16 */
  138078. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  138079. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138080. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  138081. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138082. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  138083. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138084. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  138085. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138086. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  138087. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  138088. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138089. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138090. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138091. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138092. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138093. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138094. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138095. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138096. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138097. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138098. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138099. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138100. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138101. };
  138102. /* noise bias (transition block) */
  138103. static noise3 _psy_noisebias_trans[12]={
  138104. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138105. /* -1 */
  138106. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138107. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138108. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138109. /* 0
  138110. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138111. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  138112. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138113. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138114. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  138115. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138116. /* 1
  138117. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138118. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138119. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138120. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138121. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138122. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138123. /* 2
  138124. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138125. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138126. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  138127. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138128. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138129. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  138130. /* 3
  138131. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138132. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138133. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138134. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138135. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138136. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138137. /* 4
  138138. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138139. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138140. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138141. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138142. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138143. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138144. /* 5
  138145. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138146. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138147. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  138148. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138149. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138150. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  138151. /* 6
  138152. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138153. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138154. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138155. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138156. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138157. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138158. /* 7
  138159. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138160. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  138161. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  138162. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138163. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138164. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138165. /* 8
  138166. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138167. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138168. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138169. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138170. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138171. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138172. /* 9
  138173. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138174. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138175. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138176. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138177. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  138178. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  138179. /* 10 */
  138180. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  138181. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  138182. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138183. };
  138184. /* noise bias (long block) */
  138185. static noise3 _psy_noisebias_long[12]={
  138186. /*63 125 250 500 1k 2k 4k 8k 16k*/
  138187. /* -1 */
  138188. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  138189. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  138190. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138191. /* 0 */
  138192. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138193. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  138194. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138195. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138196. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  138197. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138198. /* 1 */
  138199. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138200. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138201. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138202. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138203. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138204. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138205. /* 2 */
  138206. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138207. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138208. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138209. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138210. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138211. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138212. /* 3 */
  138213. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138214. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138215. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138216. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138217. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138218. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  138219. /* 4 */
  138220. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138221. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138222. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138223. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138224. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138225. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  138226. /* 5 */
  138227. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138228. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138229. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  138230. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138231. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138232. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  138233. /* 6 */
  138234. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138235. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138236. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138237. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138238. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138239. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  138240. /* 7 */
  138241. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138242. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  138243. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138244. /* 8 */
  138245. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  138246. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  138247. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138248. /* 9 */
  138249. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138250. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  138251. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138252. /* 10 */
  138253. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  138254. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  138255. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138256. };
  138257. /* noise bias (impulse block) */
  138258. static noise3 _psy_noisebias_impulse[12]={
  138259. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138260. /* -1 */
  138261. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138262. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138263. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138264. /* 0 */
  138265. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138266. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  138267. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  138268. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138269. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  138270. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138271. /* 1 */
  138272. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138273. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  138274. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  138275. /* 2 */
  138276. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138277. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138278. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138279. /* 3 */
  138280. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138281. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138282. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138283. /* 4 */
  138284. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138285. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138286. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138287. /* 5 */
  138288. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138289. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  138290. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  138291. /* 6
  138292. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138293. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  138294. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  138295. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138296. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  138297. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  138298. /* 7 */
  138299. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138300. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  138301. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  138302. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138303. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  138304. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138305. /* 8 */
  138306. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138307. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  138308. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138309. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138310. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  138311. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138312. /* 9 */
  138313. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138314. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  138315. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138316. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138317. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  138318. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138319. /* 10 */
  138320. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  138321. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  138322. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138323. };
  138324. /* noise bias (padding block) */
  138325. static noise3 _psy_noisebias_padding[12]={
  138326. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138327. /* -1 */
  138328. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138329. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138330. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138331. /* 0 */
  138332. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138333. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  138334. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  138335. /* 1 */
  138336. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138337. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138338. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  138339. /* 2 */
  138340. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138341. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138342. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  138343. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138344. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138345. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138346. /* 3 */
  138347. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138348. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138349. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138350. /* 4 */
  138351. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138352. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  138353. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138354. /* 5 */
  138355. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138356. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  138357. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  138358. /* 6 */
  138359. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138360. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  138361. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  138362. /* 7 */
  138363. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138364. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  138365. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  138366. /* 8 */
  138367. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  138368. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  138369. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  138370. /* 9 */
  138371. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  138372. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  138373. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  138374. /* 10 */
  138375. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  138376. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  138377. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138378. };
  138379. static noiseguard _psy_noiseguards_44[4]={
  138380. {3,3,15},
  138381. {3,3,15},
  138382. {10,10,100},
  138383. {10,10,100},
  138384. };
  138385. static int _psy_tone_suppress[12]={
  138386. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  138387. };
  138388. static int _psy_tone_0dB[12]={
  138389. 90,90,95,95,95,95,105,105,105,105,105,105,
  138390. };
  138391. static int _psy_noise_suppress[12]={
  138392. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  138393. };
  138394. static vorbis_info_psy _psy_info_template={
  138395. /* blockflag */
  138396. -1,
  138397. /* ath_adjatt, ath_maxatt */
  138398. -140.,-140.,
  138399. /* tonemask att boost/decay,suppr,curves */
  138400. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  138401. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  138402. 1, -0.f, .5f, .5f, 0,0,0,
  138403. /* noiseoffset*3, noisecompand, max_curve_dB */
  138404. {{-1},{-1},{-1}},{-1},105.f,
  138405. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  138406. 0,0,-1,-1,0.,
  138407. };
  138408. /* ath ****************/
  138409. static int _psy_ath_floater[12]={
  138410. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  138411. };
  138412. static int _psy_ath_abs[12]={
  138413. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  138414. };
  138415. /* stereo setup. These don't map directly to quality level, there's
  138416. an additional indirection as several of the below may be used in a
  138417. single bitmanaged stream
  138418. ****************/
  138419. /* various stereo possibilities */
  138420. /* stereo mode by base quality level */
  138421. static adj_stereo _psy_stereo_modes_44[12]={
  138422. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  138423. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138424. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138425. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  138426. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138427. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  138428. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138429. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138430. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  138431. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138432. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  138433. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138434. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138435. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138436. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  138437. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  138438. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138439. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138440. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138441. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  138442. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  138443. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  138444. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138445. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138446. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  138447. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138448. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138449. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138450. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  138451. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  138452. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138453. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  138454. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138455. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  138456. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138457. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  138458. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  138459. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138460. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  138461. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138462. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138463. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138464. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138465. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138466. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138467. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  138468. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138469. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  138470. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138471. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138472. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138473. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138474. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138475. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138476. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138477. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138478. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  138479. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138480. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138481. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138482. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138483. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138484. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138485. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138486. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138487. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  138488. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138489. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138490. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138491. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138492. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138493. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138494. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138495. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138496. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  138497. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138498. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138499. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138500. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138501. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  138502. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138503. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138504. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138505. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138506. };
  138507. /* tone master attenuation by base quality mode and bitrate tweak */
  138508. static att3 _psy_tone_masteratt_44[12]={
  138509. {{ 35, 21, 9}, 0, 0}, /* -1 */
  138510. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  138511. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  138512. {{ 25, 12, 2}, 0, 0}, /* 1 */
  138513. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  138514. {{ 20, 9, -3}, 0, 0}, /* 2 */
  138515. {{ 20, 9, -4}, 0, 0}, /* 3 */
  138516. {{ 20, 9, -4}, 0, 0}, /* 4 */
  138517. {{ 20, 6, -6}, 0, 0}, /* 5 */
  138518. {{ 20, 3, -10}, 0, 0}, /* 6 */
  138519. {{ 18, 1, -14}, 0, 0}, /* 7 */
  138520. {{ 18, 0, -16}, 0, 0}, /* 8 */
  138521. {{ 18, -2, -16}, 0, 0}, /* 9 */
  138522. {{ 12, -2, -20}, 0, 0}, /* 10 */
  138523. };
  138524. /* lowpass by mode **************/
  138525. static double _psy_lowpass_44[12]={
  138526. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  138527. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  138528. };
  138529. /* noise normalization **********/
  138530. static int _noise_start_short_44[11]={
  138531. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  138532. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  138533. };
  138534. static int _noise_start_long_44[11]={
  138535. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  138536. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  138537. };
  138538. static int _noise_part_short_44[11]={
  138539. 8,8,8,8,8,8,8,8,8,8,8
  138540. };
  138541. static int _noise_part_long_44[11]={
  138542. 32,32,32,32,32,32,32,32,32,32,32
  138543. };
  138544. static double _noise_thresh_44[11]={
  138545. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  138546. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  138547. };
  138548. static double _noise_thresh_5only[2]={
  138549. .5,.5,
  138550. };
  138551. /********* End of inlined file: psych_44.h *********/
  138552. static double rate_mapping_44_stereo[12]={
  138553. 22500.,32000.,40000.,48000.,56000.,64000.,
  138554. 80000.,96000.,112000.,128000.,160000.,250001.
  138555. };
  138556. static double quality_mapping_44[12]={
  138557. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  138558. };
  138559. static int blocksize_short_44[11]={
  138560. 512,256,256,256,256,256,256,256,256,256,256
  138561. };
  138562. static int blocksize_long_44[11]={
  138563. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  138564. };
  138565. static double _psy_compand_short_mapping[12]={
  138566. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  138567. };
  138568. static double _psy_compand_long_mapping[12]={
  138569. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  138570. };
  138571. static double _global_mapping_44[12]={
  138572. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  138573. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  138574. };
  138575. static int _floor_short_mapping_44[11]={
  138576. 1,0,0,2,2,4,5,5,5,5,5
  138577. };
  138578. static int _floor_long_mapping_44[11]={
  138579. 8,7,7,7,7,7,7,7,7,7,7
  138580. };
  138581. ve_setup_data_template ve_setup_44_stereo={
  138582. 11,
  138583. rate_mapping_44_stereo,
  138584. quality_mapping_44,
  138585. 2,
  138586. 40000,
  138587. 50000,
  138588. blocksize_short_44,
  138589. blocksize_long_44,
  138590. _psy_tone_masteratt_44,
  138591. _psy_tone_0dB,
  138592. _psy_tone_suppress,
  138593. _vp_tonemask_adj_otherblock,
  138594. _vp_tonemask_adj_longblock,
  138595. _vp_tonemask_adj_otherblock,
  138596. _psy_noiseguards_44,
  138597. _psy_noisebias_impulse,
  138598. _psy_noisebias_padding,
  138599. _psy_noisebias_trans,
  138600. _psy_noisebias_long,
  138601. _psy_noise_suppress,
  138602. _psy_compand_44,
  138603. _psy_compand_short_mapping,
  138604. _psy_compand_long_mapping,
  138605. {_noise_start_short_44,_noise_start_long_44},
  138606. {_noise_part_short_44,_noise_part_long_44},
  138607. _noise_thresh_44,
  138608. _psy_ath_floater,
  138609. _psy_ath_abs,
  138610. _psy_lowpass_44,
  138611. _psy_global_44,
  138612. _global_mapping_44,
  138613. _psy_stereo_modes_44,
  138614. _floor_books,
  138615. _floor,
  138616. _floor_short_mapping_44,
  138617. _floor_long_mapping_44,
  138618. _mapres_template_44_stereo
  138619. };
  138620. /********* End of inlined file: setup_44.h *********/
  138621. /********* Start of inlined file: setup_44u.h *********/
  138622. /********* Start of inlined file: residue_44u.h *********/
  138623. /********* Start of inlined file: res_books_uncoupled.h *********/
  138624. static long _vq_quantlist__16u0__p1_0[] = {
  138625. 1,
  138626. 0,
  138627. 2,
  138628. };
  138629. static long _vq_lengthlist__16u0__p1_0[] = {
  138630. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  138631. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  138632. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  138633. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  138634. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  138635. 12,
  138636. };
  138637. static float _vq_quantthresh__16u0__p1_0[] = {
  138638. -0.5, 0.5,
  138639. };
  138640. static long _vq_quantmap__16u0__p1_0[] = {
  138641. 1, 0, 2,
  138642. };
  138643. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  138644. _vq_quantthresh__16u0__p1_0,
  138645. _vq_quantmap__16u0__p1_0,
  138646. 3,
  138647. 3
  138648. };
  138649. static static_codebook _16u0__p1_0 = {
  138650. 4, 81,
  138651. _vq_lengthlist__16u0__p1_0,
  138652. 1, -535822336, 1611661312, 2, 0,
  138653. _vq_quantlist__16u0__p1_0,
  138654. NULL,
  138655. &_vq_auxt__16u0__p1_0,
  138656. NULL,
  138657. 0
  138658. };
  138659. static long _vq_quantlist__16u0__p2_0[] = {
  138660. 1,
  138661. 0,
  138662. 2,
  138663. };
  138664. static long _vq_lengthlist__16u0__p2_0[] = {
  138665. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  138666. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  138667. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  138668. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  138669. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  138670. 8,
  138671. };
  138672. static float _vq_quantthresh__16u0__p2_0[] = {
  138673. -0.5, 0.5,
  138674. };
  138675. static long _vq_quantmap__16u0__p2_0[] = {
  138676. 1, 0, 2,
  138677. };
  138678. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  138679. _vq_quantthresh__16u0__p2_0,
  138680. _vq_quantmap__16u0__p2_0,
  138681. 3,
  138682. 3
  138683. };
  138684. static static_codebook _16u0__p2_0 = {
  138685. 4, 81,
  138686. _vq_lengthlist__16u0__p2_0,
  138687. 1, -535822336, 1611661312, 2, 0,
  138688. _vq_quantlist__16u0__p2_0,
  138689. NULL,
  138690. &_vq_auxt__16u0__p2_0,
  138691. NULL,
  138692. 0
  138693. };
  138694. static long _vq_quantlist__16u0__p3_0[] = {
  138695. 2,
  138696. 1,
  138697. 3,
  138698. 0,
  138699. 4,
  138700. };
  138701. static long _vq_lengthlist__16u0__p3_0[] = {
  138702. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  138703. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  138704. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  138705. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  138706. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  138707. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  138708. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  138709. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  138710. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  138711. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  138712. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  138713. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  138714. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  138715. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  138716. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  138717. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  138718. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  138719. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  138720. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  138721. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  138722. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  138723. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  138724. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  138725. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  138726. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  138727. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  138728. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  138729. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  138730. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  138731. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  138732. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  138733. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  138734. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  138735. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  138736. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  138737. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  138738. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  138739. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  138740. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  138741. 18,
  138742. };
  138743. static float _vq_quantthresh__16u0__p3_0[] = {
  138744. -1.5, -0.5, 0.5, 1.5,
  138745. };
  138746. static long _vq_quantmap__16u0__p3_0[] = {
  138747. 3, 1, 0, 2, 4,
  138748. };
  138749. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  138750. _vq_quantthresh__16u0__p3_0,
  138751. _vq_quantmap__16u0__p3_0,
  138752. 5,
  138753. 5
  138754. };
  138755. static static_codebook _16u0__p3_0 = {
  138756. 4, 625,
  138757. _vq_lengthlist__16u0__p3_0,
  138758. 1, -533725184, 1611661312, 3, 0,
  138759. _vq_quantlist__16u0__p3_0,
  138760. NULL,
  138761. &_vq_auxt__16u0__p3_0,
  138762. NULL,
  138763. 0
  138764. };
  138765. static long _vq_quantlist__16u0__p4_0[] = {
  138766. 2,
  138767. 1,
  138768. 3,
  138769. 0,
  138770. 4,
  138771. };
  138772. static long _vq_lengthlist__16u0__p4_0[] = {
  138773. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  138774. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  138775. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  138776. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  138777. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  138778. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  138779. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  138780. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  138781. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138782. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  138783. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  138784. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  138785. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  138786. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  138787. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  138788. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  138789. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  138790. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  138791. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  138792. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  138793. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  138794. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  138795. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  138796. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  138797. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  138798. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  138799. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  138800. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  138801. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  138802. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  138803. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  138804. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  138805. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  138806. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  138807. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  138808. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  138809. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  138810. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  138811. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  138812. 11,
  138813. };
  138814. static float _vq_quantthresh__16u0__p4_0[] = {
  138815. -1.5, -0.5, 0.5, 1.5,
  138816. };
  138817. static long _vq_quantmap__16u0__p4_0[] = {
  138818. 3, 1, 0, 2, 4,
  138819. };
  138820. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  138821. _vq_quantthresh__16u0__p4_0,
  138822. _vq_quantmap__16u0__p4_0,
  138823. 5,
  138824. 5
  138825. };
  138826. static static_codebook _16u0__p4_0 = {
  138827. 4, 625,
  138828. _vq_lengthlist__16u0__p4_0,
  138829. 1, -533725184, 1611661312, 3, 0,
  138830. _vq_quantlist__16u0__p4_0,
  138831. NULL,
  138832. &_vq_auxt__16u0__p4_0,
  138833. NULL,
  138834. 0
  138835. };
  138836. static long _vq_quantlist__16u0__p5_0[] = {
  138837. 4,
  138838. 3,
  138839. 5,
  138840. 2,
  138841. 6,
  138842. 1,
  138843. 7,
  138844. 0,
  138845. 8,
  138846. };
  138847. static long _vq_lengthlist__16u0__p5_0[] = {
  138848. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138849. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  138850. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  138851. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138852. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  138853. 12,
  138854. };
  138855. static float _vq_quantthresh__16u0__p5_0[] = {
  138856. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138857. };
  138858. static long _vq_quantmap__16u0__p5_0[] = {
  138859. 7, 5, 3, 1, 0, 2, 4, 6,
  138860. 8,
  138861. };
  138862. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  138863. _vq_quantthresh__16u0__p5_0,
  138864. _vq_quantmap__16u0__p5_0,
  138865. 9,
  138866. 9
  138867. };
  138868. static static_codebook _16u0__p5_0 = {
  138869. 2, 81,
  138870. _vq_lengthlist__16u0__p5_0,
  138871. 1, -531628032, 1611661312, 4, 0,
  138872. _vq_quantlist__16u0__p5_0,
  138873. NULL,
  138874. &_vq_auxt__16u0__p5_0,
  138875. NULL,
  138876. 0
  138877. };
  138878. static long _vq_quantlist__16u0__p6_0[] = {
  138879. 6,
  138880. 5,
  138881. 7,
  138882. 4,
  138883. 8,
  138884. 3,
  138885. 9,
  138886. 2,
  138887. 10,
  138888. 1,
  138889. 11,
  138890. 0,
  138891. 12,
  138892. };
  138893. static long _vq_lengthlist__16u0__p6_0[] = {
  138894. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  138895. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  138896. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  138897. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  138898. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  138899. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  138900. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  138901. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  138902. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  138903. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  138904. 18, 0,19, 0, 0, 0, 0, 0, 0,
  138905. };
  138906. static float _vq_quantthresh__16u0__p6_0[] = {
  138907. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138908. 12.5, 17.5, 22.5, 27.5,
  138909. };
  138910. static long _vq_quantmap__16u0__p6_0[] = {
  138911. 11, 9, 7, 5, 3, 1, 0, 2,
  138912. 4, 6, 8, 10, 12,
  138913. };
  138914. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  138915. _vq_quantthresh__16u0__p6_0,
  138916. _vq_quantmap__16u0__p6_0,
  138917. 13,
  138918. 13
  138919. };
  138920. static static_codebook _16u0__p6_0 = {
  138921. 2, 169,
  138922. _vq_lengthlist__16u0__p6_0,
  138923. 1, -526516224, 1616117760, 4, 0,
  138924. _vq_quantlist__16u0__p6_0,
  138925. NULL,
  138926. &_vq_auxt__16u0__p6_0,
  138927. NULL,
  138928. 0
  138929. };
  138930. static long _vq_quantlist__16u0__p6_1[] = {
  138931. 2,
  138932. 1,
  138933. 3,
  138934. 0,
  138935. 4,
  138936. };
  138937. static long _vq_lengthlist__16u0__p6_1[] = {
  138938. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  138939. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  138940. };
  138941. static float _vq_quantthresh__16u0__p6_1[] = {
  138942. -1.5, -0.5, 0.5, 1.5,
  138943. };
  138944. static long _vq_quantmap__16u0__p6_1[] = {
  138945. 3, 1, 0, 2, 4,
  138946. };
  138947. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  138948. _vq_quantthresh__16u0__p6_1,
  138949. _vq_quantmap__16u0__p6_1,
  138950. 5,
  138951. 5
  138952. };
  138953. static static_codebook _16u0__p6_1 = {
  138954. 2, 25,
  138955. _vq_lengthlist__16u0__p6_1,
  138956. 1, -533725184, 1611661312, 3, 0,
  138957. _vq_quantlist__16u0__p6_1,
  138958. NULL,
  138959. &_vq_auxt__16u0__p6_1,
  138960. NULL,
  138961. 0
  138962. };
  138963. static long _vq_quantlist__16u0__p7_0[] = {
  138964. 1,
  138965. 0,
  138966. 2,
  138967. };
  138968. static long _vq_lengthlist__16u0__p7_0[] = {
  138969. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138970. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138971. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138972. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138973. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138974. 7,
  138975. };
  138976. static float _vq_quantthresh__16u0__p7_0[] = {
  138977. -157.5, 157.5,
  138978. };
  138979. static long _vq_quantmap__16u0__p7_0[] = {
  138980. 1, 0, 2,
  138981. };
  138982. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  138983. _vq_quantthresh__16u0__p7_0,
  138984. _vq_quantmap__16u0__p7_0,
  138985. 3,
  138986. 3
  138987. };
  138988. static static_codebook _16u0__p7_0 = {
  138989. 4, 81,
  138990. _vq_lengthlist__16u0__p7_0,
  138991. 1, -518803456, 1628680192, 2, 0,
  138992. _vq_quantlist__16u0__p7_0,
  138993. NULL,
  138994. &_vq_auxt__16u0__p7_0,
  138995. NULL,
  138996. 0
  138997. };
  138998. static long _vq_quantlist__16u0__p7_1[] = {
  138999. 7,
  139000. 6,
  139001. 8,
  139002. 5,
  139003. 9,
  139004. 4,
  139005. 10,
  139006. 3,
  139007. 11,
  139008. 2,
  139009. 12,
  139010. 1,
  139011. 13,
  139012. 0,
  139013. 14,
  139014. };
  139015. static long _vq_lengthlist__16u0__p7_1[] = {
  139016. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  139017. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  139018. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  139019. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  139020. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  139021. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  139022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139023. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139024. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139026. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139027. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139028. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139030. 10,
  139031. };
  139032. static float _vq_quantthresh__16u0__p7_1[] = {
  139033. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139034. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139035. };
  139036. static long _vq_quantmap__16u0__p7_1[] = {
  139037. 13, 11, 9, 7, 5, 3, 1, 0,
  139038. 2, 4, 6, 8, 10, 12, 14,
  139039. };
  139040. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  139041. _vq_quantthresh__16u0__p7_1,
  139042. _vq_quantmap__16u0__p7_1,
  139043. 15,
  139044. 15
  139045. };
  139046. static static_codebook _16u0__p7_1 = {
  139047. 2, 225,
  139048. _vq_lengthlist__16u0__p7_1,
  139049. 1, -520986624, 1620377600, 4, 0,
  139050. _vq_quantlist__16u0__p7_1,
  139051. NULL,
  139052. &_vq_auxt__16u0__p7_1,
  139053. NULL,
  139054. 0
  139055. };
  139056. static long _vq_quantlist__16u0__p7_2[] = {
  139057. 10,
  139058. 9,
  139059. 11,
  139060. 8,
  139061. 12,
  139062. 7,
  139063. 13,
  139064. 6,
  139065. 14,
  139066. 5,
  139067. 15,
  139068. 4,
  139069. 16,
  139070. 3,
  139071. 17,
  139072. 2,
  139073. 18,
  139074. 1,
  139075. 19,
  139076. 0,
  139077. 20,
  139078. };
  139079. static long _vq_lengthlist__16u0__p7_2[] = {
  139080. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  139081. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  139082. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  139083. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  139084. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  139085. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  139086. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  139087. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  139088. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  139089. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  139090. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  139091. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  139092. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  139093. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  139094. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  139095. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  139096. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  139097. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  139098. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  139099. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  139100. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  139101. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  139102. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  139103. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  139104. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  139105. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  139106. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  139107. 10,10,12,11,10,11,11,11,10,
  139108. };
  139109. static float _vq_quantthresh__16u0__p7_2[] = {
  139110. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139111. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139112. 6.5, 7.5, 8.5, 9.5,
  139113. };
  139114. static long _vq_quantmap__16u0__p7_2[] = {
  139115. 19, 17, 15, 13, 11, 9, 7, 5,
  139116. 3, 1, 0, 2, 4, 6, 8, 10,
  139117. 12, 14, 16, 18, 20,
  139118. };
  139119. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  139120. _vq_quantthresh__16u0__p7_2,
  139121. _vq_quantmap__16u0__p7_2,
  139122. 21,
  139123. 21
  139124. };
  139125. static static_codebook _16u0__p7_2 = {
  139126. 2, 441,
  139127. _vq_lengthlist__16u0__p7_2,
  139128. 1, -529268736, 1611661312, 5, 0,
  139129. _vq_quantlist__16u0__p7_2,
  139130. NULL,
  139131. &_vq_auxt__16u0__p7_2,
  139132. NULL,
  139133. 0
  139134. };
  139135. static long _huff_lengthlist__16u0__single[] = {
  139136. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  139137. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  139138. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  139139. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  139140. };
  139141. static static_codebook _huff_book__16u0__single = {
  139142. 2, 64,
  139143. _huff_lengthlist__16u0__single,
  139144. 0, 0, 0, 0, 0,
  139145. NULL,
  139146. NULL,
  139147. NULL,
  139148. NULL,
  139149. 0
  139150. };
  139151. static long _huff_lengthlist__16u1__long[] = {
  139152. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  139153. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  139154. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  139155. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  139156. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  139157. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  139158. 16,13,16,18,
  139159. };
  139160. static static_codebook _huff_book__16u1__long = {
  139161. 2, 100,
  139162. _huff_lengthlist__16u1__long,
  139163. 0, 0, 0, 0, 0,
  139164. NULL,
  139165. NULL,
  139166. NULL,
  139167. NULL,
  139168. 0
  139169. };
  139170. static long _vq_quantlist__16u1__p1_0[] = {
  139171. 1,
  139172. 0,
  139173. 2,
  139174. };
  139175. static long _vq_lengthlist__16u1__p1_0[] = {
  139176. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  139177. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  139178. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  139179. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139180. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  139181. 11,
  139182. };
  139183. static float _vq_quantthresh__16u1__p1_0[] = {
  139184. -0.5, 0.5,
  139185. };
  139186. static long _vq_quantmap__16u1__p1_0[] = {
  139187. 1, 0, 2,
  139188. };
  139189. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  139190. _vq_quantthresh__16u1__p1_0,
  139191. _vq_quantmap__16u1__p1_0,
  139192. 3,
  139193. 3
  139194. };
  139195. static static_codebook _16u1__p1_0 = {
  139196. 4, 81,
  139197. _vq_lengthlist__16u1__p1_0,
  139198. 1, -535822336, 1611661312, 2, 0,
  139199. _vq_quantlist__16u1__p1_0,
  139200. NULL,
  139201. &_vq_auxt__16u1__p1_0,
  139202. NULL,
  139203. 0
  139204. };
  139205. static long _vq_quantlist__16u1__p2_0[] = {
  139206. 1,
  139207. 0,
  139208. 2,
  139209. };
  139210. static long _vq_lengthlist__16u1__p2_0[] = {
  139211. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  139212. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  139213. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  139214. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  139215. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  139216. 8,
  139217. };
  139218. static float _vq_quantthresh__16u1__p2_0[] = {
  139219. -0.5, 0.5,
  139220. };
  139221. static long _vq_quantmap__16u1__p2_0[] = {
  139222. 1, 0, 2,
  139223. };
  139224. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  139225. _vq_quantthresh__16u1__p2_0,
  139226. _vq_quantmap__16u1__p2_0,
  139227. 3,
  139228. 3
  139229. };
  139230. static static_codebook _16u1__p2_0 = {
  139231. 4, 81,
  139232. _vq_lengthlist__16u1__p2_0,
  139233. 1, -535822336, 1611661312, 2, 0,
  139234. _vq_quantlist__16u1__p2_0,
  139235. NULL,
  139236. &_vq_auxt__16u1__p2_0,
  139237. NULL,
  139238. 0
  139239. };
  139240. static long _vq_quantlist__16u1__p3_0[] = {
  139241. 2,
  139242. 1,
  139243. 3,
  139244. 0,
  139245. 4,
  139246. };
  139247. static long _vq_lengthlist__16u1__p3_0[] = {
  139248. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139249. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  139250. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  139251. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139252. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  139253. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  139254. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  139255. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  139256. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139257. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  139258. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  139259. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  139260. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  139261. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  139262. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  139263. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  139264. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139265. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  139266. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  139267. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  139268. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  139269. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  139270. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  139271. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  139272. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  139273. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  139274. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  139275. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  139276. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  139277. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  139278. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  139279. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  139280. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  139281. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  139282. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  139283. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  139284. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  139285. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  139286. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  139287. 16,
  139288. };
  139289. static float _vq_quantthresh__16u1__p3_0[] = {
  139290. -1.5, -0.5, 0.5, 1.5,
  139291. };
  139292. static long _vq_quantmap__16u1__p3_0[] = {
  139293. 3, 1, 0, 2, 4,
  139294. };
  139295. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  139296. _vq_quantthresh__16u1__p3_0,
  139297. _vq_quantmap__16u1__p3_0,
  139298. 5,
  139299. 5
  139300. };
  139301. static static_codebook _16u1__p3_0 = {
  139302. 4, 625,
  139303. _vq_lengthlist__16u1__p3_0,
  139304. 1, -533725184, 1611661312, 3, 0,
  139305. _vq_quantlist__16u1__p3_0,
  139306. NULL,
  139307. &_vq_auxt__16u1__p3_0,
  139308. NULL,
  139309. 0
  139310. };
  139311. static long _vq_quantlist__16u1__p4_0[] = {
  139312. 2,
  139313. 1,
  139314. 3,
  139315. 0,
  139316. 4,
  139317. };
  139318. static long _vq_lengthlist__16u1__p4_0[] = {
  139319. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  139320. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  139321. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  139322. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  139323. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139324. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  139325. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  139326. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  139327. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  139328. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  139329. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  139330. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  139331. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  139332. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  139333. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  139334. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  139335. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  139336. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139337. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  139338. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  139339. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  139340. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  139341. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  139342. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  139343. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  139344. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  139345. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  139346. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  139347. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  139348. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  139349. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  139350. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  139351. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  139352. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  139353. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  139354. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  139355. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  139356. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  139357. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  139358. 11,
  139359. };
  139360. static float _vq_quantthresh__16u1__p4_0[] = {
  139361. -1.5, -0.5, 0.5, 1.5,
  139362. };
  139363. static long _vq_quantmap__16u1__p4_0[] = {
  139364. 3, 1, 0, 2, 4,
  139365. };
  139366. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  139367. _vq_quantthresh__16u1__p4_0,
  139368. _vq_quantmap__16u1__p4_0,
  139369. 5,
  139370. 5
  139371. };
  139372. static static_codebook _16u1__p4_0 = {
  139373. 4, 625,
  139374. _vq_lengthlist__16u1__p4_0,
  139375. 1, -533725184, 1611661312, 3, 0,
  139376. _vq_quantlist__16u1__p4_0,
  139377. NULL,
  139378. &_vq_auxt__16u1__p4_0,
  139379. NULL,
  139380. 0
  139381. };
  139382. static long _vq_quantlist__16u1__p5_0[] = {
  139383. 4,
  139384. 3,
  139385. 5,
  139386. 2,
  139387. 6,
  139388. 1,
  139389. 7,
  139390. 0,
  139391. 8,
  139392. };
  139393. static long _vq_lengthlist__16u1__p5_0[] = {
  139394. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139395. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139396. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139397. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  139398. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  139399. 13,
  139400. };
  139401. static float _vq_quantthresh__16u1__p5_0[] = {
  139402. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139403. };
  139404. static long _vq_quantmap__16u1__p5_0[] = {
  139405. 7, 5, 3, 1, 0, 2, 4, 6,
  139406. 8,
  139407. };
  139408. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  139409. _vq_quantthresh__16u1__p5_0,
  139410. _vq_quantmap__16u1__p5_0,
  139411. 9,
  139412. 9
  139413. };
  139414. static static_codebook _16u1__p5_0 = {
  139415. 2, 81,
  139416. _vq_lengthlist__16u1__p5_0,
  139417. 1, -531628032, 1611661312, 4, 0,
  139418. _vq_quantlist__16u1__p5_0,
  139419. NULL,
  139420. &_vq_auxt__16u1__p5_0,
  139421. NULL,
  139422. 0
  139423. };
  139424. static long _vq_quantlist__16u1__p6_0[] = {
  139425. 4,
  139426. 3,
  139427. 5,
  139428. 2,
  139429. 6,
  139430. 1,
  139431. 7,
  139432. 0,
  139433. 8,
  139434. };
  139435. static long _vq_lengthlist__16u1__p6_0[] = {
  139436. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  139437. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139438. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139439. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139440. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139441. 11,
  139442. };
  139443. static float _vq_quantthresh__16u1__p6_0[] = {
  139444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139445. };
  139446. static long _vq_quantmap__16u1__p6_0[] = {
  139447. 7, 5, 3, 1, 0, 2, 4, 6,
  139448. 8,
  139449. };
  139450. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  139451. _vq_quantthresh__16u1__p6_0,
  139452. _vq_quantmap__16u1__p6_0,
  139453. 9,
  139454. 9
  139455. };
  139456. static static_codebook _16u1__p6_0 = {
  139457. 2, 81,
  139458. _vq_lengthlist__16u1__p6_0,
  139459. 1, -531628032, 1611661312, 4, 0,
  139460. _vq_quantlist__16u1__p6_0,
  139461. NULL,
  139462. &_vq_auxt__16u1__p6_0,
  139463. NULL,
  139464. 0
  139465. };
  139466. static long _vq_quantlist__16u1__p7_0[] = {
  139467. 1,
  139468. 0,
  139469. 2,
  139470. };
  139471. static long _vq_lengthlist__16u1__p7_0[] = {
  139472. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  139473. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  139474. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  139475. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  139476. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  139477. 13,
  139478. };
  139479. static float _vq_quantthresh__16u1__p7_0[] = {
  139480. -5.5, 5.5,
  139481. };
  139482. static long _vq_quantmap__16u1__p7_0[] = {
  139483. 1, 0, 2,
  139484. };
  139485. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  139486. _vq_quantthresh__16u1__p7_0,
  139487. _vq_quantmap__16u1__p7_0,
  139488. 3,
  139489. 3
  139490. };
  139491. static static_codebook _16u1__p7_0 = {
  139492. 4, 81,
  139493. _vq_lengthlist__16u1__p7_0,
  139494. 1, -529137664, 1618345984, 2, 0,
  139495. _vq_quantlist__16u1__p7_0,
  139496. NULL,
  139497. &_vq_auxt__16u1__p7_0,
  139498. NULL,
  139499. 0
  139500. };
  139501. static long _vq_quantlist__16u1__p7_1[] = {
  139502. 5,
  139503. 4,
  139504. 6,
  139505. 3,
  139506. 7,
  139507. 2,
  139508. 8,
  139509. 1,
  139510. 9,
  139511. 0,
  139512. 10,
  139513. };
  139514. static long _vq_lengthlist__16u1__p7_1[] = {
  139515. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  139516. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  139517. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139518. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  139519. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  139520. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  139521. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  139522. 8, 9, 9,10,10,10,10,10,10,
  139523. };
  139524. static float _vq_quantthresh__16u1__p7_1[] = {
  139525. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139526. 3.5, 4.5,
  139527. };
  139528. static long _vq_quantmap__16u1__p7_1[] = {
  139529. 9, 7, 5, 3, 1, 0, 2, 4,
  139530. 6, 8, 10,
  139531. };
  139532. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  139533. _vq_quantthresh__16u1__p7_1,
  139534. _vq_quantmap__16u1__p7_1,
  139535. 11,
  139536. 11
  139537. };
  139538. static static_codebook _16u1__p7_1 = {
  139539. 2, 121,
  139540. _vq_lengthlist__16u1__p7_1,
  139541. 1, -531365888, 1611661312, 4, 0,
  139542. _vq_quantlist__16u1__p7_1,
  139543. NULL,
  139544. &_vq_auxt__16u1__p7_1,
  139545. NULL,
  139546. 0
  139547. };
  139548. static long _vq_quantlist__16u1__p8_0[] = {
  139549. 5,
  139550. 4,
  139551. 6,
  139552. 3,
  139553. 7,
  139554. 2,
  139555. 8,
  139556. 1,
  139557. 9,
  139558. 0,
  139559. 10,
  139560. };
  139561. static long _vq_lengthlist__16u1__p8_0[] = {
  139562. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  139563. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  139564. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  139565. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  139566. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  139567. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  139568. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  139569. 13,14,14,15,15,16,16,15,16,
  139570. };
  139571. static float _vq_quantthresh__16u1__p8_0[] = {
  139572. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139573. 38.5, 49.5,
  139574. };
  139575. static long _vq_quantmap__16u1__p8_0[] = {
  139576. 9, 7, 5, 3, 1, 0, 2, 4,
  139577. 6, 8, 10,
  139578. };
  139579. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  139580. _vq_quantthresh__16u1__p8_0,
  139581. _vq_quantmap__16u1__p8_0,
  139582. 11,
  139583. 11
  139584. };
  139585. static static_codebook _16u1__p8_0 = {
  139586. 2, 121,
  139587. _vq_lengthlist__16u1__p8_0,
  139588. 1, -524582912, 1618345984, 4, 0,
  139589. _vq_quantlist__16u1__p8_0,
  139590. NULL,
  139591. &_vq_auxt__16u1__p8_0,
  139592. NULL,
  139593. 0
  139594. };
  139595. static long _vq_quantlist__16u1__p8_1[] = {
  139596. 5,
  139597. 4,
  139598. 6,
  139599. 3,
  139600. 7,
  139601. 2,
  139602. 8,
  139603. 1,
  139604. 9,
  139605. 0,
  139606. 10,
  139607. };
  139608. static long _vq_lengthlist__16u1__p8_1[] = {
  139609. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  139610. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  139611. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  139612. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139613. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139614. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139615. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139616. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  139617. };
  139618. static float _vq_quantthresh__16u1__p8_1[] = {
  139619. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139620. 3.5, 4.5,
  139621. };
  139622. static long _vq_quantmap__16u1__p8_1[] = {
  139623. 9, 7, 5, 3, 1, 0, 2, 4,
  139624. 6, 8, 10,
  139625. };
  139626. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  139627. _vq_quantthresh__16u1__p8_1,
  139628. _vq_quantmap__16u1__p8_1,
  139629. 11,
  139630. 11
  139631. };
  139632. static static_codebook _16u1__p8_1 = {
  139633. 2, 121,
  139634. _vq_lengthlist__16u1__p8_1,
  139635. 1, -531365888, 1611661312, 4, 0,
  139636. _vq_quantlist__16u1__p8_1,
  139637. NULL,
  139638. &_vq_auxt__16u1__p8_1,
  139639. NULL,
  139640. 0
  139641. };
  139642. static long _vq_quantlist__16u1__p9_0[] = {
  139643. 7,
  139644. 6,
  139645. 8,
  139646. 5,
  139647. 9,
  139648. 4,
  139649. 10,
  139650. 3,
  139651. 11,
  139652. 2,
  139653. 12,
  139654. 1,
  139655. 13,
  139656. 0,
  139657. 14,
  139658. };
  139659. static long _vq_lengthlist__16u1__p9_0[] = {
  139660. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139661. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139662. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139663. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139664. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139665. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139667. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139668. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139669. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139670. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139671. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139672. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139673. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139674. 8,
  139675. };
  139676. static float _vq_quantthresh__16u1__p9_0[] = {
  139677. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139678. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139679. };
  139680. static long _vq_quantmap__16u1__p9_0[] = {
  139681. 13, 11, 9, 7, 5, 3, 1, 0,
  139682. 2, 4, 6, 8, 10, 12, 14,
  139683. };
  139684. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  139685. _vq_quantthresh__16u1__p9_0,
  139686. _vq_quantmap__16u1__p9_0,
  139687. 15,
  139688. 15
  139689. };
  139690. static static_codebook _16u1__p9_0 = {
  139691. 2, 225,
  139692. _vq_lengthlist__16u1__p9_0,
  139693. 1, -514071552, 1627381760, 4, 0,
  139694. _vq_quantlist__16u1__p9_0,
  139695. NULL,
  139696. &_vq_auxt__16u1__p9_0,
  139697. NULL,
  139698. 0
  139699. };
  139700. static long _vq_quantlist__16u1__p9_1[] = {
  139701. 7,
  139702. 6,
  139703. 8,
  139704. 5,
  139705. 9,
  139706. 4,
  139707. 10,
  139708. 3,
  139709. 11,
  139710. 2,
  139711. 12,
  139712. 1,
  139713. 13,
  139714. 0,
  139715. 14,
  139716. };
  139717. static long _vq_lengthlist__16u1__p9_1[] = {
  139718. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  139719. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  139720. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  139721. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  139722. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  139723. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  139724. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  139725. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  139726. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  139727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139728. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139731. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139732. 9,
  139733. };
  139734. static float _vq_quantthresh__16u1__p9_1[] = {
  139735. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139736. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139737. };
  139738. static long _vq_quantmap__16u1__p9_1[] = {
  139739. 13, 11, 9, 7, 5, 3, 1, 0,
  139740. 2, 4, 6, 8, 10, 12, 14,
  139741. };
  139742. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  139743. _vq_quantthresh__16u1__p9_1,
  139744. _vq_quantmap__16u1__p9_1,
  139745. 15,
  139746. 15
  139747. };
  139748. static static_codebook _16u1__p9_1 = {
  139749. 2, 225,
  139750. _vq_lengthlist__16u1__p9_1,
  139751. 1, -522338304, 1620115456, 4, 0,
  139752. _vq_quantlist__16u1__p9_1,
  139753. NULL,
  139754. &_vq_auxt__16u1__p9_1,
  139755. NULL,
  139756. 0
  139757. };
  139758. static long _vq_quantlist__16u1__p9_2[] = {
  139759. 8,
  139760. 7,
  139761. 9,
  139762. 6,
  139763. 10,
  139764. 5,
  139765. 11,
  139766. 4,
  139767. 12,
  139768. 3,
  139769. 13,
  139770. 2,
  139771. 14,
  139772. 1,
  139773. 15,
  139774. 0,
  139775. 16,
  139776. };
  139777. static long _vq_lengthlist__16u1__p9_2[] = {
  139778. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  139779. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  139780. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  139781. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  139782. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  139783. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  139784. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  139785. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  139786. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  139787. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  139788. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  139789. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  139790. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  139791. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  139792. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  139793. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  139794. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  139795. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  139796. 10,
  139797. };
  139798. static float _vq_quantthresh__16u1__p9_2[] = {
  139799. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139800. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139801. };
  139802. static long _vq_quantmap__16u1__p9_2[] = {
  139803. 15, 13, 11, 9, 7, 5, 3, 1,
  139804. 0, 2, 4, 6, 8, 10, 12, 14,
  139805. 16,
  139806. };
  139807. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  139808. _vq_quantthresh__16u1__p9_2,
  139809. _vq_quantmap__16u1__p9_2,
  139810. 17,
  139811. 17
  139812. };
  139813. static static_codebook _16u1__p9_2 = {
  139814. 2, 289,
  139815. _vq_lengthlist__16u1__p9_2,
  139816. 1, -529530880, 1611661312, 5, 0,
  139817. _vq_quantlist__16u1__p9_2,
  139818. NULL,
  139819. &_vq_auxt__16u1__p9_2,
  139820. NULL,
  139821. 0
  139822. };
  139823. static long _huff_lengthlist__16u1__short[] = {
  139824. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  139825. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  139826. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  139827. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  139828. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  139829. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  139830. 16,16,16,16,
  139831. };
  139832. static static_codebook _huff_book__16u1__short = {
  139833. 2, 100,
  139834. _huff_lengthlist__16u1__short,
  139835. 0, 0, 0, 0, 0,
  139836. NULL,
  139837. NULL,
  139838. NULL,
  139839. NULL,
  139840. 0
  139841. };
  139842. static long _huff_lengthlist__16u2__long[] = {
  139843. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  139844. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  139845. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  139846. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  139847. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  139848. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  139849. 13,14,18,18,
  139850. };
  139851. static static_codebook _huff_book__16u2__long = {
  139852. 2, 100,
  139853. _huff_lengthlist__16u2__long,
  139854. 0, 0, 0, 0, 0,
  139855. NULL,
  139856. NULL,
  139857. NULL,
  139858. NULL,
  139859. 0
  139860. };
  139861. static long _huff_lengthlist__16u2__short[] = {
  139862. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  139863. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  139864. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  139865. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  139866. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  139867. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  139868. 16,16,16,16,
  139869. };
  139870. static static_codebook _huff_book__16u2__short = {
  139871. 2, 100,
  139872. _huff_lengthlist__16u2__short,
  139873. 0, 0, 0, 0, 0,
  139874. NULL,
  139875. NULL,
  139876. NULL,
  139877. NULL,
  139878. 0
  139879. };
  139880. static long _vq_quantlist__16u2_p1_0[] = {
  139881. 1,
  139882. 0,
  139883. 2,
  139884. };
  139885. static long _vq_lengthlist__16u2_p1_0[] = {
  139886. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  139887. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  139888. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  139889. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  139890. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  139891. 10,
  139892. };
  139893. static float _vq_quantthresh__16u2_p1_0[] = {
  139894. -0.5, 0.5,
  139895. };
  139896. static long _vq_quantmap__16u2_p1_0[] = {
  139897. 1, 0, 2,
  139898. };
  139899. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  139900. _vq_quantthresh__16u2_p1_0,
  139901. _vq_quantmap__16u2_p1_0,
  139902. 3,
  139903. 3
  139904. };
  139905. static static_codebook _16u2_p1_0 = {
  139906. 4, 81,
  139907. _vq_lengthlist__16u2_p1_0,
  139908. 1, -535822336, 1611661312, 2, 0,
  139909. _vq_quantlist__16u2_p1_0,
  139910. NULL,
  139911. &_vq_auxt__16u2_p1_0,
  139912. NULL,
  139913. 0
  139914. };
  139915. static long _vq_quantlist__16u2_p2_0[] = {
  139916. 2,
  139917. 1,
  139918. 3,
  139919. 0,
  139920. 4,
  139921. };
  139922. static long _vq_lengthlist__16u2_p2_0[] = {
  139923. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139924. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  139925. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  139926. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  139927. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  139928. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  139929. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  139930. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  139931. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139932. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  139933. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  139934. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139935. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  139936. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  139937. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  139938. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  139939. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  139940. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  139941. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  139942. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  139943. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  139944. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  139945. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  139946. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  139947. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  139948. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  139949. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  139950. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  139951. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  139952. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  139953. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  139954. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  139955. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  139956. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  139957. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  139958. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  139959. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  139960. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  139961. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  139962. 13,
  139963. };
  139964. static float _vq_quantthresh__16u2_p2_0[] = {
  139965. -1.5, -0.5, 0.5, 1.5,
  139966. };
  139967. static long _vq_quantmap__16u2_p2_0[] = {
  139968. 3, 1, 0, 2, 4,
  139969. };
  139970. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  139971. _vq_quantthresh__16u2_p2_0,
  139972. _vq_quantmap__16u2_p2_0,
  139973. 5,
  139974. 5
  139975. };
  139976. static static_codebook _16u2_p2_0 = {
  139977. 4, 625,
  139978. _vq_lengthlist__16u2_p2_0,
  139979. 1, -533725184, 1611661312, 3, 0,
  139980. _vq_quantlist__16u2_p2_0,
  139981. NULL,
  139982. &_vq_auxt__16u2_p2_0,
  139983. NULL,
  139984. 0
  139985. };
  139986. static long _vq_quantlist__16u2_p3_0[] = {
  139987. 4,
  139988. 3,
  139989. 5,
  139990. 2,
  139991. 6,
  139992. 1,
  139993. 7,
  139994. 0,
  139995. 8,
  139996. };
  139997. static long _vq_lengthlist__16u2_p3_0[] = {
  139998. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  139999. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  140000. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140001. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140002. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140003. 11,
  140004. };
  140005. static float _vq_quantthresh__16u2_p3_0[] = {
  140006. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140007. };
  140008. static long _vq_quantmap__16u2_p3_0[] = {
  140009. 7, 5, 3, 1, 0, 2, 4, 6,
  140010. 8,
  140011. };
  140012. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  140013. _vq_quantthresh__16u2_p3_0,
  140014. _vq_quantmap__16u2_p3_0,
  140015. 9,
  140016. 9
  140017. };
  140018. static static_codebook _16u2_p3_0 = {
  140019. 2, 81,
  140020. _vq_lengthlist__16u2_p3_0,
  140021. 1, -531628032, 1611661312, 4, 0,
  140022. _vq_quantlist__16u2_p3_0,
  140023. NULL,
  140024. &_vq_auxt__16u2_p3_0,
  140025. NULL,
  140026. 0
  140027. };
  140028. static long _vq_quantlist__16u2_p4_0[] = {
  140029. 8,
  140030. 7,
  140031. 9,
  140032. 6,
  140033. 10,
  140034. 5,
  140035. 11,
  140036. 4,
  140037. 12,
  140038. 3,
  140039. 13,
  140040. 2,
  140041. 14,
  140042. 1,
  140043. 15,
  140044. 0,
  140045. 16,
  140046. };
  140047. static long _vq_lengthlist__16u2_p4_0[] = {
  140048. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  140049. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140050. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140051. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140052. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140053. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  140054. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  140055. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  140056. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  140057. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  140058. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  140059. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  140060. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  140061. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  140062. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  140063. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  140064. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  140065. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  140066. 14,
  140067. };
  140068. static float _vq_quantthresh__16u2_p4_0[] = {
  140069. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140070. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140071. };
  140072. static long _vq_quantmap__16u2_p4_0[] = {
  140073. 15, 13, 11, 9, 7, 5, 3, 1,
  140074. 0, 2, 4, 6, 8, 10, 12, 14,
  140075. 16,
  140076. };
  140077. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  140078. _vq_quantthresh__16u2_p4_0,
  140079. _vq_quantmap__16u2_p4_0,
  140080. 17,
  140081. 17
  140082. };
  140083. static static_codebook _16u2_p4_0 = {
  140084. 2, 289,
  140085. _vq_lengthlist__16u2_p4_0,
  140086. 1, -529530880, 1611661312, 5, 0,
  140087. _vq_quantlist__16u2_p4_0,
  140088. NULL,
  140089. &_vq_auxt__16u2_p4_0,
  140090. NULL,
  140091. 0
  140092. };
  140093. static long _vq_quantlist__16u2_p5_0[] = {
  140094. 1,
  140095. 0,
  140096. 2,
  140097. };
  140098. static long _vq_lengthlist__16u2_p5_0[] = {
  140099. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  140100. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  140101. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  140102. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  140103. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  140104. 10,
  140105. };
  140106. static float _vq_quantthresh__16u2_p5_0[] = {
  140107. -5.5, 5.5,
  140108. };
  140109. static long _vq_quantmap__16u2_p5_0[] = {
  140110. 1, 0, 2,
  140111. };
  140112. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  140113. _vq_quantthresh__16u2_p5_0,
  140114. _vq_quantmap__16u2_p5_0,
  140115. 3,
  140116. 3
  140117. };
  140118. static static_codebook _16u2_p5_0 = {
  140119. 4, 81,
  140120. _vq_lengthlist__16u2_p5_0,
  140121. 1, -529137664, 1618345984, 2, 0,
  140122. _vq_quantlist__16u2_p5_0,
  140123. NULL,
  140124. &_vq_auxt__16u2_p5_0,
  140125. NULL,
  140126. 0
  140127. };
  140128. static long _vq_quantlist__16u2_p5_1[] = {
  140129. 5,
  140130. 4,
  140131. 6,
  140132. 3,
  140133. 7,
  140134. 2,
  140135. 8,
  140136. 1,
  140137. 9,
  140138. 0,
  140139. 10,
  140140. };
  140141. static long _vq_lengthlist__16u2_p5_1[] = {
  140142. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  140143. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  140144. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140145. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140146. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140147. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140148. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140149. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140150. };
  140151. static float _vq_quantthresh__16u2_p5_1[] = {
  140152. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140153. 3.5, 4.5,
  140154. };
  140155. static long _vq_quantmap__16u2_p5_1[] = {
  140156. 9, 7, 5, 3, 1, 0, 2, 4,
  140157. 6, 8, 10,
  140158. };
  140159. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  140160. _vq_quantthresh__16u2_p5_1,
  140161. _vq_quantmap__16u2_p5_1,
  140162. 11,
  140163. 11
  140164. };
  140165. static static_codebook _16u2_p5_1 = {
  140166. 2, 121,
  140167. _vq_lengthlist__16u2_p5_1,
  140168. 1, -531365888, 1611661312, 4, 0,
  140169. _vq_quantlist__16u2_p5_1,
  140170. NULL,
  140171. &_vq_auxt__16u2_p5_1,
  140172. NULL,
  140173. 0
  140174. };
  140175. static long _vq_quantlist__16u2_p6_0[] = {
  140176. 6,
  140177. 5,
  140178. 7,
  140179. 4,
  140180. 8,
  140181. 3,
  140182. 9,
  140183. 2,
  140184. 10,
  140185. 1,
  140186. 11,
  140187. 0,
  140188. 12,
  140189. };
  140190. static long _vq_lengthlist__16u2_p6_0[] = {
  140191. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  140192. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  140193. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  140194. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  140195. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  140196. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  140197. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  140198. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  140199. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  140200. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  140201. 12,13,13,14,14,14,14,15,15,
  140202. };
  140203. static float _vq_quantthresh__16u2_p6_0[] = {
  140204. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140205. 12.5, 17.5, 22.5, 27.5,
  140206. };
  140207. static long _vq_quantmap__16u2_p6_0[] = {
  140208. 11, 9, 7, 5, 3, 1, 0, 2,
  140209. 4, 6, 8, 10, 12,
  140210. };
  140211. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  140212. _vq_quantthresh__16u2_p6_0,
  140213. _vq_quantmap__16u2_p6_0,
  140214. 13,
  140215. 13
  140216. };
  140217. static static_codebook _16u2_p6_0 = {
  140218. 2, 169,
  140219. _vq_lengthlist__16u2_p6_0,
  140220. 1, -526516224, 1616117760, 4, 0,
  140221. _vq_quantlist__16u2_p6_0,
  140222. NULL,
  140223. &_vq_auxt__16u2_p6_0,
  140224. NULL,
  140225. 0
  140226. };
  140227. static long _vq_quantlist__16u2_p6_1[] = {
  140228. 2,
  140229. 1,
  140230. 3,
  140231. 0,
  140232. 4,
  140233. };
  140234. static long _vq_lengthlist__16u2_p6_1[] = {
  140235. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  140236. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  140237. };
  140238. static float _vq_quantthresh__16u2_p6_1[] = {
  140239. -1.5, -0.5, 0.5, 1.5,
  140240. };
  140241. static long _vq_quantmap__16u2_p6_1[] = {
  140242. 3, 1, 0, 2, 4,
  140243. };
  140244. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  140245. _vq_quantthresh__16u2_p6_1,
  140246. _vq_quantmap__16u2_p6_1,
  140247. 5,
  140248. 5
  140249. };
  140250. static static_codebook _16u2_p6_1 = {
  140251. 2, 25,
  140252. _vq_lengthlist__16u2_p6_1,
  140253. 1, -533725184, 1611661312, 3, 0,
  140254. _vq_quantlist__16u2_p6_1,
  140255. NULL,
  140256. &_vq_auxt__16u2_p6_1,
  140257. NULL,
  140258. 0
  140259. };
  140260. static long _vq_quantlist__16u2_p7_0[] = {
  140261. 6,
  140262. 5,
  140263. 7,
  140264. 4,
  140265. 8,
  140266. 3,
  140267. 9,
  140268. 2,
  140269. 10,
  140270. 1,
  140271. 11,
  140272. 0,
  140273. 12,
  140274. };
  140275. static long _vq_lengthlist__16u2_p7_0[] = {
  140276. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  140277. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  140278. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  140279. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  140280. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  140281. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  140282. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  140283. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  140284. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  140285. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  140286. 12,13,13,13,14,14,14,15,14,
  140287. };
  140288. static float _vq_quantthresh__16u2_p7_0[] = {
  140289. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  140290. 27.5, 38.5, 49.5, 60.5,
  140291. };
  140292. static long _vq_quantmap__16u2_p7_0[] = {
  140293. 11, 9, 7, 5, 3, 1, 0, 2,
  140294. 4, 6, 8, 10, 12,
  140295. };
  140296. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  140297. _vq_quantthresh__16u2_p7_0,
  140298. _vq_quantmap__16u2_p7_0,
  140299. 13,
  140300. 13
  140301. };
  140302. static static_codebook _16u2_p7_0 = {
  140303. 2, 169,
  140304. _vq_lengthlist__16u2_p7_0,
  140305. 1, -523206656, 1618345984, 4, 0,
  140306. _vq_quantlist__16u2_p7_0,
  140307. NULL,
  140308. &_vq_auxt__16u2_p7_0,
  140309. NULL,
  140310. 0
  140311. };
  140312. static long _vq_quantlist__16u2_p7_1[] = {
  140313. 5,
  140314. 4,
  140315. 6,
  140316. 3,
  140317. 7,
  140318. 2,
  140319. 8,
  140320. 1,
  140321. 9,
  140322. 0,
  140323. 10,
  140324. };
  140325. static long _vq_lengthlist__16u2_p7_1[] = {
  140326. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  140327. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  140328. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  140329. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  140330. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  140331. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  140332. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  140333. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140334. };
  140335. static float _vq_quantthresh__16u2_p7_1[] = {
  140336. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140337. 3.5, 4.5,
  140338. };
  140339. static long _vq_quantmap__16u2_p7_1[] = {
  140340. 9, 7, 5, 3, 1, 0, 2, 4,
  140341. 6, 8, 10,
  140342. };
  140343. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  140344. _vq_quantthresh__16u2_p7_1,
  140345. _vq_quantmap__16u2_p7_1,
  140346. 11,
  140347. 11
  140348. };
  140349. static static_codebook _16u2_p7_1 = {
  140350. 2, 121,
  140351. _vq_lengthlist__16u2_p7_1,
  140352. 1, -531365888, 1611661312, 4, 0,
  140353. _vq_quantlist__16u2_p7_1,
  140354. NULL,
  140355. &_vq_auxt__16u2_p7_1,
  140356. NULL,
  140357. 0
  140358. };
  140359. static long _vq_quantlist__16u2_p8_0[] = {
  140360. 7,
  140361. 6,
  140362. 8,
  140363. 5,
  140364. 9,
  140365. 4,
  140366. 10,
  140367. 3,
  140368. 11,
  140369. 2,
  140370. 12,
  140371. 1,
  140372. 13,
  140373. 0,
  140374. 14,
  140375. };
  140376. static long _vq_lengthlist__16u2_p8_0[] = {
  140377. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  140378. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  140379. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  140380. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  140381. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  140382. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  140383. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  140384. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  140385. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  140386. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  140387. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  140388. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  140389. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  140390. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  140391. 14,
  140392. };
  140393. static float _vq_quantthresh__16u2_p8_0[] = {
  140394. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140395. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140396. };
  140397. static long _vq_quantmap__16u2_p8_0[] = {
  140398. 13, 11, 9, 7, 5, 3, 1, 0,
  140399. 2, 4, 6, 8, 10, 12, 14,
  140400. };
  140401. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  140402. _vq_quantthresh__16u2_p8_0,
  140403. _vq_quantmap__16u2_p8_0,
  140404. 15,
  140405. 15
  140406. };
  140407. static static_codebook _16u2_p8_0 = {
  140408. 2, 225,
  140409. _vq_lengthlist__16u2_p8_0,
  140410. 1, -520986624, 1620377600, 4, 0,
  140411. _vq_quantlist__16u2_p8_0,
  140412. NULL,
  140413. &_vq_auxt__16u2_p8_0,
  140414. NULL,
  140415. 0
  140416. };
  140417. static long _vq_quantlist__16u2_p8_1[] = {
  140418. 10,
  140419. 9,
  140420. 11,
  140421. 8,
  140422. 12,
  140423. 7,
  140424. 13,
  140425. 6,
  140426. 14,
  140427. 5,
  140428. 15,
  140429. 4,
  140430. 16,
  140431. 3,
  140432. 17,
  140433. 2,
  140434. 18,
  140435. 1,
  140436. 19,
  140437. 0,
  140438. 20,
  140439. };
  140440. static long _vq_lengthlist__16u2_p8_1[] = {
  140441. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  140442. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  140443. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  140444. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  140445. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  140446. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  140447. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  140448. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  140449. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  140450. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  140451. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  140452. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  140453. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  140454. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  140455. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  140456. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  140457. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  140458. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  140459. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  140460. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  140461. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  140462. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  140463. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  140464. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  140465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140466. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  140467. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  140468. 11,11,10,11,11,11,10,11,11,
  140469. };
  140470. static float _vq_quantthresh__16u2_p8_1[] = {
  140471. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140472. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140473. 6.5, 7.5, 8.5, 9.5,
  140474. };
  140475. static long _vq_quantmap__16u2_p8_1[] = {
  140476. 19, 17, 15, 13, 11, 9, 7, 5,
  140477. 3, 1, 0, 2, 4, 6, 8, 10,
  140478. 12, 14, 16, 18, 20,
  140479. };
  140480. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  140481. _vq_quantthresh__16u2_p8_1,
  140482. _vq_quantmap__16u2_p8_1,
  140483. 21,
  140484. 21
  140485. };
  140486. static static_codebook _16u2_p8_1 = {
  140487. 2, 441,
  140488. _vq_lengthlist__16u2_p8_1,
  140489. 1, -529268736, 1611661312, 5, 0,
  140490. _vq_quantlist__16u2_p8_1,
  140491. NULL,
  140492. &_vq_auxt__16u2_p8_1,
  140493. NULL,
  140494. 0
  140495. };
  140496. static long _vq_quantlist__16u2_p9_0[] = {
  140497. 5586,
  140498. 4655,
  140499. 6517,
  140500. 3724,
  140501. 7448,
  140502. 2793,
  140503. 8379,
  140504. 1862,
  140505. 9310,
  140506. 931,
  140507. 10241,
  140508. 0,
  140509. 11172,
  140510. 5521,
  140511. 5651,
  140512. };
  140513. static long _vq_lengthlist__16u2_p9_0[] = {
  140514. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  140515. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140516. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140517. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140518. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140519. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140520. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140521. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140522. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140523. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140526. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  140527. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  140528. 5,
  140529. };
  140530. static float _vq_quantthresh__16u2_p9_0[] = {
  140531. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  140532. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  140533. };
  140534. static long _vq_quantmap__16u2_p9_0[] = {
  140535. 11, 9, 7, 5, 3, 1, 13, 0,
  140536. 14, 2, 4, 6, 8, 10, 12,
  140537. };
  140538. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  140539. _vq_quantthresh__16u2_p9_0,
  140540. _vq_quantmap__16u2_p9_0,
  140541. 15,
  140542. 15
  140543. };
  140544. static static_codebook _16u2_p9_0 = {
  140545. 2, 225,
  140546. _vq_lengthlist__16u2_p9_0,
  140547. 1, -510275072, 1611661312, 14, 0,
  140548. _vq_quantlist__16u2_p9_0,
  140549. NULL,
  140550. &_vq_auxt__16u2_p9_0,
  140551. NULL,
  140552. 0
  140553. };
  140554. static long _vq_quantlist__16u2_p9_1[] = {
  140555. 392,
  140556. 343,
  140557. 441,
  140558. 294,
  140559. 490,
  140560. 245,
  140561. 539,
  140562. 196,
  140563. 588,
  140564. 147,
  140565. 637,
  140566. 98,
  140567. 686,
  140568. 49,
  140569. 735,
  140570. 0,
  140571. 784,
  140572. 388,
  140573. 396,
  140574. };
  140575. static long _vq_lengthlist__16u2_p9_1[] = {
  140576. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  140577. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  140578. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  140579. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  140580. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  140581. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  140582. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140583. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  140584. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  140585. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140586. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140587. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140588. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140589. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140590. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  140591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140596. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  140597. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  140598. 11,11,11,11,11,11,11, 5, 4,
  140599. };
  140600. static float _vq_quantthresh__16u2_p9_1[] = {
  140601. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  140602. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  140603. 318.5, 367.5,
  140604. };
  140605. static long _vq_quantmap__16u2_p9_1[] = {
  140606. 15, 13, 11, 9, 7, 5, 3, 1,
  140607. 17, 0, 18, 2, 4, 6, 8, 10,
  140608. 12, 14, 16,
  140609. };
  140610. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  140611. _vq_quantthresh__16u2_p9_1,
  140612. _vq_quantmap__16u2_p9_1,
  140613. 19,
  140614. 19
  140615. };
  140616. static static_codebook _16u2_p9_1 = {
  140617. 2, 361,
  140618. _vq_lengthlist__16u2_p9_1,
  140619. 1, -518488064, 1611661312, 10, 0,
  140620. _vq_quantlist__16u2_p9_1,
  140621. NULL,
  140622. &_vq_auxt__16u2_p9_1,
  140623. NULL,
  140624. 0
  140625. };
  140626. static long _vq_quantlist__16u2_p9_2[] = {
  140627. 24,
  140628. 23,
  140629. 25,
  140630. 22,
  140631. 26,
  140632. 21,
  140633. 27,
  140634. 20,
  140635. 28,
  140636. 19,
  140637. 29,
  140638. 18,
  140639. 30,
  140640. 17,
  140641. 31,
  140642. 16,
  140643. 32,
  140644. 15,
  140645. 33,
  140646. 14,
  140647. 34,
  140648. 13,
  140649. 35,
  140650. 12,
  140651. 36,
  140652. 11,
  140653. 37,
  140654. 10,
  140655. 38,
  140656. 9,
  140657. 39,
  140658. 8,
  140659. 40,
  140660. 7,
  140661. 41,
  140662. 6,
  140663. 42,
  140664. 5,
  140665. 43,
  140666. 4,
  140667. 44,
  140668. 3,
  140669. 45,
  140670. 2,
  140671. 46,
  140672. 1,
  140673. 47,
  140674. 0,
  140675. 48,
  140676. };
  140677. static long _vq_lengthlist__16u2_p9_2[] = {
  140678. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  140679. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  140680. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  140681. 11,
  140682. };
  140683. static float _vq_quantthresh__16u2_p9_2[] = {
  140684. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  140685. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  140686. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140687. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140688. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  140689. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  140690. };
  140691. static long _vq_quantmap__16u2_p9_2[] = {
  140692. 47, 45, 43, 41, 39, 37, 35, 33,
  140693. 31, 29, 27, 25, 23, 21, 19, 17,
  140694. 15, 13, 11, 9, 7, 5, 3, 1,
  140695. 0, 2, 4, 6, 8, 10, 12, 14,
  140696. 16, 18, 20, 22, 24, 26, 28, 30,
  140697. 32, 34, 36, 38, 40, 42, 44, 46,
  140698. 48,
  140699. };
  140700. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  140701. _vq_quantthresh__16u2_p9_2,
  140702. _vq_quantmap__16u2_p9_2,
  140703. 49,
  140704. 49
  140705. };
  140706. static static_codebook _16u2_p9_2 = {
  140707. 1, 49,
  140708. _vq_lengthlist__16u2_p9_2,
  140709. 1, -526909440, 1611661312, 6, 0,
  140710. _vq_quantlist__16u2_p9_2,
  140711. NULL,
  140712. &_vq_auxt__16u2_p9_2,
  140713. NULL,
  140714. 0
  140715. };
  140716. static long _vq_quantlist__8u0__p1_0[] = {
  140717. 1,
  140718. 0,
  140719. 2,
  140720. };
  140721. static long _vq_lengthlist__8u0__p1_0[] = {
  140722. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  140723. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  140724. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  140725. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  140726. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  140727. 11,
  140728. };
  140729. static float _vq_quantthresh__8u0__p1_0[] = {
  140730. -0.5, 0.5,
  140731. };
  140732. static long _vq_quantmap__8u0__p1_0[] = {
  140733. 1, 0, 2,
  140734. };
  140735. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  140736. _vq_quantthresh__8u0__p1_0,
  140737. _vq_quantmap__8u0__p1_0,
  140738. 3,
  140739. 3
  140740. };
  140741. static static_codebook _8u0__p1_0 = {
  140742. 4, 81,
  140743. _vq_lengthlist__8u0__p1_0,
  140744. 1, -535822336, 1611661312, 2, 0,
  140745. _vq_quantlist__8u0__p1_0,
  140746. NULL,
  140747. &_vq_auxt__8u0__p1_0,
  140748. NULL,
  140749. 0
  140750. };
  140751. static long _vq_quantlist__8u0__p2_0[] = {
  140752. 1,
  140753. 0,
  140754. 2,
  140755. };
  140756. static long _vq_lengthlist__8u0__p2_0[] = {
  140757. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  140758. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  140759. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  140760. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  140761. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  140762. 8,
  140763. };
  140764. static float _vq_quantthresh__8u0__p2_0[] = {
  140765. -0.5, 0.5,
  140766. };
  140767. static long _vq_quantmap__8u0__p2_0[] = {
  140768. 1, 0, 2,
  140769. };
  140770. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  140771. _vq_quantthresh__8u0__p2_0,
  140772. _vq_quantmap__8u0__p2_0,
  140773. 3,
  140774. 3
  140775. };
  140776. static static_codebook _8u0__p2_0 = {
  140777. 4, 81,
  140778. _vq_lengthlist__8u0__p2_0,
  140779. 1, -535822336, 1611661312, 2, 0,
  140780. _vq_quantlist__8u0__p2_0,
  140781. NULL,
  140782. &_vq_auxt__8u0__p2_0,
  140783. NULL,
  140784. 0
  140785. };
  140786. static long _vq_quantlist__8u0__p3_0[] = {
  140787. 2,
  140788. 1,
  140789. 3,
  140790. 0,
  140791. 4,
  140792. };
  140793. static long _vq_lengthlist__8u0__p3_0[] = {
  140794. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140795. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140796. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  140797. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140798. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  140799. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  140800. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  140801. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  140802. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  140803. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  140804. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  140805. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  140806. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  140807. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  140808. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  140809. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  140810. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  140811. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  140812. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  140813. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  140814. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  140815. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  140816. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  140817. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  140818. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  140819. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  140820. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  140821. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  140822. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  140823. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  140824. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  140825. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  140826. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  140827. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  140828. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  140829. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  140830. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  140831. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  140832. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  140833. 16,
  140834. };
  140835. static float _vq_quantthresh__8u0__p3_0[] = {
  140836. -1.5, -0.5, 0.5, 1.5,
  140837. };
  140838. static long _vq_quantmap__8u0__p3_0[] = {
  140839. 3, 1, 0, 2, 4,
  140840. };
  140841. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  140842. _vq_quantthresh__8u0__p3_0,
  140843. _vq_quantmap__8u0__p3_0,
  140844. 5,
  140845. 5
  140846. };
  140847. static static_codebook _8u0__p3_0 = {
  140848. 4, 625,
  140849. _vq_lengthlist__8u0__p3_0,
  140850. 1, -533725184, 1611661312, 3, 0,
  140851. _vq_quantlist__8u0__p3_0,
  140852. NULL,
  140853. &_vq_auxt__8u0__p3_0,
  140854. NULL,
  140855. 0
  140856. };
  140857. static long _vq_quantlist__8u0__p4_0[] = {
  140858. 2,
  140859. 1,
  140860. 3,
  140861. 0,
  140862. 4,
  140863. };
  140864. static long _vq_lengthlist__8u0__p4_0[] = {
  140865. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  140866. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  140867. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  140868. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  140869. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  140870. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  140871. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  140872. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  140873. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  140874. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  140875. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  140876. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  140877. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  140878. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  140879. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  140880. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  140881. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  140882. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  140883. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  140884. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  140885. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  140886. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  140887. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  140888. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  140889. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  140890. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  140891. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  140892. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  140893. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  140894. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  140895. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  140896. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  140897. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  140898. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  140899. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  140900. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  140901. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  140902. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  140903. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  140904. 12,
  140905. };
  140906. static float _vq_quantthresh__8u0__p4_0[] = {
  140907. -1.5, -0.5, 0.5, 1.5,
  140908. };
  140909. static long _vq_quantmap__8u0__p4_0[] = {
  140910. 3, 1, 0, 2, 4,
  140911. };
  140912. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  140913. _vq_quantthresh__8u0__p4_0,
  140914. _vq_quantmap__8u0__p4_0,
  140915. 5,
  140916. 5
  140917. };
  140918. static static_codebook _8u0__p4_0 = {
  140919. 4, 625,
  140920. _vq_lengthlist__8u0__p4_0,
  140921. 1, -533725184, 1611661312, 3, 0,
  140922. _vq_quantlist__8u0__p4_0,
  140923. NULL,
  140924. &_vq_auxt__8u0__p4_0,
  140925. NULL,
  140926. 0
  140927. };
  140928. static long _vq_quantlist__8u0__p5_0[] = {
  140929. 4,
  140930. 3,
  140931. 5,
  140932. 2,
  140933. 6,
  140934. 1,
  140935. 7,
  140936. 0,
  140937. 8,
  140938. };
  140939. static long _vq_lengthlist__8u0__p5_0[] = {
  140940. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  140941. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  140942. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140943. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140944. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  140945. 12,
  140946. };
  140947. static float _vq_quantthresh__8u0__p5_0[] = {
  140948. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140949. };
  140950. static long _vq_quantmap__8u0__p5_0[] = {
  140951. 7, 5, 3, 1, 0, 2, 4, 6,
  140952. 8,
  140953. };
  140954. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  140955. _vq_quantthresh__8u0__p5_0,
  140956. _vq_quantmap__8u0__p5_0,
  140957. 9,
  140958. 9
  140959. };
  140960. static static_codebook _8u0__p5_0 = {
  140961. 2, 81,
  140962. _vq_lengthlist__8u0__p5_0,
  140963. 1, -531628032, 1611661312, 4, 0,
  140964. _vq_quantlist__8u0__p5_0,
  140965. NULL,
  140966. &_vq_auxt__8u0__p5_0,
  140967. NULL,
  140968. 0
  140969. };
  140970. static long _vq_quantlist__8u0__p6_0[] = {
  140971. 6,
  140972. 5,
  140973. 7,
  140974. 4,
  140975. 8,
  140976. 3,
  140977. 9,
  140978. 2,
  140979. 10,
  140980. 1,
  140981. 11,
  140982. 0,
  140983. 12,
  140984. };
  140985. static long _vq_lengthlist__8u0__p6_0[] = {
  140986. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  140987. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  140988. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  140989. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  140990. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  140991. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  140992. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  140993. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  140994. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  140995. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  140996. 16, 0,15, 0,17, 0, 0, 0, 0,
  140997. };
  140998. static float _vq_quantthresh__8u0__p6_0[] = {
  140999. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141000. 12.5, 17.5, 22.5, 27.5,
  141001. };
  141002. static long _vq_quantmap__8u0__p6_0[] = {
  141003. 11, 9, 7, 5, 3, 1, 0, 2,
  141004. 4, 6, 8, 10, 12,
  141005. };
  141006. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  141007. _vq_quantthresh__8u0__p6_0,
  141008. _vq_quantmap__8u0__p6_0,
  141009. 13,
  141010. 13
  141011. };
  141012. static static_codebook _8u0__p6_0 = {
  141013. 2, 169,
  141014. _vq_lengthlist__8u0__p6_0,
  141015. 1, -526516224, 1616117760, 4, 0,
  141016. _vq_quantlist__8u0__p6_0,
  141017. NULL,
  141018. &_vq_auxt__8u0__p6_0,
  141019. NULL,
  141020. 0
  141021. };
  141022. static long _vq_quantlist__8u0__p6_1[] = {
  141023. 2,
  141024. 1,
  141025. 3,
  141026. 0,
  141027. 4,
  141028. };
  141029. static long _vq_lengthlist__8u0__p6_1[] = {
  141030. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  141031. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  141032. };
  141033. static float _vq_quantthresh__8u0__p6_1[] = {
  141034. -1.5, -0.5, 0.5, 1.5,
  141035. };
  141036. static long _vq_quantmap__8u0__p6_1[] = {
  141037. 3, 1, 0, 2, 4,
  141038. };
  141039. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  141040. _vq_quantthresh__8u0__p6_1,
  141041. _vq_quantmap__8u0__p6_1,
  141042. 5,
  141043. 5
  141044. };
  141045. static static_codebook _8u0__p6_1 = {
  141046. 2, 25,
  141047. _vq_lengthlist__8u0__p6_1,
  141048. 1, -533725184, 1611661312, 3, 0,
  141049. _vq_quantlist__8u0__p6_1,
  141050. NULL,
  141051. &_vq_auxt__8u0__p6_1,
  141052. NULL,
  141053. 0
  141054. };
  141055. static long _vq_quantlist__8u0__p7_0[] = {
  141056. 1,
  141057. 0,
  141058. 2,
  141059. };
  141060. static long _vq_lengthlist__8u0__p7_0[] = {
  141061. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141062. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141063. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141064. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141065. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141066. 7,
  141067. };
  141068. static float _vq_quantthresh__8u0__p7_0[] = {
  141069. -157.5, 157.5,
  141070. };
  141071. static long _vq_quantmap__8u0__p7_0[] = {
  141072. 1, 0, 2,
  141073. };
  141074. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  141075. _vq_quantthresh__8u0__p7_0,
  141076. _vq_quantmap__8u0__p7_0,
  141077. 3,
  141078. 3
  141079. };
  141080. static static_codebook _8u0__p7_0 = {
  141081. 4, 81,
  141082. _vq_lengthlist__8u0__p7_0,
  141083. 1, -518803456, 1628680192, 2, 0,
  141084. _vq_quantlist__8u0__p7_0,
  141085. NULL,
  141086. &_vq_auxt__8u0__p7_0,
  141087. NULL,
  141088. 0
  141089. };
  141090. static long _vq_quantlist__8u0__p7_1[] = {
  141091. 7,
  141092. 6,
  141093. 8,
  141094. 5,
  141095. 9,
  141096. 4,
  141097. 10,
  141098. 3,
  141099. 11,
  141100. 2,
  141101. 12,
  141102. 1,
  141103. 13,
  141104. 0,
  141105. 14,
  141106. };
  141107. static long _vq_lengthlist__8u0__p7_1[] = {
  141108. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  141109. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  141110. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  141111. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  141112. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  141113. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  141114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141120. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  141121. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141122. 10,
  141123. };
  141124. static float _vq_quantthresh__8u0__p7_1[] = {
  141125. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141126. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141127. };
  141128. static long _vq_quantmap__8u0__p7_1[] = {
  141129. 13, 11, 9, 7, 5, 3, 1, 0,
  141130. 2, 4, 6, 8, 10, 12, 14,
  141131. };
  141132. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  141133. _vq_quantthresh__8u0__p7_1,
  141134. _vq_quantmap__8u0__p7_1,
  141135. 15,
  141136. 15
  141137. };
  141138. static static_codebook _8u0__p7_1 = {
  141139. 2, 225,
  141140. _vq_lengthlist__8u0__p7_1,
  141141. 1, -520986624, 1620377600, 4, 0,
  141142. _vq_quantlist__8u0__p7_1,
  141143. NULL,
  141144. &_vq_auxt__8u0__p7_1,
  141145. NULL,
  141146. 0
  141147. };
  141148. static long _vq_quantlist__8u0__p7_2[] = {
  141149. 10,
  141150. 9,
  141151. 11,
  141152. 8,
  141153. 12,
  141154. 7,
  141155. 13,
  141156. 6,
  141157. 14,
  141158. 5,
  141159. 15,
  141160. 4,
  141161. 16,
  141162. 3,
  141163. 17,
  141164. 2,
  141165. 18,
  141166. 1,
  141167. 19,
  141168. 0,
  141169. 20,
  141170. };
  141171. static long _vq_lengthlist__8u0__p7_2[] = {
  141172. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  141173. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  141174. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  141175. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  141176. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  141177. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  141178. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  141179. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  141180. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  141181. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  141182. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  141183. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  141184. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  141185. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  141186. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  141187. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  141188. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  141189. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  141190. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  141191. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  141192. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  141193. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  141194. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  141195. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  141196. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  141197. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  141198. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  141199. 11,12,11,11,11,10,10,11,11,
  141200. };
  141201. static float _vq_quantthresh__8u0__p7_2[] = {
  141202. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141203. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141204. 6.5, 7.5, 8.5, 9.5,
  141205. };
  141206. static long _vq_quantmap__8u0__p7_2[] = {
  141207. 19, 17, 15, 13, 11, 9, 7, 5,
  141208. 3, 1, 0, 2, 4, 6, 8, 10,
  141209. 12, 14, 16, 18, 20,
  141210. };
  141211. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  141212. _vq_quantthresh__8u0__p7_2,
  141213. _vq_quantmap__8u0__p7_2,
  141214. 21,
  141215. 21
  141216. };
  141217. static static_codebook _8u0__p7_2 = {
  141218. 2, 441,
  141219. _vq_lengthlist__8u0__p7_2,
  141220. 1, -529268736, 1611661312, 5, 0,
  141221. _vq_quantlist__8u0__p7_2,
  141222. NULL,
  141223. &_vq_auxt__8u0__p7_2,
  141224. NULL,
  141225. 0
  141226. };
  141227. static long _huff_lengthlist__8u0__single[] = {
  141228. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  141229. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  141230. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  141231. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  141232. };
  141233. static static_codebook _huff_book__8u0__single = {
  141234. 2, 64,
  141235. _huff_lengthlist__8u0__single,
  141236. 0, 0, 0, 0, 0,
  141237. NULL,
  141238. NULL,
  141239. NULL,
  141240. NULL,
  141241. 0
  141242. };
  141243. static long _vq_quantlist__8u1__p1_0[] = {
  141244. 1,
  141245. 0,
  141246. 2,
  141247. };
  141248. static long _vq_lengthlist__8u1__p1_0[] = {
  141249. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  141250. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  141251. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  141252. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  141253. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  141254. 10,
  141255. };
  141256. static float _vq_quantthresh__8u1__p1_0[] = {
  141257. -0.5, 0.5,
  141258. };
  141259. static long _vq_quantmap__8u1__p1_0[] = {
  141260. 1, 0, 2,
  141261. };
  141262. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  141263. _vq_quantthresh__8u1__p1_0,
  141264. _vq_quantmap__8u1__p1_0,
  141265. 3,
  141266. 3
  141267. };
  141268. static static_codebook _8u1__p1_0 = {
  141269. 4, 81,
  141270. _vq_lengthlist__8u1__p1_0,
  141271. 1, -535822336, 1611661312, 2, 0,
  141272. _vq_quantlist__8u1__p1_0,
  141273. NULL,
  141274. &_vq_auxt__8u1__p1_0,
  141275. NULL,
  141276. 0
  141277. };
  141278. static long _vq_quantlist__8u1__p2_0[] = {
  141279. 1,
  141280. 0,
  141281. 2,
  141282. };
  141283. static long _vq_lengthlist__8u1__p2_0[] = {
  141284. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  141285. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  141286. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  141287. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  141288. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  141289. 7,
  141290. };
  141291. static float _vq_quantthresh__8u1__p2_0[] = {
  141292. -0.5, 0.5,
  141293. };
  141294. static long _vq_quantmap__8u1__p2_0[] = {
  141295. 1, 0, 2,
  141296. };
  141297. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  141298. _vq_quantthresh__8u1__p2_0,
  141299. _vq_quantmap__8u1__p2_0,
  141300. 3,
  141301. 3
  141302. };
  141303. static static_codebook _8u1__p2_0 = {
  141304. 4, 81,
  141305. _vq_lengthlist__8u1__p2_0,
  141306. 1, -535822336, 1611661312, 2, 0,
  141307. _vq_quantlist__8u1__p2_0,
  141308. NULL,
  141309. &_vq_auxt__8u1__p2_0,
  141310. NULL,
  141311. 0
  141312. };
  141313. static long _vq_quantlist__8u1__p3_0[] = {
  141314. 2,
  141315. 1,
  141316. 3,
  141317. 0,
  141318. 4,
  141319. };
  141320. static long _vq_lengthlist__8u1__p3_0[] = {
  141321. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  141322. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  141323. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  141324. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  141325. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  141326. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  141327. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  141328. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  141329. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  141330. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  141331. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  141332. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  141333. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  141334. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  141335. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  141336. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  141337. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  141338. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  141339. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  141340. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  141341. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  141342. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  141343. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  141344. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  141345. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  141346. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  141347. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  141348. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  141349. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  141350. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  141351. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  141352. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  141353. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  141354. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  141355. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  141356. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  141357. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  141358. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  141359. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  141360. 16,
  141361. };
  141362. static float _vq_quantthresh__8u1__p3_0[] = {
  141363. -1.5, -0.5, 0.5, 1.5,
  141364. };
  141365. static long _vq_quantmap__8u1__p3_0[] = {
  141366. 3, 1, 0, 2, 4,
  141367. };
  141368. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  141369. _vq_quantthresh__8u1__p3_0,
  141370. _vq_quantmap__8u1__p3_0,
  141371. 5,
  141372. 5
  141373. };
  141374. static static_codebook _8u1__p3_0 = {
  141375. 4, 625,
  141376. _vq_lengthlist__8u1__p3_0,
  141377. 1, -533725184, 1611661312, 3, 0,
  141378. _vq_quantlist__8u1__p3_0,
  141379. NULL,
  141380. &_vq_auxt__8u1__p3_0,
  141381. NULL,
  141382. 0
  141383. };
  141384. static long _vq_quantlist__8u1__p4_0[] = {
  141385. 2,
  141386. 1,
  141387. 3,
  141388. 0,
  141389. 4,
  141390. };
  141391. static long _vq_lengthlist__8u1__p4_0[] = {
  141392. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  141393. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  141394. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  141395. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  141396. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  141397. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  141398. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  141399. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  141400. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  141401. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  141402. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  141403. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  141404. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  141405. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  141406. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  141407. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  141408. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  141409. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  141410. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  141411. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  141412. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  141413. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  141414. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  141415. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  141416. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  141417. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  141418. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  141419. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  141420. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  141421. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  141422. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  141423. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  141424. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  141425. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  141426. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  141427. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  141428. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  141429. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  141430. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  141431. 10,
  141432. };
  141433. static float _vq_quantthresh__8u1__p4_0[] = {
  141434. -1.5, -0.5, 0.5, 1.5,
  141435. };
  141436. static long _vq_quantmap__8u1__p4_0[] = {
  141437. 3, 1, 0, 2, 4,
  141438. };
  141439. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  141440. _vq_quantthresh__8u1__p4_0,
  141441. _vq_quantmap__8u1__p4_0,
  141442. 5,
  141443. 5
  141444. };
  141445. static static_codebook _8u1__p4_0 = {
  141446. 4, 625,
  141447. _vq_lengthlist__8u1__p4_0,
  141448. 1, -533725184, 1611661312, 3, 0,
  141449. _vq_quantlist__8u1__p4_0,
  141450. NULL,
  141451. &_vq_auxt__8u1__p4_0,
  141452. NULL,
  141453. 0
  141454. };
  141455. static long _vq_quantlist__8u1__p5_0[] = {
  141456. 4,
  141457. 3,
  141458. 5,
  141459. 2,
  141460. 6,
  141461. 1,
  141462. 7,
  141463. 0,
  141464. 8,
  141465. };
  141466. static long _vq_lengthlist__8u1__p5_0[] = {
  141467. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  141468. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141469. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141470. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  141471. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  141472. 13,
  141473. };
  141474. static float _vq_quantthresh__8u1__p5_0[] = {
  141475. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141476. };
  141477. static long _vq_quantmap__8u1__p5_0[] = {
  141478. 7, 5, 3, 1, 0, 2, 4, 6,
  141479. 8,
  141480. };
  141481. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  141482. _vq_quantthresh__8u1__p5_0,
  141483. _vq_quantmap__8u1__p5_0,
  141484. 9,
  141485. 9
  141486. };
  141487. static static_codebook _8u1__p5_0 = {
  141488. 2, 81,
  141489. _vq_lengthlist__8u1__p5_0,
  141490. 1, -531628032, 1611661312, 4, 0,
  141491. _vq_quantlist__8u1__p5_0,
  141492. NULL,
  141493. &_vq_auxt__8u1__p5_0,
  141494. NULL,
  141495. 0
  141496. };
  141497. static long _vq_quantlist__8u1__p6_0[] = {
  141498. 4,
  141499. 3,
  141500. 5,
  141501. 2,
  141502. 6,
  141503. 1,
  141504. 7,
  141505. 0,
  141506. 8,
  141507. };
  141508. static long _vq_lengthlist__8u1__p6_0[] = {
  141509. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  141510. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  141511. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  141512. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  141513. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141514. 10,
  141515. };
  141516. static float _vq_quantthresh__8u1__p6_0[] = {
  141517. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141518. };
  141519. static long _vq_quantmap__8u1__p6_0[] = {
  141520. 7, 5, 3, 1, 0, 2, 4, 6,
  141521. 8,
  141522. };
  141523. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  141524. _vq_quantthresh__8u1__p6_0,
  141525. _vq_quantmap__8u1__p6_0,
  141526. 9,
  141527. 9
  141528. };
  141529. static static_codebook _8u1__p6_0 = {
  141530. 2, 81,
  141531. _vq_lengthlist__8u1__p6_0,
  141532. 1, -531628032, 1611661312, 4, 0,
  141533. _vq_quantlist__8u1__p6_0,
  141534. NULL,
  141535. &_vq_auxt__8u1__p6_0,
  141536. NULL,
  141537. 0
  141538. };
  141539. static long _vq_quantlist__8u1__p7_0[] = {
  141540. 1,
  141541. 0,
  141542. 2,
  141543. };
  141544. static long _vq_lengthlist__8u1__p7_0[] = {
  141545. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  141546. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  141547. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  141548. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  141549. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  141550. 11,
  141551. };
  141552. static float _vq_quantthresh__8u1__p7_0[] = {
  141553. -5.5, 5.5,
  141554. };
  141555. static long _vq_quantmap__8u1__p7_0[] = {
  141556. 1, 0, 2,
  141557. };
  141558. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  141559. _vq_quantthresh__8u1__p7_0,
  141560. _vq_quantmap__8u1__p7_0,
  141561. 3,
  141562. 3
  141563. };
  141564. static static_codebook _8u1__p7_0 = {
  141565. 4, 81,
  141566. _vq_lengthlist__8u1__p7_0,
  141567. 1, -529137664, 1618345984, 2, 0,
  141568. _vq_quantlist__8u1__p7_0,
  141569. NULL,
  141570. &_vq_auxt__8u1__p7_0,
  141571. NULL,
  141572. 0
  141573. };
  141574. static long _vq_quantlist__8u1__p7_1[] = {
  141575. 5,
  141576. 4,
  141577. 6,
  141578. 3,
  141579. 7,
  141580. 2,
  141581. 8,
  141582. 1,
  141583. 9,
  141584. 0,
  141585. 10,
  141586. };
  141587. static long _vq_lengthlist__8u1__p7_1[] = {
  141588. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  141589. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  141590. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  141591. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141592. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  141593. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  141594. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  141595. 9, 9, 9, 9, 9,10,10,10,10,
  141596. };
  141597. static float _vq_quantthresh__8u1__p7_1[] = {
  141598. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141599. 3.5, 4.5,
  141600. };
  141601. static long _vq_quantmap__8u1__p7_1[] = {
  141602. 9, 7, 5, 3, 1, 0, 2, 4,
  141603. 6, 8, 10,
  141604. };
  141605. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  141606. _vq_quantthresh__8u1__p7_1,
  141607. _vq_quantmap__8u1__p7_1,
  141608. 11,
  141609. 11
  141610. };
  141611. static static_codebook _8u1__p7_1 = {
  141612. 2, 121,
  141613. _vq_lengthlist__8u1__p7_1,
  141614. 1, -531365888, 1611661312, 4, 0,
  141615. _vq_quantlist__8u1__p7_1,
  141616. NULL,
  141617. &_vq_auxt__8u1__p7_1,
  141618. NULL,
  141619. 0
  141620. };
  141621. static long _vq_quantlist__8u1__p8_0[] = {
  141622. 5,
  141623. 4,
  141624. 6,
  141625. 3,
  141626. 7,
  141627. 2,
  141628. 8,
  141629. 1,
  141630. 9,
  141631. 0,
  141632. 10,
  141633. };
  141634. static long _vq_lengthlist__8u1__p8_0[] = {
  141635. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  141636. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  141637. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  141638. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  141639. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  141640. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  141641. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  141642. 12,13,13,14,14,15,15,15,15,
  141643. };
  141644. static float _vq_quantthresh__8u1__p8_0[] = {
  141645. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  141646. 38.5, 49.5,
  141647. };
  141648. static long _vq_quantmap__8u1__p8_0[] = {
  141649. 9, 7, 5, 3, 1, 0, 2, 4,
  141650. 6, 8, 10,
  141651. };
  141652. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  141653. _vq_quantthresh__8u1__p8_0,
  141654. _vq_quantmap__8u1__p8_0,
  141655. 11,
  141656. 11
  141657. };
  141658. static static_codebook _8u1__p8_0 = {
  141659. 2, 121,
  141660. _vq_lengthlist__8u1__p8_0,
  141661. 1, -524582912, 1618345984, 4, 0,
  141662. _vq_quantlist__8u1__p8_0,
  141663. NULL,
  141664. &_vq_auxt__8u1__p8_0,
  141665. NULL,
  141666. 0
  141667. };
  141668. static long _vq_quantlist__8u1__p8_1[] = {
  141669. 5,
  141670. 4,
  141671. 6,
  141672. 3,
  141673. 7,
  141674. 2,
  141675. 8,
  141676. 1,
  141677. 9,
  141678. 0,
  141679. 10,
  141680. };
  141681. static long _vq_lengthlist__8u1__p8_1[] = {
  141682. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  141683. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  141684. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141685. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  141686. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141687. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  141688. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  141689. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141690. };
  141691. static float _vq_quantthresh__8u1__p8_1[] = {
  141692. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141693. 3.5, 4.5,
  141694. };
  141695. static long _vq_quantmap__8u1__p8_1[] = {
  141696. 9, 7, 5, 3, 1, 0, 2, 4,
  141697. 6, 8, 10,
  141698. };
  141699. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  141700. _vq_quantthresh__8u1__p8_1,
  141701. _vq_quantmap__8u1__p8_1,
  141702. 11,
  141703. 11
  141704. };
  141705. static static_codebook _8u1__p8_1 = {
  141706. 2, 121,
  141707. _vq_lengthlist__8u1__p8_1,
  141708. 1, -531365888, 1611661312, 4, 0,
  141709. _vq_quantlist__8u1__p8_1,
  141710. NULL,
  141711. &_vq_auxt__8u1__p8_1,
  141712. NULL,
  141713. 0
  141714. };
  141715. static long _vq_quantlist__8u1__p9_0[] = {
  141716. 7,
  141717. 6,
  141718. 8,
  141719. 5,
  141720. 9,
  141721. 4,
  141722. 10,
  141723. 3,
  141724. 11,
  141725. 2,
  141726. 12,
  141727. 1,
  141728. 13,
  141729. 0,
  141730. 14,
  141731. };
  141732. static long _vq_lengthlist__8u1__p9_0[] = {
  141733. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  141734. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  141735. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141745. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  141746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141747. 10,
  141748. };
  141749. static float _vq_quantthresh__8u1__p9_0[] = {
  141750. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  141751. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  141752. };
  141753. static long _vq_quantmap__8u1__p9_0[] = {
  141754. 13, 11, 9, 7, 5, 3, 1, 0,
  141755. 2, 4, 6, 8, 10, 12, 14,
  141756. };
  141757. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  141758. _vq_quantthresh__8u1__p9_0,
  141759. _vq_quantmap__8u1__p9_0,
  141760. 15,
  141761. 15
  141762. };
  141763. static static_codebook _8u1__p9_0 = {
  141764. 2, 225,
  141765. _vq_lengthlist__8u1__p9_0,
  141766. 1, -514071552, 1627381760, 4, 0,
  141767. _vq_quantlist__8u1__p9_0,
  141768. NULL,
  141769. &_vq_auxt__8u1__p9_0,
  141770. NULL,
  141771. 0
  141772. };
  141773. static long _vq_quantlist__8u1__p9_1[] = {
  141774. 7,
  141775. 6,
  141776. 8,
  141777. 5,
  141778. 9,
  141779. 4,
  141780. 10,
  141781. 3,
  141782. 11,
  141783. 2,
  141784. 12,
  141785. 1,
  141786. 13,
  141787. 0,
  141788. 14,
  141789. };
  141790. static long _vq_lengthlist__8u1__p9_1[] = {
  141791. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  141792. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  141793. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  141794. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  141795. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  141796. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  141797. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  141798. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  141799. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  141800. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  141801. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  141802. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  141803. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  141804. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  141805. 13,
  141806. };
  141807. static float _vq_quantthresh__8u1__p9_1[] = {
  141808. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141809. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141810. };
  141811. static long _vq_quantmap__8u1__p9_1[] = {
  141812. 13, 11, 9, 7, 5, 3, 1, 0,
  141813. 2, 4, 6, 8, 10, 12, 14,
  141814. };
  141815. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  141816. _vq_quantthresh__8u1__p9_1,
  141817. _vq_quantmap__8u1__p9_1,
  141818. 15,
  141819. 15
  141820. };
  141821. static static_codebook _8u1__p9_1 = {
  141822. 2, 225,
  141823. _vq_lengthlist__8u1__p9_1,
  141824. 1, -522338304, 1620115456, 4, 0,
  141825. _vq_quantlist__8u1__p9_1,
  141826. NULL,
  141827. &_vq_auxt__8u1__p9_1,
  141828. NULL,
  141829. 0
  141830. };
  141831. static long _vq_quantlist__8u1__p9_2[] = {
  141832. 8,
  141833. 7,
  141834. 9,
  141835. 6,
  141836. 10,
  141837. 5,
  141838. 11,
  141839. 4,
  141840. 12,
  141841. 3,
  141842. 13,
  141843. 2,
  141844. 14,
  141845. 1,
  141846. 15,
  141847. 0,
  141848. 16,
  141849. };
  141850. static long _vq_lengthlist__8u1__p9_2[] = {
  141851. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141852. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  141853. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141854. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141855. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141856. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  141857. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141858. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  141859. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141860. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141861. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141862. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  141863. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  141864. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  141866. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  141867. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141868. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141869. 10,
  141870. };
  141871. static float _vq_quantthresh__8u1__p9_2[] = {
  141872. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141873. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141874. };
  141875. static long _vq_quantmap__8u1__p9_2[] = {
  141876. 15, 13, 11, 9, 7, 5, 3, 1,
  141877. 0, 2, 4, 6, 8, 10, 12, 14,
  141878. 16,
  141879. };
  141880. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  141881. _vq_quantthresh__8u1__p9_2,
  141882. _vq_quantmap__8u1__p9_2,
  141883. 17,
  141884. 17
  141885. };
  141886. static static_codebook _8u1__p9_2 = {
  141887. 2, 289,
  141888. _vq_lengthlist__8u1__p9_2,
  141889. 1, -529530880, 1611661312, 5, 0,
  141890. _vq_quantlist__8u1__p9_2,
  141891. NULL,
  141892. &_vq_auxt__8u1__p9_2,
  141893. NULL,
  141894. 0
  141895. };
  141896. static long _huff_lengthlist__8u1__single[] = {
  141897. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  141898. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  141899. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  141900. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  141901. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  141902. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  141903. 13, 8, 8,15,
  141904. };
  141905. static static_codebook _huff_book__8u1__single = {
  141906. 2, 100,
  141907. _huff_lengthlist__8u1__single,
  141908. 0, 0, 0, 0, 0,
  141909. NULL,
  141910. NULL,
  141911. NULL,
  141912. NULL,
  141913. 0
  141914. };
  141915. static long _huff_lengthlist__44u0__long[] = {
  141916. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141917. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141918. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141919. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141920. };
  141921. static static_codebook _huff_book__44u0__long = {
  141922. 2, 64,
  141923. _huff_lengthlist__44u0__long,
  141924. 0, 0, 0, 0, 0,
  141925. NULL,
  141926. NULL,
  141927. NULL,
  141928. NULL,
  141929. 0
  141930. };
  141931. static long _vq_quantlist__44u0__p1_0[] = {
  141932. 1,
  141933. 0,
  141934. 2,
  141935. };
  141936. static long _vq_lengthlist__44u0__p1_0[] = {
  141937. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141938. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141939. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141940. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141941. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141942. 13,
  141943. };
  141944. static float _vq_quantthresh__44u0__p1_0[] = {
  141945. -0.5, 0.5,
  141946. };
  141947. static long _vq_quantmap__44u0__p1_0[] = {
  141948. 1, 0, 2,
  141949. };
  141950. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  141951. _vq_quantthresh__44u0__p1_0,
  141952. _vq_quantmap__44u0__p1_0,
  141953. 3,
  141954. 3
  141955. };
  141956. static static_codebook _44u0__p1_0 = {
  141957. 4, 81,
  141958. _vq_lengthlist__44u0__p1_0,
  141959. 1, -535822336, 1611661312, 2, 0,
  141960. _vq_quantlist__44u0__p1_0,
  141961. NULL,
  141962. &_vq_auxt__44u0__p1_0,
  141963. NULL,
  141964. 0
  141965. };
  141966. static long _vq_quantlist__44u0__p2_0[] = {
  141967. 1,
  141968. 0,
  141969. 2,
  141970. };
  141971. static long _vq_lengthlist__44u0__p2_0[] = {
  141972. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141973. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141974. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141975. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141976. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141977. 9,
  141978. };
  141979. static float _vq_quantthresh__44u0__p2_0[] = {
  141980. -0.5, 0.5,
  141981. };
  141982. static long _vq_quantmap__44u0__p2_0[] = {
  141983. 1, 0, 2,
  141984. };
  141985. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  141986. _vq_quantthresh__44u0__p2_0,
  141987. _vq_quantmap__44u0__p2_0,
  141988. 3,
  141989. 3
  141990. };
  141991. static static_codebook _44u0__p2_0 = {
  141992. 4, 81,
  141993. _vq_lengthlist__44u0__p2_0,
  141994. 1, -535822336, 1611661312, 2, 0,
  141995. _vq_quantlist__44u0__p2_0,
  141996. NULL,
  141997. &_vq_auxt__44u0__p2_0,
  141998. NULL,
  141999. 0
  142000. };
  142001. static long _vq_quantlist__44u0__p3_0[] = {
  142002. 2,
  142003. 1,
  142004. 3,
  142005. 0,
  142006. 4,
  142007. };
  142008. static long _vq_lengthlist__44u0__p3_0[] = {
  142009. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142010. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142011. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142012. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142013. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142014. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142015. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142016. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142017. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142018. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142019. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142020. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142021. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142022. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142023. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142024. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142025. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142026. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142027. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142028. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142029. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142030. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142031. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142032. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142033. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142034. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142035. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142036. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142037. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142038. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142039. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142040. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142041. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142042. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142043. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142044. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142045. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142046. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142047. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142048. 19,
  142049. };
  142050. static float _vq_quantthresh__44u0__p3_0[] = {
  142051. -1.5, -0.5, 0.5, 1.5,
  142052. };
  142053. static long _vq_quantmap__44u0__p3_0[] = {
  142054. 3, 1, 0, 2, 4,
  142055. };
  142056. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  142057. _vq_quantthresh__44u0__p3_0,
  142058. _vq_quantmap__44u0__p3_0,
  142059. 5,
  142060. 5
  142061. };
  142062. static static_codebook _44u0__p3_0 = {
  142063. 4, 625,
  142064. _vq_lengthlist__44u0__p3_0,
  142065. 1, -533725184, 1611661312, 3, 0,
  142066. _vq_quantlist__44u0__p3_0,
  142067. NULL,
  142068. &_vq_auxt__44u0__p3_0,
  142069. NULL,
  142070. 0
  142071. };
  142072. static long _vq_quantlist__44u0__p4_0[] = {
  142073. 2,
  142074. 1,
  142075. 3,
  142076. 0,
  142077. 4,
  142078. };
  142079. static long _vq_lengthlist__44u0__p4_0[] = {
  142080. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142081. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142082. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142083. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142084. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142085. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142086. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142087. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142088. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142089. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142090. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142091. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142092. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142093. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142094. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142095. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142096. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142097. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142098. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142099. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142100. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142101. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142102. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142103. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142104. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142105. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142106. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142107. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142108. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142109. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142110. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142111. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142112. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142113. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142114. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142115. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142116. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142117. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142118. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142119. 12,
  142120. };
  142121. static float _vq_quantthresh__44u0__p4_0[] = {
  142122. -1.5, -0.5, 0.5, 1.5,
  142123. };
  142124. static long _vq_quantmap__44u0__p4_0[] = {
  142125. 3, 1, 0, 2, 4,
  142126. };
  142127. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  142128. _vq_quantthresh__44u0__p4_0,
  142129. _vq_quantmap__44u0__p4_0,
  142130. 5,
  142131. 5
  142132. };
  142133. static static_codebook _44u0__p4_0 = {
  142134. 4, 625,
  142135. _vq_lengthlist__44u0__p4_0,
  142136. 1, -533725184, 1611661312, 3, 0,
  142137. _vq_quantlist__44u0__p4_0,
  142138. NULL,
  142139. &_vq_auxt__44u0__p4_0,
  142140. NULL,
  142141. 0
  142142. };
  142143. static long _vq_quantlist__44u0__p5_0[] = {
  142144. 4,
  142145. 3,
  142146. 5,
  142147. 2,
  142148. 6,
  142149. 1,
  142150. 7,
  142151. 0,
  142152. 8,
  142153. };
  142154. static long _vq_lengthlist__44u0__p5_0[] = {
  142155. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142156. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142157. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142158. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142159. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142160. 12,
  142161. };
  142162. static float _vq_quantthresh__44u0__p5_0[] = {
  142163. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142164. };
  142165. static long _vq_quantmap__44u0__p5_0[] = {
  142166. 7, 5, 3, 1, 0, 2, 4, 6,
  142167. 8,
  142168. };
  142169. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  142170. _vq_quantthresh__44u0__p5_0,
  142171. _vq_quantmap__44u0__p5_0,
  142172. 9,
  142173. 9
  142174. };
  142175. static static_codebook _44u0__p5_0 = {
  142176. 2, 81,
  142177. _vq_lengthlist__44u0__p5_0,
  142178. 1, -531628032, 1611661312, 4, 0,
  142179. _vq_quantlist__44u0__p5_0,
  142180. NULL,
  142181. &_vq_auxt__44u0__p5_0,
  142182. NULL,
  142183. 0
  142184. };
  142185. static long _vq_quantlist__44u0__p6_0[] = {
  142186. 6,
  142187. 5,
  142188. 7,
  142189. 4,
  142190. 8,
  142191. 3,
  142192. 9,
  142193. 2,
  142194. 10,
  142195. 1,
  142196. 11,
  142197. 0,
  142198. 12,
  142199. };
  142200. static long _vq_lengthlist__44u0__p6_0[] = {
  142201. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142202. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142203. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142204. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142205. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142206. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142207. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142208. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142209. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142210. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142211. 15,17,16,17,18,17,17,18, 0,
  142212. };
  142213. static float _vq_quantthresh__44u0__p6_0[] = {
  142214. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142215. 12.5, 17.5, 22.5, 27.5,
  142216. };
  142217. static long _vq_quantmap__44u0__p6_0[] = {
  142218. 11, 9, 7, 5, 3, 1, 0, 2,
  142219. 4, 6, 8, 10, 12,
  142220. };
  142221. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  142222. _vq_quantthresh__44u0__p6_0,
  142223. _vq_quantmap__44u0__p6_0,
  142224. 13,
  142225. 13
  142226. };
  142227. static static_codebook _44u0__p6_0 = {
  142228. 2, 169,
  142229. _vq_lengthlist__44u0__p6_0,
  142230. 1, -526516224, 1616117760, 4, 0,
  142231. _vq_quantlist__44u0__p6_0,
  142232. NULL,
  142233. &_vq_auxt__44u0__p6_0,
  142234. NULL,
  142235. 0
  142236. };
  142237. static long _vq_quantlist__44u0__p6_1[] = {
  142238. 2,
  142239. 1,
  142240. 3,
  142241. 0,
  142242. 4,
  142243. };
  142244. static long _vq_lengthlist__44u0__p6_1[] = {
  142245. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142246. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142247. };
  142248. static float _vq_quantthresh__44u0__p6_1[] = {
  142249. -1.5, -0.5, 0.5, 1.5,
  142250. };
  142251. static long _vq_quantmap__44u0__p6_1[] = {
  142252. 3, 1, 0, 2, 4,
  142253. };
  142254. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  142255. _vq_quantthresh__44u0__p6_1,
  142256. _vq_quantmap__44u0__p6_1,
  142257. 5,
  142258. 5
  142259. };
  142260. static static_codebook _44u0__p6_1 = {
  142261. 2, 25,
  142262. _vq_lengthlist__44u0__p6_1,
  142263. 1, -533725184, 1611661312, 3, 0,
  142264. _vq_quantlist__44u0__p6_1,
  142265. NULL,
  142266. &_vq_auxt__44u0__p6_1,
  142267. NULL,
  142268. 0
  142269. };
  142270. static long _vq_quantlist__44u0__p7_0[] = {
  142271. 2,
  142272. 1,
  142273. 3,
  142274. 0,
  142275. 4,
  142276. };
  142277. static long _vq_lengthlist__44u0__p7_0[] = {
  142278. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  142279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142281. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142285. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  142286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142299. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142300. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142301. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142302. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142303. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142304. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142305. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142306. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142307. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142308. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  142309. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142310. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142311. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142312. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142313. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142314. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142316. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142317. 10,
  142318. };
  142319. static float _vq_quantthresh__44u0__p7_0[] = {
  142320. -253.5, -84.5, 84.5, 253.5,
  142321. };
  142322. static long _vq_quantmap__44u0__p7_0[] = {
  142323. 3, 1, 0, 2, 4,
  142324. };
  142325. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  142326. _vq_quantthresh__44u0__p7_0,
  142327. _vq_quantmap__44u0__p7_0,
  142328. 5,
  142329. 5
  142330. };
  142331. static static_codebook _44u0__p7_0 = {
  142332. 4, 625,
  142333. _vq_lengthlist__44u0__p7_0,
  142334. 1, -518709248, 1626677248, 3, 0,
  142335. _vq_quantlist__44u0__p7_0,
  142336. NULL,
  142337. &_vq_auxt__44u0__p7_0,
  142338. NULL,
  142339. 0
  142340. };
  142341. static long _vq_quantlist__44u0__p7_1[] = {
  142342. 6,
  142343. 5,
  142344. 7,
  142345. 4,
  142346. 8,
  142347. 3,
  142348. 9,
  142349. 2,
  142350. 10,
  142351. 1,
  142352. 11,
  142353. 0,
  142354. 12,
  142355. };
  142356. static long _vq_lengthlist__44u0__p7_1[] = {
  142357. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142358. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142359. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142360. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142361. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142362. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142363. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142364. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142365. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142366. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142367. 15,15,15,15,15,15,15,15,15,
  142368. };
  142369. static float _vq_quantthresh__44u0__p7_1[] = {
  142370. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142371. 32.5, 45.5, 58.5, 71.5,
  142372. };
  142373. static long _vq_quantmap__44u0__p7_1[] = {
  142374. 11, 9, 7, 5, 3, 1, 0, 2,
  142375. 4, 6, 8, 10, 12,
  142376. };
  142377. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  142378. _vq_quantthresh__44u0__p7_1,
  142379. _vq_quantmap__44u0__p7_1,
  142380. 13,
  142381. 13
  142382. };
  142383. static static_codebook _44u0__p7_1 = {
  142384. 2, 169,
  142385. _vq_lengthlist__44u0__p7_1,
  142386. 1, -523010048, 1618608128, 4, 0,
  142387. _vq_quantlist__44u0__p7_1,
  142388. NULL,
  142389. &_vq_auxt__44u0__p7_1,
  142390. NULL,
  142391. 0
  142392. };
  142393. static long _vq_quantlist__44u0__p7_2[] = {
  142394. 6,
  142395. 5,
  142396. 7,
  142397. 4,
  142398. 8,
  142399. 3,
  142400. 9,
  142401. 2,
  142402. 10,
  142403. 1,
  142404. 11,
  142405. 0,
  142406. 12,
  142407. };
  142408. static long _vq_lengthlist__44u0__p7_2[] = {
  142409. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142410. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142411. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142412. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142413. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142414. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142415. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142416. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142417. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142418. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142419. 9, 9, 9,10, 9, 9,10,10, 9,
  142420. };
  142421. static float _vq_quantthresh__44u0__p7_2[] = {
  142422. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142423. 2.5, 3.5, 4.5, 5.5,
  142424. };
  142425. static long _vq_quantmap__44u0__p7_2[] = {
  142426. 11, 9, 7, 5, 3, 1, 0, 2,
  142427. 4, 6, 8, 10, 12,
  142428. };
  142429. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  142430. _vq_quantthresh__44u0__p7_2,
  142431. _vq_quantmap__44u0__p7_2,
  142432. 13,
  142433. 13
  142434. };
  142435. static static_codebook _44u0__p7_2 = {
  142436. 2, 169,
  142437. _vq_lengthlist__44u0__p7_2,
  142438. 1, -531103744, 1611661312, 4, 0,
  142439. _vq_quantlist__44u0__p7_2,
  142440. NULL,
  142441. &_vq_auxt__44u0__p7_2,
  142442. NULL,
  142443. 0
  142444. };
  142445. static long _huff_lengthlist__44u0__short[] = {
  142446. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142447. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142448. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142449. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142450. };
  142451. static static_codebook _huff_book__44u0__short = {
  142452. 2, 64,
  142453. _huff_lengthlist__44u0__short,
  142454. 0, 0, 0, 0, 0,
  142455. NULL,
  142456. NULL,
  142457. NULL,
  142458. NULL,
  142459. 0
  142460. };
  142461. static long _huff_lengthlist__44u1__long[] = {
  142462. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  142463. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  142464. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  142465. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  142466. };
  142467. static static_codebook _huff_book__44u1__long = {
  142468. 2, 64,
  142469. _huff_lengthlist__44u1__long,
  142470. 0, 0, 0, 0, 0,
  142471. NULL,
  142472. NULL,
  142473. NULL,
  142474. NULL,
  142475. 0
  142476. };
  142477. static long _vq_quantlist__44u1__p1_0[] = {
  142478. 1,
  142479. 0,
  142480. 2,
  142481. };
  142482. static long _vq_lengthlist__44u1__p1_0[] = {
  142483. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142484. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142485. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  142486. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  142487. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  142488. 13,
  142489. };
  142490. static float _vq_quantthresh__44u1__p1_0[] = {
  142491. -0.5, 0.5,
  142492. };
  142493. static long _vq_quantmap__44u1__p1_0[] = {
  142494. 1, 0, 2,
  142495. };
  142496. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  142497. _vq_quantthresh__44u1__p1_0,
  142498. _vq_quantmap__44u1__p1_0,
  142499. 3,
  142500. 3
  142501. };
  142502. static static_codebook _44u1__p1_0 = {
  142503. 4, 81,
  142504. _vq_lengthlist__44u1__p1_0,
  142505. 1, -535822336, 1611661312, 2, 0,
  142506. _vq_quantlist__44u1__p1_0,
  142507. NULL,
  142508. &_vq_auxt__44u1__p1_0,
  142509. NULL,
  142510. 0
  142511. };
  142512. static long _vq_quantlist__44u1__p2_0[] = {
  142513. 1,
  142514. 0,
  142515. 2,
  142516. };
  142517. static long _vq_lengthlist__44u1__p2_0[] = {
  142518. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142519. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142520. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142521. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142522. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142523. 9,
  142524. };
  142525. static float _vq_quantthresh__44u1__p2_0[] = {
  142526. -0.5, 0.5,
  142527. };
  142528. static long _vq_quantmap__44u1__p2_0[] = {
  142529. 1, 0, 2,
  142530. };
  142531. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  142532. _vq_quantthresh__44u1__p2_0,
  142533. _vq_quantmap__44u1__p2_0,
  142534. 3,
  142535. 3
  142536. };
  142537. static static_codebook _44u1__p2_0 = {
  142538. 4, 81,
  142539. _vq_lengthlist__44u1__p2_0,
  142540. 1, -535822336, 1611661312, 2, 0,
  142541. _vq_quantlist__44u1__p2_0,
  142542. NULL,
  142543. &_vq_auxt__44u1__p2_0,
  142544. NULL,
  142545. 0
  142546. };
  142547. static long _vq_quantlist__44u1__p3_0[] = {
  142548. 2,
  142549. 1,
  142550. 3,
  142551. 0,
  142552. 4,
  142553. };
  142554. static long _vq_lengthlist__44u1__p3_0[] = {
  142555. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142556. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142557. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142558. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142559. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142560. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142561. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142562. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142563. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142564. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142565. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142566. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142567. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142568. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142569. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142570. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142571. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142572. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142573. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142574. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142575. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142576. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142577. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142578. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142579. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142580. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142581. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142582. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142583. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142584. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142585. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142586. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142587. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142588. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142589. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142590. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142591. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142592. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142593. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142594. 19,
  142595. };
  142596. static float _vq_quantthresh__44u1__p3_0[] = {
  142597. -1.5, -0.5, 0.5, 1.5,
  142598. };
  142599. static long _vq_quantmap__44u1__p3_0[] = {
  142600. 3, 1, 0, 2, 4,
  142601. };
  142602. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  142603. _vq_quantthresh__44u1__p3_0,
  142604. _vq_quantmap__44u1__p3_0,
  142605. 5,
  142606. 5
  142607. };
  142608. static static_codebook _44u1__p3_0 = {
  142609. 4, 625,
  142610. _vq_lengthlist__44u1__p3_0,
  142611. 1, -533725184, 1611661312, 3, 0,
  142612. _vq_quantlist__44u1__p3_0,
  142613. NULL,
  142614. &_vq_auxt__44u1__p3_0,
  142615. NULL,
  142616. 0
  142617. };
  142618. static long _vq_quantlist__44u1__p4_0[] = {
  142619. 2,
  142620. 1,
  142621. 3,
  142622. 0,
  142623. 4,
  142624. };
  142625. static long _vq_lengthlist__44u1__p4_0[] = {
  142626. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142627. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142628. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142629. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142630. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142631. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142632. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142633. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142634. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142635. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142636. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142637. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142638. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142639. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142640. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142641. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142642. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142643. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142644. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142645. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142646. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142647. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142648. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142649. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142650. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142651. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142652. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142653. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142654. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142655. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142656. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142657. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142658. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142659. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142660. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142661. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142662. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142663. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142664. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142665. 12,
  142666. };
  142667. static float _vq_quantthresh__44u1__p4_0[] = {
  142668. -1.5, -0.5, 0.5, 1.5,
  142669. };
  142670. static long _vq_quantmap__44u1__p4_0[] = {
  142671. 3, 1, 0, 2, 4,
  142672. };
  142673. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  142674. _vq_quantthresh__44u1__p4_0,
  142675. _vq_quantmap__44u1__p4_0,
  142676. 5,
  142677. 5
  142678. };
  142679. static static_codebook _44u1__p4_0 = {
  142680. 4, 625,
  142681. _vq_lengthlist__44u1__p4_0,
  142682. 1, -533725184, 1611661312, 3, 0,
  142683. _vq_quantlist__44u1__p4_0,
  142684. NULL,
  142685. &_vq_auxt__44u1__p4_0,
  142686. NULL,
  142687. 0
  142688. };
  142689. static long _vq_quantlist__44u1__p5_0[] = {
  142690. 4,
  142691. 3,
  142692. 5,
  142693. 2,
  142694. 6,
  142695. 1,
  142696. 7,
  142697. 0,
  142698. 8,
  142699. };
  142700. static long _vq_lengthlist__44u1__p5_0[] = {
  142701. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142702. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142703. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142704. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142705. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142706. 12,
  142707. };
  142708. static float _vq_quantthresh__44u1__p5_0[] = {
  142709. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142710. };
  142711. static long _vq_quantmap__44u1__p5_0[] = {
  142712. 7, 5, 3, 1, 0, 2, 4, 6,
  142713. 8,
  142714. };
  142715. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  142716. _vq_quantthresh__44u1__p5_0,
  142717. _vq_quantmap__44u1__p5_0,
  142718. 9,
  142719. 9
  142720. };
  142721. static static_codebook _44u1__p5_0 = {
  142722. 2, 81,
  142723. _vq_lengthlist__44u1__p5_0,
  142724. 1, -531628032, 1611661312, 4, 0,
  142725. _vq_quantlist__44u1__p5_0,
  142726. NULL,
  142727. &_vq_auxt__44u1__p5_0,
  142728. NULL,
  142729. 0
  142730. };
  142731. static long _vq_quantlist__44u1__p6_0[] = {
  142732. 6,
  142733. 5,
  142734. 7,
  142735. 4,
  142736. 8,
  142737. 3,
  142738. 9,
  142739. 2,
  142740. 10,
  142741. 1,
  142742. 11,
  142743. 0,
  142744. 12,
  142745. };
  142746. static long _vq_lengthlist__44u1__p6_0[] = {
  142747. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142748. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142749. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142750. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142751. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142752. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142753. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142754. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142755. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142756. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142757. 15,17,16,17,18,17,17,18, 0,
  142758. };
  142759. static float _vq_quantthresh__44u1__p6_0[] = {
  142760. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142761. 12.5, 17.5, 22.5, 27.5,
  142762. };
  142763. static long _vq_quantmap__44u1__p6_0[] = {
  142764. 11, 9, 7, 5, 3, 1, 0, 2,
  142765. 4, 6, 8, 10, 12,
  142766. };
  142767. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  142768. _vq_quantthresh__44u1__p6_0,
  142769. _vq_quantmap__44u1__p6_0,
  142770. 13,
  142771. 13
  142772. };
  142773. static static_codebook _44u1__p6_0 = {
  142774. 2, 169,
  142775. _vq_lengthlist__44u1__p6_0,
  142776. 1, -526516224, 1616117760, 4, 0,
  142777. _vq_quantlist__44u1__p6_0,
  142778. NULL,
  142779. &_vq_auxt__44u1__p6_0,
  142780. NULL,
  142781. 0
  142782. };
  142783. static long _vq_quantlist__44u1__p6_1[] = {
  142784. 2,
  142785. 1,
  142786. 3,
  142787. 0,
  142788. 4,
  142789. };
  142790. static long _vq_lengthlist__44u1__p6_1[] = {
  142791. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142792. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142793. };
  142794. static float _vq_quantthresh__44u1__p6_1[] = {
  142795. -1.5, -0.5, 0.5, 1.5,
  142796. };
  142797. static long _vq_quantmap__44u1__p6_1[] = {
  142798. 3, 1, 0, 2, 4,
  142799. };
  142800. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  142801. _vq_quantthresh__44u1__p6_1,
  142802. _vq_quantmap__44u1__p6_1,
  142803. 5,
  142804. 5
  142805. };
  142806. static static_codebook _44u1__p6_1 = {
  142807. 2, 25,
  142808. _vq_lengthlist__44u1__p6_1,
  142809. 1, -533725184, 1611661312, 3, 0,
  142810. _vq_quantlist__44u1__p6_1,
  142811. NULL,
  142812. &_vq_auxt__44u1__p6_1,
  142813. NULL,
  142814. 0
  142815. };
  142816. static long _vq_quantlist__44u1__p7_0[] = {
  142817. 3,
  142818. 2,
  142819. 4,
  142820. 1,
  142821. 5,
  142822. 0,
  142823. 6,
  142824. };
  142825. static long _vq_lengthlist__44u1__p7_0[] = {
  142826. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142827. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142828. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142829. 8,
  142830. };
  142831. static float _vq_quantthresh__44u1__p7_0[] = {
  142832. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  142833. };
  142834. static long _vq_quantmap__44u1__p7_0[] = {
  142835. 5, 3, 1, 0, 2, 4, 6,
  142836. };
  142837. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  142838. _vq_quantthresh__44u1__p7_0,
  142839. _vq_quantmap__44u1__p7_0,
  142840. 7,
  142841. 7
  142842. };
  142843. static static_codebook _44u1__p7_0 = {
  142844. 2, 49,
  142845. _vq_lengthlist__44u1__p7_0,
  142846. 1, -518017024, 1626677248, 3, 0,
  142847. _vq_quantlist__44u1__p7_0,
  142848. NULL,
  142849. &_vq_auxt__44u1__p7_0,
  142850. NULL,
  142851. 0
  142852. };
  142853. static long _vq_quantlist__44u1__p7_1[] = {
  142854. 6,
  142855. 5,
  142856. 7,
  142857. 4,
  142858. 8,
  142859. 3,
  142860. 9,
  142861. 2,
  142862. 10,
  142863. 1,
  142864. 11,
  142865. 0,
  142866. 12,
  142867. };
  142868. static long _vq_lengthlist__44u1__p7_1[] = {
  142869. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142870. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142871. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142872. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142873. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142874. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142875. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142876. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142877. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142878. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142879. 15,15,15,15,15,15,15,15,15,
  142880. };
  142881. static float _vq_quantthresh__44u1__p7_1[] = {
  142882. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142883. 32.5, 45.5, 58.5, 71.5,
  142884. };
  142885. static long _vq_quantmap__44u1__p7_1[] = {
  142886. 11, 9, 7, 5, 3, 1, 0, 2,
  142887. 4, 6, 8, 10, 12,
  142888. };
  142889. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  142890. _vq_quantthresh__44u1__p7_1,
  142891. _vq_quantmap__44u1__p7_1,
  142892. 13,
  142893. 13
  142894. };
  142895. static static_codebook _44u1__p7_1 = {
  142896. 2, 169,
  142897. _vq_lengthlist__44u1__p7_1,
  142898. 1, -523010048, 1618608128, 4, 0,
  142899. _vq_quantlist__44u1__p7_1,
  142900. NULL,
  142901. &_vq_auxt__44u1__p7_1,
  142902. NULL,
  142903. 0
  142904. };
  142905. static long _vq_quantlist__44u1__p7_2[] = {
  142906. 6,
  142907. 5,
  142908. 7,
  142909. 4,
  142910. 8,
  142911. 3,
  142912. 9,
  142913. 2,
  142914. 10,
  142915. 1,
  142916. 11,
  142917. 0,
  142918. 12,
  142919. };
  142920. static long _vq_lengthlist__44u1__p7_2[] = {
  142921. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142922. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142923. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142924. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142925. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142926. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142927. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142928. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142929. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142930. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142931. 9, 9, 9,10, 9, 9,10,10, 9,
  142932. };
  142933. static float _vq_quantthresh__44u1__p7_2[] = {
  142934. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142935. 2.5, 3.5, 4.5, 5.5,
  142936. };
  142937. static long _vq_quantmap__44u1__p7_2[] = {
  142938. 11, 9, 7, 5, 3, 1, 0, 2,
  142939. 4, 6, 8, 10, 12,
  142940. };
  142941. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  142942. _vq_quantthresh__44u1__p7_2,
  142943. _vq_quantmap__44u1__p7_2,
  142944. 13,
  142945. 13
  142946. };
  142947. static static_codebook _44u1__p7_2 = {
  142948. 2, 169,
  142949. _vq_lengthlist__44u1__p7_2,
  142950. 1, -531103744, 1611661312, 4, 0,
  142951. _vq_quantlist__44u1__p7_2,
  142952. NULL,
  142953. &_vq_auxt__44u1__p7_2,
  142954. NULL,
  142955. 0
  142956. };
  142957. static long _huff_lengthlist__44u1__short[] = {
  142958. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142959. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142960. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142961. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142962. };
  142963. static static_codebook _huff_book__44u1__short = {
  142964. 2, 64,
  142965. _huff_lengthlist__44u1__short,
  142966. 0, 0, 0, 0, 0,
  142967. NULL,
  142968. NULL,
  142969. NULL,
  142970. NULL,
  142971. 0
  142972. };
  142973. static long _huff_lengthlist__44u2__long[] = {
  142974. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  142975. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  142976. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  142977. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  142978. };
  142979. static static_codebook _huff_book__44u2__long = {
  142980. 2, 64,
  142981. _huff_lengthlist__44u2__long,
  142982. 0, 0, 0, 0, 0,
  142983. NULL,
  142984. NULL,
  142985. NULL,
  142986. NULL,
  142987. 0
  142988. };
  142989. static long _vq_quantlist__44u2__p1_0[] = {
  142990. 1,
  142991. 0,
  142992. 2,
  142993. };
  142994. static long _vq_lengthlist__44u2__p1_0[] = {
  142995. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142996. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142997. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  142998. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  142999. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  143000. 13,
  143001. };
  143002. static float _vq_quantthresh__44u2__p1_0[] = {
  143003. -0.5, 0.5,
  143004. };
  143005. static long _vq_quantmap__44u2__p1_0[] = {
  143006. 1, 0, 2,
  143007. };
  143008. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  143009. _vq_quantthresh__44u2__p1_0,
  143010. _vq_quantmap__44u2__p1_0,
  143011. 3,
  143012. 3
  143013. };
  143014. static static_codebook _44u2__p1_0 = {
  143015. 4, 81,
  143016. _vq_lengthlist__44u2__p1_0,
  143017. 1, -535822336, 1611661312, 2, 0,
  143018. _vq_quantlist__44u2__p1_0,
  143019. NULL,
  143020. &_vq_auxt__44u2__p1_0,
  143021. NULL,
  143022. 0
  143023. };
  143024. static long _vq_quantlist__44u2__p2_0[] = {
  143025. 1,
  143026. 0,
  143027. 2,
  143028. };
  143029. static long _vq_lengthlist__44u2__p2_0[] = {
  143030. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143031. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  143032. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143033. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143034. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143035. 9,
  143036. };
  143037. static float _vq_quantthresh__44u2__p2_0[] = {
  143038. -0.5, 0.5,
  143039. };
  143040. static long _vq_quantmap__44u2__p2_0[] = {
  143041. 1, 0, 2,
  143042. };
  143043. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  143044. _vq_quantthresh__44u2__p2_0,
  143045. _vq_quantmap__44u2__p2_0,
  143046. 3,
  143047. 3
  143048. };
  143049. static static_codebook _44u2__p2_0 = {
  143050. 4, 81,
  143051. _vq_lengthlist__44u2__p2_0,
  143052. 1, -535822336, 1611661312, 2, 0,
  143053. _vq_quantlist__44u2__p2_0,
  143054. NULL,
  143055. &_vq_auxt__44u2__p2_0,
  143056. NULL,
  143057. 0
  143058. };
  143059. static long _vq_quantlist__44u2__p3_0[] = {
  143060. 2,
  143061. 1,
  143062. 3,
  143063. 0,
  143064. 4,
  143065. };
  143066. static long _vq_lengthlist__44u2__p3_0[] = {
  143067. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143068. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143069. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143070. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143071. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  143072. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  143073. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143074. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  143075. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143076. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143077. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  143078. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143079. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  143080. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  143081. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  143082. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  143083. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143084. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  143085. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  143086. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  143087. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  143088. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  143089. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  143090. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  143091. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  143092. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  143093. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  143094. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  143095. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  143096. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  143097. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  143098. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  143099. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  143100. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  143101. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  143102. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  143103. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  143104. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  143105. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  143106. 0,
  143107. };
  143108. static float _vq_quantthresh__44u2__p3_0[] = {
  143109. -1.5, -0.5, 0.5, 1.5,
  143110. };
  143111. static long _vq_quantmap__44u2__p3_0[] = {
  143112. 3, 1, 0, 2, 4,
  143113. };
  143114. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  143115. _vq_quantthresh__44u2__p3_0,
  143116. _vq_quantmap__44u2__p3_0,
  143117. 5,
  143118. 5
  143119. };
  143120. static static_codebook _44u2__p3_0 = {
  143121. 4, 625,
  143122. _vq_lengthlist__44u2__p3_0,
  143123. 1, -533725184, 1611661312, 3, 0,
  143124. _vq_quantlist__44u2__p3_0,
  143125. NULL,
  143126. &_vq_auxt__44u2__p3_0,
  143127. NULL,
  143128. 0
  143129. };
  143130. static long _vq_quantlist__44u2__p4_0[] = {
  143131. 2,
  143132. 1,
  143133. 3,
  143134. 0,
  143135. 4,
  143136. };
  143137. static long _vq_lengthlist__44u2__p4_0[] = {
  143138. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143139. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143140. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143141. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  143142. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  143143. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143144. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  143145. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  143146. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143147. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143148. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  143149. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143150. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  143151. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  143152. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  143153. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  143154. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143155. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143156. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143157. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143158. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143159. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  143160. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143161. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143162. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143163. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  143164. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  143165. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  143166. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143167. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  143168. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  143169. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  143170. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  143171. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143172. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143173. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  143174. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143175. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  143176. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  143177. 13,
  143178. };
  143179. static float _vq_quantthresh__44u2__p4_0[] = {
  143180. -1.5, -0.5, 0.5, 1.5,
  143181. };
  143182. static long _vq_quantmap__44u2__p4_0[] = {
  143183. 3, 1, 0, 2, 4,
  143184. };
  143185. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  143186. _vq_quantthresh__44u2__p4_0,
  143187. _vq_quantmap__44u2__p4_0,
  143188. 5,
  143189. 5
  143190. };
  143191. static static_codebook _44u2__p4_0 = {
  143192. 4, 625,
  143193. _vq_lengthlist__44u2__p4_0,
  143194. 1, -533725184, 1611661312, 3, 0,
  143195. _vq_quantlist__44u2__p4_0,
  143196. NULL,
  143197. &_vq_auxt__44u2__p4_0,
  143198. NULL,
  143199. 0
  143200. };
  143201. static long _vq_quantlist__44u2__p5_0[] = {
  143202. 4,
  143203. 3,
  143204. 5,
  143205. 2,
  143206. 6,
  143207. 1,
  143208. 7,
  143209. 0,
  143210. 8,
  143211. };
  143212. static long _vq_lengthlist__44u2__p5_0[] = {
  143213. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  143214. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143215. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  143216. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  143217. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  143218. 13,
  143219. };
  143220. static float _vq_quantthresh__44u2__p5_0[] = {
  143221. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143222. };
  143223. static long _vq_quantmap__44u2__p5_0[] = {
  143224. 7, 5, 3, 1, 0, 2, 4, 6,
  143225. 8,
  143226. };
  143227. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  143228. _vq_quantthresh__44u2__p5_0,
  143229. _vq_quantmap__44u2__p5_0,
  143230. 9,
  143231. 9
  143232. };
  143233. static static_codebook _44u2__p5_0 = {
  143234. 2, 81,
  143235. _vq_lengthlist__44u2__p5_0,
  143236. 1, -531628032, 1611661312, 4, 0,
  143237. _vq_quantlist__44u2__p5_0,
  143238. NULL,
  143239. &_vq_auxt__44u2__p5_0,
  143240. NULL,
  143241. 0
  143242. };
  143243. static long _vq_quantlist__44u2__p6_0[] = {
  143244. 6,
  143245. 5,
  143246. 7,
  143247. 4,
  143248. 8,
  143249. 3,
  143250. 9,
  143251. 2,
  143252. 10,
  143253. 1,
  143254. 11,
  143255. 0,
  143256. 12,
  143257. };
  143258. static long _vq_lengthlist__44u2__p6_0[] = {
  143259. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  143260. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  143261. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  143262. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  143263. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  143264. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  143265. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  143266. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  143267. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  143268. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  143269. 15,17,17,16,18,17,18, 0, 0,
  143270. };
  143271. static float _vq_quantthresh__44u2__p6_0[] = {
  143272. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143273. 12.5, 17.5, 22.5, 27.5,
  143274. };
  143275. static long _vq_quantmap__44u2__p6_0[] = {
  143276. 11, 9, 7, 5, 3, 1, 0, 2,
  143277. 4, 6, 8, 10, 12,
  143278. };
  143279. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  143280. _vq_quantthresh__44u2__p6_0,
  143281. _vq_quantmap__44u2__p6_0,
  143282. 13,
  143283. 13
  143284. };
  143285. static static_codebook _44u2__p6_0 = {
  143286. 2, 169,
  143287. _vq_lengthlist__44u2__p6_0,
  143288. 1, -526516224, 1616117760, 4, 0,
  143289. _vq_quantlist__44u2__p6_0,
  143290. NULL,
  143291. &_vq_auxt__44u2__p6_0,
  143292. NULL,
  143293. 0
  143294. };
  143295. static long _vq_quantlist__44u2__p6_1[] = {
  143296. 2,
  143297. 1,
  143298. 3,
  143299. 0,
  143300. 4,
  143301. };
  143302. static long _vq_lengthlist__44u2__p6_1[] = {
  143303. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143304. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143305. };
  143306. static float _vq_quantthresh__44u2__p6_1[] = {
  143307. -1.5, -0.5, 0.5, 1.5,
  143308. };
  143309. static long _vq_quantmap__44u2__p6_1[] = {
  143310. 3, 1, 0, 2, 4,
  143311. };
  143312. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  143313. _vq_quantthresh__44u2__p6_1,
  143314. _vq_quantmap__44u2__p6_1,
  143315. 5,
  143316. 5
  143317. };
  143318. static static_codebook _44u2__p6_1 = {
  143319. 2, 25,
  143320. _vq_lengthlist__44u2__p6_1,
  143321. 1, -533725184, 1611661312, 3, 0,
  143322. _vq_quantlist__44u2__p6_1,
  143323. NULL,
  143324. &_vq_auxt__44u2__p6_1,
  143325. NULL,
  143326. 0
  143327. };
  143328. static long _vq_quantlist__44u2__p7_0[] = {
  143329. 4,
  143330. 3,
  143331. 5,
  143332. 2,
  143333. 6,
  143334. 1,
  143335. 7,
  143336. 0,
  143337. 8,
  143338. };
  143339. static long _vq_lengthlist__44u2__p7_0[] = {
  143340. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  143341. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  143342. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143345. 11,
  143346. };
  143347. static float _vq_quantthresh__44u2__p7_0[] = {
  143348. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  143349. };
  143350. static long _vq_quantmap__44u2__p7_0[] = {
  143351. 7, 5, 3, 1, 0, 2, 4, 6,
  143352. 8,
  143353. };
  143354. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  143355. _vq_quantthresh__44u2__p7_0,
  143356. _vq_quantmap__44u2__p7_0,
  143357. 9,
  143358. 9
  143359. };
  143360. static static_codebook _44u2__p7_0 = {
  143361. 2, 81,
  143362. _vq_lengthlist__44u2__p7_0,
  143363. 1, -516612096, 1626677248, 4, 0,
  143364. _vq_quantlist__44u2__p7_0,
  143365. NULL,
  143366. &_vq_auxt__44u2__p7_0,
  143367. NULL,
  143368. 0
  143369. };
  143370. static long _vq_quantlist__44u2__p7_1[] = {
  143371. 6,
  143372. 5,
  143373. 7,
  143374. 4,
  143375. 8,
  143376. 3,
  143377. 9,
  143378. 2,
  143379. 10,
  143380. 1,
  143381. 11,
  143382. 0,
  143383. 12,
  143384. };
  143385. static long _vq_lengthlist__44u2__p7_1[] = {
  143386. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  143387. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  143388. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  143389. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  143390. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  143391. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  143392. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  143393. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  143394. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  143395. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  143396. 14,14,14,17,15,17,17,17,17,
  143397. };
  143398. static float _vq_quantthresh__44u2__p7_1[] = {
  143399. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143400. 32.5, 45.5, 58.5, 71.5,
  143401. };
  143402. static long _vq_quantmap__44u2__p7_1[] = {
  143403. 11, 9, 7, 5, 3, 1, 0, 2,
  143404. 4, 6, 8, 10, 12,
  143405. };
  143406. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  143407. _vq_quantthresh__44u2__p7_1,
  143408. _vq_quantmap__44u2__p7_1,
  143409. 13,
  143410. 13
  143411. };
  143412. static static_codebook _44u2__p7_1 = {
  143413. 2, 169,
  143414. _vq_lengthlist__44u2__p7_1,
  143415. 1, -523010048, 1618608128, 4, 0,
  143416. _vq_quantlist__44u2__p7_1,
  143417. NULL,
  143418. &_vq_auxt__44u2__p7_1,
  143419. NULL,
  143420. 0
  143421. };
  143422. static long _vq_quantlist__44u2__p7_2[] = {
  143423. 6,
  143424. 5,
  143425. 7,
  143426. 4,
  143427. 8,
  143428. 3,
  143429. 9,
  143430. 2,
  143431. 10,
  143432. 1,
  143433. 11,
  143434. 0,
  143435. 12,
  143436. };
  143437. static long _vq_lengthlist__44u2__p7_2[] = {
  143438. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  143439. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  143440. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  143441. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143442. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  143443. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  143444. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143445. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143446. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  143447. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  143448. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143449. };
  143450. static float _vq_quantthresh__44u2__p7_2[] = {
  143451. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143452. 2.5, 3.5, 4.5, 5.5,
  143453. };
  143454. static long _vq_quantmap__44u2__p7_2[] = {
  143455. 11, 9, 7, 5, 3, 1, 0, 2,
  143456. 4, 6, 8, 10, 12,
  143457. };
  143458. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  143459. _vq_quantthresh__44u2__p7_2,
  143460. _vq_quantmap__44u2__p7_2,
  143461. 13,
  143462. 13
  143463. };
  143464. static static_codebook _44u2__p7_2 = {
  143465. 2, 169,
  143466. _vq_lengthlist__44u2__p7_2,
  143467. 1, -531103744, 1611661312, 4, 0,
  143468. _vq_quantlist__44u2__p7_2,
  143469. NULL,
  143470. &_vq_auxt__44u2__p7_2,
  143471. NULL,
  143472. 0
  143473. };
  143474. static long _huff_lengthlist__44u2__short[] = {
  143475. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  143476. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  143477. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  143478. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  143479. };
  143480. static static_codebook _huff_book__44u2__short = {
  143481. 2, 64,
  143482. _huff_lengthlist__44u2__short,
  143483. 0, 0, 0, 0, 0,
  143484. NULL,
  143485. NULL,
  143486. NULL,
  143487. NULL,
  143488. 0
  143489. };
  143490. static long _huff_lengthlist__44u3__long[] = {
  143491. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  143492. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  143493. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  143494. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  143495. };
  143496. static static_codebook _huff_book__44u3__long = {
  143497. 2, 64,
  143498. _huff_lengthlist__44u3__long,
  143499. 0, 0, 0, 0, 0,
  143500. NULL,
  143501. NULL,
  143502. NULL,
  143503. NULL,
  143504. 0
  143505. };
  143506. static long _vq_quantlist__44u3__p1_0[] = {
  143507. 1,
  143508. 0,
  143509. 2,
  143510. };
  143511. static long _vq_lengthlist__44u3__p1_0[] = {
  143512. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143513. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143514. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  143515. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143516. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  143517. 13,
  143518. };
  143519. static float _vq_quantthresh__44u3__p1_0[] = {
  143520. -0.5, 0.5,
  143521. };
  143522. static long _vq_quantmap__44u3__p1_0[] = {
  143523. 1, 0, 2,
  143524. };
  143525. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  143526. _vq_quantthresh__44u3__p1_0,
  143527. _vq_quantmap__44u3__p1_0,
  143528. 3,
  143529. 3
  143530. };
  143531. static static_codebook _44u3__p1_0 = {
  143532. 4, 81,
  143533. _vq_lengthlist__44u3__p1_0,
  143534. 1, -535822336, 1611661312, 2, 0,
  143535. _vq_quantlist__44u3__p1_0,
  143536. NULL,
  143537. &_vq_auxt__44u3__p1_0,
  143538. NULL,
  143539. 0
  143540. };
  143541. static long _vq_quantlist__44u3__p2_0[] = {
  143542. 1,
  143543. 0,
  143544. 2,
  143545. };
  143546. static long _vq_lengthlist__44u3__p2_0[] = {
  143547. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143548. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  143549. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143550. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143551. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  143552. 9,
  143553. };
  143554. static float _vq_quantthresh__44u3__p2_0[] = {
  143555. -0.5, 0.5,
  143556. };
  143557. static long _vq_quantmap__44u3__p2_0[] = {
  143558. 1, 0, 2,
  143559. };
  143560. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  143561. _vq_quantthresh__44u3__p2_0,
  143562. _vq_quantmap__44u3__p2_0,
  143563. 3,
  143564. 3
  143565. };
  143566. static static_codebook _44u3__p2_0 = {
  143567. 4, 81,
  143568. _vq_lengthlist__44u3__p2_0,
  143569. 1, -535822336, 1611661312, 2, 0,
  143570. _vq_quantlist__44u3__p2_0,
  143571. NULL,
  143572. &_vq_auxt__44u3__p2_0,
  143573. NULL,
  143574. 0
  143575. };
  143576. static long _vq_quantlist__44u3__p3_0[] = {
  143577. 2,
  143578. 1,
  143579. 3,
  143580. 0,
  143581. 4,
  143582. };
  143583. static long _vq_lengthlist__44u3__p3_0[] = {
  143584. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143585. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143586. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143587. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143588. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  143589. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  143590. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  143591. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  143592. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143593. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143594. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  143595. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143596. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  143597. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  143598. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  143599. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  143600. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  143601. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  143602. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  143603. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  143604. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  143605. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  143606. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  143607. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  143608. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  143609. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  143610. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  143611. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  143612. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  143613. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  143614. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  143615. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  143616. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  143617. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  143618. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  143619. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  143620. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  143621. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  143622. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  143623. 0,
  143624. };
  143625. static float _vq_quantthresh__44u3__p3_0[] = {
  143626. -1.5, -0.5, 0.5, 1.5,
  143627. };
  143628. static long _vq_quantmap__44u3__p3_0[] = {
  143629. 3, 1, 0, 2, 4,
  143630. };
  143631. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  143632. _vq_quantthresh__44u3__p3_0,
  143633. _vq_quantmap__44u3__p3_0,
  143634. 5,
  143635. 5
  143636. };
  143637. static static_codebook _44u3__p3_0 = {
  143638. 4, 625,
  143639. _vq_lengthlist__44u3__p3_0,
  143640. 1, -533725184, 1611661312, 3, 0,
  143641. _vq_quantlist__44u3__p3_0,
  143642. NULL,
  143643. &_vq_auxt__44u3__p3_0,
  143644. NULL,
  143645. 0
  143646. };
  143647. static long _vq_quantlist__44u3__p4_0[] = {
  143648. 2,
  143649. 1,
  143650. 3,
  143651. 0,
  143652. 4,
  143653. };
  143654. static long _vq_lengthlist__44u3__p4_0[] = {
  143655. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143656. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143657. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143658. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143659. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143660. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143661. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  143662. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  143663. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143664. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143665. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143666. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143667. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143668. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  143669. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143670. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143671. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143672. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143673. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143674. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  143675. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143676. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143677. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143678. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143679. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  143680. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  143681. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  143682. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  143683. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143684. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  143685. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  143686. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143687. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143688. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143689. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  143690. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  143691. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  143692. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  143693. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  143694. 13,
  143695. };
  143696. static float _vq_quantthresh__44u3__p4_0[] = {
  143697. -1.5, -0.5, 0.5, 1.5,
  143698. };
  143699. static long _vq_quantmap__44u3__p4_0[] = {
  143700. 3, 1, 0, 2, 4,
  143701. };
  143702. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  143703. _vq_quantthresh__44u3__p4_0,
  143704. _vq_quantmap__44u3__p4_0,
  143705. 5,
  143706. 5
  143707. };
  143708. static static_codebook _44u3__p4_0 = {
  143709. 4, 625,
  143710. _vq_lengthlist__44u3__p4_0,
  143711. 1, -533725184, 1611661312, 3, 0,
  143712. _vq_quantlist__44u3__p4_0,
  143713. NULL,
  143714. &_vq_auxt__44u3__p4_0,
  143715. NULL,
  143716. 0
  143717. };
  143718. static long _vq_quantlist__44u3__p5_0[] = {
  143719. 4,
  143720. 3,
  143721. 5,
  143722. 2,
  143723. 6,
  143724. 1,
  143725. 7,
  143726. 0,
  143727. 8,
  143728. };
  143729. static long _vq_lengthlist__44u3__p5_0[] = {
  143730. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143731. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143732. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  143733. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143734. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  143735. 12,
  143736. };
  143737. static float _vq_quantthresh__44u3__p5_0[] = {
  143738. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143739. };
  143740. static long _vq_quantmap__44u3__p5_0[] = {
  143741. 7, 5, 3, 1, 0, 2, 4, 6,
  143742. 8,
  143743. };
  143744. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  143745. _vq_quantthresh__44u3__p5_0,
  143746. _vq_quantmap__44u3__p5_0,
  143747. 9,
  143748. 9
  143749. };
  143750. static static_codebook _44u3__p5_0 = {
  143751. 2, 81,
  143752. _vq_lengthlist__44u3__p5_0,
  143753. 1, -531628032, 1611661312, 4, 0,
  143754. _vq_quantlist__44u3__p5_0,
  143755. NULL,
  143756. &_vq_auxt__44u3__p5_0,
  143757. NULL,
  143758. 0
  143759. };
  143760. static long _vq_quantlist__44u3__p6_0[] = {
  143761. 6,
  143762. 5,
  143763. 7,
  143764. 4,
  143765. 8,
  143766. 3,
  143767. 9,
  143768. 2,
  143769. 10,
  143770. 1,
  143771. 11,
  143772. 0,
  143773. 12,
  143774. };
  143775. static long _vq_lengthlist__44u3__p6_0[] = {
  143776. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  143777. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143778. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143779. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143780. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  143781. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  143782. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  143783. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  143784. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  143785. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  143786. 15,16,16,16,17,18,16,20,18,
  143787. };
  143788. static float _vq_quantthresh__44u3__p6_0[] = {
  143789. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143790. 12.5, 17.5, 22.5, 27.5,
  143791. };
  143792. static long _vq_quantmap__44u3__p6_0[] = {
  143793. 11, 9, 7, 5, 3, 1, 0, 2,
  143794. 4, 6, 8, 10, 12,
  143795. };
  143796. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  143797. _vq_quantthresh__44u3__p6_0,
  143798. _vq_quantmap__44u3__p6_0,
  143799. 13,
  143800. 13
  143801. };
  143802. static static_codebook _44u3__p6_0 = {
  143803. 2, 169,
  143804. _vq_lengthlist__44u3__p6_0,
  143805. 1, -526516224, 1616117760, 4, 0,
  143806. _vq_quantlist__44u3__p6_0,
  143807. NULL,
  143808. &_vq_auxt__44u3__p6_0,
  143809. NULL,
  143810. 0
  143811. };
  143812. static long _vq_quantlist__44u3__p6_1[] = {
  143813. 2,
  143814. 1,
  143815. 3,
  143816. 0,
  143817. 4,
  143818. };
  143819. static long _vq_lengthlist__44u3__p6_1[] = {
  143820. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143821. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143822. };
  143823. static float _vq_quantthresh__44u3__p6_1[] = {
  143824. -1.5, -0.5, 0.5, 1.5,
  143825. };
  143826. static long _vq_quantmap__44u3__p6_1[] = {
  143827. 3, 1, 0, 2, 4,
  143828. };
  143829. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  143830. _vq_quantthresh__44u3__p6_1,
  143831. _vq_quantmap__44u3__p6_1,
  143832. 5,
  143833. 5
  143834. };
  143835. static static_codebook _44u3__p6_1 = {
  143836. 2, 25,
  143837. _vq_lengthlist__44u3__p6_1,
  143838. 1, -533725184, 1611661312, 3, 0,
  143839. _vq_quantlist__44u3__p6_1,
  143840. NULL,
  143841. &_vq_auxt__44u3__p6_1,
  143842. NULL,
  143843. 0
  143844. };
  143845. static long _vq_quantlist__44u3__p7_0[] = {
  143846. 4,
  143847. 3,
  143848. 5,
  143849. 2,
  143850. 6,
  143851. 1,
  143852. 7,
  143853. 0,
  143854. 8,
  143855. };
  143856. static long _vq_lengthlist__44u3__p7_0[] = {
  143857. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  143858. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143859. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143860. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143862. 9,
  143863. };
  143864. static float _vq_quantthresh__44u3__p7_0[] = {
  143865. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  143866. };
  143867. static long _vq_quantmap__44u3__p7_0[] = {
  143868. 7, 5, 3, 1, 0, 2, 4, 6,
  143869. 8,
  143870. };
  143871. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  143872. _vq_quantthresh__44u3__p7_0,
  143873. _vq_quantmap__44u3__p7_0,
  143874. 9,
  143875. 9
  143876. };
  143877. static static_codebook _44u3__p7_0 = {
  143878. 2, 81,
  143879. _vq_lengthlist__44u3__p7_0,
  143880. 1, -515907584, 1627381760, 4, 0,
  143881. _vq_quantlist__44u3__p7_0,
  143882. NULL,
  143883. &_vq_auxt__44u3__p7_0,
  143884. NULL,
  143885. 0
  143886. };
  143887. static long _vq_quantlist__44u3__p7_1[] = {
  143888. 7,
  143889. 6,
  143890. 8,
  143891. 5,
  143892. 9,
  143893. 4,
  143894. 10,
  143895. 3,
  143896. 11,
  143897. 2,
  143898. 12,
  143899. 1,
  143900. 13,
  143901. 0,
  143902. 14,
  143903. };
  143904. static long _vq_lengthlist__44u3__p7_1[] = {
  143905. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  143906. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  143907. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  143908. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  143909. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  143910. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  143911. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  143912. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  143913. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  143914. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  143915. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  143916. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  143917. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  143918. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  143919. 17,
  143920. };
  143921. static float _vq_quantthresh__44u3__p7_1[] = {
  143922. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143923. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143924. };
  143925. static long _vq_quantmap__44u3__p7_1[] = {
  143926. 13, 11, 9, 7, 5, 3, 1, 0,
  143927. 2, 4, 6, 8, 10, 12, 14,
  143928. };
  143929. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  143930. _vq_quantthresh__44u3__p7_1,
  143931. _vq_quantmap__44u3__p7_1,
  143932. 15,
  143933. 15
  143934. };
  143935. static static_codebook _44u3__p7_1 = {
  143936. 2, 225,
  143937. _vq_lengthlist__44u3__p7_1,
  143938. 1, -522338304, 1620115456, 4, 0,
  143939. _vq_quantlist__44u3__p7_1,
  143940. NULL,
  143941. &_vq_auxt__44u3__p7_1,
  143942. NULL,
  143943. 0
  143944. };
  143945. static long _vq_quantlist__44u3__p7_2[] = {
  143946. 8,
  143947. 7,
  143948. 9,
  143949. 6,
  143950. 10,
  143951. 5,
  143952. 11,
  143953. 4,
  143954. 12,
  143955. 3,
  143956. 13,
  143957. 2,
  143958. 14,
  143959. 1,
  143960. 15,
  143961. 0,
  143962. 16,
  143963. };
  143964. static long _vq_lengthlist__44u3__p7_2[] = {
  143965. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143966. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143967. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  143968. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143969. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143970. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143971. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  143972. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143973. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  143974. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143975. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143976. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  143977. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  143978. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143979. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  143980. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  143981. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143982. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  143983. 11,
  143984. };
  143985. static float _vq_quantthresh__44u3__p7_2[] = {
  143986. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143987. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143988. };
  143989. static long _vq_quantmap__44u3__p7_2[] = {
  143990. 15, 13, 11, 9, 7, 5, 3, 1,
  143991. 0, 2, 4, 6, 8, 10, 12, 14,
  143992. 16,
  143993. };
  143994. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  143995. _vq_quantthresh__44u3__p7_2,
  143996. _vq_quantmap__44u3__p7_2,
  143997. 17,
  143998. 17
  143999. };
  144000. static static_codebook _44u3__p7_2 = {
  144001. 2, 289,
  144002. _vq_lengthlist__44u3__p7_2,
  144003. 1, -529530880, 1611661312, 5, 0,
  144004. _vq_quantlist__44u3__p7_2,
  144005. NULL,
  144006. &_vq_auxt__44u3__p7_2,
  144007. NULL,
  144008. 0
  144009. };
  144010. static long _huff_lengthlist__44u3__short[] = {
  144011. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  144012. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  144013. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  144014. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  144015. };
  144016. static static_codebook _huff_book__44u3__short = {
  144017. 2, 64,
  144018. _huff_lengthlist__44u3__short,
  144019. 0, 0, 0, 0, 0,
  144020. NULL,
  144021. NULL,
  144022. NULL,
  144023. NULL,
  144024. 0
  144025. };
  144026. static long _huff_lengthlist__44u4__long[] = {
  144027. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  144028. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  144029. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  144030. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  144031. };
  144032. static static_codebook _huff_book__44u4__long = {
  144033. 2, 64,
  144034. _huff_lengthlist__44u4__long,
  144035. 0, 0, 0, 0, 0,
  144036. NULL,
  144037. NULL,
  144038. NULL,
  144039. NULL,
  144040. 0
  144041. };
  144042. static long _vq_quantlist__44u4__p1_0[] = {
  144043. 1,
  144044. 0,
  144045. 2,
  144046. };
  144047. static long _vq_lengthlist__44u4__p1_0[] = {
  144048. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144049. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144050. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  144051. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144052. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  144053. 13,
  144054. };
  144055. static float _vq_quantthresh__44u4__p1_0[] = {
  144056. -0.5, 0.5,
  144057. };
  144058. static long _vq_quantmap__44u4__p1_0[] = {
  144059. 1, 0, 2,
  144060. };
  144061. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  144062. _vq_quantthresh__44u4__p1_0,
  144063. _vq_quantmap__44u4__p1_0,
  144064. 3,
  144065. 3
  144066. };
  144067. static static_codebook _44u4__p1_0 = {
  144068. 4, 81,
  144069. _vq_lengthlist__44u4__p1_0,
  144070. 1, -535822336, 1611661312, 2, 0,
  144071. _vq_quantlist__44u4__p1_0,
  144072. NULL,
  144073. &_vq_auxt__44u4__p1_0,
  144074. NULL,
  144075. 0
  144076. };
  144077. static long _vq_quantlist__44u4__p2_0[] = {
  144078. 1,
  144079. 0,
  144080. 2,
  144081. };
  144082. static long _vq_lengthlist__44u4__p2_0[] = {
  144083. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144084. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  144085. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144086. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  144087. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  144088. 9,
  144089. };
  144090. static float _vq_quantthresh__44u4__p2_0[] = {
  144091. -0.5, 0.5,
  144092. };
  144093. static long _vq_quantmap__44u4__p2_0[] = {
  144094. 1, 0, 2,
  144095. };
  144096. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  144097. _vq_quantthresh__44u4__p2_0,
  144098. _vq_quantmap__44u4__p2_0,
  144099. 3,
  144100. 3
  144101. };
  144102. static static_codebook _44u4__p2_0 = {
  144103. 4, 81,
  144104. _vq_lengthlist__44u4__p2_0,
  144105. 1, -535822336, 1611661312, 2, 0,
  144106. _vq_quantlist__44u4__p2_0,
  144107. NULL,
  144108. &_vq_auxt__44u4__p2_0,
  144109. NULL,
  144110. 0
  144111. };
  144112. static long _vq_quantlist__44u4__p3_0[] = {
  144113. 2,
  144114. 1,
  144115. 3,
  144116. 0,
  144117. 4,
  144118. };
  144119. static long _vq_lengthlist__44u4__p3_0[] = {
  144120. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144121. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144122. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  144123. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  144124. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144125. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  144126. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  144127. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  144128. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  144129. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  144130. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  144131. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  144132. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  144133. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  144134. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  144135. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  144136. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  144137. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  144138. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  144139. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  144140. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  144141. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  144142. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  144143. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  144144. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  144145. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  144146. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  144147. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  144148. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  144149. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  144150. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  144151. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  144152. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  144153. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  144154. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  144155. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  144156. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  144157. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  144158. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  144159. 0,
  144160. };
  144161. static float _vq_quantthresh__44u4__p3_0[] = {
  144162. -1.5, -0.5, 0.5, 1.5,
  144163. };
  144164. static long _vq_quantmap__44u4__p3_0[] = {
  144165. 3, 1, 0, 2, 4,
  144166. };
  144167. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  144168. _vq_quantthresh__44u4__p3_0,
  144169. _vq_quantmap__44u4__p3_0,
  144170. 5,
  144171. 5
  144172. };
  144173. static static_codebook _44u4__p3_0 = {
  144174. 4, 625,
  144175. _vq_lengthlist__44u4__p3_0,
  144176. 1, -533725184, 1611661312, 3, 0,
  144177. _vq_quantlist__44u4__p3_0,
  144178. NULL,
  144179. &_vq_auxt__44u4__p3_0,
  144180. NULL,
  144181. 0
  144182. };
  144183. static long _vq_quantlist__44u4__p4_0[] = {
  144184. 2,
  144185. 1,
  144186. 3,
  144187. 0,
  144188. 4,
  144189. };
  144190. static long _vq_lengthlist__44u4__p4_0[] = {
  144191. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144192. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144193. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144194. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144195. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144196. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144197. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  144198. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  144199. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144200. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144201. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144202. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144203. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144204. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  144205. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144206. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144207. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144208. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144209. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144210. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144211. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144212. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144213. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144214. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144215. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144216. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  144217. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  144218. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  144219. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  144220. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  144221. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  144222. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144223. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144224. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  144225. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144226. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  144227. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144228. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  144229. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  144230. 13,
  144231. };
  144232. static float _vq_quantthresh__44u4__p4_0[] = {
  144233. -1.5, -0.5, 0.5, 1.5,
  144234. };
  144235. static long _vq_quantmap__44u4__p4_0[] = {
  144236. 3, 1, 0, 2, 4,
  144237. };
  144238. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  144239. _vq_quantthresh__44u4__p4_0,
  144240. _vq_quantmap__44u4__p4_0,
  144241. 5,
  144242. 5
  144243. };
  144244. static static_codebook _44u4__p4_0 = {
  144245. 4, 625,
  144246. _vq_lengthlist__44u4__p4_0,
  144247. 1, -533725184, 1611661312, 3, 0,
  144248. _vq_quantlist__44u4__p4_0,
  144249. NULL,
  144250. &_vq_auxt__44u4__p4_0,
  144251. NULL,
  144252. 0
  144253. };
  144254. static long _vq_quantlist__44u4__p5_0[] = {
  144255. 4,
  144256. 3,
  144257. 5,
  144258. 2,
  144259. 6,
  144260. 1,
  144261. 7,
  144262. 0,
  144263. 8,
  144264. };
  144265. static long _vq_lengthlist__44u4__p5_0[] = {
  144266. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  144267. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  144268. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  144269. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144270. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  144271. 12,
  144272. };
  144273. static float _vq_quantthresh__44u4__p5_0[] = {
  144274. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144275. };
  144276. static long _vq_quantmap__44u4__p5_0[] = {
  144277. 7, 5, 3, 1, 0, 2, 4, 6,
  144278. 8,
  144279. };
  144280. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  144281. _vq_quantthresh__44u4__p5_0,
  144282. _vq_quantmap__44u4__p5_0,
  144283. 9,
  144284. 9
  144285. };
  144286. static static_codebook _44u4__p5_0 = {
  144287. 2, 81,
  144288. _vq_lengthlist__44u4__p5_0,
  144289. 1, -531628032, 1611661312, 4, 0,
  144290. _vq_quantlist__44u4__p5_0,
  144291. NULL,
  144292. &_vq_auxt__44u4__p5_0,
  144293. NULL,
  144294. 0
  144295. };
  144296. static long _vq_quantlist__44u4__p6_0[] = {
  144297. 6,
  144298. 5,
  144299. 7,
  144300. 4,
  144301. 8,
  144302. 3,
  144303. 9,
  144304. 2,
  144305. 10,
  144306. 1,
  144307. 11,
  144308. 0,
  144309. 12,
  144310. };
  144311. static long _vq_lengthlist__44u4__p6_0[] = {
  144312. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  144313. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  144314. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144315. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  144316. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  144317. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  144318. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  144319. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  144320. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  144321. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  144322. 16,16,16,17,17,18,17,20,21,
  144323. };
  144324. static float _vq_quantthresh__44u4__p6_0[] = {
  144325. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144326. 12.5, 17.5, 22.5, 27.5,
  144327. };
  144328. static long _vq_quantmap__44u4__p6_0[] = {
  144329. 11, 9, 7, 5, 3, 1, 0, 2,
  144330. 4, 6, 8, 10, 12,
  144331. };
  144332. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  144333. _vq_quantthresh__44u4__p6_0,
  144334. _vq_quantmap__44u4__p6_0,
  144335. 13,
  144336. 13
  144337. };
  144338. static static_codebook _44u4__p6_0 = {
  144339. 2, 169,
  144340. _vq_lengthlist__44u4__p6_0,
  144341. 1, -526516224, 1616117760, 4, 0,
  144342. _vq_quantlist__44u4__p6_0,
  144343. NULL,
  144344. &_vq_auxt__44u4__p6_0,
  144345. NULL,
  144346. 0
  144347. };
  144348. static long _vq_quantlist__44u4__p6_1[] = {
  144349. 2,
  144350. 1,
  144351. 3,
  144352. 0,
  144353. 4,
  144354. };
  144355. static long _vq_lengthlist__44u4__p6_1[] = {
  144356. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144357. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144358. };
  144359. static float _vq_quantthresh__44u4__p6_1[] = {
  144360. -1.5, -0.5, 0.5, 1.5,
  144361. };
  144362. static long _vq_quantmap__44u4__p6_1[] = {
  144363. 3, 1, 0, 2, 4,
  144364. };
  144365. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  144366. _vq_quantthresh__44u4__p6_1,
  144367. _vq_quantmap__44u4__p6_1,
  144368. 5,
  144369. 5
  144370. };
  144371. static static_codebook _44u4__p6_1 = {
  144372. 2, 25,
  144373. _vq_lengthlist__44u4__p6_1,
  144374. 1, -533725184, 1611661312, 3, 0,
  144375. _vq_quantlist__44u4__p6_1,
  144376. NULL,
  144377. &_vq_auxt__44u4__p6_1,
  144378. NULL,
  144379. 0
  144380. };
  144381. static long _vq_quantlist__44u4__p7_0[] = {
  144382. 6,
  144383. 5,
  144384. 7,
  144385. 4,
  144386. 8,
  144387. 3,
  144388. 9,
  144389. 2,
  144390. 10,
  144391. 1,
  144392. 11,
  144393. 0,
  144394. 12,
  144395. };
  144396. static long _vq_lengthlist__44u4__p7_0[] = {
  144397. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  144398. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  144399. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144400. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144401. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144402. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144403. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144404. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144405. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144406. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144407. 11,11,11,11,11,11,11,11,11,
  144408. };
  144409. static float _vq_quantthresh__44u4__p7_0[] = {
  144410. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144411. 637.5, 892.5, 1147.5, 1402.5,
  144412. };
  144413. static long _vq_quantmap__44u4__p7_0[] = {
  144414. 11, 9, 7, 5, 3, 1, 0, 2,
  144415. 4, 6, 8, 10, 12,
  144416. };
  144417. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  144418. _vq_quantthresh__44u4__p7_0,
  144419. _vq_quantmap__44u4__p7_0,
  144420. 13,
  144421. 13
  144422. };
  144423. static static_codebook _44u4__p7_0 = {
  144424. 2, 169,
  144425. _vq_lengthlist__44u4__p7_0,
  144426. 1, -514332672, 1627381760, 4, 0,
  144427. _vq_quantlist__44u4__p7_0,
  144428. NULL,
  144429. &_vq_auxt__44u4__p7_0,
  144430. NULL,
  144431. 0
  144432. };
  144433. static long _vq_quantlist__44u4__p7_1[] = {
  144434. 7,
  144435. 6,
  144436. 8,
  144437. 5,
  144438. 9,
  144439. 4,
  144440. 10,
  144441. 3,
  144442. 11,
  144443. 2,
  144444. 12,
  144445. 1,
  144446. 13,
  144447. 0,
  144448. 14,
  144449. };
  144450. static long _vq_lengthlist__44u4__p7_1[] = {
  144451. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  144452. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  144453. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  144454. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  144455. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  144456. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  144457. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  144458. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  144459. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  144460. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  144461. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  144462. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  144463. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  144464. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  144465. 16,
  144466. };
  144467. static float _vq_quantthresh__44u4__p7_1[] = {
  144468. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144469. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144470. };
  144471. static long _vq_quantmap__44u4__p7_1[] = {
  144472. 13, 11, 9, 7, 5, 3, 1, 0,
  144473. 2, 4, 6, 8, 10, 12, 14,
  144474. };
  144475. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  144476. _vq_quantthresh__44u4__p7_1,
  144477. _vq_quantmap__44u4__p7_1,
  144478. 15,
  144479. 15
  144480. };
  144481. static static_codebook _44u4__p7_1 = {
  144482. 2, 225,
  144483. _vq_lengthlist__44u4__p7_1,
  144484. 1, -522338304, 1620115456, 4, 0,
  144485. _vq_quantlist__44u4__p7_1,
  144486. NULL,
  144487. &_vq_auxt__44u4__p7_1,
  144488. NULL,
  144489. 0
  144490. };
  144491. static long _vq_quantlist__44u4__p7_2[] = {
  144492. 8,
  144493. 7,
  144494. 9,
  144495. 6,
  144496. 10,
  144497. 5,
  144498. 11,
  144499. 4,
  144500. 12,
  144501. 3,
  144502. 13,
  144503. 2,
  144504. 14,
  144505. 1,
  144506. 15,
  144507. 0,
  144508. 16,
  144509. };
  144510. static long _vq_lengthlist__44u4__p7_2[] = {
  144511. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144512. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144513. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144514. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144515. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144516. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144517. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144518. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144519. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  144520. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  144521. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144522. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  144523. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144524. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  144525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  144526. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144527. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144528. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  144529. 10,
  144530. };
  144531. static float _vq_quantthresh__44u4__p7_2[] = {
  144532. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144533. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144534. };
  144535. static long _vq_quantmap__44u4__p7_2[] = {
  144536. 15, 13, 11, 9, 7, 5, 3, 1,
  144537. 0, 2, 4, 6, 8, 10, 12, 14,
  144538. 16,
  144539. };
  144540. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  144541. _vq_quantthresh__44u4__p7_2,
  144542. _vq_quantmap__44u4__p7_2,
  144543. 17,
  144544. 17
  144545. };
  144546. static static_codebook _44u4__p7_2 = {
  144547. 2, 289,
  144548. _vq_lengthlist__44u4__p7_2,
  144549. 1, -529530880, 1611661312, 5, 0,
  144550. _vq_quantlist__44u4__p7_2,
  144551. NULL,
  144552. &_vq_auxt__44u4__p7_2,
  144553. NULL,
  144554. 0
  144555. };
  144556. static long _huff_lengthlist__44u4__short[] = {
  144557. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  144558. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  144559. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  144560. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  144561. };
  144562. static static_codebook _huff_book__44u4__short = {
  144563. 2, 64,
  144564. _huff_lengthlist__44u4__short,
  144565. 0, 0, 0, 0, 0,
  144566. NULL,
  144567. NULL,
  144568. NULL,
  144569. NULL,
  144570. 0
  144571. };
  144572. static long _huff_lengthlist__44u5__long[] = {
  144573. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  144574. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  144575. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  144576. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  144577. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  144578. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  144579. 14, 8, 7, 8,
  144580. };
  144581. static static_codebook _huff_book__44u5__long = {
  144582. 2, 100,
  144583. _huff_lengthlist__44u5__long,
  144584. 0, 0, 0, 0, 0,
  144585. NULL,
  144586. NULL,
  144587. NULL,
  144588. NULL,
  144589. 0
  144590. };
  144591. static long _vq_quantlist__44u5__p1_0[] = {
  144592. 1,
  144593. 0,
  144594. 2,
  144595. };
  144596. static long _vq_lengthlist__44u5__p1_0[] = {
  144597. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144598. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  144599. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144600. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  144601. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  144602. 12,
  144603. };
  144604. static float _vq_quantthresh__44u5__p1_0[] = {
  144605. -0.5, 0.5,
  144606. };
  144607. static long _vq_quantmap__44u5__p1_0[] = {
  144608. 1, 0, 2,
  144609. };
  144610. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  144611. _vq_quantthresh__44u5__p1_0,
  144612. _vq_quantmap__44u5__p1_0,
  144613. 3,
  144614. 3
  144615. };
  144616. static static_codebook _44u5__p1_0 = {
  144617. 4, 81,
  144618. _vq_lengthlist__44u5__p1_0,
  144619. 1, -535822336, 1611661312, 2, 0,
  144620. _vq_quantlist__44u5__p1_0,
  144621. NULL,
  144622. &_vq_auxt__44u5__p1_0,
  144623. NULL,
  144624. 0
  144625. };
  144626. static long _vq_quantlist__44u5__p2_0[] = {
  144627. 1,
  144628. 0,
  144629. 2,
  144630. };
  144631. static long _vq_lengthlist__44u5__p2_0[] = {
  144632. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144633. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144634. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144635. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144636. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144637. 9,
  144638. };
  144639. static float _vq_quantthresh__44u5__p2_0[] = {
  144640. -0.5, 0.5,
  144641. };
  144642. static long _vq_quantmap__44u5__p2_0[] = {
  144643. 1, 0, 2,
  144644. };
  144645. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  144646. _vq_quantthresh__44u5__p2_0,
  144647. _vq_quantmap__44u5__p2_0,
  144648. 3,
  144649. 3
  144650. };
  144651. static static_codebook _44u5__p2_0 = {
  144652. 4, 81,
  144653. _vq_lengthlist__44u5__p2_0,
  144654. 1, -535822336, 1611661312, 2, 0,
  144655. _vq_quantlist__44u5__p2_0,
  144656. NULL,
  144657. &_vq_auxt__44u5__p2_0,
  144658. NULL,
  144659. 0
  144660. };
  144661. static long _vq_quantlist__44u5__p3_0[] = {
  144662. 2,
  144663. 1,
  144664. 3,
  144665. 0,
  144666. 4,
  144667. };
  144668. static long _vq_lengthlist__44u5__p3_0[] = {
  144669. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144670. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144671. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144672. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  144673. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  144674. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  144675. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144676. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  144677. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  144678. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144679. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  144680. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144681. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  144682. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  144683. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  144684. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  144685. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144686. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  144687. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  144688. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  144689. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  144690. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  144691. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  144692. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  144693. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  144694. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  144695. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  144696. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  144697. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  144698. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  144699. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  144700. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  144701. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  144702. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  144703. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  144704. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  144705. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  144706. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  144707. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  144708. 0,
  144709. };
  144710. static float _vq_quantthresh__44u5__p3_0[] = {
  144711. -1.5, -0.5, 0.5, 1.5,
  144712. };
  144713. static long _vq_quantmap__44u5__p3_0[] = {
  144714. 3, 1, 0, 2, 4,
  144715. };
  144716. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  144717. _vq_quantthresh__44u5__p3_0,
  144718. _vq_quantmap__44u5__p3_0,
  144719. 5,
  144720. 5
  144721. };
  144722. static static_codebook _44u5__p3_0 = {
  144723. 4, 625,
  144724. _vq_lengthlist__44u5__p3_0,
  144725. 1, -533725184, 1611661312, 3, 0,
  144726. _vq_quantlist__44u5__p3_0,
  144727. NULL,
  144728. &_vq_auxt__44u5__p3_0,
  144729. NULL,
  144730. 0
  144731. };
  144732. static long _vq_quantlist__44u5__p4_0[] = {
  144733. 2,
  144734. 1,
  144735. 3,
  144736. 0,
  144737. 4,
  144738. };
  144739. static long _vq_lengthlist__44u5__p4_0[] = {
  144740. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144741. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144742. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  144743. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144744. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  144745. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144746. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144747. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  144748. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144749. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  144750. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  144751. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144752. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144753. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  144754. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  144755. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  144756. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144757. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144758. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144759. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  144760. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  144761. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  144762. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  144763. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  144764. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  144765. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144766. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  144767. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  144768. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  144769. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  144770. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  144771. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144772. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  144773. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  144774. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  144775. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  144776. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  144777. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  144778. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  144779. 12,
  144780. };
  144781. static float _vq_quantthresh__44u5__p4_0[] = {
  144782. -1.5, -0.5, 0.5, 1.5,
  144783. };
  144784. static long _vq_quantmap__44u5__p4_0[] = {
  144785. 3, 1, 0, 2, 4,
  144786. };
  144787. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  144788. _vq_quantthresh__44u5__p4_0,
  144789. _vq_quantmap__44u5__p4_0,
  144790. 5,
  144791. 5
  144792. };
  144793. static static_codebook _44u5__p4_0 = {
  144794. 4, 625,
  144795. _vq_lengthlist__44u5__p4_0,
  144796. 1, -533725184, 1611661312, 3, 0,
  144797. _vq_quantlist__44u5__p4_0,
  144798. NULL,
  144799. &_vq_auxt__44u5__p4_0,
  144800. NULL,
  144801. 0
  144802. };
  144803. static long _vq_quantlist__44u5__p5_0[] = {
  144804. 4,
  144805. 3,
  144806. 5,
  144807. 2,
  144808. 6,
  144809. 1,
  144810. 7,
  144811. 0,
  144812. 8,
  144813. };
  144814. static long _vq_lengthlist__44u5__p5_0[] = {
  144815. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144816. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  144817. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144818. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  144819. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  144820. 14,
  144821. };
  144822. static float _vq_quantthresh__44u5__p5_0[] = {
  144823. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144824. };
  144825. static long _vq_quantmap__44u5__p5_0[] = {
  144826. 7, 5, 3, 1, 0, 2, 4, 6,
  144827. 8,
  144828. };
  144829. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  144830. _vq_quantthresh__44u5__p5_0,
  144831. _vq_quantmap__44u5__p5_0,
  144832. 9,
  144833. 9
  144834. };
  144835. static static_codebook _44u5__p5_0 = {
  144836. 2, 81,
  144837. _vq_lengthlist__44u5__p5_0,
  144838. 1, -531628032, 1611661312, 4, 0,
  144839. _vq_quantlist__44u5__p5_0,
  144840. NULL,
  144841. &_vq_auxt__44u5__p5_0,
  144842. NULL,
  144843. 0
  144844. };
  144845. static long _vq_quantlist__44u5__p6_0[] = {
  144846. 4,
  144847. 3,
  144848. 5,
  144849. 2,
  144850. 6,
  144851. 1,
  144852. 7,
  144853. 0,
  144854. 8,
  144855. };
  144856. static long _vq_lengthlist__44u5__p6_0[] = {
  144857. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144858. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144859. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144860. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144861. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  144862. 11,
  144863. };
  144864. static float _vq_quantthresh__44u5__p6_0[] = {
  144865. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144866. };
  144867. static long _vq_quantmap__44u5__p6_0[] = {
  144868. 7, 5, 3, 1, 0, 2, 4, 6,
  144869. 8,
  144870. };
  144871. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  144872. _vq_quantthresh__44u5__p6_0,
  144873. _vq_quantmap__44u5__p6_0,
  144874. 9,
  144875. 9
  144876. };
  144877. static static_codebook _44u5__p6_0 = {
  144878. 2, 81,
  144879. _vq_lengthlist__44u5__p6_0,
  144880. 1, -531628032, 1611661312, 4, 0,
  144881. _vq_quantlist__44u5__p6_0,
  144882. NULL,
  144883. &_vq_auxt__44u5__p6_0,
  144884. NULL,
  144885. 0
  144886. };
  144887. static long _vq_quantlist__44u5__p7_0[] = {
  144888. 1,
  144889. 0,
  144890. 2,
  144891. };
  144892. static long _vq_lengthlist__44u5__p7_0[] = {
  144893. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  144894. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  144895. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  144896. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  144897. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  144898. 12,
  144899. };
  144900. static float _vq_quantthresh__44u5__p7_0[] = {
  144901. -5.5, 5.5,
  144902. };
  144903. static long _vq_quantmap__44u5__p7_0[] = {
  144904. 1, 0, 2,
  144905. };
  144906. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  144907. _vq_quantthresh__44u5__p7_0,
  144908. _vq_quantmap__44u5__p7_0,
  144909. 3,
  144910. 3
  144911. };
  144912. static static_codebook _44u5__p7_0 = {
  144913. 4, 81,
  144914. _vq_lengthlist__44u5__p7_0,
  144915. 1, -529137664, 1618345984, 2, 0,
  144916. _vq_quantlist__44u5__p7_0,
  144917. NULL,
  144918. &_vq_auxt__44u5__p7_0,
  144919. NULL,
  144920. 0
  144921. };
  144922. static long _vq_quantlist__44u5__p7_1[] = {
  144923. 5,
  144924. 4,
  144925. 6,
  144926. 3,
  144927. 7,
  144928. 2,
  144929. 8,
  144930. 1,
  144931. 9,
  144932. 0,
  144933. 10,
  144934. };
  144935. static long _vq_lengthlist__44u5__p7_1[] = {
  144936. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144937. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  144938. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144939. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  144940. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144941. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144942. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144943. 9, 9, 9, 9, 9,10,10,10,10,
  144944. };
  144945. static float _vq_quantthresh__44u5__p7_1[] = {
  144946. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144947. 3.5, 4.5,
  144948. };
  144949. static long _vq_quantmap__44u5__p7_1[] = {
  144950. 9, 7, 5, 3, 1, 0, 2, 4,
  144951. 6, 8, 10,
  144952. };
  144953. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  144954. _vq_quantthresh__44u5__p7_1,
  144955. _vq_quantmap__44u5__p7_1,
  144956. 11,
  144957. 11
  144958. };
  144959. static static_codebook _44u5__p7_1 = {
  144960. 2, 121,
  144961. _vq_lengthlist__44u5__p7_1,
  144962. 1, -531365888, 1611661312, 4, 0,
  144963. _vq_quantlist__44u5__p7_1,
  144964. NULL,
  144965. &_vq_auxt__44u5__p7_1,
  144966. NULL,
  144967. 0
  144968. };
  144969. static long _vq_quantlist__44u5__p8_0[] = {
  144970. 5,
  144971. 4,
  144972. 6,
  144973. 3,
  144974. 7,
  144975. 2,
  144976. 8,
  144977. 1,
  144978. 9,
  144979. 0,
  144980. 10,
  144981. };
  144982. static long _vq_lengthlist__44u5__p8_0[] = {
  144983. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144984. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144985. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  144986. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  144987. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  144988. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  144989. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  144990. 12,13,13,14,14,14,14,15,15,
  144991. };
  144992. static float _vq_quantthresh__44u5__p8_0[] = {
  144993. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144994. 38.5, 49.5,
  144995. };
  144996. static long _vq_quantmap__44u5__p8_0[] = {
  144997. 9, 7, 5, 3, 1, 0, 2, 4,
  144998. 6, 8, 10,
  144999. };
  145000. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  145001. _vq_quantthresh__44u5__p8_0,
  145002. _vq_quantmap__44u5__p8_0,
  145003. 11,
  145004. 11
  145005. };
  145006. static static_codebook _44u5__p8_0 = {
  145007. 2, 121,
  145008. _vq_lengthlist__44u5__p8_0,
  145009. 1, -524582912, 1618345984, 4, 0,
  145010. _vq_quantlist__44u5__p8_0,
  145011. NULL,
  145012. &_vq_auxt__44u5__p8_0,
  145013. NULL,
  145014. 0
  145015. };
  145016. static long _vq_quantlist__44u5__p8_1[] = {
  145017. 5,
  145018. 4,
  145019. 6,
  145020. 3,
  145021. 7,
  145022. 2,
  145023. 8,
  145024. 1,
  145025. 9,
  145026. 0,
  145027. 10,
  145028. };
  145029. static long _vq_lengthlist__44u5__p8_1[] = {
  145030. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  145031. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  145032. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  145033. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145034. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  145035. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145036. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145037. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145038. };
  145039. static float _vq_quantthresh__44u5__p8_1[] = {
  145040. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145041. 3.5, 4.5,
  145042. };
  145043. static long _vq_quantmap__44u5__p8_1[] = {
  145044. 9, 7, 5, 3, 1, 0, 2, 4,
  145045. 6, 8, 10,
  145046. };
  145047. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  145048. _vq_quantthresh__44u5__p8_1,
  145049. _vq_quantmap__44u5__p8_1,
  145050. 11,
  145051. 11
  145052. };
  145053. static static_codebook _44u5__p8_1 = {
  145054. 2, 121,
  145055. _vq_lengthlist__44u5__p8_1,
  145056. 1, -531365888, 1611661312, 4, 0,
  145057. _vq_quantlist__44u5__p8_1,
  145058. NULL,
  145059. &_vq_auxt__44u5__p8_1,
  145060. NULL,
  145061. 0
  145062. };
  145063. static long _vq_quantlist__44u5__p9_0[] = {
  145064. 6,
  145065. 5,
  145066. 7,
  145067. 4,
  145068. 8,
  145069. 3,
  145070. 9,
  145071. 2,
  145072. 10,
  145073. 1,
  145074. 11,
  145075. 0,
  145076. 12,
  145077. };
  145078. static long _vq_lengthlist__44u5__p9_0[] = {
  145079. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  145080. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  145081. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  145082. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  145083. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145084. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145085. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145086. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145087. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  145088. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145089. 12,12,12,12,12,12,12,12,12,
  145090. };
  145091. static float _vq_quantthresh__44u5__p9_0[] = {
  145092. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145093. 637.5, 892.5, 1147.5, 1402.5,
  145094. };
  145095. static long _vq_quantmap__44u5__p9_0[] = {
  145096. 11, 9, 7, 5, 3, 1, 0, 2,
  145097. 4, 6, 8, 10, 12,
  145098. };
  145099. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  145100. _vq_quantthresh__44u5__p9_0,
  145101. _vq_quantmap__44u5__p9_0,
  145102. 13,
  145103. 13
  145104. };
  145105. static static_codebook _44u5__p9_0 = {
  145106. 2, 169,
  145107. _vq_lengthlist__44u5__p9_0,
  145108. 1, -514332672, 1627381760, 4, 0,
  145109. _vq_quantlist__44u5__p9_0,
  145110. NULL,
  145111. &_vq_auxt__44u5__p9_0,
  145112. NULL,
  145113. 0
  145114. };
  145115. static long _vq_quantlist__44u5__p9_1[] = {
  145116. 7,
  145117. 6,
  145118. 8,
  145119. 5,
  145120. 9,
  145121. 4,
  145122. 10,
  145123. 3,
  145124. 11,
  145125. 2,
  145126. 12,
  145127. 1,
  145128. 13,
  145129. 0,
  145130. 14,
  145131. };
  145132. static long _vq_lengthlist__44u5__p9_1[] = {
  145133. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  145134. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  145135. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  145136. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  145137. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  145138. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  145139. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  145140. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  145141. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  145142. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  145143. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  145144. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  145145. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  145146. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  145147. 14,
  145148. };
  145149. static float _vq_quantthresh__44u5__p9_1[] = {
  145150. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145151. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145152. };
  145153. static long _vq_quantmap__44u5__p9_1[] = {
  145154. 13, 11, 9, 7, 5, 3, 1, 0,
  145155. 2, 4, 6, 8, 10, 12, 14,
  145156. };
  145157. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  145158. _vq_quantthresh__44u5__p9_1,
  145159. _vq_quantmap__44u5__p9_1,
  145160. 15,
  145161. 15
  145162. };
  145163. static static_codebook _44u5__p9_1 = {
  145164. 2, 225,
  145165. _vq_lengthlist__44u5__p9_1,
  145166. 1, -522338304, 1620115456, 4, 0,
  145167. _vq_quantlist__44u5__p9_1,
  145168. NULL,
  145169. &_vq_auxt__44u5__p9_1,
  145170. NULL,
  145171. 0
  145172. };
  145173. static long _vq_quantlist__44u5__p9_2[] = {
  145174. 8,
  145175. 7,
  145176. 9,
  145177. 6,
  145178. 10,
  145179. 5,
  145180. 11,
  145181. 4,
  145182. 12,
  145183. 3,
  145184. 13,
  145185. 2,
  145186. 14,
  145187. 1,
  145188. 15,
  145189. 0,
  145190. 16,
  145191. };
  145192. static long _vq_lengthlist__44u5__p9_2[] = {
  145193. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145194. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145195. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145196. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145197. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145198. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145199. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145200. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145201. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145202. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  145203. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  145204. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145205. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145206. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145207. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145208. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145209. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145210. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  145211. 10,
  145212. };
  145213. static float _vq_quantthresh__44u5__p9_2[] = {
  145214. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145215. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145216. };
  145217. static long _vq_quantmap__44u5__p9_2[] = {
  145218. 15, 13, 11, 9, 7, 5, 3, 1,
  145219. 0, 2, 4, 6, 8, 10, 12, 14,
  145220. 16,
  145221. };
  145222. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  145223. _vq_quantthresh__44u5__p9_2,
  145224. _vq_quantmap__44u5__p9_2,
  145225. 17,
  145226. 17
  145227. };
  145228. static static_codebook _44u5__p9_2 = {
  145229. 2, 289,
  145230. _vq_lengthlist__44u5__p9_2,
  145231. 1, -529530880, 1611661312, 5, 0,
  145232. _vq_quantlist__44u5__p9_2,
  145233. NULL,
  145234. &_vq_auxt__44u5__p9_2,
  145235. NULL,
  145236. 0
  145237. };
  145238. static long _huff_lengthlist__44u5__short[] = {
  145239. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  145240. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  145241. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  145242. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  145243. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  145244. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  145245. 6, 8,15,17,
  145246. };
  145247. static static_codebook _huff_book__44u5__short = {
  145248. 2, 100,
  145249. _huff_lengthlist__44u5__short,
  145250. 0, 0, 0, 0, 0,
  145251. NULL,
  145252. NULL,
  145253. NULL,
  145254. NULL,
  145255. 0
  145256. };
  145257. static long _huff_lengthlist__44u6__long[] = {
  145258. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  145259. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  145260. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  145261. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  145262. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  145263. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  145264. 13, 8, 7, 7,
  145265. };
  145266. static static_codebook _huff_book__44u6__long = {
  145267. 2, 100,
  145268. _huff_lengthlist__44u6__long,
  145269. 0, 0, 0, 0, 0,
  145270. NULL,
  145271. NULL,
  145272. NULL,
  145273. NULL,
  145274. 0
  145275. };
  145276. static long _vq_quantlist__44u6__p1_0[] = {
  145277. 1,
  145278. 0,
  145279. 2,
  145280. };
  145281. static long _vq_lengthlist__44u6__p1_0[] = {
  145282. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145283. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145284. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145285. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  145286. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145287. 12,
  145288. };
  145289. static float _vq_quantthresh__44u6__p1_0[] = {
  145290. -0.5, 0.5,
  145291. };
  145292. static long _vq_quantmap__44u6__p1_0[] = {
  145293. 1, 0, 2,
  145294. };
  145295. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  145296. _vq_quantthresh__44u6__p1_0,
  145297. _vq_quantmap__44u6__p1_0,
  145298. 3,
  145299. 3
  145300. };
  145301. static static_codebook _44u6__p1_0 = {
  145302. 4, 81,
  145303. _vq_lengthlist__44u6__p1_0,
  145304. 1, -535822336, 1611661312, 2, 0,
  145305. _vq_quantlist__44u6__p1_0,
  145306. NULL,
  145307. &_vq_auxt__44u6__p1_0,
  145308. NULL,
  145309. 0
  145310. };
  145311. static long _vq_quantlist__44u6__p2_0[] = {
  145312. 1,
  145313. 0,
  145314. 2,
  145315. };
  145316. static long _vq_lengthlist__44u6__p2_0[] = {
  145317. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145318. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145319. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  145320. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145321. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145322. 9,
  145323. };
  145324. static float _vq_quantthresh__44u6__p2_0[] = {
  145325. -0.5, 0.5,
  145326. };
  145327. static long _vq_quantmap__44u6__p2_0[] = {
  145328. 1, 0, 2,
  145329. };
  145330. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  145331. _vq_quantthresh__44u6__p2_0,
  145332. _vq_quantmap__44u6__p2_0,
  145333. 3,
  145334. 3
  145335. };
  145336. static static_codebook _44u6__p2_0 = {
  145337. 4, 81,
  145338. _vq_lengthlist__44u6__p2_0,
  145339. 1, -535822336, 1611661312, 2, 0,
  145340. _vq_quantlist__44u6__p2_0,
  145341. NULL,
  145342. &_vq_auxt__44u6__p2_0,
  145343. NULL,
  145344. 0
  145345. };
  145346. static long _vq_quantlist__44u6__p3_0[] = {
  145347. 2,
  145348. 1,
  145349. 3,
  145350. 0,
  145351. 4,
  145352. };
  145353. static long _vq_lengthlist__44u6__p3_0[] = {
  145354. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145355. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145356. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145357. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  145358. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  145359. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  145360. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  145361. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  145362. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  145363. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145364. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  145365. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145366. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  145367. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  145368. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  145369. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  145370. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145371. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145372. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  145373. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  145374. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  145375. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  145376. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  145377. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  145378. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  145379. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  145380. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  145381. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  145382. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  145383. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  145384. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  145385. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  145386. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  145387. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  145388. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  145389. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  145390. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  145391. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  145392. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  145393. 19,
  145394. };
  145395. static float _vq_quantthresh__44u6__p3_0[] = {
  145396. -1.5, -0.5, 0.5, 1.5,
  145397. };
  145398. static long _vq_quantmap__44u6__p3_0[] = {
  145399. 3, 1, 0, 2, 4,
  145400. };
  145401. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  145402. _vq_quantthresh__44u6__p3_0,
  145403. _vq_quantmap__44u6__p3_0,
  145404. 5,
  145405. 5
  145406. };
  145407. static static_codebook _44u6__p3_0 = {
  145408. 4, 625,
  145409. _vq_lengthlist__44u6__p3_0,
  145410. 1, -533725184, 1611661312, 3, 0,
  145411. _vq_quantlist__44u6__p3_0,
  145412. NULL,
  145413. &_vq_auxt__44u6__p3_0,
  145414. NULL,
  145415. 0
  145416. };
  145417. static long _vq_quantlist__44u6__p4_0[] = {
  145418. 2,
  145419. 1,
  145420. 3,
  145421. 0,
  145422. 4,
  145423. };
  145424. static long _vq_lengthlist__44u6__p4_0[] = {
  145425. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145426. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145427. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145428. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  145429. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145430. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  145431. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145432. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  145433. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145434. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145435. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  145436. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145437. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145438. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  145439. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  145440. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145441. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  145442. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145443. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  145444. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  145445. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145446. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145447. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  145448. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145449. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  145450. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145451. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145452. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  145453. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  145454. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  145455. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  145456. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145457. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  145458. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145459. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145460. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145461. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  145462. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  145463. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  145464. 13,
  145465. };
  145466. static float _vq_quantthresh__44u6__p4_0[] = {
  145467. -1.5, -0.5, 0.5, 1.5,
  145468. };
  145469. static long _vq_quantmap__44u6__p4_0[] = {
  145470. 3, 1, 0, 2, 4,
  145471. };
  145472. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  145473. _vq_quantthresh__44u6__p4_0,
  145474. _vq_quantmap__44u6__p4_0,
  145475. 5,
  145476. 5
  145477. };
  145478. static static_codebook _44u6__p4_0 = {
  145479. 4, 625,
  145480. _vq_lengthlist__44u6__p4_0,
  145481. 1, -533725184, 1611661312, 3, 0,
  145482. _vq_quantlist__44u6__p4_0,
  145483. NULL,
  145484. &_vq_auxt__44u6__p4_0,
  145485. NULL,
  145486. 0
  145487. };
  145488. static long _vq_quantlist__44u6__p5_0[] = {
  145489. 4,
  145490. 3,
  145491. 5,
  145492. 2,
  145493. 6,
  145494. 1,
  145495. 7,
  145496. 0,
  145497. 8,
  145498. };
  145499. static long _vq_lengthlist__44u6__p5_0[] = {
  145500. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145501. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  145502. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  145503. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  145504. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  145505. 14,
  145506. };
  145507. static float _vq_quantthresh__44u6__p5_0[] = {
  145508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145509. };
  145510. static long _vq_quantmap__44u6__p5_0[] = {
  145511. 7, 5, 3, 1, 0, 2, 4, 6,
  145512. 8,
  145513. };
  145514. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  145515. _vq_quantthresh__44u6__p5_0,
  145516. _vq_quantmap__44u6__p5_0,
  145517. 9,
  145518. 9
  145519. };
  145520. static static_codebook _44u6__p5_0 = {
  145521. 2, 81,
  145522. _vq_lengthlist__44u6__p5_0,
  145523. 1, -531628032, 1611661312, 4, 0,
  145524. _vq_quantlist__44u6__p5_0,
  145525. NULL,
  145526. &_vq_auxt__44u6__p5_0,
  145527. NULL,
  145528. 0
  145529. };
  145530. static long _vq_quantlist__44u6__p6_0[] = {
  145531. 4,
  145532. 3,
  145533. 5,
  145534. 2,
  145535. 6,
  145536. 1,
  145537. 7,
  145538. 0,
  145539. 8,
  145540. };
  145541. static long _vq_lengthlist__44u6__p6_0[] = {
  145542. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145543. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  145544. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  145545. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  145546. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  145547. 12,
  145548. };
  145549. static float _vq_quantthresh__44u6__p6_0[] = {
  145550. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145551. };
  145552. static long _vq_quantmap__44u6__p6_0[] = {
  145553. 7, 5, 3, 1, 0, 2, 4, 6,
  145554. 8,
  145555. };
  145556. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  145557. _vq_quantthresh__44u6__p6_0,
  145558. _vq_quantmap__44u6__p6_0,
  145559. 9,
  145560. 9
  145561. };
  145562. static static_codebook _44u6__p6_0 = {
  145563. 2, 81,
  145564. _vq_lengthlist__44u6__p6_0,
  145565. 1, -531628032, 1611661312, 4, 0,
  145566. _vq_quantlist__44u6__p6_0,
  145567. NULL,
  145568. &_vq_auxt__44u6__p6_0,
  145569. NULL,
  145570. 0
  145571. };
  145572. static long _vq_quantlist__44u6__p7_0[] = {
  145573. 1,
  145574. 0,
  145575. 2,
  145576. };
  145577. static long _vq_lengthlist__44u6__p7_0[] = {
  145578. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  145579. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  145580. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  145581. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  145582. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  145583. 10,
  145584. };
  145585. static float _vq_quantthresh__44u6__p7_0[] = {
  145586. -5.5, 5.5,
  145587. };
  145588. static long _vq_quantmap__44u6__p7_0[] = {
  145589. 1, 0, 2,
  145590. };
  145591. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  145592. _vq_quantthresh__44u6__p7_0,
  145593. _vq_quantmap__44u6__p7_0,
  145594. 3,
  145595. 3
  145596. };
  145597. static static_codebook _44u6__p7_0 = {
  145598. 4, 81,
  145599. _vq_lengthlist__44u6__p7_0,
  145600. 1, -529137664, 1618345984, 2, 0,
  145601. _vq_quantlist__44u6__p7_0,
  145602. NULL,
  145603. &_vq_auxt__44u6__p7_0,
  145604. NULL,
  145605. 0
  145606. };
  145607. static long _vq_quantlist__44u6__p7_1[] = {
  145608. 5,
  145609. 4,
  145610. 6,
  145611. 3,
  145612. 7,
  145613. 2,
  145614. 8,
  145615. 1,
  145616. 9,
  145617. 0,
  145618. 10,
  145619. };
  145620. static long _vq_lengthlist__44u6__p7_1[] = {
  145621. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  145622. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  145623. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145624. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  145625. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  145626. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  145627. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  145628. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145629. };
  145630. static float _vq_quantthresh__44u6__p7_1[] = {
  145631. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145632. 3.5, 4.5,
  145633. };
  145634. static long _vq_quantmap__44u6__p7_1[] = {
  145635. 9, 7, 5, 3, 1, 0, 2, 4,
  145636. 6, 8, 10,
  145637. };
  145638. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  145639. _vq_quantthresh__44u6__p7_1,
  145640. _vq_quantmap__44u6__p7_1,
  145641. 11,
  145642. 11
  145643. };
  145644. static static_codebook _44u6__p7_1 = {
  145645. 2, 121,
  145646. _vq_lengthlist__44u6__p7_1,
  145647. 1, -531365888, 1611661312, 4, 0,
  145648. _vq_quantlist__44u6__p7_1,
  145649. NULL,
  145650. &_vq_auxt__44u6__p7_1,
  145651. NULL,
  145652. 0
  145653. };
  145654. static long _vq_quantlist__44u6__p8_0[] = {
  145655. 5,
  145656. 4,
  145657. 6,
  145658. 3,
  145659. 7,
  145660. 2,
  145661. 8,
  145662. 1,
  145663. 9,
  145664. 0,
  145665. 10,
  145666. };
  145667. static long _vq_lengthlist__44u6__p8_0[] = {
  145668. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145669. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145670. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  145671. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  145672. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  145673. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  145674. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  145675. 12,13,13,14,14,14,15,15,15,
  145676. };
  145677. static float _vq_quantthresh__44u6__p8_0[] = {
  145678. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145679. 38.5, 49.5,
  145680. };
  145681. static long _vq_quantmap__44u6__p8_0[] = {
  145682. 9, 7, 5, 3, 1, 0, 2, 4,
  145683. 6, 8, 10,
  145684. };
  145685. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  145686. _vq_quantthresh__44u6__p8_0,
  145687. _vq_quantmap__44u6__p8_0,
  145688. 11,
  145689. 11
  145690. };
  145691. static static_codebook _44u6__p8_0 = {
  145692. 2, 121,
  145693. _vq_lengthlist__44u6__p8_0,
  145694. 1, -524582912, 1618345984, 4, 0,
  145695. _vq_quantlist__44u6__p8_0,
  145696. NULL,
  145697. &_vq_auxt__44u6__p8_0,
  145698. NULL,
  145699. 0
  145700. };
  145701. static long _vq_quantlist__44u6__p8_1[] = {
  145702. 5,
  145703. 4,
  145704. 6,
  145705. 3,
  145706. 7,
  145707. 2,
  145708. 8,
  145709. 1,
  145710. 9,
  145711. 0,
  145712. 10,
  145713. };
  145714. static long _vq_lengthlist__44u6__p8_1[] = {
  145715. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  145716. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  145717. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  145718. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145719. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  145720. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145721. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145722. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145723. };
  145724. static float _vq_quantthresh__44u6__p8_1[] = {
  145725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145726. 3.5, 4.5,
  145727. };
  145728. static long _vq_quantmap__44u6__p8_1[] = {
  145729. 9, 7, 5, 3, 1, 0, 2, 4,
  145730. 6, 8, 10,
  145731. };
  145732. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  145733. _vq_quantthresh__44u6__p8_1,
  145734. _vq_quantmap__44u6__p8_1,
  145735. 11,
  145736. 11
  145737. };
  145738. static static_codebook _44u6__p8_1 = {
  145739. 2, 121,
  145740. _vq_lengthlist__44u6__p8_1,
  145741. 1, -531365888, 1611661312, 4, 0,
  145742. _vq_quantlist__44u6__p8_1,
  145743. NULL,
  145744. &_vq_auxt__44u6__p8_1,
  145745. NULL,
  145746. 0
  145747. };
  145748. static long _vq_quantlist__44u6__p9_0[] = {
  145749. 7,
  145750. 6,
  145751. 8,
  145752. 5,
  145753. 9,
  145754. 4,
  145755. 10,
  145756. 3,
  145757. 11,
  145758. 2,
  145759. 12,
  145760. 1,
  145761. 13,
  145762. 0,
  145763. 14,
  145764. };
  145765. static long _vq_lengthlist__44u6__p9_0[] = {
  145766. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  145767. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  145768. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  145769. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  145770. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145771. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145772. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145773. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145774. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145775. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145776. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145777. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145778. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145779. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145780. 14,
  145781. };
  145782. static float _vq_quantthresh__44u6__p9_0[] = {
  145783. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145784. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145785. };
  145786. static long _vq_quantmap__44u6__p9_0[] = {
  145787. 13, 11, 9, 7, 5, 3, 1, 0,
  145788. 2, 4, 6, 8, 10, 12, 14,
  145789. };
  145790. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  145791. _vq_quantthresh__44u6__p9_0,
  145792. _vq_quantmap__44u6__p9_0,
  145793. 15,
  145794. 15
  145795. };
  145796. static static_codebook _44u6__p9_0 = {
  145797. 2, 225,
  145798. _vq_lengthlist__44u6__p9_0,
  145799. 1, -514071552, 1627381760, 4, 0,
  145800. _vq_quantlist__44u6__p9_0,
  145801. NULL,
  145802. &_vq_auxt__44u6__p9_0,
  145803. NULL,
  145804. 0
  145805. };
  145806. static long _vq_quantlist__44u6__p9_1[] = {
  145807. 7,
  145808. 6,
  145809. 8,
  145810. 5,
  145811. 9,
  145812. 4,
  145813. 10,
  145814. 3,
  145815. 11,
  145816. 2,
  145817. 12,
  145818. 1,
  145819. 13,
  145820. 0,
  145821. 14,
  145822. };
  145823. static long _vq_lengthlist__44u6__p9_1[] = {
  145824. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  145825. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  145826. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  145827. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  145828. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  145829. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  145830. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  145831. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  145832. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  145833. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  145834. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  145835. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  145836. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  145837. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  145838. 13,
  145839. };
  145840. static float _vq_quantthresh__44u6__p9_1[] = {
  145841. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145842. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145843. };
  145844. static long _vq_quantmap__44u6__p9_1[] = {
  145845. 13, 11, 9, 7, 5, 3, 1, 0,
  145846. 2, 4, 6, 8, 10, 12, 14,
  145847. };
  145848. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  145849. _vq_quantthresh__44u6__p9_1,
  145850. _vq_quantmap__44u6__p9_1,
  145851. 15,
  145852. 15
  145853. };
  145854. static static_codebook _44u6__p9_1 = {
  145855. 2, 225,
  145856. _vq_lengthlist__44u6__p9_1,
  145857. 1, -522338304, 1620115456, 4, 0,
  145858. _vq_quantlist__44u6__p9_1,
  145859. NULL,
  145860. &_vq_auxt__44u6__p9_1,
  145861. NULL,
  145862. 0
  145863. };
  145864. static long _vq_quantlist__44u6__p9_2[] = {
  145865. 8,
  145866. 7,
  145867. 9,
  145868. 6,
  145869. 10,
  145870. 5,
  145871. 11,
  145872. 4,
  145873. 12,
  145874. 3,
  145875. 13,
  145876. 2,
  145877. 14,
  145878. 1,
  145879. 15,
  145880. 0,
  145881. 16,
  145882. };
  145883. static long _vq_lengthlist__44u6__p9_2[] = {
  145884. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  145885. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145886. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  145887. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145888. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145889. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145890. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145891. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145892. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145893. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  145894. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  145895. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145896. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  145897. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  145898. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  145899. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  145900. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  145901. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  145902. 10,
  145903. };
  145904. static float _vq_quantthresh__44u6__p9_2[] = {
  145905. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145906. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145907. };
  145908. static long _vq_quantmap__44u6__p9_2[] = {
  145909. 15, 13, 11, 9, 7, 5, 3, 1,
  145910. 0, 2, 4, 6, 8, 10, 12, 14,
  145911. 16,
  145912. };
  145913. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  145914. _vq_quantthresh__44u6__p9_2,
  145915. _vq_quantmap__44u6__p9_2,
  145916. 17,
  145917. 17
  145918. };
  145919. static static_codebook _44u6__p9_2 = {
  145920. 2, 289,
  145921. _vq_lengthlist__44u6__p9_2,
  145922. 1, -529530880, 1611661312, 5, 0,
  145923. _vq_quantlist__44u6__p9_2,
  145924. NULL,
  145925. &_vq_auxt__44u6__p9_2,
  145926. NULL,
  145927. 0
  145928. };
  145929. static long _huff_lengthlist__44u6__short[] = {
  145930. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  145931. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  145932. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  145933. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  145934. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  145935. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  145936. 7, 6, 9,16,
  145937. };
  145938. static static_codebook _huff_book__44u6__short = {
  145939. 2, 100,
  145940. _huff_lengthlist__44u6__short,
  145941. 0, 0, 0, 0, 0,
  145942. NULL,
  145943. NULL,
  145944. NULL,
  145945. NULL,
  145946. 0
  145947. };
  145948. static long _huff_lengthlist__44u7__long[] = {
  145949. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  145950. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  145951. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  145952. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  145953. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  145954. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  145955. 12, 8, 6, 7,
  145956. };
  145957. static static_codebook _huff_book__44u7__long = {
  145958. 2, 100,
  145959. _huff_lengthlist__44u7__long,
  145960. 0, 0, 0, 0, 0,
  145961. NULL,
  145962. NULL,
  145963. NULL,
  145964. NULL,
  145965. 0
  145966. };
  145967. static long _vq_quantlist__44u7__p1_0[] = {
  145968. 1,
  145969. 0,
  145970. 2,
  145971. };
  145972. static long _vq_lengthlist__44u7__p1_0[] = {
  145973. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145974. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  145975. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145976. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  145977. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  145978. 12,
  145979. };
  145980. static float _vq_quantthresh__44u7__p1_0[] = {
  145981. -0.5, 0.5,
  145982. };
  145983. static long _vq_quantmap__44u7__p1_0[] = {
  145984. 1, 0, 2,
  145985. };
  145986. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  145987. _vq_quantthresh__44u7__p1_0,
  145988. _vq_quantmap__44u7__p1_0,
  145989. 3,
  145990. 3
  145991. };
  145992. static static_codebook _44u7__p1_0 = {
  145993. 4, 81,
  145994. _vq_lengthlist__44u7__p1_0,
  145995. 1, -535822336, 1611661312, 2, 0,
  145996. _vq_quantlist__44u7__p1_0,
  145997. NULL,
  145998. &_vq_auxt__44u7__p1_0,
  145999. NULL,
  146000. 0
  146001. };
  146002. static long _vq_quantlist__44u7__p2_0[] = {
  146003. 1,
  146004. 0,
  146005. 2,
  146006. };
  146007. static long _vq_lengthlist__44u7__p2_0[] = {
  146008. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146009. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146010. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  146011. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146012. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146013. 9,
  146014. };
  146015. static float _vq_quantthresh__44u7__p2_0[] = {
  146016. -0.5, 0.5,
  146017. };
  146018. static long _vq_quantmap__44u7__p2_0[] = {
  146019. 1, 0, 2,
  146020. };
  146021. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  146022. _vq_quantthresh__44u7__p2_0,
  146023. _vq_quantmap__44u7__p2_0,
  146024. 3,
  146025. 3
  146026. };
  146027. static static_codebook _44u7__p2_0 = {
  146028. 4, 81,
  146029. _vq_lengthlist__44u7__p2_0,
  146030. 1, -535822336, 1611661312, 2, 0,
  146031. _vq_quantlist__44u7__p2_0,
  146032. NULL,
  146033. &_vq_auxt__44u7__p2_0,
  146034. NULL,
  146035. 0
  146036. };
  146037. static long _vq_quantlist__44u7__p3_0[] = {
  146038. 2,
  146039. 1,
  146040. 3,
  146041. 0,
  146042. 4,
  146043. };
  146044. static long _vq_lengthlist__44u7__p3_0[] = {
  146045. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146046. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146047. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146048. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  146049. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  146050. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  146051. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  146052. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  146053. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  146054. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146055. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  146056. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146057. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  146058. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  146059. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  146060. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  146061. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  146062. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146063. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  146064. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  146065. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  146066. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  146067. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  146068. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  146069. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  146070. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  146071. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  146072. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  146073. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  146074. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  146075. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  146076. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  146077. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  146078. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  146079. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  146080. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  146081. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  146082. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  146083. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  146084. 0,
  146085. };
  146086. static float _vq_quantthresh__44u7__p3_0[] = {
  146087. -1.5, -0.5, 0.5, 1.5,
  146088. };
  146089. static long _vq_quantmap__44u7__p3_0[] = {
  146090. 3, 1, 0, 2, 4,
  146091. };
  146092. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  146093. _vq_quantthresh__44u7__p3_0,
  146094. _vq_quantmap__44u7__p3_0,
  146095. 5,
  146096. 5
  146097. };
  146098. static static_codebook _44u7__p3_0 = {
  146099. 4, 625,
  146100. _vq_lengthlist__44u7__p3_0,
  146101. 1, -533725184, 1611661312, 3, 0,
  146102. _vq_quantlist__44u7__p3_0,
  146103. NULL,
  146104. &_vq_auxt__44u7__p3_0,
  146105. NULL,
  146106. 0
  146107. };
  146108. static long _vq_quantlist__44u7__p4_0[] = {
  146109. 2,
  146110. 1,
  146111. 3,
  146112. 0,
  146113. 4,
  146114. };
  146115. static long _vq_lengthlist__44u7__p4_0[] = {
  146116. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146117. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  146118. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  146119. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  146120. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146121. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  146122. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  146123. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  146124. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146125. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146126. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  146127. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146128. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146129. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  146130. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  146131. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146132. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  146133. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146134. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  146135. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  146136. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146137. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146138. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  146139. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146140. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  146141. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146142. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146143. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  146144. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  146145. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  146146. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  146147. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146148. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  146149. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146150. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  146151. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146152. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  146153. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  146154. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  146155. 14,
  146156. };
  146157. static float _vq_quantthresh__44u7__p4_0[] = {
  146158. -1.5, -0.5, 0.5, 1.5,
  146159. };
  146160. static long _vq_quantmap__44u7__p4_0[] = {
  146161. 3, 1, 0, 2, 4,
  146162. };
  146163. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  146164. _vq_quantthresh__44u7__p4_0,
  146165. _vq_quantmap__44u7__p4_0,
  146166. 5,
  146167. 5
  146168. };
  146169. static static_codebook _44u7__p4_0 = {
  146170. 4, 625,
  146171. _vq_lengthlist__44u7__p4_0,
  146172. 1, -533725184, 1611661312, 3, 0,
  146173. _vq_quantlist__44u7__p4_0,
  146174. NULL,
  146175. &_vq_auxt__44u7__p4_0,
  146176. NULL,
  146177. 0
  146178. };
  146179. static long _vq_quantlist__44u7__p5_0[] = {
  146180. 4,
  146181. 3,
  146182. 5,
  146183. 2,
  146184. 6,
  146185. 1,
  146186. 7,
  146187. 0,
  146188. 8,
  146189. };
  146190. static long _vq_lengthlist__44u7__p5_0[] = {
  146191. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146192. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  146193. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  146194. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  146195. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  146196. 14,
  146197. };
  146198. static float _vq_quantthresh__44u7__p5_0[] = {
  146199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146200. };
  146201. static long _vq_quantmap__44u7__p5_0[] = {
  146202. 7, 5, 3, 1, 0, 2, 4, 6,
  146203. 8,
  146204. };
  146205. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  146206. _vq_quantthresh__44u7__p5_0,
  146207. _vq_quantmap__44u7__p5_0,
  146208. 9,
  146209. 9
  146210. };
  146211. static static_codebook _44u7__p5_0 = {
  146212. 2, 81,
  146213. _vq_lengthlist__44u7__p5_0,
  146214. 1, -531628032, 1611661312, 4, 0,
  146215. _vq_quantlist__44u7__p5_0,
  146216. NULL,
  146217. &_vq_auxt__44u7__p5_0,
  146218. NULL,
  146219. 0
  146220. };
  146221. static long _vq_quantlist__44u7__p6_0[] = {
  146222. 4,
  146223. 3,
  146224. 5,
  146225. 2,
  146226. 6,
  146227. 1,
  146228. 7,
  146229. 0,
  146230. 8,
  146231. };
  146232. static long _vq_lengthlist__44u7__p6_0[] = {
  146233. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  146234. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146235. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146236. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  146237. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  146238. 12,
  146239. };
  146240. static float _vq_quantthresh__44u7__p6_0[] = {
  146241. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146242. };
  146243. static long _vq_quantmap__44u7__p6_0[] = {
  146244. 7, 5, 3, 1, 0, 2, 4, 6,
  146245. 8,
  146246. };
  146247. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  146248. _vq_quantthresh__44u7__p6_0,
  146249. _vq_quantmap__44u7__p6_0,
  146250. 9,
  146251. 9
  146252. };
  146253. static static_codebook _44u7__p6_0 = {
  146254. 2, 81,
  146255. _vq_lengthlist__44u7__p6_0,
  146256. 1, -531628032, 1611661312, 4, 0,
  146257. _vq_quantlist__44u7__p6_0,
  146258. NULL,
  146259. &_vq_auxt__44u7__p6_0,
  146260. NULL,
  146261. 0
  146262. };
  146263. static long _vq_quantlist__44u7__p7_0[] = {
  146264. 1,
  146265. 0,
  146266. 2,
  146267. };
  146268. static long _vq_lengthlist__44u7__p7_0[] = {
  146269. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  146270. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  146271. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  146272. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  146273. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  146274. 10,
  146275. };
  146276. static float _vq_quantthresh__44u7__p7_0[] = {
  146277. -5.5, 5.5,
  146278. };
  146279. static long _vq_quantmap__44u7__p7_0[] = {
  146280. 1, 0, 2,
  146281. };
  146282. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  146283. _vq_quantthresh__44u7__p7_0,
  146284. _vq_quantmap__44u7__p7_0,
  146285. 3,
  146286. 3
  146287. };
  146288. static static_codebook _44u7__p7_0 = {
  146289. 4, 81,
  146290. _vq_lengthlist__44u7__p7_0,
  146291. 1, -529137664, 1618345984, 2, 0,
  146292. _vq_quantlist__44u7__p7_0,
  146293. NULL,
  146294. &_vq_auxt__44u7__p7_0,
  146295. NULL,
  146296. 0
  146297. };
  146298. static long _vq_quantlist__44u7__p7_1[] = {
  146299. 5,
  146300. 4,
  146301. 6,
  146302. 3,
  146303. 7,
  146304. 2,
  146305. 8,
  146306. 1,
  146307. 9,
  146308. 0,
  146309. 10,
  146310. };
  146311. static long _vq_lengthlist__44u7__p7_1[] = {
  146312. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  146313. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  146314. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  146315. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  146316. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  146317. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146318. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  146319. 8, 9, 9, 9, 9, 9,10,10,10,
  146320. };
  146321. static float _vq_quantthresh__44u7__p7_1[] = {
  146322. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146323. 3.5, 4.5,
  146324. };
  146325. static long _vq_quantmap__44u7__p7_1[] = {
  146326. 9, 7, 5, 3, 1, 0, 2, 4,
  146327. 6, 8, 10,
  146328. };
  146329. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  146330. _vq_quantthresh__44u7__p7_1,
  146331. _vq_quantmap__44u7__p7_1,
  146332. 11,
  146333. 11
  146334. };
  146335. static static_codebook _44u7__p7_1 = {
  146336. 2, 121,
  146337. _vq_lengthlist__44u7__p7_1,
  146338. 1, -531365888, 1611661312, 4, 0,
  146339. _vq_quantlist__44u7__p7_1,
  146340. NULL,
  146341. &_vq_auxt__44u7__p7_1,
  146342. NULL,
  146343. 0
  146344. };
  146345. static long _vq_quantlist__44u7__p8_0[] = {
  146346. 5,
  146347. 4,
  146348. 6,
  146349. 3,
  146350. 7,
  146351. 2,
  146352. 8,
  146353. 1,
  146354. 9,
  146355. 0,
  146356. 10,
  146357. };
  146358. static long _vq_lengthlist__44u7__p8_0[] = {
  146359. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146360. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  146361. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  146362. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  146363. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  146364. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  146365. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  146366. 12,13,13,14,14,15,15,15,16,
  146367. };
  146368. static float _vq_quantthresh__44u7__p8_0[] = {
  146369. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146370. 38.5, 49.5,
  146371. };
  146372. static long _vq_quantmap__44u7__p8_0[] = {
  146373. 9, 7, 5, 3, 1, 0, 2, 4,
  146374. 6, 8, 10,
  146375. };
  146376. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  146377. _vq_quantthresh__44u7__p8_0,
  146378. _vq_quantmap__44u7__p8_0,
  146379. 11,
  146380. 11
  146381. };
  146382. static static_codebook _44u7__p8_0 = {
  146383. 2, 121,
  146384. _vq_lengthlist__44u7__p8_0,
  146385. 1, -524582912, 1618345984, 4, 0,
  146386. _vq_quantlist__44u7__p8_0,
  146387. NULL,
  146388. &_vq_auxt__44u7__p8_0,
  146389. NULL,
  146390. 0
  146391. };
  146392. static long _vq_quantlist__44u7__p8_1[] = {
  146393. 5,
  146394. 4,
  146395. 6,
  146396. 3,
  146397. 7,
  146398. 2,
  146399. 8,
  146400. 1,
  146401. 9,
  146402. 0,
  146403. 10,
  146404. };
  146405. static long _vq_lengthlist__44u7__p8_1[] = {
  146406. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146407. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  146408. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146409. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146410. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146411. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146412. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146413. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146414. };
  146415. static float _vq_quantthresh__44u7__p8_1[] = {
  146416. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146417. 3.5, 4.5,
  146418. };
  146419. static long _vq_quantmap__44u7__p8_1[] = {
  146420. 9, 7, 5, 3, 1, 0, 2, 4,
  146421. 6, 8, 10,
  146422. };
  146423. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  146424. _vq_quantthresh__44u7__p8_1,
  146425. _vq_quantmap__44u7__p8_1,
  146426. 11,
  146427. 11
  146428. };
  146429. static static_codebook _44u7__p8_1 = {
  146430. 2, 121,
  146431. _vq_lengthlist__44u7__p8_1,
  146432. 1, -531365888, 1611661312, 4, 0,
  146433. _vq_quantlist__44u7__p8_1,
  146434. NULL,
  146435. &_vq_auxt__44u7__p8_1,
  146436. NULL,
  146437. 0
  146438. };
  146439. static long _vq_quantlist__44u7__p9_0[] = {
  146440. 5,
  146441. 4,
  146442. 6,
  146443. 3,
  146444. 7,
  146445. 2,
  146446. 8,
  146447. 1,
  146448. 9,
  146449. 0,
  146450. 10,
  146451. };
  146452. static long _vq_lengthlist__44u7__p9_0[] = {
  146453. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  146454. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  146455. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146456. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146457. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146458. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146459. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146460. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146461. };
  146462. static float _vq_quantthresh__44u7__p9_0[] = {
  146463. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  146464. 2229.5, 2866.5,
  146465. };
  146466. static long _vq_quantmap__44u7__p9_0[] = {
  146467. 9, 7, 5, 3, 1, 0, 2, 4,
  146468. 6, 8, 10,
  146469. };
  146470. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  146471. _vq_quantthresh__44u7__p9_0,
  146472. _vq_quantmap__44u7__p9_0,
  146473. 11,
  146474. 11
  146475. };
  146476. static static_codebook _44u7__p9_0 = {
  146477. 2, 121,
  146478. _vq_lengthlist__44u7__p9_0,
  146479. 1, -512171520, 1630791680, 4, 0,
  146480. _vq_quantlist__44u7__p9_0,
  146481. NULL,
  146482. &_vq_auxt__44u7__p9_0,
  146483. NULL,
  146484. 0
  146485. };
  146486. static long _vq_quantlist__44u7__p9_1[] = {
  146487. 6,
  146488. 5,
  146489. 7,
  146490. 4,
  146491. 8,
  146492. 3,
  146493. 9,
  146494. 2,
  146495. 10,
  146496. 1,
  146497. 11,
  146498. 0,
  146499. 12,
  146500. };
  146501. static long _vq_lengthlist__44u7__p9_1[] = {
  146502. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  146503. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  146504. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  146505. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  146506. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  146507. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  146508. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  146509. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  146510. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  146511. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  146512. 15,15,15,15,17,17,16,17,16,
  146513. };
  146514. static float _vq_quantthresh__44u7__p9_1[] = {
  146515. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  146516. 122.5, 171.5, 220.5, 269.5,
  146517. };
  146518. static long _vq_quantmap__44u7__p9_1[] = {
  146519. 11, 9, 7, 5, 3, 1, 0, 2,
  146520. 4, 6, 8, 10, 12,
  146521. };
  146522. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  146523. _vq_quantthresh__44u7__p9_1,
  146524. _vq_quantmap__44u7__p9_1,
  146525. 13,
  146526. 13
  146527. };
  146528. static static_codebook _44u7__p9_1 = {
  146529. 2, 169,
  146530. _vq_lengthlist__44u7__p9_1,
  146531. 1, -518889472, 1622704128, 4, 0,
  146532. _vq_quantlist__44u7__p9_1,
  146533. NULL,
  146534. &_vq_auxt__44u7__p9_1,
  146535. NULL,
  146536. 0
  146537. };
  146538. static long _vq_quantlist__44u7__p9_2[] = {
  146539. 24,
  146540. 23,
  146541. 25,
  146542. 22,
  146543. 26,
  146544. 21,
  146545. 27,
  146546. 20,
  146547. 28,
  146548. 19,
  146549. 29,
  146550. 18,
  146551. 30,
  146552. 17,
  146553. 31,
  146554. 16,
  146555. 32,
  146556. 15,
  146557. 33,
  146558. 14,
  146559. 34,
  146560. 13,
  146561. 35,
  146562. 12,
  146563. 36,
  146564. 11,
  146565. 37,
  146566. 10,
  146567. 38,
  146568. 9,
  146569. 39,
  146570. 8,
  146571. 40,
  146572. 7,
  146573. 41,
  146574. 6,
  146575. 42,
  146576. 5,
  146577. 43,
  146578. 4,
  146579. 44,
  146580. 3,
  146581. 45,
  146582. 2,
  146583. 46,
  146584. 1,
  146585. 47,
  146586. 0,
  146587. 48,
  146588. };
  146589. static long _vq_lengthlist__44u7__p9_2[] = {
  146590. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146591. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146592. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  146593. 8,
  146594. };
  146595. static float _vq_quantthresh__44u7__p9_2[] = {
  146596. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146597. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146598. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146599. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146600. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146601. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146602. };
  146603. static long _vq_quantmap__44u7__p9_2[] = {
  146604. 47, 45, 43, 41, 39, 37, 35, 33,
  146605. 31, 29, 27, 25, 23, 21, 19, 17,
  146606. 15, 13, 11, 9, 7, 5, 3, 1,
  146607. 0, 2, 4, 6, 8, 10, 12, 14,
  146608. 16, 18, 20, 22, 24, 26, 28, 30,
  146609. 32, 34, 36, 38, 40, 42, 44, 46,
  146610. 48,
  146611. };
  146612. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  146613. _vq_quantthresh__44u7__p9_2,
  146614. _vq_quantmap__44u7__p9_2,
  146615. 49,
  146616. 49
  146617. };
  146618. static static_codebook _44u7__p9_2 = {
  146619. 1, 49,
  146620. _vq_lengthlist__44u7__p9_2,
  146621. 1, -526909440, 1611661312, 6, 0,
  146622. _vq_quantlist__44u7__p9_2,
  146623. NULL,
  146624. &_vq_auxt__44u7__p9_2,
  146625. NULL,
  146626. 0
  146627. };
  146628. static long _huff_lengthlist__44u7__short[] = {
  146629. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  146630. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  146631. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  146632. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  146633. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  146634. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  146635. 6, 8, 5, 9,
  146636. };
  146637. static static_codebook _huff_book__44u7__short = {
  146638. 2, 100,
  146639. _huff_lengthlist__44u7__short,
  146640. 0, 0, 0, 0, 0,
  146641. NULL,
  146642. NULL,
  146643. NULL,
  146644. NULL,
  146645. 0
  146646. };
  146647. static long _huff_lengthlist__44u8__long[] = {
  146648. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  146649. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  146650. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  146651. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  146652. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  146653. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  146654. 10, 8, 8, 9,
  146655. };
  146656. static static_codebook _huff_book__44u8__long = {
  146657. 2, 100,
  146658. _huff_lengthlist__44u8__long,
  146659. 0, 0, 0, 0, 0,
  146660. NULL,
  146661. NULL,
  146662. NULL,
  146663. NULL,
  146664. 0
  146665. };
  146666. static long _huff_lengthlist__44u8__short[] = {
  146667. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  146668. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  146669. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  146670. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  146671. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  146672. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  146673. 10,10,15,17,
  146674. };
  146675. static static_codebook _huff_book__44u8__short = {
  146676. 2, 100,
  146677. _huff_lengthlist__44u8__short,
  146678. 0, 0, 0, 0, 0,
  146679. NULL,
  146680. NULL,
  146681. NULL,
  146682. NULL,
  146683. 0
  146684. };
  146685. static long _vq_quantlist__44u8_p1_0[] = {
  146686. 1,
  146687. 0,
  146688. 2,
  146689. };
  146690. static long _vq_lengthlist__44u8_p1_0[] = {
  146691. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  146692. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  146693. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  146694. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  146695. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  146696. 10,
  146697. };
  146698. static float _vq_quantthresh__44u8_p1_0[] = {
  146699. -0.5, 0.5,
  146700. };
  146701. static long _vq_quantmap__44u8_p1_0[] = {
  146702. 1, 0, 2,
  146703. };
  146704. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  146705. _vq_quantthresh__44u8_p1_0,
  146706. _vq_quantmap__44u8_p1_0,
  146707. 3,
  146708. 3
  146709. };
  146710. static static_codebook _44u8_p1_0 = {
  146711. 4, 81,
  146712. _vq_lengthlist__44u8_p1_0,
  146713. 1, -535822336, 1611661312, 2, 0,
  146714. _vq_quantlist__44u8_p1_0,
  146715. NULL,
  146716. &_vq_auxt__44u8_p1_0,
  146717. NULL,
  146718. 0
  146719. };
  146720. static long _vq_quantlist__44u8_p2_0[] = {
  146721. 2,
  146722. 1,
  146723. 3,
  146724. 0,
  146725. 4,
  146726. };
  146727. static long _vq_lengthlist__44u8_p2_0[] = {
  146728. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146729. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146730. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  146731. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146732. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  146733. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  146734. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146735. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  146736. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146737. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146738. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  146739. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146740. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  146741. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  146742. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  146743. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  146744. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146745. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  146746. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  146747. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146748. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  146749. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  146750. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146751. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146752. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  146753. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146754. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  146755. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  146756. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  146757. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  146758. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  146759. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146760. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  146761. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  146762. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146763. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  146764. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  146765. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  146766. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  146767. 14,
  146768. };
  146769. static float _vq_quantthresh__44u8_p2_0[] = {
  146770. -1.5, -0.5, 0.5, 1.5,
  146771. };
  146772. static long _vq_quantmap__44u8_p2_0[] = {
  146773. 3, 1, 0, 2, 4,
  146774. };
  146775. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  146776. _vq_quantthresh__44u8_p2_0,
  146777. _vq_quantmap__44u8_p2_0,
  146778. 5,
  146779. 5
  146780. };
  146781. static static_codebook _44u8_p2_0 = {
  146782. 4, 625,
  146783. _vq_lengthlist__44u8_p2_0,
  146784. 1, -533725184, 1611661312, 3, 0,
  146785. _vq_quantlist__44u8_p2_0,
  146786. NULL,
  146787. &_vq_auxt__44u8_p2_0,
  146788. NULL,
  146789. 0
  146790. };
  146791. static long _vq_quantlist__44u8_p3_0[] = {
  146792. 4,
  146793. 3,
  146794. 5,
  146795. 2,
  146796. 6,
  146797. 1,
  146798. 7,
  146799. 0,
  146800. 8,
  146801. };
  146802. static long _vq_lengthlist__44u8_p3_0[] = {
  146803. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146804. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146805. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146806. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146807. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  146808. 12,
  146809. };
  146810. static float _vq_quantthresh__44u8_p3_0[] = {
  146811. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146812. };
  146813. static long _vq_quantmap__44u8_p3_0[] = {
  146814. 7, 5, 3, 1, 0, 2, 4, 6,
  146815. 8,
  146816. };
  146817. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  146818. _vq_quantthresh__44u8_p3_0,
  146819. _vq_quantmap__44u8_p3_0,
  146820. 9,
  146821. 9
  146822. };
  146823. static static_codebook _44u8_p3_0 = {
  146824. 2, 81,
  146825. _vq_lengthlist__44u8_p3_0,
  146826. 1, -531628032, 1611661312, 4, 0,
  146827. _vq_quantlist__44u8_p3_0,
  146828. NULL,
  146829. &_vq_auxt__44u8_p3_0,
  146830. NULL,
  146831. 0
  146832. };
  146833. static long _vq_quantlist__44u8_p4_0[] = {
  146834. 8,
  146835. 7,
  146836. 9,
  146837. 6,
  146838. 10,
  146839. 5,
  146840. 11,
  146841. 4,
  146842. 12,
  146843. 3,
  146844. 13,
  146845. 2,
  146846. 14,
  146847. 1,
  146848. 15,
  146849. 0,
  146850. 16,
  146851. };
  146852. static long _vq_lengthlist__44u8_p4_0[] = {
  146853. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  146854. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  146855. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  146856. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  146857. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  146858. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  146859. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  146860. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  146861. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  146862. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  146863. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  146864. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  146865. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  146866. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  146867. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  146868. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  146869. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  146870. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  146871. 14,
  146872. };
  146873. static float _vq_quantthresh__44u8_p4_0[] = {
  146874. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146875. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146876. };
  146877. static long _vq_quantmap__44u8_p4_0[] = {
  146878. 15, 13, 11, 9, 7, 5, 3, 1,
  146879. 0, 2, 4, 6, 8, 10, 12, 14,
  146880. 16,
  146881. };
  146882. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  146883. _vq_quantthresh__44u8_p4_0,
  146884. _vq_quantmap__44u8_p4_0,
  146885. 17,
  146886. 17
  146887. };
  146888. static static_codebook _44u8_p4_0 = {
  146889. 2, 289,
  146890. _vq_lengthlist__44u8_p4_0,
  146891. 1, -529530880, 1611661312, 5, 0,
  146892. _vq_quantlist__44u8_p4_0,
  146893. NULL,
  146894. &_vq_auxt__44u8_p4_0,
  146895. NULL,
  146896. 0
  146897. };
  146898. static long _vq_quantlist__44u8_p5_0[] = {
  146899. 1,
  146900. 0,
  146901. 2,
  146902. };
  146903. static long _vq_lengthlist__44u8_p5_0[] = {
  146904. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146905. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146906. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  146907. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146908. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146909. 10,
  146910. };
  146911. static float _vq_quantthresh__44u8_p5_0[] = {
  146912. -5.5, 5.5,
  146913. };
  146914. static long _vq_quantmap__44u8_p5_0[] = {
  146915. 1, 0, 2,
  146916. };
  146917. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  146918. _vq_quantthresh__44u8_p5_0,
  146919. _vq_quantmap__44u8_p5_0,
  146920. 3,
  146921. 3
  146922. };
  146923. static static_codebook _44u8_p5_0 = {
  146924. 4, 81,
  146925. _vq_lengthlist__44u8_p5_0,
  146926. 1, -529137664, 1618345984, 2, 0,
  146927. _vq_quantlist__44u8_p5_0,
  146928. NULL,
  146929. &_vq_auxt__44u8_p5_0,
  146930. NULL,
  146931. 0
  146932. };
  146933. static long _vq_quantlist__44u8_p5_1[] = {
  146934. 5,
  146935. 4,
  146936. 6,
  146937. 3,
  146938. 7,
  146939. 2,
  146940. 8,
  146941. 1,
  146942. 9,
  146943. 0,
  146944. 10,
  146945. };
  146946. static long _vq_lengthlist__44u8_p5_1[] = {
  146947. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  146948. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  146949. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  146950. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146951. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  146952. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146953. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  146954. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  146955. };
  146956. static float _vq_quantthresh__44u8_p5_1[] = {
  146957. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146958. 3.5, 4.5,
  146959. };
  146960. static long _vq_quantmap__44u8_p5_1[] = {
  146961. 9, 7, 5, 3, 1, 0, 2, 4,
  146962. 6, 8, 10,
  146963. };
  146964. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  146965. _vq_quantthresh__44u8_p5_1,
  146966. _vq_quantmap__44u8_p5_1,
  146967. 11,
  146968. 11
  146969. };
  146970. static static_codebook _44u8_p5_1 = {
  146971. 2, 121,
  146972. _vq_lengthlist__44u8_p5_1,
  146973. 1, -531365888, 1611661312, 4, 0,
  146974. _vq_quantlist__44u8_p5_1,
  146975. NULL,
  146976. &_vq_auxt__44u8_p5_1,
  146977. NULL,
  146978. 0
  146979. };
  146980. static long _vq_quantlist__44u8_p6_0[] = {
  146981. 6,
  146982. 5,
  146983. 7,
  146984. 4,
  146985. 8,
  146986. 3,
  146987. 9,
  146988. 2,
  146989. 10,
  146990. 1,
  146991. 11,
  146992. 0,
  146993. 12,
  146994. };
  146995. static long _vq_lengthlist__44u8_p6_0[] = {
  146996. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146997. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  146998. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  146999. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  147000. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  147001. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147002. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147003. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  147004. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  147005. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147006. 11,11,11,11,11,12,11,12,12,
  147007. };
  147008. static float _vq_quantthresh__44u8_p6_0[] = {
  147009. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147010. 12.5, 17.5, 22.5, 27.5,
  147011. };
  147012. static long _vq_quantmap__44u8_p6_0[] = {
  147013. 11, 9, 7, 5, 3, 1, 0, 2,
  147014. 4, 6, 8, 10, 12,
  147015. };
  147016. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  147017. _vq_quantthresh__44u8_p6_0,
  147018. _vq_quantmap__44u8_p6_0,
  147019. 13,
  147020. 13
  147021. };
  147022. static static_codebook _44u8_p6_0 = {
  147023. 2, 169,
  147024. _vq_lengthlist__44u8_p6_0,
  147025. 1, -526516224, 1616117760, 4, 0,
  147026. _vq_quantlist__44u8_p6_0,
  147027. NULL,
  147028. &_vq_auxt__44u8_p6_0,
  147029. NULL,
  147030. 0
  147031. };
  147032. static long _vq_quantlist__44u8_p6_1[] = {
  147033. 2,
  147034. 1,
  147035. 3,
  147036. 0,
  147037. 4,
  147038. };
  147039. static long _vq_lengthlist__44u8_p6_1[] = {
  147040. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147041. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147042. };
  147043. static float _vq_quantthresh__44u8_p6_1[] = {
  147044. -1.5, -0.5, 0.5, 1.5,
  147045. };
  147046. static long _vq_quantmap__44u8_p6_1[] = {
  147047. 3, 1, 0, 2, 4,
  147048. };
  147049. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  147050. _vq_quantthresh__44u8_p6_1,
  147051. _vq_quantmap__44u8_p6_1,
  147052. 5,
  147053. 5
  147054. };
  147055. static static_codebook _44u8_p6_1 = {
  147056. 2, 25,
  147057. _vq_lengthlist__44u8_p6_1,
  147058. 1, -533725184, 1611661312, 3, 0,
  147059. _vq_quantlist__44u8_p6_1,
  147060. NULL,
  147061. &_vq_auxt__44u8_p6_1,
  147062. NULL,
  147063. 0
  147064. };
  147065. static long _vq_quantlist__44u8_p7_0[] = {
  147066. 6,
  147067. 5,
  147068. 7,
  147069. 4,
  147070. 8,
  147071. 3,
  147072. 9,
  147073. 2,
  147074. 10,
  147075. 1,
  147076. 11,
  147077. 0,
  147078. 12,
  147079. };
  147080. static long _vq_lengthlist__44u8_p7_0[] = {
  147081. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  147082. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  147083. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  147084. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  147085. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147086. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147087. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  147088. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  147089. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  147090. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  147091. 13,13,14,14,14,15,15,15,16,
  147092. };
  147093. static float _vq_quantthresh__44u8_p7_0[] = {
  147094. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147095. 27.5, 38.5, 49.5, 60.5,
  147096. };
  147097. static long _vq_quantmap__44u8_p7_0[] = {
  147098. 11, 9, 7, 5, 3, 1, 0, 2,
  147099. 4, 6, 8, 10, 12,
  147100. };
  147101. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  147102. _vq_quantthresh__44u8_p7_0,
  147103. _vq_quantmap__44u8_p7_0,
  147104. 13,
  147105. 13
  147106. };
  147107. static static_codebook _44u8_p7_0 = {
  147108. 2, 169,
  147109. _vq_lengthlist__44u8_p7_0,
  147110. 1, -523206656, 1618345984, 4, 0,
  147111. _vq_quantlist__44u8_p7_0,
  147112. NULL,
  147113. &_vq_auxt__44u8_p7_0,
  147114. NULL,
  147115. 0
  147116. };
  147117. static long _vq_quantlist__44u8_p7_1[] = {
  147118. 5,
  147119. 4,
  147120. 6,
  147121. 3,
  147122. 7,
  147123. 2,
  147124. 8,
  147125. 1,
  147126. 9,
  147127. 0,
  147128. 10,
  147129. };
  147130. static long _vq_lengthlist__44u8_p7_1[] = {
  147131. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147132. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147133. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147134. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  147135. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  147136. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147137. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147138. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147139. };
  147140. static float _vq_quantthresh__44u8_p7_1[] = {
  147141. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147142. 3.5, 4.5,
  147143. };
  147144. static long _vq_quantmap__44u8_p7_1[] = {
  147145. 9, 7, 5, 3, 1, 0, 2, 4,
  147146. 6, 8, 10,
  147147. };
  147148. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  147149. _vq_quantthresh__44u8_p7_1,
  147150. _vq_quantmap__44u8_p7_1,
  147151. 11,
  147152. 11
  147153. };
  147154. static static_codebook _44u8_p7_1 = {
  147155. 2, 121,
  147156. _vq_lengthlist__44u8_p7_1,
  147157. 1, -531365888, 1611661312, 4, 0,
  147158. _vq_quantlist__44u8_p7_1,
  147159. NULL,
  147160. &_vq_auxt__44u8_p7_1,
  147161. NULL,
  147162. 0
  147163. };
  147164. static long _vq_quantlist__44u8_p8_0[] = {
  147165. 7,
  147166. 6,
  147167. 8,
  147168. 5,
  147169. 9,
  147170. 4,
  147171. 10,
  147172. 3,
  147173. 11,
  147174. 2,
  147175. 12,
  147176. 1,
  147177. 13,
  147178. 0,
  147179. 14,
  147180. };
  147181. static long _vq_lengthlist__44u8_p8_0[] = {
  147182. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  147183. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147184. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  147185. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  147186. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  147187. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  147188. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  147189. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  147190. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  147191. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  147192. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  147193. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  147194. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  147195. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  147196. 17,
  147197. };
  147198. static float _vq_quantthresh__44u8_p8_0[] = {
  147199. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147200. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147201. };
  147202. static long _vq_quantmap__44u8_p8_0[] = {
  147203. 13, 11, 9, 7, 5, 3, 1, 0,
  147204. 2, 4, 6, 8, 10, 12, 14,
  147205. };
  147206. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  147207. _vq_quantthresh__44u8_p8_0,
  147208. _vq_quantmap__44u8_p8_0,
  147209. 15,
  147210. 15
  147211. };
  147212. static static_codebook _44u8_p8_0 = {
  147213. 2, 225,
  147214. _vq_lengthlist__44u8_p8_0,
  147215. 1, -520986624, 1620377600, 4, 0,
  147216. _vq_quantlist__44u8_p8_0,
  147217. NULL,
  147218. &_vq_auxt__44u8_p8_0,
  147219. NULL,
  147220. 0
  147221. };
  147222. static long _vq_quantlist__44u8_p8_1[] = {
  147223. 10,
  147224. 9,
  147225. 11,
  147226. 8,
  147227. 12,
  147228. 7,
  147229. 13,
  147230. 6,
  147231. 14,
  147232. 5,
  147233. 15,
  147234. 4,
  147235. 16,
  147236. 3,
  147237. 17,
  147238. 2,
  147239. 18,
  147240. 1,
  147241. 19,
  147242. 0,
  147243. 20,
  147244. };
  147245. static long _vq_lengthlist__44u8_p8_1[] = {
  147246. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147247. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147248. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  147249. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147250. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147251. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147252. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147253. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  147254. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147255. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147256. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  147257. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  147258. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147259. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147260. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147261. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147262. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  147263. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147264. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147265. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147266. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147267. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147268. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147269. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147270. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147271. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147272. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  147273. 10,10,10,10,10,10,10,10,10,
  147274. };
  147275. static float _vq_quantthresh__44u8_p8_1[] = {
  147276. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147277. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147278. 6.5, 7.5, 8.5, 9.5,
  147279. };
  147280. static long _vq_quantmap__44u8_p8_1[] = {
  147281. 19, 17, 15, 13, 11, 9, 7, 5,
  147282. 3, 1, 0, 2, 4, 6, 8, 10,
  147283. 12, 14, 16, 18, 20,
  147284. };
  147285. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  147286. _vq_quantthresh__44u8_p8_1,
  147287. _vq_quantmap__44u8_p8_1,
  147288. 21,
  147289. 21
  147290. };
  147291. static static_codebook _44u8_p8_1 = {
  147292. 2, 441,
  147293. _vq_lengthlist__44u8_p8_1,
  147294. 1, -529268736, 1611661312, 5, 0,
  147295. _vq_quantlist__44u8_p8_1,
  147296. NULL,
  147297. &_vq_auxt__44u8_p8_1,
  147298. NULL,
  147299. 0
  147300. };
  147301. static long _vq_quantlist__44u8_p9_0[] = {
  147302. 4,
  147303. 3,
  147304. 5,
  147305. 2,
  147306. 6,
  147307. 1,
  147308. 7,
  147309. 0,
  147310. 8,
  147311. };
  147312. static long _vq_lengthlist__44u8_p9_0[] = {
  147313. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  147314. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147315. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147316. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147317. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147318. 8,
  147319. };
  147320. static float _vq_quantthresh__44u8_p9_0[] = {
  147321. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  147322. };
  147323. static long _vq_quantmap__44u8_p9_0[] = {
  147324. 7, 5, 3, 1, 0, 2, 4, 6,
  147325. 8,
  147326. };
  147327. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  147328. _vq_quantthresh__44u8_p9_0,
  147329. _vq_quantmap__44u8_p9_0,
  147330. 9,
  147331. 9
  147332. };
  147333. static static_codebook _44u8_p9_0 = {
  147334. 2, 81,
  147335. _vq_lengthlist__44u8_p9_0,
  147336. 1, -511895552, 1631393792, 4, 0,
  147337. _vq_quantlist__44u8_p9_0,
  147338. NULL,
  147339. &_vq_auxt__44u8_p9_0,
  147340. NULL,
  147341. 0
  147342. };
  147343. static long _vq_quantlist__44u8_p9_1[] = {
  147344. 9,
  147345. 8,
  147346. 10,
  147347. 7,
  147348. 11,
  147349. 6,
  147350. 12,
  147351. 5,
  147352. 13,
  147353. 4,
  147354. 14,
  147355. 3,
  147356. 15,
  147357. 2,
  147358. 16,
  147359. 1,
  147360. 17,
  147361. 0,
  147362. 18,
  147363. };
  147364. static long _vq_lengthlist__44u8_p9_1[] = {
  147365. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  147366. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  147367. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  147368. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  147369. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  147370. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  147371. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  147372. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  147373. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  147374. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  147375. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  147376. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  147377. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  147378. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  147379. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  147380. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  147381. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  147382. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  147383. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  147384. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  147385. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  147386. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  147387. 16,15,16,16,16,16,16,16,16,
  147388. };
  147389. static float _vq_quantthresh__44u8_p9_1[] = {
  147390. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  147391. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  147392. 367.5, 416.5,
  147393. };
  147394. static long _vq_quantmap__44u8_p9_1[] = {
  147395. 17, 15, 13, 11, 9, 7, 5, 3,
  147396. 1, 0, 2, 4, 6, 8, 10, 12,
  147397. 14, 16, 18,
  147398. };
  147399. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  147400. _vq_quantthresh__44u8_p9_1,
  147401. _vq_quantmap__44u8_p9_1,
  147402. 19,
  147403. 19
  147404. };
  147405. static static_codebook _44u8_p9_1 = {
  147406. 2, 361,
  147407. _vq_lengthlist__44u8_p9_1,
  147408. 1, -518287360, 1622704128, 5, 0,
  147409. _vq_quantlist__44u8_p9_1,
  147410. NULL,
  147411. &_vq_auxt__44u8_p9_1,
  147412. NULL,
  147413. 0
  147414. };
  147415. static long _vq_quantlist__44u8_p9_2[] = {
  147416. 24,
  147417. 23,
  147418. 25,
  147419. 22,
  147420. 26,
  147421. 21,
  147422. 27,
  147423. 20,
  147424. 28,
  147425. 19,
  147426. 29,
  147427. 18,
  147428. 30,
  147429. 17,
  147430. 31,
  147431. 16,
  147432. 32,
  147433. 15,
  147434. 33,
  147435. 14,
  147436. 34,
  147437. 13,
  147438. 35,
  147439. 12,
  147440. 36,
  147441. 11,
  147442. 37,
  147443. 10,
  147444. 38,
  147445. 9,
  147446. 39,
  147447. 8,
  147448. 40,
  147449. 7,
  147450. 41,
  147451. 6,
  147452. 42,
  147453. 5,
  147454. 43,
  147455. 4,
  147456. 44,
  147457. 3,
  147458. 45,
  147459. 2,
  147460. 46,
  147461. 1,
  147462. 47,
  147463. 0,
  147464. 48,
  147465. };
  147466. static long _vq_lengthlist__44u8_p9_2[] = {
  147467. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  147468. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147469. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147470. 7,
  147471. };
  147472. static float _vq_quantthresh__44u8_p9_2[] = {
  147473. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147474. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147475. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147476. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147477. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147478. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147479. };
  147480. static long _vq_quantmap__44u8_p9_2[] = {
  147481. 47, 45, 43, 41, 39, 37, 35, 33,
  147482. 31, 29, 27, 25, 23, 21, 19, 17,
  147483. 15, 13, 11, 9, 7, 5, 3, 1,
  147484. 0, 2, 4, 6, 8, 10, 12, 14,
  147485. 16, 18, 20, 22, 24, 26, 28, 30,
  147486. 32, 34, 36, 38, 40, 42, 44, 46,
  147487. 48,
  147488. };
  147489. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  147490. _vq_quantthresh__44u8_p9_2,
  147491. _vq_quantmap__44u8_p9_2,
  147492. 49,
  147493. 49
  147494. };
  147495. static static_codebook _44u8_p9_2 = {
  147496. 1, 49,
  147497. _vq_lengthlist__44u8_p9_2,
  147498. 1, -526909440, 1611661312, 6, 0,
  147499. _vq_quantlist__44u8_p9_2,
  147500. NULL,
  147501. &_vq_auxt__44u8_p9_2,
  147502. NULL,
  147503. 0
  147504. };
  147505. static long _huff_lengthlist__44u9__long[] = {
  147506. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  147507. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  147508. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  147509. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  147510. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  147511. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  147512. 10, 8, 8, 9,
  147513. };
  147514. static static_codebook _huff_book__44u9__long = {
  147515. 2, 100,
  147516. _huff_lengthlist__44u9__long,
  147517. 0, 0, 0, 0, 0,
  147518. NULL,
  147519. NULL,
  147520. NULL,
  147521. NULL,
  147522. 0
  147523. };
  147524. static long _huff_lengthlist__44u9__short[] = {
  147525. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  147526. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  147527. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  147528. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  147529. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  147530. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  147531. 9, 9,12,15,
  147532. };
  147533. static static_codebook _huff_book__44u9__short = {
  147534. 2, 100,
  147535. _huff_lengthlist__44u9__short,
  147536. 0, 0, 0, 0, 0,
  147537. NULL,
  147538. NULL,
  147539. NULL,
  147540. NULL,
  147541. 0
  147542. };
  147543. static long _vq_quantlist__44u9_p1_0[] = {
  147544. 1,
  147545. 0,
  147546. 2,
  147547. };
  147548. static long _vq_lengthlist__44u9_p1_0[] = {
  147549. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  147550. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  147551. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  147552. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  147553. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  147554. 10,
  147555. };
  147556. static float _vq_quantthresh__44u9_p1_0[] = {
  147557. -0.5, 0.5,
  147558. };
  147559. static long _vq_quantmap__44u9_p1_0[] = {
  147560. 1, 0, 2,
  147561. };
  147562. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  147563. _vq_quantthresh__44u9_p1_0,
  147564. _vq_quantmap__44u9_p1_0,
  147565. 3,
  147566. 3
  147567. };
  147568. static static_codebook _44u9_p1_0 = {
  147569. 4, 81,
  147570. _vq_lengthlist__44u9_p1_0,
  147571. 1, -535822336, 1611661312, 2, 0,
  147572. _vq_quantlist__44u9_p1_0,
  147573. NULL,
  147574. &_vq_auxt__44u9_p1_0,
  147575. NULL,
  147576. 0
  147577. };
  147578. static long _vq_quantlist__44u9_p2_0[] = {
  147579. 2,
  147580. 1,
  147581. 3,
  147582. 0,
  147583. 4,
  147584. };
  147585. static long _vq_lengthlist__44u9_p2_0[] = {
  147586. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  147587. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  147588. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  147589. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  147590. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  147591. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  147592. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  147593. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  147594. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147595. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  147596. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  147597. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  147598. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  147599. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  147600. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  147601. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  147602. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  147603. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  147604. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  147605. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  147606. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  147607. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  147608. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  147609. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  147610. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  147611. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  147612. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  147613. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  147614. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  147615. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  147616. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  147617. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  147618. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  147619. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  147620. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  147621. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  147622. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  147623. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  147624. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  147625. 14,
  147626. };
  147627. static float _vq_quantthresh__44u9_p2_0[] = {
  147628. -1.5, -0.5, 0.5, 1.5,
  147629. };
  147630. static long _vq_quantmap__44u9_p2_0[] = {
  147631. 3, 1, 0, 2, 4,
  147632. };
  147633. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  147634. _vq_quantthresh__44u9_p2_0,
  147635. _vq_quantmap__44u9_p2_0,
  147636. 5,
  147637. 5
  147638. };
  147639. static static_codebook _44u9_p2_0 = {
  147640. 4, 625,
  147641. _vq_lengthlist__44u9_p2_0,
  147642. 1, -533725184, 1611661312, 3, 0,
  147643. _vq_quantlist__44u9_p2_0,
  147644. NULL,
  147645. &_vq_auxt__44u9_p2_0,
  147646. NULL,
  147647. 0
  147648. };
  147649. static long _vq_quantlist__44u9_p3_0[] = {
  147650. 4,
  147651. 3,
  147652. 5,
  147653. 2,
  147654. 6,
  147655. 1,
  147656. 7,
  147657. 0,
  147658. 8,
  147659. };
  147660. static long _vq_lengthlist__44u9_p3_0[] = {
  147661. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  147662. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147663. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  147664. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  147665. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  147666. 11,
  147667. };
  147668. static float _vq_quantthresh__44u9_p3_0[] = {
  147669. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147670. };
  147671. static long _vq_quantmap__44u9_p3_0[] = {
  147672. 7, 5, 3, 1, 0, 2, 4, 6,
  147673. 8,
  147674. };
  147675. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  147676. _vq_quantthresh__44u9_p3_0,
  147677. _vq_quantmap__44u9_p3_0,
  147678. 9,
  147679. 9
  147680. };
  147681. static static_codebook _44u9_p3_0 = {
  147682. 2, 81,
  147683. _vq_lengthlist__44u9_p3_0,
  147684. 1, -531628032, 1611661312, 4, 0,
  147685. _vq_quantlist__44u9_p3_0,
  147686. NULL,
  147687. &_vq_auxt__44u9_p3_0,
  147688. NULL,
  147689. 0
  147690. };
  147691. static long _vq_quantlist__44u9_p4_0[] = {
  147692. 8,
  147693. 7,
  147694. 9,
  147695. 6,
  147696. 10,
  147697. 5,
  147698. 11,
  147699. 4,
  147700. 12,
  147701. 3,
  147702. 13,
  147703. 2,
  147704. 14,
  147705. 1,
  147706. 15,
  147707. 0,
  147708. 16,
  147709. };
  147710. static long _vq_lengthlist__44u9_p4_0[] = {
  147711. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  147712. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  147713. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  147714. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  147715. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  147716. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  147717. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  147718. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  147719. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  147720. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  147721. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  147722. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  147723. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  147724. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  147725. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  147726. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  147727. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  147728. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  147729. 14,
  147730. };
  147731. static float _vq_quantthresh__44u9_p4_0[] = {
  147732. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147733. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147734. };
  147735. static long _vq_quantmap__44u9_p4_0[] = {
  147736. 15, 13, 11, 9, 7, 5, 3, 1,
  147737. 0, 2, 4, 6, 8, 10, 12, 14,
  147738. 16,
  147739. };
  147740. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  147741. _vq_quantthresh__44u9_p4_0,
  147742. _vq_quantmap__44u9_p4_0,
  147743. 17,
  147744. 17
  147745. };
  147746. static static_codebook _44u9_p4_0 = {
  147747. 2, 289,
  147748. _vq_lengthlist__44u9_p4_0,
  147749. 1, -529530880, 1611661312, 5, 0,
  147750. _vq_quantlist__44u9_p4_0,
  147751. NULL,
  147752. &_vq_auxt__44u9_p4_0,
  147753. NULL,
  147754. 0
  147755. };
  147756. static long _vq_quantlist__44u9_p5_0[] = {
  147757. 1,
  147758. 0,
  147759. 2,
  147760. };
  147761. static long _vq_lengthlist__44u9_p5_0[] = {
  147762. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147763. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147764. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  147765. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147766. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147767. 10,
  147768. };
  147769. static float _vq_quantthresh__44u9_p5_0[] = {
  147770. -5.5, 5.5,
  147771. };
  147772. static long _vq_quantmap__44u9_p5_0[] = {
  147773. 1, 0, 2,
  147774. };
  147775. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  147776. _vq_quantthresh__44u9_p5_0,
  147777. _vq_quantmap__44u9_p5_0,
  147778. 3,
  147779. 3
  147780. };
  147781. static static_codebook _44u9_p5_0 = {
  147782. 4, 81,
  147783. _vq_lengthlist__44u9_p5_0,
  147784. 1, -529137664, 1618345984, 2, 0,
  147785. _vq_quantlist__44u9_p5_0,
  147786. NULL,
  147787. &_vq_auxt__44u9_p5_0,
  147788. NULL,
  147789. 0
  147790. };
  147791. static long _vq_quantlist__44u9_p5_1[] = {
  147792. 5,
  147793. 4,
  147794. 6,
  147795. 3,
  147796. 7,
  147797. 2,
  147798. 8,
  147799. 1,
  147800. 9,
  147801. 0,
  147802. 10,
  147803. };
  147804. static long _vq_lengthlist__44u9_p5_1[] = {
  147805. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  147806. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  147807. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  147808. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147809. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147810. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  147811. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  147812. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147813. };
  147814. static float _vq_quantthresh__44u9_p5_1[] = {
  147815. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147816. 3.5, 4.5,
  147817. };
  147818. static long _vq_quantmap__44u9_p5_1[] = {
  147819. 9, 7, 5, 3, 1, 0, 2, 4,
  147820. 6, 8, 10,
  147821. };
  147822. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  147823. _vq_quantthresh__44u9_p5_1,
  147824. _vq_quantmap__44u9_p5_1,
  147825. 11,
  147826. 11
  147827. };
  147828. static static_codebook _44u9_p5_1 = {
  147829. 2, 121,
  147830. _vq_lengthlist__44u9_p5_1,
  147831. 1, -531365888, 1611661312, 4, 0,
  147832. _vq_quantlist__44u9_p5_1,
  147833. NULL,
  147834. &_vq_auxt__44u9_p5_1,
  147835. NULL,
  147836. 0
  147837. };
  147838. static long _vq_quantlist__44u9_p6_0[] = {
  147839. 6,
  147840. 5,
  147841. 7,
  147842. 4,
  147843. 8,
  147844. 3,
  147845. 9,
  147846. 2,
  147847. 10,
  147848. 1,
  147849. 11,
  147850. 0,
  147851. 12,
  147852. };
  147853. static long _vq_lengthlist__44u9_p6_0[] = {
  147854. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147855. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  147856. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147857. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  147858. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  147859. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147860. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147861. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  147862. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  147863. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147864. 10,11,11,11,11,12,11,12,12,
  147865. };
  147866. static float _vq_quantthresh__44u9_p6_0[] = {
  147867. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147868. 12.5, 17.5, 22.5, 27.5,
  147869. };
  147870. static long _vq_quantmap__44u9_p6_0[] = {
  147871. 11, 9, 7, 5, 3, 1, 0, 2,
  147872. 4, 6, 8, 10, 12,
  147873. };
  147874. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  147875. _vq_quantthresh__44u9_p6_0,
  147876. _vq_quantmap__44u9_p6_0,
  147877. 13,
  147878. 13
  147879. };
  147880. static static_codebook _44u9_p6_0 = {
  147881. 2, 169,
  147882. _vq_lengthlist__44u9_p6_0,
  147883. 1, -526516224, 1616117760, 4, 0,
  147884. _vq_quantlist__44u9_p6_0,
  147885. NULL,
  147886. &_vq_auxt__44u9_p6_0,
  147887. NULL,
  147888. 0
  147889. };
  147890. static long _vq_quantlist__44u9_p6_1[] = {
  147891. 2,
  147892. 1,
  147893. 3,
  147894. 0,
  147895. 4,
  147896. };
  147897. static long _vq_lengthlist__44u9_p6_1[] = {
  147898. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  147899. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147900. };
  147901. static float _vq_quantthresh__44u9_p6_1[] = {
  147902. -1.5, -0.5, 0.5, 1.5,
  147903. };
  147904. static long _vq_quantmap__44u9_p6_1[] = {
  147905. 3, 1, 0, 2, 4,
  147906. };
  147907. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  147908. _vq_quantthresh__44u9_p6_1,
  147909. _vq_quantmap__44u9_p6_1,
  147910. 5,
  147911. 5
  147912. };
  147913. static static_codebook _44u9_p6_1 = {
  147914. 2, 25,
  147915. _vq_lengthlist__44u9_p6_1,
  147916. 1, -533725184, 1611661312, 3, 0,
  147917. _vq_quantlist__44u9_p6_1,
  147918. NULL,
  147919. &_vq_auxt__44u9_p6_1,
  147920. NULL,
  147921. 0
  147922. };
  147923. static long _vq_quantlist__44u9_p7_0[] = {
  147924. 6,
  147925. 5,
  147926. 7,
  147927. 4,
  147928. 8,
  147929. 3,
  147930. 9,
  147931. 2,
  147932. 10,
  147933. 1,
  147934. 11,
  147935. 0,
  147936. 12,
  147937. };
  147938. static long _vq_lengthlist__44u9_p7_0[] = {
  147939. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  147940. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  147941. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  147942. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  147943. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147944. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147945. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  147946. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  147947. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  147948. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  147949. 12,13,13,14,14,14,15,15,15,
  147950. };
  147951. static float _vq_quantthresh__44u9_p7_0[] = {
  147952. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147953. 27.5, 38.5, 49.5, 60.5,
  147954. };
  147955. static long _vq_quantmap__44u9_p7_0[] = {
  147956. 11, 9, 7, 5, 3, 1, 0, 2,
  147957. 4, 6, 8, 10, 12,
  147958. };
  147959. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  147960. _vq_quantthresh__44u9_p7_0,
  147961. _vq_quantmap__44u9_p7_0,
  147962. 13,
  147963. 13
  147964. };
  147965. static static_codebook _44u9_p7_0 = {
  147966. 2, 169,
  147967. _vq_lengthlist__44u9_p7_0,
  147968. 1, -523206656, 1618345984, 4, 0,
  147969. _vq_quantlist__44u9_p7_0,
  147970. NULL,
  147971. &_vq_auxt__44u9_p7_0,
  147972. NULL,
  147973. 0
  147974. };
  147975. static long _vq_quantlist__44u9_p7_1[] = {
  147976. 5,
  147977. 4,
  147978. 6,
  147979. 3,
  147980. 7,
  147981. 2,
  147982. 8,
  147983. 1,
  147984. 9,
  147985. 0,
  147986. 10,
  147987. };
  147988. static long _vq_lengthlist__44u9_p7_1[] = {
  147989. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  147990. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147991. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  147992. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147993. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147994. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147995. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  147996. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147997. };
  147998. static float _vq_quantthresh__44u9_p7_1[] = {
  147999. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148000. 3.5, 4.5,
  148001. };
  148002. static long _vq_quantmap__44u9_p7_1[] = {
  148003. 9, 7, 5, 3, 1, 0, 2, 4,
  148004. 6, 8, 10,
  148005. };
  148006. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  148007. _vq_quantthresh__44u9_p7_1,
  148008. _vq_quantmap__44u9_p7_1,
  148009. 11,
  148010. 11
  148011. };
  148012. static static_codebook _44u9_p7_1 = {
  148013. 2, 121,
  148014. _vq_lengthlist__44u9_p7_1,
  148015. 1, -531365888, 1611661312, 4, 0,
  148016. _vq_quantlist__44u9_p7_1,
  148017. NULL,
  148018. &_vq_auxt__44u9_p7_1,
  148019. NULL,
  148020. 0
  148021. };
  148022. static long _vq_quantlist__44u9_p8_0[] = {
  148023. 7,
  148024. 6,
  148025. 8,
  148026. 5,
  148027. 9,
  148028. 4,
  148029. 10,
  148030. 3,
  148031. 11,
  148032. 2,
  148033. 12,
  148034. 1,
  148035. 13,
  148036. 0,
  148037. 14,
  148038. };
  148039. static long _vq_lengthlist__44u9_p8_0[] = {
  148040. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  148041. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  148042. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  148043. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  148044. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  148045. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  148046. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  148047. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  148048. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  148049. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  148050. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  148051. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  148052. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  148053. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  148054. 15,
  148055. };
  148056. static float _vq_quantthresh__44u9_p8_0[] = {
  148057. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  148058. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  148059. };
  148060. static long _vq_quantmap__44u9_p8_0[] = {
  148061. 13, 11, 9, 7, 5, 3, 1, 0,
  148062. 2, 4, 6, 8, 10, 12, 14,
  148063. };
  148064. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  148065. _vq_quantthresh__44u9_p8_0,
  148066. _vq_quantmap__44u9_p8_0,
  148067. 15,
  148068. 15
  148069. };
  148070. static static_codebook _44u9_p8_0 = {
  148071. 2, 225,
  148072. _vq_lengthlist__44u9_p8_0,
  148073. 1, -520986624, 1620377600, 4, 0,
  148074. _vq_quantlist__44u9_p8_0,
  148075. NULL,
  148076. &_vq_auxt__44u9_p8_0,
  148077. NULL,
  148078. 0
  148079. };
  148080. static long _vq_quantlist__44u9_p8_1[] = {
  148081. 10,
  148082. 9,
  148083. 11,
  148084. 8,
  148085. 12,
  148086. 7,
  148087. 13,
  148088. 6,
  148089. 14,
  148090. 5,
  148091. 15,
  148092. 4,
  148093. 16,
  148094. 3,
  148095. 17,
  148096. 2,
  148097. 18,
  148098. 1,
  148099. 19,
  148100. 0,
  148101. 20,
  148102. };
  148103. static long _vq_lengthlist__44u9_p8_1[] = {
  148104. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148105. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148106. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  148107. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148108. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148109. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148110. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148111. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  148112. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148113. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148114. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148115. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  148116. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148117. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148118. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148119. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148120. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148121. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148122. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  148123. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148125. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  148126. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  148127. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  148128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148129. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148130. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148131. 10,10,10,10,10,10,10,10,10,
  148132. };
  148133. static float _vq_quantthresh__44u9_p8_1[] = {
  148134. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148135. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148136. 6.5, 7.5, 8.5, 9.5,
  148137. };
  148138. static long _vq_quantmap__44u9_p8_1[] = {
  148139. 19, 17, 15, 13, 11, 9, 7, 5,
  148140. 3, 1, 0, 2, 4, 6, 8, 10,
  148141. 12, 14, 16, 18, 20,
  148142. };
  148143. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  148144. _vq_quantthresh__44u9_p8_1,
  148145. _vq_quantmap__44u9_p8_1,
  148146. 21,
  148147. 21
  148148. };
  148149. static static_codebook _44u9_p8_1 = {
  148150. 2, 441,
  148151. _vq_lengthlist__44u9_p8_1,
  148152. 1, -529268736, 1611661312, 5, 0,
  148153. _vq_quantlist__44u9_p8_1,
  148154. NULL,
  148155. &_vq_auxt__44u9_p8_1,
  148156. NULL,
  148157. 0
  148158. };
  148159. static long _vq_quantlist__44u9_p9_0[] = {
  148160. 7,
  148161. 6,
  148162. 8,
  148163. 5,
  148164. 9,
  148165. 4,
  148166. 10,
  148167. 3,
  148168. 11,
  148169. 2,
  148170. 12,
  148171. 1,
  148172. 13,
  148173. 0,
  148174. 14,
  148175. };
  148176. static long _vq_lengthlist__44u9_p9_0[] = {
  148177. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  148178. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  148179. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148180. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148181. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148182. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148183. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148184. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148185. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148186. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148187. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148188. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148189. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148190. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148191. 10,
  148192. };
  148193. static float _vq_quantthresh__44u9_p9_0[] = {
  148194. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  148195. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  148196. };
  148197. static long _vq_quantmap__44u9_p9_0[] = {
  148198. 13, 11, 9, 7, 5, 3, 1, 0,
  148199. 2, 4, 6, 8, 10, 12, 14,
  148200. };
  148201. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  148202. _vq_quantthresh__44u9_p9_0,
  148203. _vq_quantmap__44u9_p9_0,
  148204. 15,
  148205. 15
  148206. };
  148207. static static_codebook _44u9_p9_0 = {
  148208. 2, 225,
  148209. _vq_lengthlist__44u9_p9_0,
  148210. 1, -510036736, 1631393792, 4, 0,
  148211. _vq_quantlist__44u9_p9_0,
  148212. NULL,
  148213. &_vq_auxt__44u9_p9_0,
  148214. NULL,
  148215. 0
  148216. };
  148217. static long _vq_quantlist__44u9_p9_1[] = {
  148218. 9,
  148219. 8,
  148220. 10,
  148221. 7,
  148222. 11,
  148223. 6,
  148224. 12,
  148225. 5,
  148226. 13,
  148227. 4,
  148228. 14,
  148229. 3,
  148230. 15,
  148231. 2,
  148232. 16,
  148233. 1,
  148234. 17,
  148235. 0,
  148236. 18,
  148237. };
  148238. static long _vq_lengthlist__44u9_p9_1[] = {
  148239. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  148240. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  148241. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  148242. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  148243. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  148244. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  148245. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  148246. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  148247. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  148248. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  148249. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  148250. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  148251. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  148252. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  148253. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  148254. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  148255. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  148256. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  148257. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  148258. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  148259. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  148260. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  148261. 17,17,15,17,15,17,16,16,17,
  148262. };
  148263. static float _vq_quantthresh__44u9_p9_1[] = {
  148264. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148265. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148266. 367.5, 416.5,
  148267. };
  148268. static long _vq_quantmap__44u9_p9_1[] = {
  148269. 17, 15, 13, 11, 9, 7, 5, 3,
  148270. 1, 0, 2, 4, 6, 8, 10, 12,
  148271. 14, 16, 18,
  148272. };
  148273. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  148274. _vq_quantthresh__44u9_p9_1,
  148275. _vq_quantmap__44u9_p9_1,
  148276. 19,
  148277. 19
  148278. };
  148279. static static_codebook _44u9_p9_1 = {
  148280. 2, 361,
  148281. _vq_lengthlist__44u9_p9_1,
  148282. 1, -518287360, 1622704128, 5, 0,
  148283. _vq_quantlist__44u9_p9_1,
  148284. NULL,
  148285. &_vq_auxt__44u9_p9_1,
  148286. NULL,
  148287. 0
  148288. };
  148289. static long _vq_quantlist__44u9_p9_2[] = {
  148290. 24,
  148291. 23,
  148292. 25,
  148293. 22,
  148294. 26,
  148295. 21,
  148296. 27,
  148297. 20,
  148298. 28,
  148299. 19,
  148300. 29,
  148301. 18,
  148302. 30,
  148303. 17,
  148304. 31,
  148305. 16,
  148306. 32,
  148307. 15,
  148308. 33,
  148309. 14,
  148310. 34,
  148311. 13,
  148312. 35,
  148313. 12,
  148314. 36,
  148315. 11,
  148316. 37,
  148317. 10,
  148318. 38,
  148319. 9,
  148320. 39,
  148321. 8,
  148322. 40,
  148323. 7,
  148324. 41,
  148325. 6,
  148326. 42,
  148327. 5,
  148328. 43,
  148329. 4,
  148330. 44,
  148331. 3,
  148332. 45,
  148333. 2,
  148334. 46,
  148335. 1,
  148336. 47,
  148337. 0,
  148338. 48,
  148339. };
  148340. static long _vq_lengthlist__44u9_p9_2[] = {
  148341. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  148342. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148343. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148344. 7,
  148345. };
  148346. static float _vq_quantthresh__44u9_p9_2[] = {
  148347. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148348. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148349. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148350. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148351. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148352. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148353. };
  148354. static long _vq_quantmap__44u9_p9_2[] = {
  148355. 47, 45, 43, 41, 39, 37, 35, 33,
  148356. 31, 29, 27, 25, 23, 21, 19, 17,
  148357. 15, 13, 11, 9, 7, 5, 3, 1,
  148358. 0, 2, 4, 6, 8, 10, 12, 14,
  148359. 16, 18, 20, 22, 24, 26, 28, 30,
  148360. 32, 34, 36, 38, 40, 42, 44, 46,
  148361. 48,
  148362. };
  148363. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  148364. _vq_quantthresh__44u9_p9_2,
  148365. _vq_quantmap__44u9_p9_2,
  148366. 49,
  148367. 49
  148368. };
  148369. static static_codebook _44u9_p9_2 = {
  148370. 1, 49,
  148371. _vq_lengthlist__44u9_p9_2,
  148372. 1, -526909440, 1611661312, 6, 0,
  148373. _vq_quantlist__44u9_p9_2,
  148374. NULL,
  148375. &_vq_auxt__44u9_p9_2,
  148376. NULL,
  148377. 0
  148378. };
  148379. static long _huff_lengthlist__44un1__long[] = {
  148380. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  148381. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  148382. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  148383. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  148384. };
  148385. static static_codebook _huff_book__44un1__long = {
  148386. 2, 64,
  148387. _huff_lengthlist__44un1__long,
  148388. 0, 0, 0, 0, 0,
  148389. NULL,
  148390. NULL,
  148391. NULL,
  148392. NULL,
  148393. 0
  148394. };
  148395. static long _vq_quantlist__44un1__p1_0[] = {
  148396. 1,
  148397. 0,
  148398. 2,
  148399. };
  148400. static long _vq_lengthlist__44un1__p1_0[] = {
  148401. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148402. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  148403. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  148404. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  148405. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  148406. 12,
  148407. };
  148408. static float _vq_quantthresh__44un1__p1_0[] = {
  148409. -0.5, 0.5,
  148410. };
  148411. static long _vq_quantmap__44un1__p1_0[] = {
  148412. 1, 0, 2,
  148413. };
  148414. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  148415. _vq_quantthresh__44un1__p1_0,
  148416. _vq_quantmap__44un1__p1_0,
  148417. 3,
  148418. 3
  148419. };
  148420. static static_codebook _44un1__p1_0 = {
  148421. 4, 81,
  148422. _vq_lengthlist__44un1__p1_0,
  148423. 1, -535822336, 1611661312, 2, 0,
  148424. _vq_quantlist__44un1__p1_0,
  148425. NULL,
  148426. &_vq_auxt__44un1__p1_0,
  148427. NULL,
  148428. 0
  148429. };
  148430. static long _vq_quantlist__44un1__p2_0[] = {
  148431. 1,
  148432. 0,
  148433. 2,
  148434. };
  148435. static long _vq_lengthlist__44un1__p2_0[] = {
  148436. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  148437. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  148438. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  148439. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  148440. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  148441. 8,
  148442. };
  148443. static float _vq_quantthresh__44un1__p2_0[] = {
  148444. -0.5, 0.5,
  148445. };
  148446. static long _vq_quantmap__44un1__p2_0[] = {
  148447. 1, 0, 2,
  148448. };
  148449. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  148450. _vq_quantthresh__44un1__p2_0,
  148451. _vq_quantmap__44un1__p2_0,
  148452. 3,
  148453. 3
  148454. };
  148455. static static_codebook _44un1__p2_0 = {
  148456. 4, 81,
  148457. _vq_lengthlist__44un1__p2_0,
  148458. 1, -535822336, 1611661312, 2, 0,
  148459. _vq_quantlist__44un1__p2_0,
  148460. NULL,
  148461. &_vq_auxt__44un1__p2_0,
  148462. NULL,
  148463. 0
  148464. };
  148465. static long _vq_quantlist__44un1__p3_0[] = {
  148466. 2,
  148467. 1,
  148468. 3,
  148469. 0,
  148470. 4,
  148471. };
  148472. static long _vq_lengthlist__44un1__p3_0[] = {
  148473. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  148474. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  148475. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  148476. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  148477. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  148478. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  148479. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  148480. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  148481. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  148482. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  148483. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  148484. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  148485. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  148486. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  148487. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  148488. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  148489. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  148490. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  148491. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  148492. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  148493. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  148494. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  148495. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  148496. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  148497. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  148498. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  148499. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  148500. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  148501. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  148502. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  148503. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  148504. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  148505. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  148506. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  148507. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  148508. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  148509. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  148510. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  148511. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  148512. 17,
  148513. };
  148514. static float _vq_quantthresh__44un1__p3_0[] = {
  148515. -1.5, -0.5, 0.5, 1.5,
  148516. };
  148517. static long _vq_quantmap__44un1__p3_0[] = {
  148518. 3, 1, 0, 2, 4,
  148519. };
  148520. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  148521. _vq_quantthresh__44un1__p3_0,
  148522. _vq_quantmap__44un1__p3_0,
  148523. 5,
  148524. 5
  148525. };
  148526. static static_codebook _44un1__p3_0 = {
  148527. 4, 625,
  148528. _vq_lengthlist__44un1__p3_0,
  148529. 1, -533725184, 1611661312, 3, 0,
  148530. _vq_quantlist__44un1__p3_0,
  148531. NULL,
  148532. &_vq_auxt__44un1__p3_0,
  148533. NULL,
  148534. 0
  148535. };
  148536. static long _vq_quantlist__44un1__p4_0[] = {
  148537. 2,
  148538. 1,
  148539. 3,
  148540. 0,
  148541. 4,
  148542. };
  148543. static long _vq_lengthlist__44un1__p4_0[] = {
  148544. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  148545. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  148546. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  148547. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  148548. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  148549. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  148550. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  148551. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  148552. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  148553. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  148554. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  148555. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  148556. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  148557. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  148558. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  148559. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  148560. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  148561. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  148562. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  148563. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  148564. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  148565. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  148566. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  148567. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  148568. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  148569. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  148570. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  148571. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  148572. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  148573. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  148574. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  148575. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  148576. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  148577. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  148578. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  148579. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  148580. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  148581. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  148582. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  148583. 12,
  148584. };
  148585. static float _vq_quantthresh__44un1__p4_0[] = {
  148586. -1.5, -0.5, 0.5, 1.5,
  148587. };
  148588. static long _vq_quantmap__44un1__p4_0[] = {
  148589. 3, 1, 0, 2, 4,
  148590. };
  148591. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  148592. _vq_quantthresh__44un1__p4_0,
  148593. _vq_quantmap__44un1__p4_0,
  148594. 5,
  148595. 5
  148596. };
  148597. static static_codebook _44un1__p4_0 = {
  148598. 4, 625,
  148599. _vq_lengthlist__44un1__p4_0,
  148600. 1, -533725184, 1611661312, 3, 0,
  148601. _vq_quantlist__44un1__p4_0,
  148602. NULL,
  148603. &_vq_auxt__44un1__p4_0,
  148604. NULL,
  148605. 0
  148606. };
  148607. static long _vq_quantlist__44un1__p5_0[] = {
  148608. 4,
  148609. 3,
  148610. 5,
  148611. 2,
  148612. 6,
  148613. 1,
  148614. 7,
  148615. 0,
  148616. 8,
  148617. };
  148618. static long _vq_lengthlist__44un1__p5_0[] = {
  148619. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  148620. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  148621. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  148622. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  148623. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148624. 12,
  148625. };
  148626. static float _vq_quantthresh__44un1__p5_0[] = {
  148627. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148628. };
  148629. static long _vq_quantmap__44un1__p5_0[] = {
  148630. 7, 5, 3, 1, 0, 2, 4, 6,
  148631. 8,
  148632. };
  148633. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  148634. _vq_quantthresh__44un1__p5_0,
  148635. _vq_quantmap__44un1__p5_0,
  148636. 9,
  148637. 9
  148638. };
  148639. static static_codebook _44un1__p5_0 = {
  148640. 2, 81,
  148641. _vq_lengthlist__44un1__p5_0,
  148642. 1, -531628032, 1611661312, 4, 0,
  148643. _vq_quantlist__44un1__p5_0,
  148644. NULL,
  148645. &_vq_auxt__44un1__p5_0,
  148646. NULL,
  148647. 0
  148648. };
  148649. static long _vq_quantlist__44un1__p6_0[] = {
  148650. 6,
  148651. 5,
  148652. 7,
  148653. 4,
  148654. 8,
  148655. 3,
  148656. 9,
  148657. 2,
  148658. 10,
  148659. 1,
  148660. 11,
  148661. 0,
  148662. 12,
  148663. };
  148664. static long _vq_lengthlist__44un1__p6_0[] = {
  148665. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  148666. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  148667. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  148668. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  148669. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  148670. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  148671. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  148672. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  148673. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  148674. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  148675. 16, 0,15,18,18, 0,16, 0, 0,
  148676. };
  148677. static float _vq_quantthresh__44un1__p6_0[] = {
  148678. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148679. 12.5, 17.5, 22.5, 27.5,
  148680. };
  148681. static long _vq_quantmap__44un1__p6_0[] = {
  148682. 11, 9, 7, 5, 3, 1, 0, 2,
  148683. 4, 6, 8, 10, 12,
  148684. };
  148685. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  148686. _vq_quantthresh__44un1__p6_0,
  148687. _vq_quantmap__44un1__p6_0,
  148688. 13,
  148689. 13
  148690. };
  148691. static static_codebook _44un1__p6_0 = {
  148692. 2, 169,
  148693. _vq_lengthlist__44un1__p6_0,
  148694. 1, -526516224, 1616117760, 4, 0,
  148695. _vq_quantlist__44un1__p6_0,
  148696. NULL,
  148697. &_vq_auxt__44un1__p6_0,
  148698. NULL,
  148699. 0
  148700. };
  148701. static long _vq_quantlist__44un1__p6_1[] = {
  148702. 2,
  148703. 1,
  148704. 3,
  148705. 0,
  148706. 4,
  148707. };
  148708. static long _vq_lengthlist__44un1__p6_1[] = {
  148709. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  148710. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  148711. };
  148712. static float _vq_quantthresh__44un1__p6_1[] = {
  148713. -1.5, -0.5, 0.5, 1.5,
  148714. };
  148715. static long _vq_quantmap__44un1__p6_1[] = {
  148716. 3, 1, 0, 2, 4,
  148717. };
  148718. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  148719. _vq_quantthresh__44un1__p6_1,
  148720. _vq_quantmap__44un1__p6_1,
  148721. 5,
  148722. 5
  148723. };
  148724. static static_codebook _44un1__p6_1 = {
  148725. 2, 25,
  148726. _vq_lengthlist__44un1__p6_1,
  148727. 1, -533725184, 1611661312, 3, 0,
  148728. _vq_quantlist__44un1__p6_1,
  148729. NULL,
  148730. &_vq_auxt__44un1__p6_1,
  148731. NULL,
  148732. 0
  148733. };
  148734. static long _vq_quantlist__44un1__p7_0[] = {
  148735. 2,
  148736. 1,
  148737. 3,
  148738. 0,
  148739. 4,
  148740. };
  148741. static long _vq_lengthlist__44un1__p7_0[] = {
  148742. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  148743. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  148744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148745. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148749. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  148750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  148753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148757. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  148758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148759. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  148760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148766. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148767. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148776. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148777. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148781. 10,
  148782. };
  148783. static float _vq_quantthresh__44un1__p7_0[] = {
  148784. -253.5, -84.5, 84.5, 253.5,
  148785. };
  148786. static long _vq_quantmap__44un1__p7_0[] = {
  148787. 3, 1, 0, 2, 4,
  148788. };
  148789. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  148790. _vq_quantthresh__44un1__p7_0,
  148791. _vq_quantmap__44un1__p7_0,
  148792. 5,
  148793. 5
  148794. };
  148795. static static_codebook _44un1__p7_0 = {
  148796. 4, 625,
  148797. _vq_lengthlist__44un1__p7_0,
  148798. 1, -518709248, 1626677248, 3, 0,
  148799. _vq_quantlist__44un1__p7_0,
  148800. NULL,
  148801. &_vq_auxt__44un1__p7_0,
  148802. NULL,
  148803. 0
  148804. };
  148805. static long _vq_quantlist__44un1__p7_1[] = {
  148806. 6,
  148807. 5,
  148808. 7,
  148809. 4,
  148810. 8,
  148811. 3,
  148812. 9,
  148813. 2,
  148814. 10,
  148815. 1,
  148816. 11,
  148817. 0,
  148818. 12,
  148819. };
  148820. static long _vq_lengthlist__44un1__p7_1[] = {
  148821. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  148822. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  148823. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  148824. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  148825. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  148826. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  148827. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  148828. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  148829. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  148830. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  148831. 12,13,13,12,13,13,14,14,14,
  148832. };
  148833. static float _vq_quantthresh__44un1__p7_1[] = {
  148834. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148835. 32.5, 45.5, 58.5, 71.5,
  148836. };
  148837. static long _vq_quantmap__44un1__p7_1[] = {
  148838. 11, 9, 7, 5, 3, 1, 0, 2,
  148839. 4, 6, 8, 10, 12,
  148840. };
  148841. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  148842. _vq_quantthresh__44un1__p7_1,
  148843. _vq_quantmap__44un1__p7_1,
  148844. 13,
  148845. 13
  148846. };
  148847. static static_codebook _44un1__p7_1 = {
  148848. 2, 169,
  148849. _vq_lengthlist__44un1__p7_1,
  148850. 1, -523010048, 1618608128, 4, 0,
  148851. _vq_quantlist__44un1__p7_1,
  148852. NULL,
  148853. &_vq_auxt__44un1__p7_1,
  148854. NULL,
  148855. 0
  148856. };
  148857. static long _vq_quantlist__44un1__p7_2[] = {
  148858. 6,
  148859. 5,
  148860. 7,
  148861. 4,
  148862. 8,
  148863. 3,
  148864. 9,
  148865. 2,
  148866. 10,
  148867. 1,
  148868. 11,
  148869. 0,
  148870. 12,
  148871. };
  148872. static long _vq_lengthlist__44un1__p7_2[] = {
  148873. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  148874. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  148875. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  148876. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  148877. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  148878. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  148879. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  148880. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  148881. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  148882. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  148883. 9, 9, 9,10,10,10,10,10,10,
  148884. };
  148885. static float _vq_quantthresh__44un1__p7_2[] = {
  148886. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148887. 2.5, 3.5, 4.5, 5.5,
  148888. };
  148889. static long _vq_quantmap__44un1__p7_2[] = {
  148890. 11, 9, 7, 5, 3, 1, 0, 2,
  148891. 4, 6, 8, 10, 12,
  148892. };
  148893. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  148894. _vq_quantthresh__44un1__p7_2,
  148895. _vq_quantmap__44un1__p7_2,
  148896. 13,
  148897. 13
  148898. };
  148899. static static_codebook _44un1__p7_2 = {
  148900. 2, 169,
  148901. _vq_lengthlist__44un1__p7_2,
  148902. 1, -531103744, 1611661312, 4, 0,
  148903. _vq_quantlist__44un1__p7_2,
  148904. NULL,
  148905. &_vq_auxt__44un1__p7_2,
  148906. NULL,
  148907. 0
  148908. };
  148909. static long _huff_lengthlist__44un1__short[] = {
  148910. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  148911. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  148912. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  148913. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  148914. };
  148915. static static_codebook _huff_book__44un1__short = {
  148916. 2, 64,
  148917. _huff_lengthlist__44un1__short,
  148918. 0, 0, 0, 0, 0,
  148919. NULL,
  148920. NULL,
  148921. NULL,
  148922. NULL,
  148923. 0
  148924. };
  148925. /********* End of inlined file: res_books_uncoupled.h *********/
  148926. /***** residue backends *********************************************/
  148927. static vorbis_info_residue0 _residue_44_low_un={
  148928. 0,-1, -1, 8,-1,
  148929. {0},
  148930. {-1},
  148931. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  148932. { -1, 25, -1, 45, -1, -1, -1}
  148933. };
  148934. static vorbis_info_residue0 _residue_44_mid_un={
  148935. 0,-1, -1, 10,-1,
  148936. /* 0 1 2 3 4 5 6 7 8 9 */
  148937. {0},
  148938. {-1},
  148939. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  148940. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  148941. };
  148942. static vorbis_info_residue0 _residue_44_hi_un={
  148943. 0,-1, -1, 10,-1,
  148944. /* 0 1 2 3 4 5 6 7 8 9 */
  148945. {0},
  148946. {-1},
  148947. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  148948. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  148949. };
  148950. /* mapping conventions:
  148951. only one submap (this would change for efficient 5.1 support for example)*/
  148952. /* Four psychoacoustic profiles are used, one for each blocktype */
  148953. static vorbis_info_mapping0 _map_nominal_u[2]={
  148954. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  148955. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  148956. };
  148957. static static_bookblock _resbook_44u_n1={
  148958. {
  148959. {0},
  148960. {0,0,&_44un1__p1_0},
  148961. {0,0,&_44un1__p2_0},
  148962. {0,0,&_44un1__p3_0},
  148963. {0,0,&_44un1__p4_0},
  148964. {0,0,&_44un1__p5_0},
  148965. {&_44un1__p6_0,&_44un1__p6_1},
  148966. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  148967. }
  148968. };
  148969. static static_bookblock _resbook_44u_0={
  148970. {
  148971. {0},
  148972. {0,0,&_44u0__p1_0},
  148973. {0,0,&_44u0__p2_0},
  148974. {0,0,&_44u0__p3_0},
  148975. {0,0,&_44u0__p4_0},
  148976. {0,0,&_44u0__p5_0},
  148977. {&_44u0__p6_0,&_44u0__p6_1},
  148978. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  148979. }
  148980. };
  148981. static static_bookblock _resbook_44u_1={
  148982. {
  148983. {0},
  148984. {0,0,&_44u1__p1_0},
  148985. {0,0,&_44u1__p2_0},
  148986. {0,0,&_44u1__p3_0},
  148987. {0,0,&_44u1__p4_0},
  148988. {0,0,&_44u1__p5_0},
  148989. {&_44u1__p6_0,&_44u1__p6_1},
  148990. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  148991. }
  148992. };
  148993. static static_bookblock _resbook_44u_2={
  148994. {
  148995. {0},
  148996. {0,0,&_44u2__p1_0},
  148997. {0,0,&_44u2__p2_0},
  148998. {0,0,&_44u2__p3_0},
  148999. {0,0,&_44u2__p4_0},
  149000. {0,0,&_44u2__p5_0},
  149001. {&_44u2__p6_0,&_44u2__p6_1},
  149002. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  149003. }
  149004. };
  149005. static static_bookblock _resbook_44u_3={
  149006. {
  149007. {0},
  149008. {0,0,&_44u3__p1_0},
  149009. {0,0,&_44u3__p2_0},
  149010. {0,0,&_44u3__p3_0},
  149011. {0,0,&_44u3__p4_0},
  149012. {0,0,&_44u3__p5_0},
  149013. {&_44u3__p6_0,&_44u3__p6_1},
  149014. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  149015. }
  149016. };
  149017. static static_bookblock _resbook_44u_4={
  149018. {
  149019. {0},
  149020. {0,0,&_44u4__p1_0},
  149021. {0,0,&_44u4__p2_0},
  149022. {0,0,&_44u4__p3_0},
  149023. {0,0,&_44u4__p4_0},
  149024. {0,0,&_44u4__p5_0},
  149025. {&_44u4__p6_0,&_44u4__p6_1},
  149026. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  149027. }
  149028. };
  149029. static static_bookblock _resbook_44u_5={
  149030. {
  149031. {0},
  149032. {0,0,&_44u5__p1_0},
  149033. {0,0,&_44u5__p2_0},
  149034. {0,0,&_44u5__p3_0},
  149035. {0,0,&_44u5__p4_0},
  149036. {0,0,&_44u5__p5_0},
  149037. {0,0,&_44u5__p6_0},
  149038. {&_44u5__p7_0,&_44u5__p7_1},
  149039. {&_44u5__p8_0,&_44u5__p8_1},
  149040. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  149041. }
  149042. };
  149043. static static_bookblock _resbook_44u_6={
  149044. {
  149045. {0},
  149046. {0,0,&_44u6__p1_0},
  149047. {0,0,&_44u6__p2_0},
  149048. {0,0,&_44u6__p3_0},
  149049. {0,0,&_44u6__p4_0},
  149050. {0,0,&_44u6__p5_0},
  149051. {0,0,&_44u6__p6_0},
  149052. {&_44u6__p7_0,&_44u6__p7_1},
  149053. {&_44u6__p8_0,&_44u6__p8_1},
  149054. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  149055. }
  149056. };
  149057. static static_bookblock _resbook_44u_7={
  149058. {
  149059. {0},
  149060. {0,0,&_44u7__p1_0},
  149061. {0,0,&_44u7__p2_0},
  149062. {0,0,&_44u7__p3_0},
  149063. {0,0,&_44u7__p4_0},
  149064. {0,0,&_44u7__p5_0},
  149065. {0,0,&_44u7__p6_0},
  149066. {&_44u7__p7_0,&_44u7__p7_1},
  149067. {&_44u7__p8_0,&_44u7__p8_1},
  149068. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  149069. }
  149070. };
  149071. static static_bookblock _resbook_44u_8={
  149072. {
  149073. {0},
  149074. {0,0,&_44u8_p1_0},
  149075. {0,0,&_44u8_p2_0},
  149076. {0,0,&_44u8_p3_0},
  149077. {0,0,&_44u8_p4_0},
  149078. {&_44u8_p5_0,&_44u8_p5_1},
  149079. {&_44u8_p6_0,&_44u8_p6_1},
  149080. {&_44u8_p7_0,&_44u8_p7_1},
  149081. {&_44u8_p8_0,&_44u8_p8_1},
  149082. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  149083. }
  149084. };
  149085. static static_bookblock _resbook_44u_9={
  149086. {
  149087. {0},
  149088. {0,0,&_44u9_p1_0},
  149089. {0,0,&_44u9_p2_0},
  149090. {0,0,&_44u9_p3_0},
  149091. {0,0,&_44u9_p4_0},
  149092. {&_44u9_p5_0,&_44u9_p5_1},
  149093. {&_44u9_p6_0,&_44u9_p6_1},
  149094. {&_44u9_p7_0,&_44u9_p7_1},
  149095. {&_44u9_p8_0,&_44u9_p8_1},
  149096. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  149097. }
  149098. };
  149099. static vorbis_residue_template _res_44u_n1[]={
  149100. {1,0, &_residue_44_low_un,
  149101. &_huff_book__44un1__short,&_huff_book__44un1__short,
  149102. &_resbook_44u_n1,&_resbook_44u_n1},
  149103. {1,0, &_residue_44_low_un,
  149104. &_huff_book__44un1__long,&_huff_book__44un1__long,
  149105. &_resbook_44u_n1,&_resbook_44u_n1}
  149106. };
  149107. static vorbis_residue_template _res_44u_0[]={
  149108. {1,0, &_residue_44_low_un,
  149109. &_huff_book__44u0__short,&_huff_book__44u0__short,
  149110. &_resbook_44u_0,&_resbook_44u_0},
  149111. {1,0, &_residue_44_low_un,
  149112. &_huff_book__44u0__long,&_huff_book__44u0__long,
  149113. &_resbook_44u_0,&_resbook_44u_0}
  149114. };
  149115. static vorbis_residue_template _res_44u_1[]={
  149116. {1,0, &_residue_44_low_un,
  149117. &_huff_book__44u1__short,&_huff_book__44u1__short,
  149118. &_resbook_44u_1,&_resbook_44u_1},
  149119. {1,0, &_residue_44_low_un,
  149120. &_huff_book__44u1__long,&_huff_book__44u1__long,
  149121. &_resbook_44u_1,&_resbook_44u_1}
  149122. };
  149123. static vorbis_residue_template _res_44u_2[]={
  149124. {1,0, &_residue_44_low_un,
  149125. &_huff_book__44u2__short,&_huff_book__44u2__short,
  149126. &_resbook_44u_2,&_resbook_44u_2},
  149127. {1,0, &_residue_44_low_un,
  149128. &_huff_book__44u2__long,&_huff_book__44u2__long,
  149129. &_resbook_44u_2,&_resbook_44u_2}
  149130. };
  149131. static vorbis_residue_template _res_44u_3[]={
  149132. {1,0, &_residue_44_low_un,
  149133. &_huff_book__44u3__short,&_huff_book__44u3__short,
  149134. &_resbook_44u_3,&_resbook_44u_3},
  149135. {1,0, &_residue_44_low_un,
  149136. &_huff_book__44u3__long,&_huff_book__44u3__long,
  149137. &_resbook_44u_3,&_resbook_44u_3}
  149138. };
  149139. static vorbis_residue_template _res_44u_4[]={
  149140. {1,0, &_residue_44_low_un,
  149141. &_huff_book__44u4__short,&_huff_book__44u4__short,
  149142. &_resbook_44u_4,&_resbook_44u_4},
  149143. {1,0, &_residue_44_low_un,
  149144. &_huff_book__44u4__long,&_huff_book__44u4__long,
  149145. &_resbook_44u_4,&_resbook_44u_4}
  149146. };
  149147. static vorbis_residue_template _res_44u_5[]={
  149148. {1,0, &_residue_44_mid_un,
  149149. &_huff_book__44u5__short,&_huff_book__44u5__short,
  149150. &_resbook_44u_5,&_resbook_44u_5},
  149151. {1,0, &_residue_44_mid_un,
  149152. &_huff_book__44u5__long,&_huff_book__44u5__long,
  149153. &_resbook_44u_5,&_resbook_44u_5}
  149154. };
  149155. static vorbis_residue_template _res_44u_6[]={
  149156. {1,0, &_residue_44_mid_un,
  149157. &_huff_book__44u6__short,&_huff_book__44u6__short,
  149158. &_resbook_44u_6,&_resbook_44u_6},
  149159. {1,0, &_residue_44_mid_un,
  149160. &_huff_book__44u6__long,&_huff_book__44u6__long,
  149161. &_resbook_44u_6,&_resbook_44u_6}
  149162. };
  149163. static vorbis_residue_template _res_44u_7[]={
  149164. {1,0, &_residue_44_mid_un,
  149165. &_huff_book__44u7__short,&_huff_book__44u7__short,
  149166. &_resbook_44u_7,&_resbook_44u_7},
  149167. {1,0, &_residue_44_mid_un,
  149168. &_huff_book__44u7__long,&_huff_book__44u7__long,
  149169. &_resbook_44u_7,&_resbook_44u_7}
  149170. };
  149171. static vorbis_residue_template _res_44u_8[]={
  149172. {1,0, &_residue_44_hi_un,
  149173. &_huff_book__44u8__short,&_huff_book__44u8__short,
  149174. &_resbook_44u_8,&_resbook_44u_8},
  149175. {1,0, &_residue_44_hi_un,
  149176. &_huff_book__44u8__long,&_huff_book__44u8__long,
  149177. &_resbook_44u_8,&_resbook_44u_8}
  149178. };
  149179. static vorbis_residue_template _res_44u_9[]={
  149180. {1,0, &_residue_44_hi_un,
  149181. &_huff_book__44u9__short,&_huff_book__44u9__short,
  149182. &_resbook_44u_9,&_resbook_44u_9},
  149183. {1,0, &_residue_44_hi_un,
  149184. &_huff_book__44u9__long,&_huff_book__44u9__long,
  149185. &_resbook_44u_9,&_resbook_44u_9}
  149186. };
  149187. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  149188. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  149189. { _map_nominal_u, _res_44u_0 }, /* 0 */
  149190. { _map_nominal_u, _res_44u_1 }, /* 1 */
  149191. { _map_nominal_u, _res_44u_2 }, /* 2 */
  149192. { _map_nominal_u, _res_44u_3 }, /* 3 */
  149193. { _map_nominal_u, _res_44u_4 }, /* 4 */
  149194. { _map_nominal_u, _res_44u_5 }, /* 5 */
  149195. { _map_nominal_u, _res_44u_6 }, /* 6 */
  149196. { _map_nominal_u, _res_44u_7 }, /* 7 */
  149197. { _map_nominal_u, _res_44u_8 }, /* 8 */
  149198. { _map_nominal_u, _res_44u_9 }, /* 9 */
  149199. };
  149200. /********* End of inlined file: residue_44u.h *********/
  149201. static double rate_mapping_44_un[12]={
  149202. 32000.,48000.,60000.,70000.,80000.,86000.,
  149203. 96000.,110000.,120000.,140000.,160000.,240001.
  149204. };
  149205. ve_setup_data_template ve_setup_44_uncoupled={
  149206. 11,
  149207. rate_mapping_44_un,
  149208. quality_mapping_44,
  149209. -1,
  149210. 40000,
  149211. 50000,
  149212. blocksize_short_44,
  149213. blocksize_long_44,
  149214. _psy_tone_masteratt_44,
  149215. _psy_tone_0dB,
  149216. _psy_tone_suppress,
  149217. _vp_tonemask_adj_otherblock,
  149218. _vp_tonemask_adj_longblock,
  149219. _vp_tonemask_adj_otherblock,
  149220. _psy_noiseguards_44,
  149221. _psy_noisebias_impulse,
  149222. _psy_noisebias_padding,
  149223. _psy_noisebias_trans,
  149224. _psy_noisebias_long,
  149225. _psy_noise_suppress,
  149226. _psy_compand_44,
  149227. _psy_compand_short_mapping,
  149228. _psy_compand_long_mapping,
  149229. {_noise_start_short_44,_noise_start_long_44},
  149230. {_noise_part_short_44,_noise_part_long_44},
  149231. _noise_thresh_44,
  149232. _psy_ath_floater,
  149233. _psy_ath_abs,
  149234. _psy_lowpass_44,
  149235. _psy_global_44,
  149236. _global_mapping_44,
  149237. NULL,
  149238. _floor_books,
  149239. _floor,
  149240. _floor_short_mapping_44,
  149241. _floor_long_mapping_44,
  149242. _mapres_template_44_uncoupled
  149243. };
  149244. /********* End of inlined file: setup_44u.h *********/
  149245. /********* Start of inlined file: setup_32.h *********/
  149246. static double rate_mapping_32[12]={
  149247. 18000.,28000.,35000.,45000.,56000.,60000.,
  149248. 75000.,90000.,100000.,115000.,150000.,190000.,
  149249. };
  149250. static double rate_mapping_32_un[12]={
  149251. 30000.,42000.,52000.,64000.,72000.,78000.,
  149252. 86000.,92000.,110000.,120000.,140000.,190000.,
  149253. };
  149254. static double _psy_lowpass_32[12]={
  149255. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  149256. };
  149257. ve_setup_data_template ve_setup_32_stereo={
  149258. 11,
  149259. rate_mapping_32,
  149260. quality_mapping_44,
  149261. 2,
  149262. 26000,
  149263. 40000,
  149264. blocksize_short_44,
  149265. blocksize_long_44,
  149266. _psy_tone_masteratt_44,
  149267. _psy_tone_0dB,
  149268. _psy_tone_suppress,
  149269. _vp_tonemask_adj_otherblock,
  149270. _vp_tonemask_adj_longblock,
  149271. _vp_tonemask_adj_otherblock,
  149272. _psy_noiseguards_44,
  149273. _psy_noisebias_impulse,
  149274. _psy_noisebias_padding,
  149275. _psy_noisebias_trans,
  149276. _psy_noisebias_long,
  149277. _psy_noise_suppress,
  149278. _psy_compand_44,
  149279. _psy_compand_short_mapping,
  149280. _psy_compand_long_mapping,
  149281. {_noise_start_short_44,_noise_start_long_44},
  149282. {_noise_part_short_44,_noise_part_long_44},
  149283. _noise_thresh_44,
  149284. _psy_ath_floater,
  149285. _psy_ath_abs,
  149286. _psy_lowpass_32,
  149287. _psy_global_44,
  149288. _global_mapping_44,
  149289. _psy_stereo_modes_44,
  149290. _floor_books,
  149291. _floor,
  149292. _floor_short_mapping_44,
  149293. _floor_long_mapping_44,
  149294. _mapres_template_44_stereo
  149295. };
  149296. ve_setup_data_template ve_setup_32_uncoupled={
  149297. 11,
  149298. rate_mapping_32_un,
  149299. quality_mapping_44,
  149300. -1,
  149301. 26000,
  149302. 40000,
  149303. blocksize_short_44,
  149304. blocksize_long_44,
  149305. _psy_tone_masteratt_44,
  149306. _psy_tone_0dB,
  149307. _psy_tone_suppress,
  149308. _vp_tonemask_adj_otherblock,
  149309. _vp_tonemask_adj_longblock,
  149310. _vp_tonemask_adj_otherblock,
  149311. _psy_noiseguards_44,
  149312. _psy_noisebias_impulse,
  149313. _psy_noisebias_padding,
  149314. _psy_noisebias_trans,
  149315. _psy_noisebias_long,
  149316. _psy_noise_suppress,
  149317. _psy_compand_44,
  149318. _psy_compand_short_mapping,
  149319. _psy_compand_long_mapping,
  149320. {_noise_start_short_44,_noise_start_long_44},
  149321. {_noise_part_short_44,_noise_part_long_44},
  149322. _noise_thresh_44,
  149323. _psy_ath_floater,
  149324. _psy_ath_abs,
  149325. _psy_lowpass_32,
  149326. _psy_global_44,
  149327. _global_mapping_44,
  149328. NULL,
  149329. _floor_books,
  149330. _floor,
  149331. _floor_short_mapping_44,
  149332. _floor_long_mapping_44,
  149333. _mapres_template_44_uncoupled
  149334. };
  149335. /********* End of inlined file: setup_32.h *********/
  149336. /********* Start of inlined file: setup_8.h *********/
  149337. /********* Start of inlined file: psych_8.h *********/
  149338. static att3 _psy_tone_masteratt_8[3]={
  149339. {{ 32, 25, 12}, 0, 0}, /* 0 */
  149340. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149341. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149342. };
  149343. static vp_adjblock _vp_tonemask_adj_8[3]={
  149344. /* adjust for mode zero */
  149345. /* 63 125 250 500 1 2 4 8 16 */
  149346. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149347. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149348. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  149349. };
  149350. static noise3 _psy_noisebias_8[3]={
  149351. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149352. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149353. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  149354. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149355. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149356. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149357. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149358. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149359. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149360. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149361. };
  149362. /* stereo mode by base quality level */
  149363. static adj_stereo _psy_stereo_modes_8[3]={
  149364. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149365. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149366. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149367. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149368. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149369. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149370. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149371. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149372. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149373. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149374. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149375. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149376. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149377. };
  149378. static noiseguard _psy_noiseguards_8[2]={
  149379. {10,10,-1},
  149380. {10,10,-1},
  149381. };
  149382. static compandblock _psy_compand_8[2]={
  149383. {{
  149384. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  149385. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  149386. 12,12,13,13,14,14,15, 15, /* 23dB */
  149387. 16,16,17,17,17,18,18, 19, /* 31dB */
  149388. 19,19,20,21,22,23,24, 25, /* 39dB */
  149389. }},
  149390. {{
  149391. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  149392. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  149393. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  149394. 9,10,11,12,13,14,15, 16, /* 31dB */
  149395. 17,18,19,20,21,22,23, 24, /* 39dB */
  149396. }},
  149397. };
  149398. static double _psy_lowpass_8[3]={3.,4.,4.};
  149399. static int _noise_start_8[2]={
  149400. 64,64,
  149401. };
  149402. static int _noise_part_8[2]={
  149403. 8,8,
  149404. };
  149405. static int _psy_ath_floater_8[3]={
  149406. -100,-100,-105,
  149407. };
  149408. static int _psy_ath_abs_8[3]={
  149409. -130,-130,-140,
  149410. };
  149411. /********* End of inlined file: psych_8.h *********/
  149412. /********* Start of inlined file: residue_8.h *********/
  149413. /***** residue backends *********************************************/
  149414. static static_bookblock _resbook_8s_0={
  149415. {
  149416. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  149417. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  149418. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  149419. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  149420. }
  149421. };
  149422. static static_bookblock _resbook_8s_1={
  149423. {
  149424. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  149425. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  149426. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  149427. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  149428. }
  149429. };
  149430. static vorbis_residue_template _res_8s_0[]={
  149431. {2,0, &_residue_44_mid,
  149432. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  149433. &_resbook_8s_0,&_resbook_8s_0},
  149434. };
  149435. static vorbis_residue_template _res_8s_1[]={
  149436. {2,0, &_residue_44_mid,
  149437. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  149438. &_resbook_8s_1,&_resbook_8s_1},
  149439. };
  149440. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  149441. { _map_nominal, _res_8s_0 }, /* 0 */
  149442. { _map_nominal, _res_8s_1 }, /* 1 */
  149443. };
  149444. static static_bookblock _resbook_8u_0={
  149445. {
  149446. {0},
  149447. {0,0,&_8u0__p1_0},
  149448. {0,0,&_8u0__p2_0},
  149449. {0,0,&_8u0__p3_0},
  149450. {0,0,&_8u0__p4_0},
  149451. {0,0,&_8u0__p5_0},
  149452. {&_8u0__p6_0,&_8u0__p6_1},
  149453. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  149454. }
  149455. };
  149456. static static_bookblock _resbook_8u_1={
  149457. {
  149458. {0},
  149459. {0,0,&_8u1__p1_0},
  149460. {0,0,&_8u1__p2_0},
  149461. {0,0,&_8u1__p3_0},
  149462. {0,0,&_8u1__p4_0},
  149463. {0,0,&_8u1__p5_0},
  149464. {0,0,&_8u1__p6_0},
  149465. {&_8u1__p7_0,&_8u1__p7_1},
  149466. {&_8u1__p8_0,&_8u1__p8_1},
  149467. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  149468. }
  149469. };
  149470. static vorbis_residue_template _res_8u_0[]={
  149471. {1,0, &_residue_44_low_un,
  149472. &_huff_book__8u0__single,&_huff_book__8u0__single,
  149473. &_resbook_8u_0,&_resbook_8u_0},
  149474. };
  149475. static vorbis_residue_template _res_8u_1[]={
  149476. {1,0, &_residue_44_mid_un,
  149477. &_huff_book__8u1__single,&_huff_book__8u1__single,
  149478. &_resbook_8u_1,&_resbook_8u_1},
  149479. };
  149480. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  149481. { _map_nominal_u, _res_8u_0 }, /* 0 */
  149482. { _map_nominal_u, _res_8u_1 }, /* 1 */
  149483. };
  149484. /********* End of inlined file: residue_8.h *********/
  149485. static int blocksize_8[2]={
  149486. 512,512
  149487. };
  149488. static int _floor_mapping_8[2]={
  149489. 6,6,
  149490. };
  149491. static double rate_mapping_8[3]={
  149492. 6000.,9000.,32000.,
  149493. };
  149494. static double rate_mapping_8_uncoupled[3]={
  149495. 8000.,14000.,42000.,
  149496. };
  149497. static double quality_mapping_8[3]={
  149498. -.1,.0,1.
  149499. };
  149500. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  149501. static double _global_mapping_8[3]={ 1., 2., 3. };
  149502. ve_setup_data_template ve_setup_8_stereo={
  149503. 2,
  149504. rate_mapping_8,
  149505. quality_mapping_8,
  149506. 2,
  149507. 8000,
  149508. 9000,
  149509. blocksize_8,
  149510. blocksize_8,
  149511. _psy_tone_masteratt_8,
  149512. _psy_tone_0dB,
  149513. _psy_tone_suppress,
  149514. _vp_tonemask_adj_8,
  149515. NULL,
  149516. _vp_tonemask_adj_8,
  149517. _psy_noiseguards_8,
  149518. _psy_noisebias_8,
  149519. _psy_noisebias_8,
  149520. NULL,
  149521. NULL,
  149522. _psy_noise_suppress,
  149523. _psy_compand_8,
  149524. _psy_compand_8_mapping,
  149525. NULL,
  149526. {_noise_start_8,_noise_start_8},
  149527. {_noise_part_8,_noise_part_8},
  149528. _noise_thresh_5only,
  149529. _psy_ath_floater_8,
  149530. _psy_ath_abs_8,
  149531. _psy_lowpass_8,
  149532. _psy_global_44,
  149533. _global_mapping_8,
  149534. _psy_stereo_modes_8,
  149535. _floor_books,
  149536. _floor,
  149537. _floor_mapping_8,
  149538. NULL,
  149539. _mapres_template_8_stereo
  149540. };
  149541. ve_setup_data_template ve_setup_8_uncoupled={
  149542. 2,
  149543. rate_mapping_8_uncoupled,
  149544. quality_mapping_8,
  149545. -1,
  149546. 8000,
  149547. 9000,
  149548. blocksize_8,
  149549. blocksize_8,
  149550. _psy_tone_masteratt_8,
  149551. _psy_tone_0dB,
  149552. _psy_tone_suppress,
  149553. _vp_tonemask_adj_8,
  149554. NULL,
  149555. _vp_tonemask_adj_8,
  149556. _psy_noiseguards_8,
  149557. _psy_noisebias_8,
  149558. _psy_noisebias_8,
  149559. NULL,
  149560. NULL,
  149561. _psy_noise_suppress,
  149562. _psy_compand_8,
  149563. _psy_compand_8_mapping,
  149564. NULL,
  149565. {_noise_start_8,_noise_start_8},
  149566. {_noise_part_8,_noise_part_8},
  149567. _noise_thresh_5only,
  149568. _psy_ath_floater_8,
  149569. _psy_ath_abs_8,
  149570. _psy_lowpass_8,
  149571. _psy_global_44,
  149572. _global_mapping_8,
  149573. _psy_stereo_modes_8,
  149574. _floor_books,
  149575. _floor,
  149576. _floor_mapping_8,
  149577. NULL,
  149578. _mapres_template_8_uncoupled
  149579. };
  149580. /********* End of inlined file: setup_8.h *********/
  149581. /********* Start of inlined file: setup_11.h *********/
  149582. /********* Start of inlined file: psych_11.h *********/
  149583. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  149584. static att3 _psy_tone_masteratt_11[3]={
  149585. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149586. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149587. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149588. };
  149589. static vp_adjblock _vp_tonemask_adj_11[3]={
  149590. /* adjust for mode zero */
  149591. /* 63 125 250 500 1 2 4 8 16 */
  149592. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  149593. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  149594. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  149595. };
  149596. static noise3 _psy_noisebias_11[3]={
  149597. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149598. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149599. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  149600. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149601. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149602. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149603. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149604. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149605. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149606. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149607. };
  149608. static double _noise_thresh_11[3]={ .3,.5,.5 };
  149609. /********* End of inlined file: psych_11.h *********/
  149610. static int blocksize_11[2]={
  149611. 512,512
  149612. };
  149613. static int _floor_mapping_11[2]={
  149614. 6,6,
  149615. };
  149616. static double rate_mapping_11[3]={
  149617. 8000.,13000.,44000.,
  149618. };
  149619. static double rate_mapping_11_uncoupled[3]={
  149620. 12000.,20000.,50000.,
  149621. };
  149622. static double quality_mapping_11[3]={
  149623. -.1,.0,1.
  149624. };
  149625. ve_setup_data_template ve_setup_11_stereo={
  149626. 2,
  149627. rate_mapping_11,
  149628. quality_mapping_11,
  149629. 2,
  149630. 9000,
  149631. 15000,
  149632. blocksize_11,
  149633. blocksize_11,
  149634. _psy_tone_masteratt_11,
  149635. _psy_tone_0dB,
  149636. _psy_tone_suppress,
  149637. _vp_tonemask_adj_11,
  149638. NULL,
  149639. _vp_tonemask_adj_11,
  149640. _psy_noiseguards_8,
  149641. _psy_noisebias_11,
  149642. _psy_noisebias_11,
  149643. NULL,
  149644. NULL,
  149645. _psy_noise_suppress,
  149646. _psy_compand_8,
  149647. _psy_compand_8_mapping,
  149648. NULL,
  149649. {_noise_start_8,_noise_start_8},
  149650. {_noise_part_8,_noise_part_8},
  149651. _noise_thresh_11,
  149652. _psy_ath_floater_8,
  149653. _psy_ath_abs_8,
  149654. _psy_lowpass_11,
  149655. _psy_global_44,
  149656. _global_mapping_8,
  149657. _psy_stereo_modes_8,
  149658. _floor_books,
  149659. _floor,
  149660. _floor_mapping_11,
  149661. NULL,
  149662. _mapres_template_8_stereo
  149663. };
  149664. ve_setup_data_template ve_setup_11_uncoupled={
  149665. 2,
  149666. rate_mapping_11_uncoupled,
  149667. quality_mapping_11,
  149668. -1,
  149669. 9000,
  149670. 15000,
  149671. blocksize_11,
  149672. blocksize_11,
  149673. _psy_tone_masteratt_11,
  149674. _psy_tone_0dB,
  149675. _psy_tone_suppress,
  149676. _vp_tonemask_adj_11,
  149677. NULL,
  149678. _vp_tonemask_adj_11,
  149679. _psy_noiseguards_8,
  149680. _psy_noisebias_11,
  149681. _psy_noisebias_11,
  149682. NULL,
  149683. NULL,
  149684. _psy_noise_suppress,
  149685. _psy_compand_8,
  149686. _psy_compand_8_mapping,
  149687. NULL,
  149688. {_noise_start_8,_noise_start_8},
  149689. {_noise_part_8,_noise_part_8},
  149690. _noise_thresh_11,
  149691. _psy_ath_floater_8,
  149692. _psy_ath_abs_8,
  149693. _psy_lowpass_11,
  149694. _psy_global_44,
  149695. _global_mapping_8,
  149696. _psy_stereo_modes_8,
  149697. _floor_books,
  149698. _floor,
  149699. _floor_mapping_11,
  149700. NULL,
  149701. _mapres_template_8_uncoupled
  149702. };
  149703. /********* End of inlined file: setup_11.h *********/
  149704. /********* Start of inlined file: setup_16.h *********/
  149705. /********* Start of inlined file: psych_16.h *********/
  149706. /* stereo mode by base quality level */
  149707. static adj_stereo _psy_stereo_modes_16[4]={
  149708. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149709. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149710. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149711. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  149712. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149713. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149714. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149715. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  149716. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149717. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149718. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149719. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149720. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149721. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149722. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149723. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  149724. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149725. };
  149726. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  149727. static att3 _psy_tone_masteratt_16[4]={
  149728. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149729. {{ 25, 22, 12}, 0, 0}, /* 0 */
  149730. {{ 20, 12, 0}, 0, 0}, /* 0 */
  149731. {{ 15, 0, -14}, 0, 0}, /* 0 */
  149732. };
  149733. static vp_adjblock _vp_tonemask_adj_16[4]={
  149734. /* adjust for mode zero */
  149735. /* 63 125 250 500 1 2 4 8 16 */
  149736. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  149737. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  149738. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149739. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149740. };
  149741. static noise3 _psy_noisebias_16_short[4]={
  149742. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149743. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149744. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149745. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149746. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149747. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  149748. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149749. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149750. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  149751. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149752. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149753. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149754. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149755. };
  149756. static noise3 _psy_noisebias_16_impulse[4]={
  149757. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149758. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149759. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149760. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149761. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  149762. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  149763. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149764. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  149765. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  149766. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149767. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149768. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  149769. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149770. };
  149771. static noise3 _psy_noisebias_16[4]={
  149772. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149773. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  149774. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149775. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149776. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149777. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149778. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149779. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149780. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  149781. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149782. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149783. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149784. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149785. };
  149786. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  149787. static int _noise_start_16[3]={ 256,256,9999 };
  149788. static int _noise_part_16[4]={ 8,8,8,8 };
  149789. static int _psy_ath_floater_16[4]={
  149790. -100,-100,-100,-105,
  149791. };
  149792. static int _psy_ath_abs_16[4]={
  149793. -130,-130,-130,-140,
  149794. };
  149795. /********* End of inlined file: psych_16.h *********/
  149796. /********* Start of inlined file: residue_16.h *********/
  149797. /***** residue backends *********************************************/
  149798. static static_bookblock _resbook_16s_0={
  149799. {
  149800. {0},
  149801. {0,0,&_16c0_s_p1_0},
  149802. {0,0,&_16c0_s_p2_0},
  149803. {0,0,&_16c0_s_p3_0},
  149804. {0,0,&_16c0_s_p4_0},
  149805. {0,0,&_16c0_s_p5_0},
  149806. {0,0,&_16c0_s_p6_0},
  149807. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  149808. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  149809. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  149810. }
  149811. };
  149812. static static_bookblock _resbook_16s_1={
  149813. {
  149814. {0},
  149815. {0,0,&_16c1_s_p1_0},
  149816. {0,0,&_16c1_s_p2_0},
  149817. {0,0,&_16c1_s_p3_0},
  149818. {0,0,&_16c1_s_p4_0},
  149819. {0,0,&_16c1_s_p5_0},
  149820. {0,0,&_16c1_s_p6_0},
  149821. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  149822. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  149823. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  149824. }
  149825. };
  149826. static static_bookblock _resbook_16s_2={
  149827. {
  149828. {0},
  149829. {0,0,&_16c2_s_p1_0},
  149830. {0,0,&_16c2_s_p2_0},
  149831. {0,0,&_16c2_s_p3_0},
  149832. {0,0,&_16c2_s_p4_0},
  149833. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  149834. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  149835. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  149836. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  149837. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  149838. }
  149839. };
  149840. static vorbis_residue_template _res_16s_0[]={
  149841. {2,0, &_residue_44_mid,
  149842. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  149843. &_resbook_16s_0,&_resbook_16s_0},
  149844. };
  149845. static vorbis_residue_template _res_16s_1[]={
  149846. {2,0, &_residue_44_mid,
  149847. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  149848. &_resbook_16s_1,&_resbook_16s_1},
  149849. {2,0, &_residue_44_mid,
  149850. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  149851. &_resbook_16s_1,&_resbook_16s_1}
  149852. };
  149853. static vorbis_residue_template _res_16s_2[]={
  149854. {2,0, &_residue_44_high,
  149855. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  149856. &_resbook_16s_2,&_resbook_16s_2},
  149857. {2,0, &_residue_44_high,
  149858. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  149859. &_resbook_16s_2,&_resbook_16s_2}
  149860. };
  149861. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  149862. { _map_nominal, _res_16s_0 }, /* 0 */
  149863. { _map_nominal, _res_16s_1 }, /* 1 */
  149864. { _map_nominal, _res_16s_2 }, /* 2 */
  149865. };
  149866. static static_bookblock _resbook_16u_0={
  149867. {
  149868. {0},
  149869. {0,0,&_16u0__p1_0},
  149870. {0,0,&_16u0__p2_0},
  149871. {0,0,&_16u0__p3_0},
  149872. {0,0,&_16u0__p4_0},
  149873. {0,0,&_16u0__p5_0},
  149874. {&_16u0__p6_0,&_16u0__p6_1},
  149875. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  149876. }
  149877. };
  149878. static static_bookblock _resbook_16u_1={
  149879. {
  149880. {0},
  149881. {0,0,&_16u1__p1_0},
  149882. {0,0,&_16u1__p2_0},
  149883. {0,0,&_16u1__p3_0},
  149884. {0,0,&_16u1__p4_0},
  149885. {0,0,&_16u1__p5_0},
  149886. {0,0,&_16u1__p6_0},
  149887. {&_16u1__p7_0,&_16u1__p7_1},
  149888. {&_16u1__p8_0,&_16u1__p8_1},
  149889. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  149890. }
  149891. };
  149892. static static_bookblock _resbook_16u_2={
  149893. {
  149894. {0},
  149895. {0,0,&_16u2_p1_0},
  149896. {0,0,&_16u2_p2_0},
  149897. {0,0,&_16u2_p3_0},
  149898. {0,0,&_16u2_p4_0},
  149899. {&_16u2_p5_0,&_16u2_p5_1},
  149900. {&_16u2_p6_0,&_16u2_p6_1},
  149901. {&_16u2_p7_0,&_16u2_p7_1},
  149902. {&_16u2_p8_0,&_16u2_p8_1},
  149903. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  149904. }
  149905. };
  149906. static vorbis_residue_template _res_16u_0[]={
  149907. {1,0, &_residue_44_low_un,
  149908. &_huff_book__16u0__single,&_huff_book__16u0__single,
  149909. &_resbook_16u_0,&_resbook_16u_0},
  149910. };
  149911. static vorbis_residue_template _res_16u_1[]={
  149912. {1,0, &_residue_44_mid_un,
  149913. &_huff_book__16u1__short,&_huff_book__16u1__short,
  149914. &_resbook_16u_1,&_resbook_16u_1},
  149915. {1,0, &_residue_44_mid_un,
  149916. &_huff_book__16u1__long,&_huff_book__16u1__long,
  149917. &_resbook_16u_1,&_resbook_16u_1}
  149918. };
  149919. static vorbis_residue_template _res_16u_2[]={
  149920. {1,0, &_residue_44_hi_un,
  149921. &_huff_book__16u2__short,&_huff_book__16u2__short,
  149922. &_resbook_16u_2,&_resbook_16u_2},
  149923. {1,0, &_residue_44_hi_un,
  149924. &_huff_book__16u2__long,&_huff_book__16u2__long,
  149925. &_resbook_16u_2,&_resbook_16u_2}
  149926. };
  149927. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  149928. { _map_nominal_u, _res_16u_0 }, /* 0 */
  149929. { _map_nominal_u, _res_16u_1 }, /* 1 */
  149930. { _map_nominal_u, _res_16u_2 }, /* 2 */
  149931. };
  149932. /********* End of inlined file: residue_16.h *********/
  149933. static int blocksize_16_short[3]={
  149934. 1024,512,512
  149935. };
  149936. static int blocksize_16_long[3]={
  149937. 1024,1024,1024
  149938. };
  149939. static int _floor_mapping_16_short[3]={
  149940. 9,3,3
  149941. };
  149942. static int _floor_mapping_16[3]={
  149943. 9,9,9
  149944. };
  149945. static double rate_mapping_16[4]={
  149946. 12000.,20000.,44000.,86000.
  149947. };
  149948. static double rate_mapping_16_uncoupled[4]={
  149949. 16000.,28000.,64000.,100000.
  149950. };
  149951. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  149952. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  149953. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  149954. ve_setup_data_template ve_setup_16_stereo={
  149955. 3,
  149956. rate_mapping_16,
  149957. quality_mapping_16,
  149958. 2,
  149959. 15000,
  149960. 19000,
  149961. blocksize_16_short,
  149962. blocksize_16_long,
  149963. _psy_tone_masteratt_16,
  149964. _psy_tone_0dB,
  149965. _psy_tone_suppress,
  149966. _vp_tonemask_adj_16,
  149967. _vp_tonemask_adj_16,
  149968. _vp_tonemask_adj_16,
  149969. _psy_noiseguards_8,
  149970. _psy_noisebias_16_impulse,
  149971. _psy_noisebias_16_short,
  149972. _psy_noisebias_16_short,
  149973. _psy_noisebias_16,
  149974. _psy_noise_suppress,
  149975. _psy_compand_8,
  149976. _psy_compand_16_mapping,
  149977. _psy_compand_16_mapping,
  149978. {_noise_start_16,_noise_start_16},
  149979. { _noise_part_16, _noise_part_16},
  149980. _noise_thresh_16,
  149981. _psy_ath_floater_16,
  149982. _psy_ath_abs_16,
  149983. _psy_lowpass_16,
  149984. _psy_global_44,
  149985. _global_mapping_16,
  149986. _psy_stereo_modes_16,
  149987. _floor_books,
  149988. _floor,
  149989. _floor_mapping_16_short,
  149990. _floor_mapping_16,
  149991. _mapres_template_16_stereo
  149992. };
  149993. ve_setup_data_template ve_setup_16_uncoupled={
  149994. 3,
  149995. rate_mapping_16_uncoupled,
  149996. quality_mapping_16,
  149997. -1,
  149998. 15000,
  149999. 19000,
  150000. blocksize_16_short,
  150001. blocksize_16_long,
  150002. _psy_tone_masteratt_16,
  150003. _psy_tone_0dB,
  150004. _psy_tone_suppress,
  150005. _vp_tonemask_adj_16,
  150006. _vp_tonemask_adj_16,
  150007. _vp_tonemask_adj_16,
  150008. _psy_noiseguards_8,
  150009. _psy_noisebias_16_impulse,
  150010. _psy_noisebias_16_short,
  150011. _psy_noisebias_16_short,
  150012. _psy_noisebias_16,
  150013. _psy_noise_suppress,
  150014. _psy_compand_8,
  150015. _psy_compand_16_mapping,
  150016. _psy_compand_16_mapping,
  150017. {_noise_start_16,_noise_start_16},
  150018. { _noise_part_16, _noise_part_16},
  150019. _noise_thresh_16,
  150020. _psy_ath_floater_16,
  150021. _psy_ath_abs_16,
  150022. _psy_lowpass_16,
  150023. _psy_global_44,
  150024. _global_mapping_16,
  150025. _psy_stereo_modes_16,
  150026. _floor_books,
  150027. _floor,
  150028. _floor_mapping_16_short,
  150029. _floor_mapping_16,
  150030. _mapres_template_16_uncoupled
  150031. };
  150032. /********* End of inlined file: setup_16.h *********/
  150033. /********* Start of inlined file: setup_22.h *********/
  150034. static double rate_mapping_22[4]={
  150035. 15000.,20000.,44000.,86000.
  150036. };
  150037. static double rate_mapping_22_uncoupled[4]={
  150038. 16000.,28000.,50000.,90000.
  150039. };
  150040. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  150041. ve_setup_data_template ve_setup_22_stereo={
  150042. 3,
  150043. rate_mapping_22,
  150044. quality_mapping_16,
  150045. 2,
  150046. 19000,
  150047. 26000,
  150048. blocksize_16_short,
  150049. blocksize_16_long,
  150050. _psy_tone_masteratt_16,
  150051. _psy_tone_0dB,
  150052. _psy_tone_suppress,
  150053. _vp_tonemask_adj_16,
  150054. _vp_tonemask_adj_16,
  150055. _vp_tonemask_adj_16,
  150056. _psy_noiseguards_8,
  150057. _psy_noisebias_16_impulse,
  150058. _psy_noisebias_16_short,
  150059. _psy_noisebias_16_short,
  150060. _psy_noisebias_16,
  150061. _psy_noise_suppress,
  150062. _psy_compand_8,
  150063. _psy_compand_8_mapping,
  150064. _psy_compand_8_mapping,
  150065. {_noise_start_16,_noise_start_16},
  150066. { _noise_part_16, _noise_part_16},
  150067. _noise_thresh_16,
  150068. _psy_ath_floater_16,
  150069. _psy_ath_abs_16,
  150070. _psy_lowpass_22,
  150071. _psy_global_44,
  150072. _global_mapping_16,
  150073. _psy_stereo_modes_16,
  150074. _floor_books,
  150075. _floor,
  150076. _floor_mapping_16_short,
  150077. _floor_mapping_16,
  150078. _mapres_template_16_stereo
  150079. };
  150080. ve_setup_data_template ve_setup_22_uncoupled={
  150081. 3,
  150082. rate_mapping_22_uncoupled,
  150083. quality_mapping_16,
  150084. -1,
  150085. 19000,
  150086. 26000,
  150087. blocksize_16_short,
  150088. blocksize_16_long,
  150089. _psy_tone_masteratt_16,
  150090. _psy_tone_0dB,
  150091. _psy_tone_suppress,
  150092. _vp_tonemask_adj_16,
  150093. _vp_tonemask_adj_16,
  150094. _vp_tonemask_adj_16,
  150095. _psy_noiseguards_8,
  150096. _psy_noisebias_16_impulse,
  150097. _psy_noisebias_16_short,
  150098. _psy_noisebias_16_short,
  150099. _psy_noisebias_16,
  150100. _psy_noise_suppress,
  150101. _psy_compand_8,
  150102. _psy_compand_8_mapping,
  150103. _psy_compand_8_mapping,
  150104. {_noise_start_16,_noise_start_16},
  150105. { _noise_part_16, _noise_part_16},
  150106. _noise_thresh_16,
  150107. _psy_ath_floater_16,
  150108. _psy_ath_abs_16,
  150109. _psy_lowpass_22,
  150110. _psy_global_44,
  150111. _global_mapping_16,
  150112. _psy_stereo_modes_16,
  150113. _floor_books,
  150114. _floor,
  150115. _floor_mapping_16_short,
  150116. _floor_mapping_16,
  150117. _mapres_template_16_uncoupled
  150118. };
  150119. /********* End of inlined file: setup_22.h *********/
  150120. /********* Start of inlined file: setup_X.h *********/
  150121. static double rate_mapping_X[12]={
  150122. -1.,-1.,-1.,-1.,-1.,-1.,
  150123. -1.,-1.,-1.,-1.,-1.,-1.
  150124. };
  150125. ve_setup_data_template ve_setup_X_stereo={
  150126. 11,
  150127. rate_mapping_X,
  150128. quality_mapping_44,
  150129. 2,
  150130. 50000,
  150131. 200000,
  150132. blocksize_short_44,
  150133. blocksize_long_44,
  150134. _psy_tone_masteratt_44,
  150135. _psy_tone_0dB,
  150136. _psy_tone_suppress,
  150137. _vp_tonemask_adj_otherblock,
  150138. _vp_tonemask_adj_longblock,
  150139. _vp_tonemask_adj_otherblock,
  150140. _psy_noiseguards_44,
  150141. _psy_noisebias_impulse,
  150142. _psy_noisebias_padding,
  150143. _psy_noisebias_trans,
  150144. _psy_noisebias_long,
  150145. _psy_noise_suppress,
  150146. _psy_compand_44,
  150147. _psy_compand_short_mapping,
  150148. _psy_compand_long_mapping,
  150149. {_noise_start_short_44,_noise_start_long_44},
  150150. {_noise_part_short_44,_noise_part_long_44},
  150151. _noise_thresh_44,
  150152. _psy_ath_floater,
  150153. _psy_ath_abs,
  150154. _psy_lowpass_44,
  150155. _psy_global_44,
  150156. _global_mapping_44,
  150157. _psy_stereo_modes_44,
  150158. _floor_books,
  150159. _floor,
  150160. _floor_short_mapping_44,
  150161. _floor_long_mapping_44,
  150162. _mapres_template_44_stereo
  150163. };
  150164. ve_setup_data_template ve_setup_X_uncoupled={
  150165. 11,
  150166. rate_mapping_X,
  150167. quality_mapping_44,
  150168. -1,
  150169. 50000,
  150170. 200000,
  150171. blocksize_short_44,
  150172. blocksize_long_44,
  150173. _psy_tone_masteratt_44,
  150174. _psy_tone_0dB,
  150175. _psy_tone_suppress,
  150176. _vp_tonemask_adj_otherblock,
  150177. _vp_tonemask_adj_longblock,
  150178. _vp_tonemask_adj_otherblock,
  150179. _psy_noiseguards_44,
  150180. _psy_noisebias_impulse,
  150181. _psy_noisebias_padding,
  150182. _psy_noisebias_trans,
  150183. _psy_noisebias_long,
  150184. _psy_noise_suppress,
  150185. _psy_compand_44,
  150186. _psy_compand_short_mapping,
  150187. _psy_compand_long_mapping,
  150188. {_noise_start_short_44,_noise_start_long_44},
  150189. {_noise_part_short_44,_noise_part_long_44},
  150190. _noise_thresh_44,
  150191. _psy_ath_floater,
  150192. _psy_ath_abs,
  150193. _psy_lowpass_44,
  150194. _psy_global_44,
  150195. _global_mapping_44,
  150196. NULL,
  150197. _floor_books,
  150198. _floor,
  150199. _floor_short_mapping_44,
  150200. _floor_long_mapping_44,
  150201. _mapres_template_44_uncoupled
  150202. };
  150203. ve_setup_data_template ve_setup_XX_stereo={
  150204. 2,
  150205. rate_mapping_X,
  150206. quality_mapping_8,
  150207. 2,
  150208. 0,
  150209. 8000,
  150210. blocksize_8,
  150211. blocksize_8,
  150212. _psy_tone_masteratt_8,
  150213. _psy_tone_0dB,
  150214. _psy_tone_suppress,
  150215. _vp_tonemask_adj_8,
  150216. NULL,
  150217. _vp_tonemask_adj_8,
  150218. _psy_noiseguards_8,
  150219. _psy_noisebias_8,
  150220. _psy_noisebias_8,
  150221. NULL,
  150222. NULL,
  150223. _psy_noise_suppress,
  150224. _psy_compand_8,
  150225. _psy_compand_8_mapping,
  150226. NULL,
  150227. {_noise_start_8,_noise_start_8},
  150228. {_noise_part_8,_noise_part_8},
  150229. _noise_thresh_5only,
  150230. _psy_ath_floater_8,
  150231. _psy_ath_abs_8,
  150232. _psy_lowpass_8,
  150233. _psy_global_44,
  150234. _global_mapping_8,
  150235. _psy_stereo_modes_8,
  150236. _floor_books,
  150237. _floor,
  150238. _floor_mapping_8,
  150239. NULL,
  150240. _mapres_template_8_stereo
  150241. };
  150242. ve_setup_data_template ve_setup_XX_uncoupled={
  150243. 2,
  150244. rate_mapping_X,
  150245. quality_mapping_8,
  150246. -1,
  150247. 0,
  150248. 8000,
  150249. blocksize_8,
  150250. blocksize_8,
  150251. _psy_tone_masteratt_8,
  150252. _psy_tone_0dB,
  150253. _psy_tone_suppress,
  150254. _vp_tonemask_adj_8,
  150255. NULL,
  150256. _vp_tonemask_adj_8,
  150257. _psy_noiseguards_8,
  150258. _psy_noisebias_8,
  150259. _psy_noisebias_8,
  150260. NULL,
  150261. NULL,
  150262. _psy_noise_suppress,
  150263. _psy_compand_8,
  150264. _psy_compand_8_mapping,
  150265. NULL,
  150266. {_noise_start_8,_noise_start_8},
  150267. {_noise_part_8,_noise_part_8},
  150268. _noise_thresh_5only,
  150269. _psy_ath_floater_8,
  150270. _psy_ath_abs_8,
  150271. _psy_lowpass_8,
  150272. _psy_global_44,
  150273. _global_mapping_8,
  150274. _psy_stereo_modes_8,
  150275. _floor_books,
  150276. _floor,
  150277. _floor_mapping_8,
  150278. NULL,
  150279. _mapres_template_8_uncoupled
  150280. };
  150281. /********* End of inlined file: setup_X.h *********/
  150282. static ve_setup_data_template *setup_list[]={
  150283. &ve_setup_44_stereo,
  150284. &ve_setup_44_uncoupled,
  150285. &ve_setup_32_stereo,
  150286. &ve_setup_32_uncoupled,
  150287. &ve_setup_22_stereo,
  150288. &ve_setup_22_uncoupled,
  150289. &ve_setup_16_stereo,
  150290. &ve_setup_16_uncoupled,
  150291. &ve_setup_11_stereo,
  150292. &ve_setup_11_uncoupled,
  150293. &ve_setup_8_stereo,
  150294. &ve_setup_8_uncoupled,
  150295. &ve_setup_X_stereo,
  150296. &ve_setup_X_uncoupled,
  150297. &ve_setup_XX_stereo,
  150298. &ve_setup_XX_uncoupled,
  150299. 0
  150300. };
  150301. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  150302. if(vi && vi->codec_setup){
  150303. vi->version=0;
  150304. vi->channels=ch;
  150305. vi->rate=rate;
  150306. return(0);
  150307. }
  150308. return(OV_EINVAL);
  150309. }
  150310. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  150311. static_codebook ***books,
  150312. vorbis_info_floor1 *in,
  150313. int *x){
  150314. int i,k,is=s;
  150315. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  150316. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150317. memcpy(f,in+x[is],sizeof(*f));
  150318. /* fill in the lowpass field, even if it's temporary */
  150319. f->n=ci->blocksizes[block]>>1;
  150320. /* books */
  150321. {
  150322. int partitions=f->partitions;
  150323. int maxclass=-1;
  150324. int maxbook=-1;
  150325. for(i=0;i<partitions;i++)
  150326. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  150327. for(i=0;i<=maxclass;i++){
  150328. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  150329. f->class_book[i]+=ci->books;
  150330. for(k=0;k<(1<<f->class_subs[i]);k++){
  150331. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  150332. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  150333. }
  150334. }
  150335. for(i=0;i<=maxbook;i++)
  150336. ci->book_param[ci->books++]=books[x[is]][i];
  150337. }
  150338. /* for now, we're only using floor 1 */
  150339. ci->floor_type[ci->floors]=1;
  150340. ci->floor_param[ci->floors]=f;
  150341. ci->floors++;
  150342. return;
  150343. }
  150344. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  150345. vorbis_info_psy_global *in,
  150346. double *x){
  150347. int i,is=s;
  150348. double ds=s-is;
  150349. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150350. vorbis_info_psy_global *g=&ci->psy_g_param;
  150351. memcpy(g,in+(int)x[is],sizeof(*g));
  150352. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150353. is=(int)ds;
  150354. ds-=is;
  150355. if(ds==0 && is>0){
  150356. is--;
  150357. ds=1.;
  150358. }
  150359. /* interpolate the trigger threshholds */
  150360. for(i=0;i<4;i++){
  150361. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  150362. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  150363. }
  150364. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  150365. return;
  150366. }
  150367. static void vorbis_encode_global_stereo(vorbis_info *vi,
  150368. highlevel_encode_setup *hi,
  150369. adj_stereo *p){
  150370. float s=hi->stereo_point_setting;
  150371. int i,is=s;
  150372. double ds=s-is;
  150373. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150374. vorbis_info_psy_global *g=&ci->psy_g_param;
  150375. if(p){
  150376. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  150377. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  150378. if(hi->managed){
  150379. /* interpolate the kHz threshholds */
  150380. for(i=0;i<PACKETBLOBS;i++){
  150381. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  150382. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150383. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150384. g->coupling_pkHz[i]=kHz;
  150385. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  150386. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150387. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150388. }
  150389. }else{
  150390. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  150391. for(i=0;i<PACKETBLOBS;i++){
  150392. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150393. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150394. g->coupling_pkHz[i]=kHz;
  150395. }
  150396. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  150397. for(i=0;i<PACKETBLOBS;i++){
  150398. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150399. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150400. }
  150401. }
  150402. }else{
  150403. for(i=0;i<PACKETBLOBS;i++){
  150404. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  150405. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  150406. }
  150407. }
  150408. return;
  150409. }
  150410. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  150411. int *nn_start,
  150412. int *nn_partition,
  150413. double *nn_thresh,
  150414. int block){
  150415. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150416. vorbis_info_psy *p=ci->psy_param[block];
  150417. highlevel_encode_setup *hi=&ci->hi;
  150418. int is=s;
  150419. if(block>=ci->psys)
  150420. ci->psys=block+1;
  150421. if(!p){
  150422. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  150423. ci->psy_param[block]=p;
  150424. }
  150425. memcpy(p,&_psy_info_template,sizeof(*p));
  150426. p->blockflag=block>>1;
  150427. if(hi->noise_normalize_p){
  150428. p->normal_channel_p=1;
  150429. p->normal_point_p=1;
  150430. p->normal_start=nn_start[is];
  150431. p->normal_partition=nn_partition[is];
  150432. p->normal_thresh=nn_thresh[is];
  150433. }
  150434. return;
  150435. }
  150436. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  150437. att3 *att,
  150438. int *max,
  150439. vp_adjblock *in){
  150440. int i,is=s;
  150441. double ds=s-is;
  150442. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150443. vorbis_info_psy *p=ci->psy_param[block];
  150444. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  150445. filling the values in here */
  150446. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  150447. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  150448. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  150449. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  150450. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  150451. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  150452. for(i=0;i<P_BANDS;i++)
  150453. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  150454. return;
  150455. }
  150456. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  150457. compandblock *in, double *x){
  150458. int i,is=s;
  150459. double ds=s-is;
  150460. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150461. vorbis_info_psy *p=ci->psy_param[block];
  150462. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150463. is=(int)ds;
  150464. ds-=is;
  150465. if(ds==0 && is>0){
  150466. is--;
  150467. ds=1.;
  150468. }
  150469. /* interpolate the compander settings */
  150470. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  150471. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  150472. return;
  150473. }
  150474. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  150475. int *suppress){
  150476. int is=s;
  150477. double ds=s-is;
  150478. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150479. vorbis_info_psy *p=ci->psy_param[block];
  150480. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150481. return;
  150482. }
  150483. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  150484. int *suppress,
  150485. noise3 *in,
  150486. noiseguard *guard,
  150487. double userbias){
  150488. int i,is=s,j;
  150489. double ds=s-is;
  150490. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150491. vorbis_info_psy *p=ci->psy_param[block];
  150492. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150493. p->noisewindowlomin=guard[block].lo;
  150494. p->noisewindowhimin=guard[block].hi;
  150495. p->noisewindowfixed=guard[block].fixed;
  150496. for(j=0;j<P_NOISECURVES;j++)
  150497. for(i=0;i<P_BANDS;i++)
  150498. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  150499. /* impulse blocks may take a user specified bias to boost the
  150500. nominal/high noise encoding depth */
  150501. for(j=0;j<P_NOISECURVES;j++){
  150502. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  150503. for(i=0;i<P_BANDS;i++){
  150504. p->noiseoff[j][i]+=userbias;
  150505. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  150506. }
  150507. }
  150508. return;
  150509. }
  150510. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  150511. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150512. vorbis_info_psy *p=ci->psy_param[block];
  150513. p->ath_adjatt=ci->hi.ath_floating_dB;
  150514. p->ath_maxatt=ci->hi.ath_absolute_dB;
  150515. return;
  150516. }
  150517. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  150518. int i;
  150519. for(i=0;i<ci->books;i++)
  150520. if(ci->book_param[i]==book)return(i);
  150521. return(ci->books++);
  150522. }
  150523. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  150524. int *shortb,int *longb){
  150525. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150526. int is=s;
  150527. int blockshort=shortb[is];
  150528. int blocklong=longb[is];
  150529. ci->blocksizes[0]=blockshort;
  150530. ci->blocksizes[1]=blocklong;
  150531. }
  150532. static void vorbis_encode_residue_setup(vorbis_info *vi,
  150533. int number, int block,
  150534. vorbis_residue_template *res){
  150535. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150536. int i,n;
  150537. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  150538. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  150539. memcpy(r,res->res,sizeof(*r));
  150540. if(ci->residues<=number)ci->residues=number+1;
  150541. switch(ci->blocksizes[block]){
  150542. case 64:case 128:case 256:
  150543. r->grouping=16;
  150544. break;
  150545. default:
  150546. r->grouping=32;
  150547. break;
  150548. }
  150549. ci->residue_type[number]=res->res_type;
  150550. /* to be adjusted by lowpass/pointlimit later */
  150551. n=r->end=ci->blocksizes[block]>>1;
  150552. if(res->res_type==2)
  150553. n=r->end*=vi->channels;
  150554. /* fill in all the books */
  150555. {
  150556. int booklist=0,k;
  150557. if(ci->hi.managed){
  150558. for(i=0;i<r->partitions;i++)
  150559. for(k=0;k<3;k++)
  150560. if(res->books_base_managed->books[i][k])
  150561. r->secondstages[i]|=(1<<k);
  150562. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  150563. ci->book_param[r->groupbook]=res->book_aux_managed;
  150564. for(i=0;i<r->partitions;i++){
  150565. for(k=0;k<3;k++){
  150566. if(res->books_base_managed->books[i][k]){
  150567. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  150568. r->booklist[booklist++]=bookid;
  150569. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  150570. }
  150571. }
  150572. }
  150573. }else{
  150574. for(i=0;i<r->partitions;i++)
  150575. for(k=0;k<3;k++)
  150576. if(res->books_base->books[i][k])
  150577. r->secondstages[i]|=(1<<k);
  150578. r->groupbook=book_dup_or_new(ci,res->book_aux);
  150579. ci->book_param[r->groupbook]=res->book_aux;
  150580. for(i=0;i<r->partitions;i++){
  150581. for(k=0;k<3;k++){
  150582. if(res->books_base->books[i][k]){
  150583. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  150584. r->booklist[booklist++]=bookid;
  150585. ci->book_param[bookid]=res->books_base->books[i][k];
  150586. }
  150587. }
  150588. }
  150589. }
  150590. }
  150591. /* lowpass setup/pointlimit */
  150592. {
  150593. double freq=ci->hi.lowpass_kHz*1000.;
  150594. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  150595. double nyq=vi->rate/2.;
  150596. long blocksize=ci->blocksizes[block]>>1;
  150597. /* lowpass needs to be set in the floor and the residue. */
  150598. if(freq>nyq)freq=nyq;
  150599. /* in the floor, the granularity can be very fine; it doesn't alter
  150600. the encoding structure, only the samples used to fit the floor
  150601. approximation */
  150602. f->n=freq/nyq*blocksize;
  150603. /* this res may by limited by the maximum pointlimit of the mode,
  150604. not the lowpass. the floor is always lowpass limited. */
  150605. if(res->limit_type){
  150606. if(ci->hi.managed)
  150607. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  150608. else
  150609. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  150610. if(freq>nyq)freq=nyq;
  150611. }
  150612. /* in the residue, we're constrained, physically, by partition
  150613. boundaries. We still lowpass 'wherever', but we have to round up
  150614. here to next boundary, or the vorbis spec will round it *down* to
  150615. previous boundary in encode/decode */
  150616. if(ci->residue_type[block]==2)
  150617. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  150618. r->grouping;
  150619. else
  150620. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  150621. r->grouping;
  150622. }
  150623. }
  150624. /* we assume two maps in this encoder */
  150625. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  150626. vorbis_mapping_template *maps){
  150627. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150628. int i,j,is=s,modes=2;
  150629. vorbis_info_mapping0 *map=maps[is].map;
  150630. vorbis_info_mode *mode=_mode_template;
  150631. vorbis_residue_template *res=maps[is].res;
  150632. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  150633. for(i=0;i<modes;i++){
  150634. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  150635. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  150636. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  150637. if(i>=ci->modes)ci->modes=i+1;
  150638. ci->map_type[i]=0;
  150639. memcpy(ci->map_param[i],map+i,sizeof(*map));
  150640. if(i>=ci->maps)ci->maps=i+1;
  150641. for(j=0;j<map[i].submaps;j++)
  150642. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  150643. ,res+map[i].residuesubmap[j]);
  150644. }
  150645. }
  150646. static double setting_to_approx_bitrate(vorbis_info *vi){
  150647. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150648. highlevel_encode_setup *hi=&ci->hi;
  150649. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  150650. int is=hi->base_setting;
  150651. double ds=hi->base_setting-is;
  150652. int ch=vi->channels;
  150653. double *r=setup->rate_mapping;
  150654. if(r==NULL)
  150655. return(-1);
  150656. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  150657. }
  150658. static void get_setup_template(vorbis_info *vi,
  150659. long ch,long srate,
  150660. double req,int q_or_bitrate){
  150661. int i=0,j;
  150662. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150663. highlevel_encode_setup *hi=&ci->hi;
  150664. if(q_or_bitrate)req/=ch;
  150665. while(setup_list[i]){
  150666. if(setup_list[i]->coupling_restriction==-1 ||
  150667. setup_list[i]->coupling_restriction==ch){
  150668. if(srate>=setup_list[i]->samplerate_min_restriction &&
  150669. srate<=setup_list[i]->samplerate_max_restriction){
  150670. int mappings=setup_list[i]->mappings;
  150671. double *map=(q_or_bitrate?
  150672. setup_list[i]->rate_mapping:
  150673. setup_list[i]->quality_mapping);
  150674. /* the template matches. Does the requested quality mode
  150675. fall within this template's modes? */
  150676. if(req<map[0]){++i;continue;}
  150677. if(req>map[setup_list[i]->mappings]){++i;continue;}
  150678. for(j=0;j<mappings;j++)
  150679. if(req>=map[j] && req<map[j+1])break;
  150680. /* an all-points match */
  150681. hi->setup=setup_list[i];
  150682. if(j==mappings)
  150683. hi->base_setting=j-.001;
  150684. else{
  150685. float low=map[j];
  150686. float high=map[j+1];
  150687. float del=(req-low)/(high-low);
  150688. hi->base_setting=j+del;
  150689. }
  150690. return;
  150691. }
  150692. }
  150693. i++;
  150694. }
  150695. hi->setup=NULL;
  150696. }
  150697. /* encoders will need to use vorbis_info_init beforehand and call
  150698. vorbis_info clear when all done */
  150699. /* two interfaces; this, more detailed one, and later a convenience
  150700. layer on top */
  150701. /* the final setup call */
  150702. int vorbis_encode_setup_init(vorbis_info *vi){
  150703. int i0=0,singleblock=0;
  150704. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150705. ve_setup_data_template *setup=NULL;
  150706. highlevel_encode_setup *hi=&ci->hi;
  150707. if(ci==NULL)return(OV_EINVAL);
  150708. if(!hi->impulse_block_p)i0=1;
  150709. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  150710. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  150711. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  150712. /* again, bound this to avoid the app shooting itself int he foot
  150713. too badly */
  150714. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  150715. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  150716. /* get the appropriate setup template; matches the fetch in previous
  150717. stages */
  150718. setup=(ve_setup_data_template *)hi->setup;
  150719. if(setup==NULL)return(OV_EINVAL);
  150720. hi->set_in_stone=1;
  150721. /* choose block sizes from configured sizes as well as paying
  150722. attention to long_block_p and short_block_p. If the configured
  150723. short and long blocks are the same length, we set long_block_p
  150724. and unset short_block_p */
  150725. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  150726. setup->blocksize_short,
  150727. setup->blocksize_long);
  150728. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  150729. /* floor setup; choose proper floor params. Allocated on the floor
  150730. stack in order; if we alloc only long floor, it's 0 */
  150731. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  150732. setup->floor_books,
  150733. setup->floor_params,
  150734. setup->floor_short_mapping);
  150735. if(!singleblock)
  150736. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  150737. setup->floor_books,
  150738. setup->floor_params,
  150739. setup->floor_long_mapping);
  150740. /* setup of [mostly] short block detection and stereo*/
  150741. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  150742. setup->global_params,
  150743. setup->global_mapping);
  150744. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  150745. /* basic psych setup and noise normalization */
  150746. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150747. setup->psy_noise_normal_start[0],
  150748. setup->psy_noise_normal_partition[0],
  150749. setup->psy_noise_normal_thresh,
  150750. 0);
  150751. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150752. setup->psy_noise_normal_start[0],
  150753. setup->psy_noise_normal_partition[0],
  150754. setup->psy_noise_normal_thresh,
  150755. 1);
  150756. if(!singleblock){
  150757. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150758. setup->psy_noise_normal_start[1],
  150759. setup->psy_noise_normal_partition[1],
  150760. setup->psy_noise_normal_thresh,
  150761. 2);
  150762. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150763. setup->psy_noise_normal_start[1],
  150764. setup->psy_noise_normal_partition[1],
  150765. setup->psy_noise_normal_thresh,
  150766. 3);
  150767. }
  150768. /* tone masking setup */
  150769. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  150770. setup->psy_tone_masteratt,
  150771. setup->psy_tone_0dB,
  150772. setup->psy_tone_adj_impulse);
  150773. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  150774. setup->psy_tone_masteratt,
  150775. setup->psy_tone_0dB,
  150776. setup->psy_tone_adj_other);
  150777. if(!singleblock){
  150778. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  150779. setup->psy_tone_masteratt,
  150780. setup->psy_tone_0dB,
  150781. setup->psy_tone_adj_other);
  150782. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  150783. setup->psy_tone_masteratt,
  150784. setup->psy_tone_0dB,
  150785. setup->psy_tone_adj_long);
  150786. }
  150787. /* noise companding setup */
  150788. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  150789. setup->psy_noise_compand,
  150790. setup->psy_noise_compand_short_mapping);
  150791. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  150792. setup->psy_noise_compand,
  150793. setup->psy_noise_compand_short_mapping);
  150794. if(!singleblock){
  150795. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  150796. setup->psy_noise_compand,
  150797. setup->psy_noise_compand_long_mapping);
  150798. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  150799. setup->psy_noise_compand,
  150800. setup->psy_noise_compand_long_mapping);
  150801. }
  150802. /* peak guarding setup */
  150803. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  150804. setup->psy_tone_dBsuppress);
  150805. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  150806. setup->psy_tone_dBsuppress);
  150807. if(!singleblock){
  150808. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  150809. setup->psy_tone_dBsuppress);
  150810. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  150811. setup->psy_tone_dBsuppress);
  150812. }
  150813. /* noise bias setup */
  150814. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  150815. setup->psy_noise_dBsuppress,
  150816. setup->psy_noise_bias_impulse,
  150817. setup->psy_noiseguards,
  150818. (i0==0?hi->impulse_noisetune:0.));
  150819. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  150820. setup->psy_noise_dBsuppress,
  150821. setup->psy_noise_bias_padding,
  150822. setup->psy_noiseguards,0.);
  150823. if(!singleblock){
  150824. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  150825. setup->psy_noise_dBsuppress,
  150826. setup->psy_noise_bias_trans,
  150827. setup->psy_noiseguards,0.);
  150828. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  150829. setup->psy_noise_dBsuppress,
  150830. setup->psy_noise_bias_long,
  150831. setup->psy_noiseguards,0.);
  150832. }
  150833. vorbis_encode_ath_setup(vi,0);
  150834. vorbis_encode_ath_setup(vi,1);
  150835. if(!singleblock){
  150836. vorbis_encode_ath_setup(vi,2);
  150837. vorbis_encode_ath_setup(vi,3);
  150838. }
  150839. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  150840. /* set bitrate readonlies and management */
  150841. if(hi->bitrate_av>0)
  150842. vi->bitrate_nominal=hi->bitrate_av;
  150843. else{
  150844. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  150845. }
  150846. vi->bitrate_lower=hi->bitrate_min;
  150847. vi->bitrate_upper=hi->bitrate_max;
  150848. if(hi->bitrate_av)
  150849. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  150850. else
  150851. vi->bitrate_window=0.;
  150852. if(hi->managed){
  150853. ci->bi.avg_rate=hi->bitrate_av;
  150854. ci->bi.min_rate=hi->bitrate_min;
  150855. ci->bi.max_rate=hi->bitrate_max;
  150856. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  150857. ci->bi.reservoir_bias=
  150858. hi->bitrate_reservoir_bias;
  150859. ci->bi.slew_damp=hi->bitrate_av_damp;
  150860. }
  150861. return(0);
  150862. }
  150863. static int vorbis_encode_setup_setting(vorbis_info *vi,
  150864. long channels,
  150865. long rate){
  150866. int ret=0,i,is;
  150867. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150868. highlevel_encode_setup *hi=&ci->hi;
  150869. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  150870. double ds;
  150871. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  150872. if(ret)return(ret);
  150873. is=hi->base_setting;
  150874. ds=hi->base_setting-is;
  150875. hi->short_setting=hi->base_setting;
  150876. hi->long_setting=hi->base_setting;
  150877. hi->managed=0;
  150878. hi->impulse_block_p=1;
  150879. hi->noise_normalize_p=1;
  150880. hi->stereo_point_setting=hi->base_setting;
  150881. hi->lowpass_kHz=
  150882. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  150883. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  150884. setup->psy_ath_float[is+1]*ds;
  150885. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  150886. setup->psy_ath_abs[is+1]*ds;
  150887. hi->amplitude_track_dBpersec=-6.;
  150888. hi->trigger_setting=hi->base_setting;
  150889. for(i=0;i<4;i++){
  150890. hi->block[i].tone_mask_setting=hi->base_setting;
  150891. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  150892. hi->block[i].noise_bias_setting=hi->base_setting;
  150893. hi->block[i].noise_compand_setting=hi->base_setting;
  150894. }
  150895. return(ret);
  150896. }
  150897. int vorbis_encode_setup_vbr(vorbis_info *vi,
  150898. long channels,
  150899. long rate,
  150900. float quality){
  150901. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150902. highlevel_encode_setup *hi=&ci->hi;
  150903. quality+=.0000001;
  150904. if(quality>=1.)quality=.9999;
  150905. get_setup_template(vi,channels,rate,quality,0);
  150906. if(!hi->setup)return OV_EIMPL;
  150907. return vorbis_encode_setup_setting(vi,channels,rate);
  150908. }
  150909. int vorbis_encode_init_vbr(vorbis_info *vi,
  150910. long channels,
  150911. long rate,
  150912. float base_quality /* 0. to 1. */
  150913. ){
  150914. int ret=0;
  150915. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  150916. if(ret){
  150917. vorbis_info_clear(vi);
  150918. return ret;
  150919. }
  150920. ret=vorbis_encode_setup_init(vi);
  150921. if(ret)
  150922. vorbis_info_clear(vi);
  150923. return(ret);
  150924. }
  150925. int vorbis_encode_setup_managed(vorbis_info *vi,
  150926. long channels,
  150927. long rate,
  150928. long max_bitrate,
  150929. long nominal_bitrate,
  150930. long min_bitrate){
  150931. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150932. highlevel_encode_setup *hi=&ci->hi;
  150933. double tnominal=nominal_bitrate;
  150934. int ret=0;
  150935. if(nominal_bitrate<=0.){
  150936. if(max_bitrate>0.){
  150937. if(min_bitrate>0.)
  150938. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  150939. else
  150940. nominal_bitrate=max_bitrate*.875;
  150941. }else{
  150942. if(min_bitrate>0.){
  150943. nominal_bitrate=min_bitrate;
  150944. }else{
  150945. return(OV_EINVAL);
  150946. }
  150947. }
  150948. }
  150949. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  150950. if(!hi->setup)return OV_EIMPL;
  150951. ret=vorbis_encode_setup_setting(vi,channels,rate);
  150952. if(ret){
  150953. vorbis_info_clear(vi);
  150954. return ret;
  150955. }
  150956. /* initialize management with sane defaults */
  150957. hi->managed=1;
  150958. hi->bitrate_min=min_bitrate;
  150959. hi->bitrate_max=max_bitrate;
  150960. hi->bitrate_av=tnominal;
  150961. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  150962. hi->bitrate_reservoir=nominal_bitrate*2;
  150963. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  150964. return(ret);
  150965. }
  150966. int vorbis_encode_init(vorbis_info *vi,
  150967. long channels,
  150968. long rate,
  150969. long max_bitrate,
  150970. long nominal_bitrate,
  150971. long min_bitrate){
  150972. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  150973. max_bitrate,
  150974. nominal_bitrate,
  150975. min_bitrate);
  150976. if(ret){
  150977. vorbis_info_clear(vi);
  150978. return(ret);
  150979. }
  150980. ret=vorbis_encode_setup_init(vi);
  150981. if(ret)
  150982. vorbis_info_clear(vi);
  150983. return(ret);
  150984. }
  150985. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  150986. if(vi){
  150987. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150988. highlevel_encode_setup *hi=&ci->hi;
  150989. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  150990. if(setp && hi->set_in_stone)return(OV_EINVAL);
  150991. switch(number){
  150992. /* now deprecated *****************/
  150993. case OV_ECTL_RATEMANAGE_GET:
  150994. {
  150995. struct ovectl_ratemanage_arg *ai=
  150996. (struct ovectl_ratemanage_arg *)arg;
  150997. ai->management_active=hi->managed;
  150998. ai->bitrate_hard_window=ai->bitrate_av_window=
  150999. (double)hi->bitrate_reservoir/vi->rate;
  151000. ai->bitrate_av_window_center=1.;
  151001. ai->bitrate_hard_min=hi->bitrate_min;
  151002. ai->bitrate_hard_max=hi->bitrate_max;
  151003. ai->bitrate_av_lo=hi->bitrate_av;
  151004. ai->bitrate_av_hi=hi->bitrate_av;
  151005. }
  151006. return(0);
  151007. /* now deprecated *****************/
  151008. case OV_ECTL_RATEMANAGE_SET:
  151009. {
  151010. struct ovectl_ratemanage_arg *ai=
  151011. (struct ovectl_ratemanage_arg *)arg;
  151012. if(ai==NULL){
  151013. hi->managed=0;
  151014. }else{
  151015. hi->managed=ai->management_active;
  151016. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  151017. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  151018. }
  151019. }
  151020. return 0;
  151021. /* now deprecated *****************/
  151022. case OV_ECTL_RATEMANAGE_AVG:
  151023. {
  151024. struct ovectl_ratemanage_arg *ai=
  151025. (struct ovectl_ratemanage_arg *)arg;
  151026. if(ai==NULL){
  151027. hi->bitrate_av=0;
  151028. }else{
  151029. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  151030. }
  151031. }
  151032. return(0);
  151033. /* now deprecated *****************/
  151034. case OV_ECTL_RATEMANAGE_HARD:
  151035. {
  151036. struct ovectl_ratemanage_arg *ai=
  151037. (struct ovectl_ratemanage_arg *)arg;
  151038. if(ai==NULL){
  151039. hi->bitrate_min=0;
  151040. hi->bitrate_max=0;
  151041. }else{
  151042. hi->bitrate_min=ai->bitrate_hard_min;
  151043. hi->bitrate_max=ai->bitrate_hard_max;
  151044. hi->bitrate_reservoir=ai->bitrate_hard_window*
  151045. (hi->bitrate_max+hi->bitrate_min)*.5;
  151046. }
  151047. if(hi->bitrate_reservoir<128.)
  151048. hi->bitrate_reservoir=128.;
  151049. }
  151050. return(0);
  151051. /* replacement ratemanage interface */
  151052. case OV_ECTL_RATEMANAGE2_GET:
  151053. {
  151054. struct ovectl_ratemanage2_arg *ai=
  151055. (struct ovectl_ratemanage2_arg *)arg;
  151056. if(ai==NULL)return OV_EINVAL;
  151057. ai->management_active=hi->managed;
  151058. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  151059. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  151060. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  151061. ai->bitrate_average_damping=hi->bitrate_av_damp;
  151062. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  151063. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  151064. }
  151065. return (0);
  151066. case OV_ECTL_RATEMANAGE2_SET:
  151067. {
  151068. struct ovectl_ratemanage2_arg *ai=
  151069. (struct ovectl_ratemanage2_arg *)arg;
  151070. if(ai==NULL){
  151071. hi->managed=0;
  151072. }else{
  151073. /* sanity check; only catch invariant violations */
  151074. if(ai->bitrate_limit_min_kbps>0 &&
  151075. ai->bitrate_average_kbps>0 &&
  151076. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  151077. return OV_EINVAL;
  151078. if(ai->bitrate_limit_max_kbps>0 &&
  151079. ai->bitrate_average_kbps>0 &&
  151080. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  151081. return OV_EINVAL;
  151082. if(ai->bitrate_limit_min_kbps>0 &&
  151083. ai->bitrate_limit_max_kbps>0 &&
  151084. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  151085. return OV_EINVAL;
  151086. if(ai->bitrate_average_damping <= 0.)
  151087. return OV_EINVAL;
  151088. if(ai->bitrate_limit_reservoir_bits < 0)
  151089. return OV_EINVAL;
  151090. if(ai->bitrate_limit_reservoir_bias < 0.)
  151091. return OV_EINVAL;
  151092. if(ai->bitrate_limit_reservoir_bias > 1.)
  151093. return OV_EINVAL;
  151094. hi->managed=ai->management_active;
  151095. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  151096. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  151097. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  151098. hi->bitrate_av_damp=ai->bitrate_average_damping;
  151099. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  151100. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  151101. }
  151102. }
  151103. return 0;
  151104. case OV_ECTL_LOWPASS_GET:
  151105. {
  151106. double *farg=(double *)arg;
  151107. *farg=hi->lowpass_kHz;
  151108. }
  151109. return(0);
  151110. case OV_ECTL_LOWPASS_SET:
  151111. {
  151112. double *farg=(double *)arg;
  151113. hi->lowpass_kHz=*farg;
  151114. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  151115. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  151116. }
  151117. return(0);
  151118. case OV_ECTL_IBLOCK_GET:
  151119. {
  151120. double *farg=(double *)arg;
  151121. *farg=hi->impulse_noisetune;
  151122. }
  151123. return(0);
  151124. case OV_ECTL_IBLOCK_SET:
  151125. {
  151126. double *farg=(double *)arg;
  151127. hi->impulse_noisetune=*farg;
  151128. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  151129. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  151130. }
  151131. return(0);
  151132. }
  151133. return(OV_EIMPL);
  151134. }
  151135. return(OV_EINVAL);
  151136. }
  151137. #endif
  151138. /********* End of inlined file: vorbisenc.c *********/
  151139. /********* Start of inlined file: vorbisfile.c *********/
  151140. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151141. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151142. // tasks..
  151143. #if JUCE_MSVC
  151144. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151145. #endif
  151146. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151147. #if JUCE_USE_OGGVORBIS
  151148. #include <stdlib.h>
  151149. #include <stdio.h>
  151150. #include <errno.h>
  151151. #include <string.h>
  151152. #include <math.h>
  151153. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  151154. one logical bitstream arranged end to end (the only form of Ogg
  151155. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  151156. multiplexing] is not allowed in Vorbis) */
  151157. /* A Vorbis file can be played beginning to end (streamed) without
  151158. worrying ahead of time about chaining (see decoder_example.c). If
  151159. we have the whole file, however, and want random access
  151160. (seeking/scrubbing) or desire to know the total length/time of a
  151161. file, we need to account for the possibility of chaining. */
  151162. /* We can handle things a number of ways; we can determine the entire
  151163. bitstream structure right off the bat, or find pieces on demand.
  151164. This example determines and caches structure for the entire
  151165. bitstream, but builds a virtual decoder on the fly when moving
  151166. between links in the chain. */
  151167. /* There are also different ways to implement seeking. Enough
  151168. information exists in an Ogg bitstream to seek to
  151169. sample-granularity positions in the output. Or, one can seek by
  151170. picking some portion of the stream roughly in the desired area if
  151171. we only want coarse navigation through the stream. */
  151172. /*************************************************************************
  151173. * Many, many internal helpers. The intention is not to be confusing;
  151174. * rampant duplication and monolithic function implementation would be
  151175. * harder to understand anyway. The high level functions are last. Begin
  151176. * grokking near the end of the file */
  151177. /* read a little more data from the file/pipe into the ogg_sync framer
  151178. */
  151179. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  151180. over 8k gets what they deserve */
  151181. static long _get_data(OggVorbis_File *vf){
  151182. errno=0;
  151183. if(vf->datasource){
  151184. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  151185. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  151186. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  151187. if(bytes==0 && errno)return(-1);
  151188. return(bytes);
  151189. }else
  151190. return(0);
  151191. }
  151192. /* save a tiny smidge of verbosity to make the code more readable */
  151193. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  151194. if(vf->datasource){
  151195. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  151196. vf->offset=offset;
  151197. ogg_sync_reset(&vf->oy);
  151198. }else{
  151199. /* shouldn't happen unless someone writes a broken callback */
  151200. return;
  151201. }
  151202. }
  151203. /* The read/seek functions track absolute position within the stream */
  151204. /* from the head of the stream, get the next page. boundary specifies
  151205. if the function is allowed to fetch more data from the stream (and
  151206. how much) or only use internally buffered data.
  151207. boundary: -1) unbounded search
  151208. 0) read no additional data; use cached only
  151209. n) search for a new page beginning for n bytes
  151210. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  151211. n) found a page at absolute offset n */
  151212. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  151213. ogg_int64_t boundary){
  151214. if(boundary>0)boundary+=vf->offset;
  151215. while(1){
  151216. long more;
  151217. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  151218. more=ogg_sync_pageseek(&vf->oy,og);
  151219. if(more<0){
  151220. /* skipped n bytes */
  151221. vf->offset-=more;
  151222. }else{
  151223. if(more==0){
  151224. /* send more paramedics */
  151225. if(!boundary)return(OV_FALSE);
  151226. {
  151227. long ret=_get_data(vf);
  151228. if(ret==0)return(OV_EOF);
  151229. if(ret<0)return(OV_EREAD);
  151230. }
  151231. }else{
  151232. /* got a page. Return the offset at the page beginning,
  151233. advance the internal offset past the page end */
  151234. ogg_int64_t ret=vf->offset;
  151235. vf->offset+=more;
  151236. return(ret);
  151237. }
  151238. }
  151239. }
  151240. }
  151241. /* find the latest page beginning before the current stream cursor
  151242. position. Much dirtier than the above as Ogg doesn't have any
  151243. backward search linkage. no 'readp' as it will certainly have to
  151244. read. */
  151245. /* returns offset or OV_EREAD, OV_FAULT */
  151246. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  151247. ogg_int64_t begin=vf->offset;
  151248. ogg_int64_t end=begin;
  151249. ogg_int64_t ret;
  151250. ogg_int64_t offset=-1;
  151251. while(offset==-1){
  151252. begin-=CHUNKSIZE;
  151253. if(begin<0)
  151254. begin=0;
  151255. _seek_helper(vf,begin);
  151256. while(vf->offset<end){
  151257. ret=_get_next_page(vf,og,end-vf->offset);
  151258. if(ret==OV_EREAD)return(OV_EREAD);
  151259. if(ret<0){
  151260. break;
  151261. }else{
  151262. offset=ret;
  151263. }
  151264. }
  151265. }
  151266. /* we have the offset. Actually snork and hold the page now */
  151267. _seek_helper(vf,offset);
  151268. ret=_get_next_page(vf,og,CHUNKSIZE);
  151269. if(ret<0)
  151270. /* this shouldn't be possible */
  151271. return(OV_EFAULT);
  151272. return(offset);
  151273. }
  151274. /* finds each bitstream link one at a time using a bisection search
  151275. (has to begin by knowing the offset of the lb's initial page).
  151276. Recurses for each link so it can alloc the link storage after
  151277. finding them all, then unroll and fill the cache at the same time */
  151278. static int _bisect_forward_serialno(OggVorbis_File *vf,
  151279. ogg_int64_t begin,
  151280. ogg_int64_t searched,
  151281. ogg_int64_t end,
  151282. long currentno,
  151283. long m){
  151284. ogg_int64_t endsearched=end;
  151285. ogg_int64_t next=end;
  151286. ogg_page og;
  151287. ogg_int64_t ret;
  151288. /* the below guards against garbage seperating the last and
  151289. first pages of two links. */
  151290. while(searched<endsearched){
  151291. ogg_int64_t bisect;
  151292. if(endsearched-searched<CHUNKSIZE){
  151293. bisect=searched;
  151294. }else{
  151295. bisect=(searched+endsearched)/2;
  151296. }
  151297. _seek_helper(vf,bisect);
  151298. ret=_get_next_page(vf,&og,-1);
  151299. if(ret==OV_EREAD)return(OV_EREAD);
  151300. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  151301. endsearched=bisect;
  151302. if(ret>=0)next=ret;
  151303. }else{
  151304. searched=ret+og.header_len+og.body_len;
  151305. }
  151306. }
  151307. _seek_helper(vf,next);
  151308. ret=_get_next_page(vf,&og,-1);
  151309. if(ret==OV_EREAD)return(OV_EREAD);
  151310. if(searched>=end || ret<0){
  151311. vf->links=m+1;
  151312. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  151313. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  151314. vf->offsets[m+1]=searched;
  151315. }else{
  151316. ret=_bisect_forward_serialno(vf,next,vf->offset,
  151317. end,ogg_page_serialno(&og),m+1);
  151318. if(ret==OV_EREAD)return(OV_EREAD);
  151319. }
  151320. vf->offsets[m]=begin;
  151321. vf->serialnos[m]=currentno;
  151322. return(0);
  151323. }
  151324. /* uses the local ogg_stream storage in vf; this is important for
  151325. non-streaming input sources */
  151326. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  151327. long *serialno,ogg_page *og_ptr){
  151328. ogg_page og;
  151329. ogg_packet op;
  151330. int i,ret;
  151331. if(!og_ptr){
  151332. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  151333. if(llret==OV_EREAD)return(OV_EREAD);
  151334. if(llret<0)return OV_ENOTVORBIS;
  151335. og_ptr=&og;
  151336. }
  151337. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  151338. if(serialno)*serialno=vf->os.serialno;
  151339. vf->ready_state=STREAMSET;
  151340. /* extract the initial header from the first page and verify that the
  151341. Ogg bitstream is in fact Vorbis data */
  151342. vorbis_info_init(vi);
  151343. vorbis_comment_init(vc);
  151344. i=0;
  151345. while(i<3){
  151346. ogg_stream_pagein(&vf->os,og_ptr);
  151347. while(i<3){
  151348. int result=ogg_stream_packetout(&vf->os,&op);
  151349. if(result==0)break;
  151350. if(result==-1){
  151351. ret=OV_EBADHEADER;
  151352. goto bail_header;
  151353. }
  151354. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  151355. goto bail_header;
  151356. }
  151357. i++;
  151358. }
  151359. if(i<3)
  151360. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  151361. ret=OV_EBADHEADER;
  151362. goto bail_header;
  151363. }
  151364. }
  151365. return 0;
  151366. bail_header:
  151367. vorbis_info_clear(vi);
  151368. vorbis_comment_clear(vc);
  151369. vf->ready_state=OPENED;
  151370. return ret;
  151371. }
  151372. /* last step of the OggVorbis_File initialization; get all the
  151373. vorbis_info structs and PCM positions. Only called by the seekable
  151374. initialization (local stream storage is hacked slightly; pay
  151375. attention to how that's done) */
  151376. /* this is void and does not propogate errors up because we want to be
  151377. able to open and use damaged bitstreams as well as we can. Just
  151378. watch out for missing information for links in the OggVorbis_File
  151379. struct */
  151380. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  151381. ogg_page og;
  151382. int i;
  151383. ogg_int64_t ret;
  151384. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  151385. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  151386. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  151387. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  151388. for(i=0;i<vf->links;i++){
  151389. if(i==0){
  151390. /* we already grabbed the initial header earlier. Just set the offset */
  151391. vf->dataoffsets[i]=dataoffset;
  151392. _seek_helper(vf,dataoffset);
  151393. }else{
  151394. /* seek to the location of the initial header */
  151395. _seek_helper(vf,vf->offsets[i]);
  151396. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  151397. vf->dataoffsets[i]=-1;
  151398. }else{
  151399. vf->dataoffsets[i]=vf->offset;
  151400. }
  151401. }
  151402. /* fetch beginning PCM offset */
  151403. if(vf->dataoffsets[i]!=-1){
  151404. ogg_int64_t accumulated=0;
  151405. long lastblock=-1;
  151406. int result;
  151407. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  151408. while(1){
  151409. ogg_packet op;
  151410. ret=_get_next_page(vf,&og,-1);
  151411. if(ret<0)
  151412. /* this should not be possible unless the file is
  151413. truncated/mangled */
  151414. break;
  151415. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  151416. break;
  151417. /* count blocksizes of all frames in the page */
  151418. ogg_stream_pagein(&vf->os,&og);
  151419. while((result=ogg_stream_packetout(&vf->os,&op))){
  151420. if(result>0){ /* ignore holes */
  151421. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  151422. if(lastblock!=-1)
  151423. accumulated+=(lastblock+thisblock)>>2;
  151424. lastblock=thisblock;
  151425. }
  151426. }
  151427. if(ogg_page_granulepos(&og)!=-1){
  151428. /* pcm offset of last packet on the first audio page */
  151429. accumulated= ogg_page_granulepos(&og)-accumulated;
  151430. break;
  151431. }
  151432. }
  151433. /* less than zero? This is a stream with samples trimmed off
  151434. the beginning, a normal occurrence; set the offset to zero */
  151435. if(accumulated<0)accumulated=0;
  151436. vf->pcmlengths[i*2]=accumulated;
  151437. }
  151438. /* get the PCM length of this link. To do this,
  151439. get the last page of the stream */
  151440. {
  151441. ogg_int64_t end=vf->offsets[i+1];
  151442. _seek_helper(vf,end);
  151443. while(1){
  151444. ret=_get_prev_page(vf,&og);
  151445. if(ret<0){
  151446. /* this should not be possible */
  151447. vorbis_info_clear(vf->vi+i);
  151448. vorbis_comment_clear(vf->vc+i);
  151449. break;
  151450. }
  151451. if(ogg_page_granulepos(&og)!=-1){
  151452. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  151453. break;
  151454. }
  151455. vf->offset=ret;
  151456. }
  151457. }
  151458. }
  151459. }
  151460. static int _make_decode_ready(OggVorbis_File *vf){
  151461. if(vf->ready_state>STREAMSET)return 0;
  151462. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  151463. if(vf->seekable){
  151464. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  151465. return OV_EBADLINK;
  151466. }else{
  151467. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  151468. return OV_EBADLINK;
  151469. }
  151470. vorbis_block_init(&vf->vd,&vf->vb);
  151471. vf->ready_state=INITSET;
  151472. vf->bittrack=0.f;
  151473. vf->samptrack=0.f;
  151474. return 0;
  151475. }
  151476. static int _open_seekable2(OggVorbis_File *vf){
  151477. long serialno=vf->current_serialno;
  151478. ogg_int64_t dataoffset=vf->offset, end;
  151479. ogg_page og;
  151480. /* we're partially open and have a first link header state in
  151481. storage in vf */
  151482. /* we can seek, so set out learning all about this file */
  151483. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  151484. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  151485. /* We get the offset for the last page of the physical bitstream.
  151486. Most OggVorbis files will contain a single logical bitstream */
  151487. end=_get_prev_page(vf,&og);
  151488. if(end<0)return(end);
  151489. /* more than one logical bitstream? */
  151490. if(ogg_page_serialno(&og)!=serialno){
  151491. /* Chained bitstream. Bisect-search each logical bitstream
  151492. section. Do so based on serial number only */
  151493. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  151494. }else{
  151495. /* Only one logical bitstream */
  151496. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  151497. }
  151498. /* the initial header memory is referenced by vf after; don't free it */
  151499. _prefetch_all_headers(vf,dataoffset);
  151500. return(ov_raw_seek(vf,0));
  151501. }
  151502. /* clear out the current logical bitstream decoder */
  151503. static void _decode_clear(OggVorbis_File *vf){
  151504. vorbis_dsp_clear(&vf->vd);
  151505. vorbis_block_clear(&vf->vb);
  151506. vf->ready_state=OPENED;
  151507. }
  151508. /* fetch and process a packet. Handles the case where we're at a
  151509. bitstream boundary and dumps the decoding machine. If the decoding
  151510. machine is unloaded, it loads it. It also keeps pcm_offset up to
  151511. date (seek and read both use this. seek uses a special hack with
  151512. readp).
  151513. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  151514. 0) need more data (only if readp==0)
  151515. 1) got a packet
  151516. */
  151517. static int _fetch_and_process_packet(OggVorbis_File *vf,
  151518. ogg_packet *op_in,
  151519. int readp,
  151520. int spanp){
  151521. ogg_page og;
  151522. /* handle one packet. Try to fetch it from current stream state */
  151523. /* extract packets from page */
  151524. while(1){
  151525. /* process a packet if we can. If the machine isn't loaded,
  151526. neither is a page */
  151527. if(vf->ready_state==INITSET){
  151528. while(1) {
  151529. ogg_packet op;
  151530. ogg_packet *op_ptr=(op_in?op_in:&op);
  151531. int result=ogg_stream_packetout(&vf->os,op_ptr);
  151532. ogg_int64_t granulepos;
  151533. op_in=NULL;
  151534. if(result==-1)return(OV_HOLE); /* hole in the data. */
  151535. if(result>0){
  151536. /* got a packet. process it */
  151537. granulepos=op_ptr->granulepos;
  151538. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  151539. header handling. The
  151540. header packets aren't
  151541. audio, so if/when we
  151542. submit them,
  151543. vorbis_synthesis will
  151544. reject them */
  151545. /* suck in the synthesis data and track bitrate */
  151546. {
  151547. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151548. /* for proper use of libvorbis within libvorbisfile,
  151549. oldsamples will always be zero. */
  151550. if(oldsamples)return(OV_EFAULT);
  151551. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  151552. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  151553. vf->bittrack+=op_ptr->bytes*8;
  151554. }
  151555. /* update the pcm offset. */
  151556. if(granulepos!=-1 && !op_ptr->e_o_s){
  151557. int link=(vf->seekable?vf->current_link:0);
  151558. int i,samples;
  151559. /* this packet has a pcm_offset on it (the last packet
  151560. completed on a page carries the offset) After processing
  151561. (above), we know the pcm position of the *last* sample
  151562. ready to be returned. Find the offset of the *first*
  151563. As an aside, this trick is inaccurate if we begin
  151564. reading anew right at the last page; the end-of-stream
  151565. granulepos declares the last frame in the stream, and the
  151566. last packet of the last page may be a partial frame.
  151567. So, we need a previous granulepos from an in-sequence page
  151568. to have a reference point. Thus the !op_ptr->e_o_s clause
  151569. above */
  151570. if(vf->seekable && link>0)
  151571. granulepos-=vf->pcmlengths[link*2];
  151572. if(granulepos<0)granulepos=0; /* actually, this
  151573. shouldn't be possible
  151574. here unless the stream
  151575. is very broken */
  151576. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151577. granulepos-=samples;
  151578. for(i=0;i<link;i++)
  151579. granulepos+=vf->pcmlengths[i*2+1];
  151580. vf->pcm_offset=granulepos;
  151581. }
  151582. return(1);
  151583. }
  151584. }
  151585. else
  151586. break;
  151587. }
  151588. }
  151589. if(vf->ready_state>=OPENED){
  151590. ogg_int64_t ret;
  151591. if(!readp)return(0);
  151592. if((ret=_get_next_page(vf,&og,-1))<0){
  151593. return(OV_EOF); /* eof.
  151594. leave unitialized */
  151595. }
  151596. /* bitrate tracking; add the header's bytes here, the body bytes
  151597. are done by packet above */
  151598. vf->bittrack+=og.header_len*8;
  151599. /* has our decoding just traversed a bitstream boundary? */
  151600. if(vf->ready_state==INITSET){
  151601. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151602. if(!spanp)
  151603. return(OV_EOF);
  151604. _decode_clear(vf);
  151605. if(!vf->seekable){
  151606. vorbis_info_clear(vf->vi);
  151607. vorbis_comment_clear(vf->vc);
  151608. }
  151609. }
  151610. }
  151611. }
  151612. /* Do we need to load a new machine before submitting the page? */
  151613. /* This is different in the seekable and non-seekable cases.
  151614. In the seekable case, we already have all the header
  151615. information loaded and cached; we just initialize the machine
  151616. with it and continue on our merry way.
  151617. In the non-seekable (streaming) case, we'll only be at a
  151618. boundary if we just left the previous logical bitstream and
  151619. we're now nominally at the header of the next bitstream
  151620. */
  151621. if(vf->ready_state!=INITSET){
  151622. int link;
  151623. if(vf->ready_state<STREAMSET){
  151624. if(vf->seekable){
  151625. vf->current_serialno=ogg_page_serialno(&og);
  151626. /* match the serialno to bitstream section. We use this rather than
  151627. offset positions to avoid problems near logical bitstream
  151628. boundaries */
  151629. for(link=0;link<vf->links;link++)
  151630. if(vf->serialnos[link]==vf->current_serialno)break;
  151631. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  151632. stream. error out,
  151633. leave machine
  151634. uninitialized */
  151635. vf->current_link=link;
  151636. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151637. vf->ready_state=STREAMSET;
  151638. }else{
  151639. /* we're streaming */
  151640. /* fetch the three header packets, build the info struct */
  151641. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  151642. if(ret)return(ret);
  151643. vf->current_link++;
  151644. link=0;
  151645. }
  151646. }
  151647. {
  151648. int ret=_make_decode_ready(vf);
  151649. if(ret<0)return ret;
  151650. }
  151651. }
  151652. ogg_stream_pagein(&vf->os,&og);
  151653. }
  151654. }
  151655. /* if, eg, 64 bit stdio is configured by default, this will build with
  151656. fseek64 */
  151657. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  151658. if(f==NULL)return(-1);
  151659. return fseek(f,off,whence);
  151660. }
  151661. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  151662. long ibytes, ov_callbacks callbacks){
  151663. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  151664. int ret;
  151665. memset(vf,0,sizeof(*vf));
  151666. vf->datasource=f;
  151667. vf->callbacks = callbacks;
  151668. /* init the framing state */
  151669. ogg_sync_init(&vf->oy);
  151670. /* perhaps some data was previously read into a buffer for testing
  151671. against other stream types. Allow initialization from this
  151672. previously read data (as we may be reading from a non-seekable
  151673. stream) */
  151674. if(initial){
  151675. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  151676. memcpy(buffer,initial,ibytes);
  151677. ogg_sync_wrote(&vf->oy,ibytes);
  151678. }
  151679. /* can we seek? Stevens suggests the seek test was portable */
  151680. if(offsettest!=-1)vf->seekable=1;
  151681. /* No seeking yet; Set up a 'single' (current) logical bitstream
  151682. entry for partial open */
  151683. vf->links=1;
  151684. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  151685. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  151686. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  151687. /* Try to fetch the headers, maintaining all the storage */
  151688. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  151689. vf->datasource=NULL;
  151690. ov_clear(vf);
  151691. }else
  151692. vf->ready_state=PARTOPEN;
  151693. return(ret);
  151694. }
  151695. static int _ov_open2(OggVorbis_File *vf){
  151696. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  151697. vf->ready_state=OPENED;
  151698. if(vf->seekable){
  151699. int ret=_open_seekable2(vf);
  151700. if(ret){
  151701. vf->datasource=NULL;
  151702. ov_clear(vf);
  151703. }
  151704. return(ret);
  151705. }else
  151706. vf->ready_state=STREAMSET;
  151707. return 0;
  151708. }
  151709. /* clear out the OggVorbis_File struct */
  151710. int ov_clear(OggVorbis_File *vf){
  151711. if(vf){
  151712. vorbis_block_clear(&vf->vb);
  151713. vorbis_dsp_clear(&vf->vd);
  151714. ogg_stream_clear(&vf->os);
  151715. if(vf->vi && vf->links){
  151716. int i;
  151717. for(i=0;i<vf->links;i++){
  151718. vorbis_info_clear(vf->vi+i);
  151719. vorbis_comment_clear(vf->vc+i);
  151720. }
  151721. _ogg_free(vf->vi);
  151722. _ogg_free(vf->vc);
  151723. }
  151724. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  151725. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  151726. if(vf->serialnos)_ogg_free(vf->serialnos);
  151727. if(vf->offsets)_ogg_free(vf->offsets);
  151728. ogg_sync_clear(&vf->oy);
  151729. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  151730. memset(vf,0,sizeof(*vf));
  151731. }
  151732. #ifdef DEBUG_LEAKS
  151733. _VDBG_dump();
  151734. #endif
  151735. return(0);
  151736. }
  151737. /* inspects the OggVorbis file and finds/documents all the logical
  151738. bitstreams contained in it. Tries to be tolerant of logical
  151739. bitstream sections that are truncated/woogie.
  151740. return: -1) error
  151741. 0) OK
  151742. */
  151743. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151744. ov_callbacks callbacks){
  151745. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  151746. if(ret)return ret;
  151747. return _ov_open2(vf);
  151748. }
  151749. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151750. ov_callbacks callbacks = {
  151751. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151752. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151753. (int (*)(void *)) fclose,
  151754. (long (*)(void *)) ftell
  151755. };
  151756. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151757. }
  151758. /* cheap hack for game usage where downsampling is desirable; there's
  151759. no need for SRC as we can just do it cheaply in libvorbis. */
  151760. int ov_halfrate(OggVorbis_File *vf,int flag){
  151761. int i;
  151762. if(vf->vi==NULL)return OV_EINVAL;
  151763. if(!vf->seekable)return OV_EINVAL;
  151764. if(vf->ready_state>=STREAMSET)
  151765. _decode_clear(vf); /* clear out stream state; later on libvorbis
  151766. will be able to swap this on the fly, but
  151767. for now dumping the decode machine is needed
  151768. to reinit the MDCT lookups. 1.1 libvorbis
  151769. is planned to be able to switch on the fly */
  151770. for(i=0;i<vf->links;i++){
  151771. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  151772. ov_halfrate(vf,0);
  151773. return OV_EINVAL;
  151774. }
  151775. }
  151776. return 0;
  151777. }
  151778. int ov_halfrate_p(OggVorbis_File *vf){
  151779. if(vf->vi==NULL)return OV_EINVAL;
  151780. return vorbis_synthesis_halfrate_p(vf->vi);
  151781. }
  151782. /* Only partially open the vorbis file; test for Vorbisness, and load
  151783. the headers for the first chain. Do not seek (although test for
  151784. seekability). Use ov_test_open to finish opening the file, else
  151785. ov_clear to close/free it. Same return codes as open. */
  151786. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151787. ov_callbacks callbacks)
  151788. {
  151789. return _ov_open1(f,vf,initial,ibytes,callbacks);
  151790. }
  151791. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151792. ov_callbacks callbacks = {
  151793. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151794. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151795. (int (*)(void *)) fclose,
  151796. (long (*)(void *)) ftell
  151797. };
  151798. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151799. }
  151800. int ov_test_open(OggVorbis_File *vf){
  151801. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  151802. return _ov_open2(vf);
  151803. }
  151804. /* How many logical bitstreams in this physical bitstream? */
  151805. long ov_streams(OggVorbis_File *vf){
  151806. return vf->links;
  151807. }
  151808. /* Is the FILE * associated with vf seekable? */
  151809. long ov_seekable(OggVorbis_File *vf){
  151810. return vf->seekable;
  151811. }
  151812. /* returns the bitrate for a given logical bitstream or the entire
  151813. physical bitstream. If the file is open for random access, it will
  151814. find the *actual* average bitrate. If the file is streaming, it
  151815. returns the nominal bitrate (if set) else the average of the
  151816. upper/lower bounds (if set) else -1 (unset).
  151817. If you want the actual bitrate field settings, get them from the
  151818. vorbis_info structs */
  151819. long ov_bitrate(OggVorbis_File *vf,int i){
  151820. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151821. if(i>=vf->links)return(OV_EINVAL);
  151822. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  151823. if(i<0){
  151824. ogg_int64_t bits=0;
  151825. int i;
  151826. float br;
  151827. for(i=0;i<vf->links;i++)
  151828. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  151829. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  151830. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  151831. * so this is slightly transformed to make it work.
  151832. */
  151833. br = bits/ov_time_total(vf,-1);
  151834. return(rint(br));
  151835. }else{
  151836. if(vf->seekable){
  151837. /* return the actual bitrate */
  151838. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  151839. }else{
  151840. /* return nominal if set */
  151841. if(vf->vi[i].bitrate_nominal>0){
  151842. return vf->vi[i].bitrate_nominal;
  151843. }else{
  151844. if(vf->vi[i].bitrate_upper>0){
  151845. if(vf->vi[i].bitrate_lower>0){
  151846. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  151847. }else{
  151848. return vf->vi[i].bitrate_upper;
  151849. }
  151850. }
  151851. return(OV_FALSE);
  151852. }
  151853. }
  151854. }
  151855. }
  151856. /* returns the actual bitrate since last call. returns -1 if no
  151857. additional data to offer since last call (or at beginning of stream),
  151858. EINVAL if stream is only partially open
  151859. */
  151860. long ov_bitrate_instant(OggVorbis_File *vf){
  151861. int link=(vf->seekable?vf->current_link:0);
  151862. long ret;
  151863. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151864. if(vf->samptrack==0)return(OV_FALSE);
  151865. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  151866. vf->bittrack=0.f;
  151867. vf->samptrack=0.f;
  151868. return(ret);
  151869. }
  151870. /* Guess */
  151871. long ov_serialnumber(OggVorbis_File *vf,int i){
  151872. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  151873. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  151874. if(i<0){
  151875. return(vf->current_serialno);
  151876. }else{
  151877. return(vf->serialnos[i]);
  151878. }
  151879. }
  151880. /* returns: total raw (compressed) length of content if i==-1
  151881. raw (compressed) length of that logical bitstream for i==0 to n
  151882. OV_EINVAL if the stream is not seekable (we can't know the length)
  151883. or if stream is only partially open
  151884. */
  151885. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  151886. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151887. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151888. if(i<0){
  151889. ogg_int64_t acc=0;
  151890. int i;
  151891. for(i=0;i<vf->links;i++)
  151892. acc+=ov_raw_total(vf,i);
  151893. return(acc);
  151894. }else{
  151895. return(vf->offsets[i+1]-vf->offsets[i]);
  151896. }
  151897. }
  151898. /* returns: total PCM length (samples) of content if i==-1 PCM length
  151899. (samples) of that logical bitstream for i==0 to n
  151900. OV_EINVAL if the stream is not seekable (we can't know the
  151901. length) or only partially open
  151902. */
  151903. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  151904. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151905. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151906. if(i<0){
  151907. ogg_int64_t acc=0;
  151908. int i;
  151909. for(i=0;i<vf->links;i++)
  151910. acc+=ov_pcm_total(vf,i);
  151911. return(acc);
  151912. }else{
  151913. return(vf->pcmlengths[i*2+1]);
  151914. }
  151915. }
  151916. /* returns: total seconds of content if i==-1
  151917. seconds in that logical bitstream for i==0 to n
  151918. OV_EINVAL if the stream is not seekable (we can't know the
  151919. length) or only partially open
  151920. */
  151921. double ov_time_total(OggVorbis_File *vf,int i){
  151922. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151923. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151924. if(i<0){
  151925. double acc=0;
  151926. int i;
  151927. for(i=0;i<vf->links;i++)
  151928. acc+=ov_time_total(vf,i);
  151929. return(acc);
  151930. }else{
  151931. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  151932. }
  151933. }
  151934. /* seek to an offset relative to the *compressed* data. This also
  151935. scans packets to update the PCM cursor. It will cross a logical
  151936. bitstream boundary, but only if it can't get any packets out of the
  151937. tail of the bitstream we seek to (so no surprises).
  151938. returns zero on success, nonzero on failure */
  151939. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151940. ogg_stream_state work_os;
  151941. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151942. if(!vf->seekable)
  151943. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  151944. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  151945. /* don't yet clear out decoding machine (if it's initialized), in
  151946. the case we're in the same link. Restart the decode lapping, and
  151947. let _fetch_and_process_packet deal with a potential bitstream
  151948. boundary */
  151949. vf->pcm_offset=-1;
  151950. ogg_stream_reset_serialno(&vf->os,
  151951. vf->current_serialno); /* must set serialno */
  151952. vorbis_synthesis_restart(&vf->vd);
  151953. _seek_helper(vf,pos);
  151954. /* we need to make sure the pcm_offset is set, but we don't want to
  151955. advance the raw cursor past good packets just to get to the first
  151956. with a granulepos. That's not equivalent behavior to beginning
  151957. decoding as immediately after the seek position as possible.
  151958. So, a hack. We use two stream states; a local scratch state and
  151959. the shared vf->os stream state. We use the local state to
  151960. scan, and the shared state as a buffer for later decode.
  151961. Unfortuantely, on the last page we still advance to last packet
  151962. because the granulepos on the last page is not necessarily on a
  151963. packet boundary, and we need to make sure the granpos is
  151964. correct.
  151965. */
  151966. {
  151967. ogg_page og;
  151968. ogg_packet op;
  151969. int lastblock=0;
  151970. int accblock=0;
  151971. int thisblock;
  151972. int eosflag;
  151973. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  151974. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  151975. return from not necessarily
  151976. starting from the beginning */
  151977. while(1){
  151978. if(vf->ready_state>=STREAMSET){
  151979. /* snarf/scan a packet if we can */
  151980. int result=ogg_stream_packetout(&work_os,&op);
  151981. if(result>0){
  151982. if(vf->vi[vf->current_link].codec_setup){
  151983. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151984. if(thisblock<0){
  151985. ogg_stream_packetout(&vf->os,NULL);
  151986. thisblock=0;
  151987. }else{
  151988. if(eosflag)
  151989. ogg_stream_packetout(&vf->os,NULL);
  151990. else
  151991. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  151992. }
  151993. if(op.granulepos!=-1){
  151994. int i,link=vf->current_link;
  151995. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  151996. if(granulepos<0)granulepos=0;
  151997. for(i=0;i<link;i++)
  151998. granulepos+=vf->pcmlengths[i*2+1];
  151999. vf->pcm_offset=granulepos-accblock;
  152000. break;
  152001. }
  152002. lastblock=thisblock;
  152003. continue;
  152004. }else
  152005. ogg_stream_packetout(&vf->os,NULL);
  152006. }
  152007. }
  152008. if(!lastblock){
  152009. if(_get_next_page(vf,&og,-1)<0){
  152010. vf->pcm_offset=ov_pcm_total(vf,-1);
  152011. break;
  152012. }
  152013. }else{
  152014. /* huh? Bogus stream with packets but no granulepos */
  152015. vf->pcm_offset=-1;
  152016. break;
  152017. }
  152018. /* has our decoding just traversed a bitstream boundary? */
  152019. if(vf->ready_state>=STREAMSET)
  152020. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152021. _decode_clear(vf); /* clear out stream state */
  152022. ogg_stream_clear(&work_os);
  152023. }
  152024. if(vf->ready_state<STREAMSET){
  152025. int link;
  152026. vf->current_serialno=ogg_page_serialno(&og);
  152027. for(link=0;link<vf->links;link++)
  152028. if(vf->serialnos[link]==vf->current_serialno)break;
  152029. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  152030. error out, leave
  152031. machine uninitialized */
  152032. vf->current_link=link;
  152033. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152034. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  152035. vf->ready_state=STREAMSET;
  152036. }
  152037. ogg_stream_pagein(&vf->os,&og);
  152038. ogg_stream_pagein(&work_os,&og);
  152039. eosflag=ogg_page_eos(&og);
  152040. }
  152041. }
  152042. ogg_stream_clear(&work_os);
  152043. vf->bittrack=0.f;
  152044. vf->samptrack=0.f;
  152045. return(0);
  152046. seek_error:
  152047. /* dump the machine so we're in a known state */
  152048. vf->pcm_offset=-1;
  152049. ogg_stream_clear(&work_os);
  152050. _decode_clear(vf);
  152051. return OV_EBADLINK;
  152052. }
  152053. /* Page granularity seek (faster than sample granularity because we
  152054. don't do the last bit of decode to find a specific sample).
  152055. Seek to the last [granule marked] page preceeding the specified pos
  152056. location, such that decoding past the returned point will quickly
  152057. arrive at the requested position. */
  152058. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  152059. int link=-1;
  152060. ogg_int64_t result=0;
  152061. ogg_int64_t total=ov_pcm_total(vf,-1);
  152062. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152063. if(!vf->seekable)return(OV_ENOSEEK);
  152064. if(pos<0 || pos>total)return(OV_EINVAL);
  152065. /* which bitstream section does this pcm offset occur in? */
  152066. for(link=vf->links-1;link>=0;link--){
  152067. total-=vf->pcmlengths[link*2+1];
  152068. if(pos>=total)break;
  152069. }
  152070. /* search within the logical bitstream for the page with the highest
  152071. pcm_pos preceeding (or equal to) pos. There is a danger here;
  152072. missing pages or incorrect frame number information in the
  152073. bitstream could make our task impossible. Account for that (it
  152074. would be an error condition) */
  152075. /* new search algorithm by HB (Nicholas Vinen) */
  152076. {
  152077. ogg_int64_t end=vf->offsets[link+1];
  152078. ogg_int64_t begin=vf->offsets[link];
  152079. ogg_int64_t begintime = vf->pcmlengths[link*2];
  152080. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  152081. ogg_int64_t target=pos-total+begintime;
  152082. ogg_int64_t best=begin;
  152083. ogg_page og;
  152084. while(begin<end){
  152085. ogg_int64_t bisect;
  152086. if(end-begin<CHUNKSIZE){
  152087. bisect=begin;
  152088. }else{
  152089. /* take a (pretty decent) guess. */
  152090. bisect=begin +
  152091. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  152092. if(bisect<=begin)
  152093. bisect=begin+1;
  152094. }
  152095. _seek_helper(vf,bisect);
  152096. while(begin<end){
  152097. result=_get_next_page(vf,&og,end-vf->offset);
  152098. if(result==OV_EREAD) goto seek_error;
  152099. if(result<0){
  152100. if(bisect<=begin+1)
  152101. end=begin; /* found it */
  152102. else{
  152103. if(bisect==0) goto seek_error;
  152104. bisect-=CHUNKSIZE;
  152105. if(bisect<=begin)bisect=begin+1;
  152106. _seek_helper(vf,bisect);
  152107. }
  152108. }else{
  152109. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  152110. if(granulepos==-1)continue;
  152111. if(granulepos<target){
  152112. best=result; /* raw offset of packet with granulepos */
  152113. begin=vf->offset; /* raw offset of next page */
  152114. begintime=granulepos;
  152115. if(target-begintime>44100)break;
  152116. bisect=begin; /* *not* begin + 1 */
  152117. }else{
  152118. if(bisect<=begin+1)
  152119. end=begin; /* found it */
  152120. else{
  152121. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  152122. end=result;
  152123. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  152124. if(bisect<=begin)bisect=begin+1;
  152125. _seek_helper(vf,bisect);
  152126. }else{
  152127. end=result;
  152128. endtime=granulepos;
  152129. break;
  152130. }
  152131. }
  152132. }
  152133. }
  152134. }
  152135. }
  152136. /* found our page. seek to it, update pcm offset. Easier case than
  152137. raw_seek, don't keep packets preceeding granulepos. */
  152138. {
  152139. ogg_page og;
  152140. ogg_packet op;
  152141. /* seek */
  152142. _seek_helper(vf,best);
  152143. vf->pcm_offset=-1;
  152144. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  152145. if(link!=vf->current_link){
  152146. /* Different link; dump entire decode machine */
  152147. _decode_clear(vf);
  152148. vf->current_link=link;
  152149. vf->current_serialno=ogg_page_serialno(&og);
  152150. vf->ready_state=STREAMSET;
  152151. }else{
  152152. vorbis_synthesis_restart(&vf->vd);
  152153. }
  152154. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152155. ogg_stream_pagein(&vf->os,&og);
  152156. /* pull out all but last packet; the one with granulepos */
  152157. while(1){
  152158. result=ogg_stream_packetpeek(&vf->os,&op);
  152159. if(result==0){
  152160. /* !!! the packet finishing this page originated on a
  152161. preceeding page. Keep fetching previous pages until we
  152162. get one with a granulepos or without the 'continued' flag
  152163. set. Then just use raw_seek for simplicity. */
  152164. _seek_helper(vf,best);
  152165. while(1){
  152166. result=_get_prev_page(vf,&og);
  152167. if(result<0) goto seek_error;
  152168. if(ogg_page_granulepos(&og)>-1 ||
  152169. !ogg_page_continued(&og)){
  152170. return ov_raw_seek(vf,result);
  152171. }
  152172. vf->offset=result;
  152173. }
  152174. }
  152175. if(result<0){
  152176. result = OV_EBADPACKET;
  152177. goto seek_error;
  152178. }
  152179. if(op.granulepos!=-1){
  152180. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152181. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152182. vf->pcm_offset+=total;
  152183. break;
  152184. }else
  152185. result=ogg_stream_packetout(&vf->os,NULL);
  152186. }
  152187. }
  152188. }
  152189. /* verify result */
  152190. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  152191. result=OV_EFAULT;
  152192. goto seek_error;
  152193. }
  152194. vf->bittrack=0.f;
  152195. vf->samptrack=0.f;
  152196. return(0);
  152197. seek_error:
  152198. /* dump machine so we're in a known state */
  152199. vf->pcm_offset=-1;
  152200. _decode_clear(vf);
  152201. return (int)result;
  152202. }
  152203. /* seek to a sample offset relative to the decompressed pcm stream
  152204. returns zero on success, nonzero on failure */
  152205. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152206. int thisblock,lastblock=0;
  152207. int ret=ov_pcm_seek_page(vf,pos);
  152208. if(ret<0)return(ret);
  152209. if((ret=_make_decode_ready(vf)))return ret;
  152210. /* discard leading packets we don't need for the lapping of the
  152211. position we want; don't decode them */
  152212. while(1){
  152213. ogg_packet op;
  152214. ogg_page og;
  152215. int ret=ogg_stream_packetpeek(&vf->os,&op);
  152216. if(ret>0){
  152217. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152218. if(thisblock<0){
  152219. ogg_stream_packetout(&vf->os,NULL);
  152220. continue; /* non audio packet */
  152221. }
  152222. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  152223. if(vf->pcm_offset+((thisblock+
  152224. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  152225. /* remove the packet from packet queue and track its granulepos */
  152226. ogg_stream_packetout(&vf->os,NULL);
  152227. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  152228. only tracking, no
  152229. pcm_decode */
  152230. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152231. /* end of logical stream case is hard, especially with exact
  152232. length positioning. */
  152233. if(op.granulepos>-1){
  152234. int i;
  152235. /* always believe the stream markers */
  152236. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152237. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152238. for(i=0;i<vf->current_link;i++)
  152239. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  152240. }
  152241. lastblock=thisblock;
  152242. }else{
  152243. if(ret<0 && ret!=OV_HOLE)break;
  152244. /* suck in a new page */
  152245. if(_get_next_page(vf,&og,-1)<0)break;
  152246. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  152247. if(vf->ready_state<STREAMSET){
  152248. int link;
  152249. vf->current_serialno=ogg_page_serialno(&og);
  152250. for(link=0;link<vf->links;link++)
  152251. if(vf->serialnos[link]==vf->current_serialno)break;
  152252. if(link==vf->links)return(OV_EBADLINK);
  152253. vf->current_link=link;
  152254. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152255. vf->ready_state=STREAMSET;
  152256. ret=_make_decode_ready(vf);
  152257. if(ret)return ret;
  152258. lastblock=0;
  152259. }
  152260. ogg_stream_pagein(&vf->os,&og);
  152261. }
  152262. }
  152263. vf->bittrack=0.f;
  152264. vf->samptrack=0.f;
  152265. /* discard samples until we reach the desired position. Crossing a
  152266. logical bitstream boundary with abandon is OK. */
  152267. while(vf->pcm_offset<pos){
  152268. ogg_int64_t target=pos-vf->pcm_offset;
  152269. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152270. if(samples>target)samples=target;
  152271. vorbis_synthesis_read(&vf->vd,samples);
  152272. vf->pcm_offset+=samples;
  152273. if(samples<target)
  152274. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  152275. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  152276. }
  152277. return 0;
  152278. }
  152279. /* seek to a playback time relative to the decompressed pcm stream
  152280. returns zero on success, nonzero on failure */
  152281. int ov_time_seek(OggVorbis_File *vf,double seconds){
  152282. /* translate time to PCM position and call ov_pcm_seek */
  152283. int link=-1;
  152284. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152285. double time_total=ov_time_total(vf,-1);
  152286. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152287. if(!vf->seekable)return(OV_ENOSEEK);
  152288. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152289. /* which bitstream section does this time offset occur in? */
  152290. for(link=vf->links-1;link>=0;link--){
  152291. pcm_total-=vf->pcmlengths[link*2+1];
  152292. time_total-=ov_time_total(vf,link);
  152293. if(seconds>=time_total)break;
  152294. }
  152295. /* enough information to convert time offset to pcm offset */
  152296. {
  152297. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152298. return(ov_pcm_seek(vf,target));
  152299. }
  152300. }
  152301. /* page-granularity version of ov_time_seek
  152302. returns zero on success, nonzero on failure */
  152303. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  152304. /* translate time to PCM position and call ov_pcm_seek */
  152305. int link=-1;
  152306. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152307. double time_total=ov_time_total(vf,-1);
  152308. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152309. if(!vf->seekable)return(OV_ENOSEEK);
  152310. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152311. /* which bitstream section does this time offset occur in? */
  152312. for(link=vf->links-1;link>=0;link--){
  152313. pcm_total-=vf->pcmlengths[link*2+1];
  152314. time_total-=ov_time_total(vf,link);
  152315. if(seconds>=time_total)break;
  152316. }
  152317. /* enough information to convert time offset to pcm offset */
  152318. {
  152319. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152320. return(ov_pcm_seek_page(vf,target));
  152321. }
  152322. }
  152323. /* tell the current stream offset cursor. Note that seek followed by
  152324. tell will likely not give the set offset due to caching */
  152325. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  152326. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152327. return(vf->offset);
  152328. }
  152329. /* return PCM offset (sample) of next PCM sample to be read */
  152330. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  152331. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152332. return(vf->pcm_offset);
  152333. }
  152334. /* return time offset (seconds) of next PCM sample to be read */
  152335. double ov_time_tell(OggVorbis_File *vf){
  152336. int link=0;
  152337. ogg_int64_t pcm_total=0;
  152338. double time_total=0.f;
  152339. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152340. if(vf->seekable){
  152341. pcm_total=ov_pcm_total(vf,-1);
  152342. time_total=ov_time_total(vf,-1);
  152343. /* which bitstream section does this time offset occur in? */
  152344. for(link=vf->links-1;link>=0;link--){
  152345. pcm_total-=vf->pcmlengths[link*2+1];
  152346. time_total-=ov_time_total(vf,link);
  152347. if(vf->pcm_offset>=pcm_total)break;
  152348. }
  152349. }
  152350. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  152351. }
  152352. /* link: -1) return the vorbis_info struct for the bitstream section
  152353. currently being decoded
  152354. 0-n) to request information for a specific bitstream section
  152355. In the case of a non-seekable bitstream, any call returns the
  152356. current bitstream. NULL in the case that the machine is not
  152357. initialized */
  152358. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  152359. if(vf->seekable){
  152360. if(link<0)
  152361. if(vf->ready_state>=STREAMSET)
  152362. return vf->vi+vf->current_link;
  152363. else
  152364. return vf->vi;
  152365. else
  152366. if(link>=vf->links)
  152367. return NULL;
  152368. else
  152369. return vf->vi+link;
  152370. }else{
  152371. return vf->vi;
  152372. }
  152373. }
  152374. /* grr, strong typing, grr, no templates/inheritence, grr */
  152375. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  152376. if(vf->seekable){
  152377. if(link<0)
  152378. if(vf->ready_state>=STREAMSET)
  152379. return vf->vc+vf->current_link;
  152380. else
  152381. return vf->vc;
  152382. else
  152383. if(link>=vf->links)
  152384. return NULL;
  152385. else
  152386. return vf->vc+link;
  152387. }else{
  152388. return vf->vc;
  152389. }
  152390. }
  152391. static int host_is_big_endian() {
  152392. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  152393. unsigned char *bytewise = (unsigned char *)&pattern;
  152394. if (bytewise[0] == 0xfe) return 1;
  152395. return 0;
  152396. }
  152397. /* up to this point, everything could more or less hide the multiple
  152398. logical bitstream nature of chaining from the toplevel application
  152399. if the toplevel application didn't particularly care. However, at
  152400. the point that we actually read audio back, the multiple-section
  152401. nature must surface: Multiple bitstream sections do not necessarily
  152402. have to have the same number of channels or sampling rate.
  152403. ov_read returns the sequential logical bitstream number currently
  152404. being decoded along with the PCM data in order that the toplevel
  152405. application can take action on channel/sample rate changes. This
  152406. number will be incremented even for streamed (non-seekable) streams
  152407. (for seekable streams, it represents the actual logical bitstream
  152408. index within the physical bitstream. Note that the accessor
  152409. functions above are aware of this dichotomy).
  152410. input values: buffer) a buffer to hold packed PCM data for return
  152411. length) the byte length requested to be placed into buffer
  152412. bigendianp) should the data be packed LSB first (0) or
  152413. MSB first (1)
  152414. word) word size for output. currently 1 (byte) or
  152415. 2 (16 bit short)
  152416. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152417. 0) EOF
  152418. n) number of bytes of PCM actually returned. The
  152419. below works on a packet-by-packet basis, so the
  152420. return length is not related to the 'length' passed
  152421. in, just guaranteed to fit.
  152422. *section) set to the logical bitstream number */
  152423. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  152424. int bigendianp,int word,int sgned,int *bitstream){
  152425. int i,j;
  152426. int host_endian = host_is_big_endian();
  152427. float **pcm;
  152428. long samples;
  152429. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152430. while(1){
  152431. if(vf->ready_state==INITSET){
  152432. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152433. if(samples)break;
  152434. }
  152435. /* suck in another packet */
  152436. {
  152437. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152438. if(ret==OV_EOF)
  152439. return(0);
  152440. if(ret<=0)
  152441. return(ret);
  152442. }
  152443. }
  152444. if(samples>0){
  152445. /* yay! proceed to pack data into the byte buffer */
  152446. long channels=ov_info(vf,-1)->channels;
  152447. long bytespersample=word * channels;
  152448. vorbis_fpu_control fpu;
  152449. (void) fpu; // (to avoid a warning about it being unused)
  152450. if(samples>length/bytespersample)samples=length/bytespersample;
  152451. if(samples <= 0)
  152452. return OV_EINVAL;
  152453. /* a tight loop to pack each size */
  152454. {
  152455. int val;
  152456. if(word==1){
  152457. int off=(sgned?0:128);
  152458. vorbis_fpu_setround(&fpu);
  152459. for(j=0;j<samples;j++)
  152460. for(i=0;i<channels;i++){
  152461. val=vorbis_ftoi(pcm[i][j]*128.f);
  152462. if(val>127)val=127;
  152463. else if(val<-128)val=-128;
  152464. *buffer++=val+off;
  152465. }
  152466. vorbis_fpu_restore(fpu);
  152467. }else{
  152468. int off=(sgned?0:32768);
  152469. if(host_endian==bigendianp){
  152470. if(sgned){
  152471. vorbis_fpu_setround(&fpu);
  152472. for(i=0;i<channels;i++) { /* It's faster in this order */
  152473. float *src=pcm[i];
  152474. short *dest=((short *)buffer)+i;
  152475. for(j=0;j<samples;j++) {
  152476. val=vorbis_ftoi(src[j]*32768.f);
  152477. if(val>32767)val=32767;
  152478. else if(val<-32768)val=-32768;
  152479. *dest=val;
  152480. dest+=channels;
  152481. }
  152482. }
  152483. vorbis_fpu_restore(fpu);
  152484. }else{
  152485. vorbis_fpu_setround(&fpu);
  152486. for(i=0;i<channels;i++) {
  152487. float *src=pcm[i];
  152488. short *dest=((short *)buffer)+i;
  152489. for(j=0;j<samples;j++) {
  152490. val=vorbis_ftoi(src[j]*32768.f);
  152491. if(val>32767)val=32767;
  152492. else if(val<-32768)val=-32768;
  152493. *dest=val+off;
  152494. dest+=channels;
  152495. }
  152496. }
  152497. vorbis_fpu_restore(fpu);
  152498. }
  152499. }else if(bigendianp){
  152500. vorbis_fpu_setround(&fpu);
  152501. for(j=0;j<samples;j++)
  152502. for(i=0;i<channels;i++){
  152503. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152504. if(val>32767)val=32767;
  152505. else if(val<-32768)val=-32768;
  152506. val+=off;
  152507. *buffer++=(val>>8);
  152508. *buffer++=(val&0xff);
  152509. }
  152510. vorbis_fpu_restore(fpu);
  152511. }else{
  152512. int val;
  152513. vorbis_fpu_setround(&fpu);
  152514. for(j=0;j<samples;j++)
  152515. for(i=0;i<channels;i++){
  152516. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152517. if(val>32767)val=32767;
  152518. else if(val<-32768)val=-32768;
  152519. val+=off;
  152520. *buffer++=(val&0xff);
  152521. *buffer++=(val>>8);
  152522. }
  152523. vorbis_fpu_restore(fpu);
  152524. }
  152525. }
  152526. }
  152527. vorbis_synthesis_read(&vf->vd,samples);
  152528. vf->pcm_offset+=samples;
  152529. if(bitstream)*bitstream=vf->current_link;
  152530. return(samples*bytespersample);
  152531. }else{
  152532. return(samples);
  152533. }
  152534. }
  152535. /* input values: pcm_channels) a float vector per channel of output
  152536. length) the sample length being read by the app
  152537. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152538. 0) EOF
  152539. n) number of samples of PCM actually returned. The
  152540. below works on a packet-by-packet basis, so the
  152541. return length is not related to the 'length' passed
  152542. in, just guaranteed to fit.
  152543. *section) set to the logical bitstream number */
  152544. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  152545. int *bitstream){
  152546. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152547. while(1){
  152548. if(vf->ready_state==INITSET){
  152549. float **pcm;
  152550. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152551. if(samples){
  152552. if(pcm_channels)*pcm_channels=pcm;
  152553. if(samples>length)samples=length;
  152554. vorbis_synthesis_read(&vf->vd,samples);
  152555. vf->pcm_offset+=samples;
  152556. if(bitstream)*bitstream=vf->current_link;
  152557. return samples;
  152558. }
  152559. }
  152560. /* suck in another packet */
  152561. {
  152562. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152563. if(ret==OV_EOF)return(0);
  152564. if(ret<=0)return(ret);
  152565. }
  152566. }
  152567. }
  152568. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  152569. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  152570. ogg_int64_t off);
  152571. static void _ov_splice(float **pcm,float **lappcm,
  152572. int n1, int n2,
  152573. int ch1, int ch2,
  152574. float *w1, float *w2){
  152575. int i,j;
  152576. float *w=w1;
  152577. int n=n1;
  152578. if(n1>n2){
  152579. n=n2;
  152580. w=w2;
  152581. }
  152582. /* splice */
  152583. for(j=0;j<ch1 && j<ch2;j++){
  152584. float *s=lappcm[j];
  152585. float *d=pcm[j];
  152586. for(i=0;i<n;i++){
  152587. float wd=w[i]*w[i];
  152588. float ws=1.-wd;
  152589. d[i]=d[i]*wd + s[i]*ws;
  152590. }
  152591. }
  152592. /* window from zero */
  152593. for(;j<ch2;j++){
  152594. float *d=pcm[j];
  152595. for(i=0;i<n;i++){
  152596. float wd=w[i]*w[i];
  152597. d[i]=d[i]*wd;
  152598. }
  152599. }
  152600. }
  152601. /* make sure vf is INITSET */
  152602. static int _ov_initset(OggVorbis_File *vf){
  152603. while(1){
  152604. if(vf->ready_state==INITSET)break;
  152605. /* suck in another packet */
  152606. {
  152607. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152608. if(ret<0 && ret!=OV_HOLE)return(ret);
  152609. }
  152610. }
  152611. return 0;
  152612. }
  152613. /* make sure vf is INITSET and that we have a primed buffer; if
  152614. we're crosslapping at a stream section boundary, this also makes
  152615. sure we're sanity checking against the right stream information */
  152616. static int _ov_initprime(OggVorbis_File *vf){
  152617. vorbis_dsp_state *vd=&vf->vd;
  152618. while(1){
  152619. if(vf->ready_state==INITSET)
  152620. if(vorbis_synthesis_pcmout(vd,NULL))break;
  152621. /* suck in another packet */
  152622. {
  152623. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152624. if(ret<0 && ret!=OV_HOLE)return(ret);
  152625. }
  152626. }
  152627. return 0;
  152628. }
  152629. /* grab enough data for lapping from vf; this may be in the form of
  152630. unreturned, already-decoded pcm, remaining PCM we will need to
  152631. decode, or synthetic postextrapolation from last packets. */
  152632. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  152633. float **lappcm,int lapsize){
  152634. int lapcount=0,i;
  152635. float **pcm;
  152636. /* try first to decode the lapping data */
  152637. while(lapcount<lapsize){
  152638. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  152639. if(samples){
  152640. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152641. for(i=0;i<vi->channels;i++)
  152642. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152643. lapcount+=samples;
  152644. vorbis_synthesis_read(vd,samples);
  152645. }else{
  152646. /* suck in another packet */
  152647. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  152648. if(ret==OV_EOF)break;
  152649. }
  152650. }
  152651. if(lapcount<lapsize){
  152652. /* failed to get lapping data from normal decode; pry it from the
  152653. postextrapolation buffering, or the second half of the MDCT
  152654. from the last packet */
  152655. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  152656. if(samples==0){
  152657. for(i=0;i<vi->channels;i++)
  152658. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  152659. lapcount=lapsize;
  152660. }else{
  152661. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152662. for(i=0;i<vi->channels;i++)
  152663. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152664. lapcount+=samples;
  152665. }
  152666. }
  152667. }
  152668. /* this sets up crosslapping of a sample by using trailing data from
  152669. sample 1 and lapping it into the windowing buffer of sample 2 */
  152670. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  152671. vorbis_info *vi1,*vi2;
  152672. float **lappcm;
  152673. float **pcm;
  152674. float *w1,*w2;
  152675. int n1,n2,i,ret,hs1,hs2;
  152676. if(vf1==vf2)return(0); /* degenerate case */
  152677. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  152678. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  152679. /* the relevant overlap buffers must be pre-checked and pre-primed
  152680. before looking at settings in the event that priming would cross
  152681. a bitstream boundary. So, do it now */
  152682. ret=_ov_initset(vf1);
  152683. if(ret)return(ret);
  152684. ret=_ov_initprime(vf2);
  152685. if(ret)return(ret);
  152686. vi1=ov_info(vf1,-1);
  152687. vi2=ov_info(vf2,-1);
  152688. hs1=ov_halfrate_p(vf1);
  152689. hs2=ov_halfrate_p(vf2);
  152690. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  152691. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  152692. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  152693. w1=vorbis_window(&vf1->vd,0);
  152694. w2=vorbis_window(&vf2->vd,0);
  152695. for(i=0;i<vi1->channels;i++)
  152696. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152697. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  152698. /* have a lapping buffer from vf1; now to splice it into the lapping
  152699. buffer of vf2 */
  152700. /* consolidate and expose the buffer. */
  152701. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  152702. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  152703. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  152704. /* splice */
  152705. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  152706. /* done */
  152707. return(0);
  152708. }
  152709. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  152710. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  152711. vorbis_info *vi;
  152712. float **lappcm;
  152713. float **pcm;
  152714. float *w1,*w2;
  152715. int n1,n2,ch1,ch2,hs;
  152716. int i,ret;
  152717. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152718. ret=_ov_initset(vf);
  152719. if(ret)return(ret);
  152720. vi=ov_info(vf,-1);
  152721. hs=ov_halfrate_p(vf);
  152722. ch1=vi->channels;
  152723. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152724. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152725. persistent; even if the decode state
  152726. from this link gets dumped, this
  152727. window array continues to exist */
  152728. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152729. for(i=0;i<ch1;i++)
  152730. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152731. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152732. /* have lapping data; seek and prime the buffer */
  152733. ret=localseek(vf,pos);
  152734. if(ret)return ret;
  152735. ret=_ov_initprime(vf);
  152736. if(ret)return(ret);
  152737. /* Guard against cross-link changes; they're perfectly legal */
  152738. vi=ov_info(vf,-1);
  152739. ch2=vi->channels;
  152740. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152741. w2=vorbis_window(&vf->vd,0);
  152742. /* consolidate and expose the buffer. */
  152743. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152744. /* splice */
  152745. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152746. /* done */
  152747. return(0);
  152748. }
  152749. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152750. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  152751. }
  152752. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152753. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  152754. }
  152755. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152756. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  152757. }
  152758. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  152759. int (*localseek)(OggVorbis_File *,double)){
  152760. vorbis_info *vi;
  152761. float **lappcm;
  152762. float **pcm;
  152763. float *w1,*w2;
  152764. int n1,n2,ch1,ch2,hs;
  152765. int i,ret;
  152766. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152767. ret=_ov_initset(vf);
  152768. if(ret)return(ret);
  152769. vi=ov_info(vf,-1);
  152770. hs=ov_halfrate_p(vf);
  152771. ch1=vi->channels;
  152772. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152773. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152774. persistent; even if the decode state
  152775. from this link gets dumped, this
  152776. window array continues to exist */
  152777. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152778. for(i=0;i<ch1;i++)
  152779. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152780. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152781. /* have lapping data; seek and prime the buffer */
  152782. ret=localseek(vf,pos);
  152783. if(ret)return ret;
  152784. ret=_ov_initprime(vf);
  152785. if(ret)return(ret);
  152786. /* Guard against cross-link changes; they're perfectly legal */
  152787. vi=ov_info(vf,-1);
  152788. ch2=vi->channels;
  152789. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152790. w2=vorbis_window(&vf->vd,0);
  152791. /* consolidate and expose the buffer. */
  152792. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152793. /* splice */
  152794. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152795. /* done */
  152796. return(0);
  152797. }
  152798. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  152799. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  152800. }
  152801. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  152802. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  152803. }
  152804. #endif
  152805. /********* End of inlined file: vorbisfile.c *********/
  152806. /********* Start of inlined file: window.c *********/
  152807. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  152808. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152809. // tasks..
  152810. #if JUCE_MSVC
  152811. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152812. #endif
  152813. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  152814. #if JUCE_USE_OGGVORBIS
  152815. #include <stdlib.h>
  152816. #include <math.h>
  152817. static float vwin64[32] = {
  152818. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  152819. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  152820. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  152821. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  152822. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  152823. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  152824. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  152825. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  152826. };
  152827. static float vwin128[64] = {
  152828. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  152829. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  152830. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  152831. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  152832. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  152833. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  152834. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  152835. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  152836. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  152837. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  152838. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  152839. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  152840. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  152841. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  152842. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  152843. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  152844. };
  152845. static float vwin256[128] = {
  152846. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  152847. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  152848. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  152849. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  152850. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  152851. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  152852. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  152853. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  152854. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  152855. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  152856. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  152857. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  152858. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  152859. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  152860. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  152861. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  152862. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  152863. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  152864. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  152865. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  152866. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  152867. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  152868. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  152869. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  152870. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  152871. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  152872. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  152873. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  152874. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  152875. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  152876. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  152877. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  152878. };
  152879. static float vwin512[256] = {
  152880. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  152881. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  152882. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  152883. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  152884. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  152885. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  152886. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  152887. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  152888. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  152889. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  152890. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  152891. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  152892. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  152893. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  152894. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  152895. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  152896. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  152897. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  152898. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  152899. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  152900. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  152901. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  152902. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  152903. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  152904. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  152905. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  152906. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  152907. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  152908. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  152909. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  152910. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  152911. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  152912. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  152913. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  152914. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  152915. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  152916. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  152917. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  152918. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  152919. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  152920. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  152921. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  152922. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  152923. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  152924. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  152925. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  152926. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  152927. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  152928. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  152929. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  152930. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  152931. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  152932. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  152933. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  152934. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  152935. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  152936. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  152937. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  152938. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  152939. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  152940. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  152941. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  152942. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  152943. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  152944. };
  152945. static float vwin1024[512] = {
  152946. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  152947. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  152948. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  152949. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  152950. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  152951. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  152952. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  152953. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  152954. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  152955. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  152956. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  152957. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  152958. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  152959. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  152960. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  152961. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  152962. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  152963. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  152964. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  152965. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  152966. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  152967. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  152968. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  152969. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  152970. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  152971. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  152972. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  152973. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  152974. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  152975. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  152976. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  152977. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  152978. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  152979. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  152980. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  152981. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  152982. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  152983. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  152984. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  152985. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  152986. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  152987. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  152988. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  152989. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  152990. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  152991. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  152992. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  152993. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  152994. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  152995. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  152996. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  152997. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  152998. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  152999. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  153000. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  153001. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  153002. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  153003. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  153004. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  153005. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  153006. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  153007. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  153008. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  153009. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  153010. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  153011. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  153012. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  153013. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  153014. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  153015. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  153016. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  153017. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  153018. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  153019. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  153020. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  153021. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  153022. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  153023. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  153024. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  153025. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  153026. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  153027. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  153028. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  153029. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  153030. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  153031. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  153032. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  153033. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  153034. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  153035. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  153036. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  153037. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  153038. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  153039. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  153040. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  153041. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  153042. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  153043. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  153044. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  153045. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  153046. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  153047. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  153048. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  153049. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  153050. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  153051. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  153052. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  153053. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  153054. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  153055. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  153056. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  153057. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  153058. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  153059. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  153060. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  153061. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  153062. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  153063. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  153064. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  153065. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  153066. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  153067. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  153068. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  153069. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  153070. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  153071. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  153072. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  153073. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  153074. };
  153075. static float vwin2048[1024] = {
  153076. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  153077. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  153078. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  153079. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  153080. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  153081. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  153082. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  153083. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  153084. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  153085. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  153086. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  153087. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  153088. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  153089. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  153090. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  153091. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  153092. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  153093. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  153094. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  153095. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  153096. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  153097. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  153098. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  153099. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  153100. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  153101. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  153102. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  153103. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  153104. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  153105. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  153106. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  153107. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  153108. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  153109. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  153110. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  153111. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  153112. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  153113. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  153114. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  153115. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  153116. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  153117. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  153118. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  153119. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  153120. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  153121. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  153122. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  153123. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  153124. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  153125. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  153126. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  153127. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  153128. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  153129. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  153130. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  153131. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  153132. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  153133. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  153134. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  153135. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  153136. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  153137. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  153138. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  153139. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  153140. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  153141. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  153142. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  153143. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  153144. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  153145. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  153146. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  153147. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  153148. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  153149. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  153150. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  153151. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  153152. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  153153. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  153154. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  153155. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  153156. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  153157. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  153158. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  153159. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  153160. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  153161. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  153162. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  153163. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  153164. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  153165. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  153166. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  153167. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  153168. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  153169. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  153170. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  153171. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  153172. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  153173. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  153174. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  153175. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  153176. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  153177. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  153178. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  153179. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  153180. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  153181. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  153182. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  153183. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  153184. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  153185. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  153186. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  153187. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  153188. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  153189. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  153190. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  153191. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  153192. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  153193. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  153194. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  153195. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  153196. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  153197. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  153198. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  153199. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  153200. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  153201. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  153202. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  153203. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  153204. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  153205. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  153206. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  153207. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  153208. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  153209. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  153210. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  153211. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  153212. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  153213. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  153214. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  153215. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  153216. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  153217. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  153218. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  153219. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  153220. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  153221. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  153222. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  153223. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  153224. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  153225. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  153226. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  153227. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  153228. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  153229. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  153230. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  153231. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  153232. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  153233. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  153234. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  153235. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  153236. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  153237. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  153238. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  153239. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  153240. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  153241. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  153242. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  153243. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  153244. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  153245. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  153246. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  153247. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  153248. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  153249. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  153250. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  153251. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  153252. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  153253. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  153254. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  153255. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  153256. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  153257. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  153258. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  153259. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  153260. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  153261. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  153262. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  153263. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  153264. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  153265. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  153266. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  153267. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  153268. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  153269. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  153270. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  153271. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  153272. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  153273. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  153274. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  153275. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  153276. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  153277. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  153278. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  153279. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  153280. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  153281. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  153282. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  153283. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  153284. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  153285. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  153286. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  153287. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  153288. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  153289. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  153290. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  153291. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  153292. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  153293. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  153294. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  153295. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  153296. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  153297. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  153298. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  153299. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  153300. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  153301. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  153302. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  153303. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  153304. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  153305. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  153306. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  153307. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  153308. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  153309. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  153310. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  153311. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  153312. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  153313. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  153314. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  153315. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  153316. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  153317. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  153318. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  153319. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  153320. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  153321. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  153322. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  153323. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  153324. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  153325. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  153326. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  153327. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  153328. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  153329. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  153330. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  153331. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  153332. };
  153333. static float vwin4096[2048] = {
  153334. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  153335. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  153336. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  153337. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  153338. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  153339. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  153340. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  153341. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  153342. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  153343. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  153344. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  153345. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  153346. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  153347. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  153348. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  153349. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  153350. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  153351. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  153352. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  153353. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  153354. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  153355. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  153356. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  153357. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  153358. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  153359. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  153360. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  153361. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  153362. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  153363. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  153364. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  153365. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  153366. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  153367. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  153368. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  153369. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  153370. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  153371. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  153372. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  153373. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  153374. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  153375. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  153376. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  153377. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  153378. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  153379. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  153380. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  153381. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  153382. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  153383. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  153384. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  153385. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  153386. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  153387. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  153388. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  153389. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  153390. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  153391. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  153392. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  153393. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  153394. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  153395. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  153396. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  153397. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  153398. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  153399. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  153400. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  153401. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  153402. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  153403. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  153404. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  153405. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  153406. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  153407. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  153408. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  153409. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  153410. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  153411. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  153412. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  153413. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  153414. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  153415. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  153416. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  153417. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  153418. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  153419. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  153420. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  153421. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  153422. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  153423. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  153424. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  153425. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  153426. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  153427. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  153428. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  153429. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  153430. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  153431. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  153432. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  153433. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  153434. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  153435. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  153436. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  153437. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  153438. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  153439. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  153440. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  153441. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  153442. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  153443. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  153444. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  153445. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  153446. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  153447. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  153448. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  153449. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  153450. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  153451. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  153452. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  153453. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  153454. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  153455. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  153456. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  153457. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  153458. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  153459. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  153460. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  153461. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  153462. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  153463. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  153464. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  153465. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  153466. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  153467. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  153468. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  153469. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  153470. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  153471. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  153472. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  153473. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  153474. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  153475. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  153476. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  153477. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  153478. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  153479. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  153480. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  153481. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  153482. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  153483. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  153484. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  153485. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  153486. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  153487. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  153488. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  153489. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  153490. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  153491. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  153492. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  153493. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  153494. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  153495. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  153496. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  153497. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  153498. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  153499. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  153500. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  153501. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  153502. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  153503. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  153504. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  153505. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  153506. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  153507. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  153508. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  153509. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  153510. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  153511. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  153512. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  153513. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  153514. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  153515. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  153516. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  153517. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  153518. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  153519. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  153520. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  153521. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  153522. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  153523. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  153524. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  153525. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  153526. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  153527. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  153528. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  153529. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  153530. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  153531. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  153532. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  153533. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  153534. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  153535. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  153536. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  153537. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  153538. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  153539. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  153540. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  153541. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  153542. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  153543. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  153544. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  153545. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  153546. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  153547. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  153548. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  153549. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  153550. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  153551. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  153552. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  153553. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  153554. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  153555. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  153556. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  153557. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  153558. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  153559. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  153560. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  153561. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  153562. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  153563. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  153564. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  153565. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  153566. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  153567. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  153568. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  153569. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  153570. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  153571. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  153572. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  153573. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  153574. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  153575. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  153576. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  153577. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  153578. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  153579. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  153580. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  153581. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  153582. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  153583. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  153584. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  153585. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  153586. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  153587. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  153588. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  153589. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  153590. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  153591. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  153592. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  153593. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  153594. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  153595. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  153596. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  153597. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  153598. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  153599. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  153600. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  153601. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  153602. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  153603. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  153604. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  153605. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  153606. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  153607. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  153608. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  153609. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  153610. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  153611. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  153612. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  153613. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  153614. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  153615. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  153616. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  153617. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  153618. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  153619. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  153620. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  153621. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  153622. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  153623. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  153624. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  153625. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  153626. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  153627. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  153628. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  153629. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  153630. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  153631. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  153632. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  153633. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  153634. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  153635. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  153636. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  153637. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  153638. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  153639. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  153640. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  153641. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  153642. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  153643. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  153644. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  153645. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  153646. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  153647. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  153648. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  153649. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  153650. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  153651. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  153652. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  153653. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  153654. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  153655. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  153656. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  153657. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  153658. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  153659. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  153660. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  153661. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  153662. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  153663. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  153664. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  153665. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  153666. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  153667. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  153668. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  153669. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  153670. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  153671. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  153672. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  153673. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  153674. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  153675. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  153676. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  153677. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  153678. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  153679. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  153680. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  153681. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  153682. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  153683. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  153684. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  153685. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  153686. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  153687. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  153688. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  153689. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  153690. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  153691. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  153692. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  153693. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  153694. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  153695. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  153696. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  153697. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  153698. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  153699. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  153700. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  153701. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  153702. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  153703. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  153704. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  153705. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  153706. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  153707. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  153708. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  153709. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  153710. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  153711. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  153712. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  153713. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  153714. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  153715. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  153716. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  153717. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  153718. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  153719. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  153720. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  153721. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  153722. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  153723. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  153724. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  153725. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  153726. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  153727. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  153728. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  153729. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  153730. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  153731. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  153732. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  153733. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  153734. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  153735. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  153736. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  153737. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  153738. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  153739. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  153740. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  153741. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  153742. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  153743. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  153744. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  153745. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  153746. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  153747. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  153748. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  153749. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  153750. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  153751. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  153752. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  153753. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  153754. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  153755. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  153756. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  153757. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  153758. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  153759. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  153760. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  153761. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  153762. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  153763. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  153764. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  153765. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  153766. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  153767. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  153768. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  153769. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  153770. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  153771. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  153772. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  153773. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  153774. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  153775. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  153776. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  153777. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  153778. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  153779. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  153780. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  153781. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  153782. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  153783. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  153784. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  153785. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  153786. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  153787. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  153788. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  153789. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  153790. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  153791. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  153792. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  153793. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  153794. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  153795. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  153796. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  153797. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  153798. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  153799. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  153800. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  153801. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  153802. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  153803. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  153804. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  153805. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  153806. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  153807. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  153808. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  153809. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  153810. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  153811. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  153812. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  153813. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  153814. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  153815. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  153816. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  153817. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  153818. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  153819. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  153820. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  153821. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  153822. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  153823. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  153824. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  153825. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  153826. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  153827. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  153828. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  153829. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  153830. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  153831. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  153832. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  153833. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  153834. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  153835. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  153836. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  153837. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  153838. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  153839. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  153840. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  153841. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  153842. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  153843. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  153844. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  153845. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153846. };
  153847. static float vwin8192[4096] = {
  153848. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  153849. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  153850. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  153851. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  153852. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  153853. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  153854. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  153855. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  153856. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  153857. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  153858. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  153859. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  153860. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  153861. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  153862. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  153863. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  153864. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  153865. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  153866. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  153867. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  153868. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  153869. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  153870. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  153871. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  153872. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  153873. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  153874. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  153875. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  153876. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  153877. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  153878. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  153879. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  153880. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  153881. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  153882. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  153883. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  153884. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  153885. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  153886. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  153887. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  153888. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  153889. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  153890. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  153891. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  153892. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  153893. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  153894. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  153895. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  153896. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  153897. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  153898. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  153899. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  153900. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  153901. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  153902. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  153903. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  153904. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  153905. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  153906. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  153907. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  153908. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  153909. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  153910. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  153911. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  153912. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  153913. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  153914. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  153915. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  153916. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  153917. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  153918. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  153919. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  153920. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  153921. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  153922. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  153923. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  153924. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  153925. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  153926. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  153927. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  153928. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  153929. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  153930. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  153931. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  153932. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  153933. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  153934. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  153935. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  153936. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  153937. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  153938. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  153939. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  153940. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  153941. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  153942. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  153943. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  153944. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  153945. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  153946. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  153947. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  153948. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  153949. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  153950. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  153951. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  153952. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  153953. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  153954. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  153955. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  153956. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  153957. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  153958. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  153959. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  153960. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  153961. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  153962. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  153963. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  153964. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  153965. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  153966. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  153967. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  153968. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  153969. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  153970. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  153971. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  153972. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  153973. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  153974. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  153975. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  153976. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  153977. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  153978. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  153979. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  153980. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  153981. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  153982. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  153983. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  153984. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  153985. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  153986. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  153987. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  153988. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  153989. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  153990. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  153991. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  153992. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  153993. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  153994. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  153995. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  153996. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  153997. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  153998. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  153999. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  154000. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  154001. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  154002. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  154003. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  154004. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  154005. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  154006. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  154007. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  154008. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  154009. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  154010. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  154011. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  154012. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  154013. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  154014. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  154015. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  154016. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  154017. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  154018. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  154019. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  154020. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  154021. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  154022. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  154023. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  154024. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  154025. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  154026. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  154027. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  154028. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  154029. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  154030. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  154031. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  154032. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  154033. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  154034. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  154035. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  154036. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  154037. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  154038. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  154039. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  154040. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  154041. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  154042. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  154043. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  154044. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  154045. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  154046. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  154047. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  154048. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  154049. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  154050. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  154051. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  154052. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  154053. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  154054. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  154055. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  154056. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  154057. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  154058. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  154059. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  154060. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  154061. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  154062. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  154063. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  154064. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  154065. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  154066. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  154067. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  154068. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  154069. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  154070. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  154071. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  154072. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  154073. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  154074. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  154075. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  154076. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  154077. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  154078. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  154079. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  154080. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  154081. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  154082. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  154083. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  154084. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  154085. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  154086. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  154087. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  154088. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  154089. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  154090. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  154091. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  154092. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  154093. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  154094. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  154095. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  154096. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  154097. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  154098. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  154099. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  154100. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  154101. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  154102. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  154103. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  154104. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  154105. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  154106. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  154107. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  154108. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  154109. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  154110. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  154111. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  154112. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  154113. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  154114. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  154115. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  154116. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  154117. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  154118. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  154119. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  154120. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  154121. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  154122. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  154123. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  154124. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  154125. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  154126. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  154127. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  154128. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  154129. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  154130. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  154131. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  154132. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  154133. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  154134. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  154135. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  154136. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  154137. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  154138. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  154139. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  154140. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  154141. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  154142. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  154143. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  154144. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  154145. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  154146. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  154147. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  154148. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  154149. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  154150. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  154151. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  154152. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  154153. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  154154. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  154155. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  154156. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  154157. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  154158. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  154159. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  154160. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  154161. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  154162. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  154163. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  154164. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  154165. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  154166. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  154167. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  154168. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  154169. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  154170. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  154171. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  154172. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  154173. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  154174. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  154175. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  154176. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  154177. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  154178. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  154179. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  154180. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  154181. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  154182. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  154183. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  154184. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  154185. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  154186. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  154187. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  154188. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  154189. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  154190. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  154191. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  154192. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  154193. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  154194. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  154195. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  154196. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  154197. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  154198. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  154199. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  154200. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  154201. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  154202. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  154203. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  154204. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  154205. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  154206. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  154207. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  154208. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  154209. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  154210. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  154211. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  154212. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  154213. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  154214. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  154215. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  154216. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  154217. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  154218. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  154219. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  154220. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  154221. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  154222. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  154223. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  154224. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  154225. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  154226. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  154227. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  154228. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  154229. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  154230. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  154231. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  154232. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  154233. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  154234. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  154235. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  154236. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  154237. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  154238. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  154239. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  154240. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  154241. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  154242. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  154243. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  154244. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  154245. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  154246. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  154247. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  154248. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  154249. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  154250. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  154251. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  154252. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  154253. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  154254. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  154255. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  154256. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  154257. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  154258. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  154259. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  154260. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  154261. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  154262. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  154263. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  154264. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  154265. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  154266. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  154267. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  154268. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  154269. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  154270. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  154271. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  154272. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  154273. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  154274. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  154275. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  154276. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  154277. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  154278. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  154279. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  154280. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  154281. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  154282. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  154283. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  154284. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  154285. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  154286. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  154287. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  154288. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  154289. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  154290. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  154291. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  154292. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  154293. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  154294. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  154295. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  154296. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  154297. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  154298. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  154299. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  154300. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  154301. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  154302. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  154303. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  154304. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  154305. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  154306. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  154307. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  154308. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  154309. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  154310. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  154311. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  154312. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  154313. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  154314. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  154315. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  154316. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  154317. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  154318. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  154319. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  154320. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  154321. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  154322. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  154323. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  154324. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  154325. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  154326. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  154327. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  154328. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  154329. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  154330. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  154331. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  154332. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  154333. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  154334. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  154335. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  154336. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  154337. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  154338. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  154339. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  154340. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  154341. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  154342. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  154343. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  154344. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  154345. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  154346. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  154347. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  154348. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  154349. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  154350. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  154351. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  154352. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  154353. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  154354. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  154355. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  154356. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  154357. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  154358. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  154359. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  154360. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  154361. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  154362. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  154363. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  154364. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  154365. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  154366. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  154367. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  154368. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  154369. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  154370. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  154371. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  154372. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  154373. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  154374. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  154375. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  154376. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  154377. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  154378. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  154379. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  154380. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  154381. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  154382. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  154383. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  154384. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  154385. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  154386. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  154387. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  154388. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  154389. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  154390. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  154391. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  154392. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  154393. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  154394. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  154395. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  154396. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  154397. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  154398. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  154399. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  154400. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  154401. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  154402. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  154403. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  154404. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  154405. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  154406. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  154407. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  154408. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  154409. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  154410. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  154411. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  154412. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  154413. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  154414. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  154415. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  154416. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  154417. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  154418. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  154419. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  154420. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  154421. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  154422. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  154423. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  154424. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  154425. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  154426. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  154427. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  154428. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  154429. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  154430. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  154431. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  154432. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  154433. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  154434. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  154435. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  154436. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  154437. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  154438. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  154439. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  154440. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  154441. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  154442. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  154443. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  154444. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  154445. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  154446. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  154447. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  154448. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  154449. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  154450. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  154451. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  154452. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  154453. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  154454. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  154455. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  154456. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  154457. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  154458. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  154459. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  154460. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  154461. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  154462. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  154463. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  154464. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  154465. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  154466. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  154467. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  154468. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  154469. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  154470. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  154471. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  154472. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  154473. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  154474. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  154475. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  154476. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  154477. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  154478. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  154479. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  154480. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  154481. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  154482. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  154483. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  154484. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  154485. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  154486. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  154487. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  154488. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  154489. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  154490. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  154491. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  154492. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  154493. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  154494. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  154495. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  154496. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  154497. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  154498. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  154499. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  154500. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  154501. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  154502. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  154503. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  154504. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  154505. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  154506. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  154507. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  154508. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  154509. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  154510. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  154511. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  154512. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  154513. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  154514. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  154515. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  154516. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  154517. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  154518. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  154519. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  154520. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  154521. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  154522. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  154523. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  154524. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  154525. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  154526. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  154527. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  154528. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  154529. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  154530. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  154531. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  154532. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  154533. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  154534. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  154535. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  154536. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  154537. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  154538. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  154539. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  154540. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  154541. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  154542. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  154543. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  154544. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  154545. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  154546. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  154547. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  154548. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  154549. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  154550. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  154551. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  154552. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  154553. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  154554. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  154555. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  154556. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  154557. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  154558. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  154559. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  154560. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  154561. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  154562. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  154563. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  154564. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  154565. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  154566. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  154567. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  154568. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  154569. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  154570. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  154571. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  154572. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  154573. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  154574. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  154575. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  154576. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  154577. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  154578. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  154579. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  154580. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  154581. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  154582. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  154583. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  154584. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  154585. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  154586. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  154587. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  154588. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  154589. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  154590. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  154591. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  154592. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  154593. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  154594. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  154595. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  154596. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  154597. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  154598. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  154599. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  154600. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  154601. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  154602. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  154603. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  154604. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  154605. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  154606. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  154607. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  154608. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  154609. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  154610. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  154611. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  154612. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  154613. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  154614. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  154615. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  154616. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  154617. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  154618. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  154619. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  154620. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  154621. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  154622. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  154623. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  154624. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  154625. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  154626. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  154627. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  154628. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  154629. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  154630. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  154631. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  154632. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  154633. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  154634. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  154635. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  154636. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  154637. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  154638. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  154639. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  154640. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  154641. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  154642. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  154643. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  154644. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  154645. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  154646. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  154647. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  154648. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  154649. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  154650. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  154651. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  154652. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  154653. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  154654. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  154655. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  154656. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  154657. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  154658. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  154659. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  154660. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  154661. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  154662. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  154663. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  154664. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  154665. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  154666. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  154667. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  154668. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  154669. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  154670. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  154671. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  154672. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  154673. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  154674. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  154675. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  154676. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  154677. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  154678. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  154679. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  154680. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  154681. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  154682. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  154683. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  154684. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  154685. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  154686. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  154687. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  154688. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  154689. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  154690. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  154691. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  154692. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  154693. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  154694. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  154695. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  154696. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  154697. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  154698. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  154699. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  154700. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  154701. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  154702. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  154703. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  154704. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  154705. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  154706. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  154707. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  154708. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  154709. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  154710. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  154711. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  154712. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  154713. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  154714. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  154715. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  154716. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  154717. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  154718. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  154719. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  154720. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  154721. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  154722. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  154723. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  154724. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  154725. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  154726. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  154727. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  154728. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  154729. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  154730. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  154731. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  154732. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  154733. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  154734. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  154735. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  154736. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  154737. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  154738. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  154739. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  154740. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  154741. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  154742. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  154743. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  154744. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  154745. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  154746. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  154747. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  154748. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  154749. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  154750. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  154751. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  154752. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  154753. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  154754. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  154755. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  154756. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  154757. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  154758. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  154759. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  154760. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  154761. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  154762. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  154763. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  154764. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  154765. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  154766. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  154767. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  154768. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  154769. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  154770. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  154771. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  154772. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  154773. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  154774. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  154775. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  154776. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  154777. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  154778. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  154779. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  154780. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  154781. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  154782. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  154783. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  154784. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  154785. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  154786. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  154787. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  154788. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  154789. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  154790. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  154791. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  154792. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  154793. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  154794. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  154795. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  154796. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  154797. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  154798. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  154799. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  154800. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  154801. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  154802. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  154803. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  154804. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  154805. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  154806. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  154807. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  154808. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  154809. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  154810. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  154811. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  154812. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  154813. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  154814. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  154815. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  154816. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  154817. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  154818. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  154819. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  154820. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  154821. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  154822. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  154823. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  154824. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  154825. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  154826. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  154827. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  154828. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  154829. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  154830. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  154831. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  154832. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  154833. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  154834. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  154835. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  154836. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  154837. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  154838. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  154839. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  154840. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  154841. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  154842. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  154843. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  154844. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  154845. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  154846. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  154847. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  154848. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  154849. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  154850. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  154851. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  154852. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  154853. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  154854. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  154855. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  154856. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  154857. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  154858. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  154859. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  154860. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  154861. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  154862. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  154863. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  154864. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  154865. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  154866. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  154867. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  154868. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  154869. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  154870. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154871. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154872. };
  154873. static float *vwin[8] = {
  154874. vwin64,
  154875. vwin128,
  154876. vwin256,
  154877. vwin512,
  154878. vwin1024,
  154879. vwin2048,
  154880. vwin4096,
  154881. vwin8192,
  154882. };
  154883. float *_vorbis_window_get(int n){
  154884. return vwin[n];
  154885. }
  154886. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  154887. int lW,int W,int nW){
  154888. lW=(W?lW:0);
  154889. nW=(W?nW:0);
  154890. {
  154891. float *windowLW=vwin[winno[lW]];
  154892. float *windowNW=vwin[winno[nW]];
  154893. long n=blocksizes[W];
  154894. long ln=blocksizes[lW];
  154895. long rn=blocksizes[nW];
  154896. long leftbegin=n/4-ln/4;
  154897. long leftend=leftbegin+ln/2;
  154898. long rightbegin=n/2+n/4-rn/4;
  154899. long rightend=rightbegin+rn/2;
  154900. int i,p;
  154901. for(i=0;i<leftbegin;i++)
  154902. d[i]=0.f;
  154903. for(p=0;i<leftend;i++,p++)
  154904. d[i]*=windowLW[p];
  154905. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  154906. d[i]*=windowNW[p];
  154907. for(;i<n;i++)
  154908. d[i]=0.f;
  154909. }
  154910. }
  154911. #endif
  154912. /********* End of inlined file: window.c *********/
  154913. #else
  154914. #include <vorbis/vorbisenc.h>
  154915. #include <vorbis/codec.h>
  154916. #include <vorbis/vorbisfile.h>
  154917. #endif
  154918. }
  154919. BEGIN_JUCE_NAMESPACE
  154920. using namespace OggVorbisNamespace;
  154921. #define oggFormatName TRANS("Ogg-Vorbis file")
  154922. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  154923. class OggReader : public AudioFormatReader
  154924. {
  154925. OggVorbis_File ovFile;
  154926. ov_callbacks callbacks;
  154927. AudioSampleBuffer reservoir;
  154928. int reservoirStart, samplesInReservoir;
  154929. public:
  154930. OggReader (InputStream* const inp)
  154931. : AudioFormatReader (inp, oggFormatName),
  154932. reservoir (2, 4096),
  154933. reservoirStart (0),
  154934. samplesInReservoir (0)
  154935. {
  154936. sampleRate = 0;
  154937. usesFloatingPointData = true;
  154938. callbacks.read_func = &oggReadCallback;
  154939. callbacks.seek_func = &oggSeekCallback;
  154940. callbacks.close_func = &oggCloseCallback;
  154941. callbacks.tell_func = &oggTellCallback;
  154942. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  154943. if (err == 0)
  154944. {
  154945. vorbis_info* info = ov_info (&ovFile, -1);
  154946. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  154947. numChannels = info->channels;
  154948. bitsPerSample = 16;
  154949. sampleRate = info->rate;
  154950. reservoir.setSize (numChannels,
  154951. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  154952. }
  154953. }
  154954. ~OggReader()
  154955. {
  154956. ov_clear (&ovFile);
  154957. }
  154958. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  154959. int64 startSampleInFile, int numSamples)
  154960. {
  154961. while (numSamples > 0)
  154962. {
  154963. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  154964. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  154965. {
  154966. // got a few samples overlapping, so use them before seeking..
  154967. const int numToUse = jmin (numSamples, numAvailable);
  154968. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  154969. if (destSamples[i] != 0)
  154970. memcpy (destSamples[i] + startOffsetInDestBuffer,
  154971. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  154972. sizeof (float) * numToUse);
  154973. startSampleInFile += numToUse;
  154974. numSamples -= numToUse;
  154975. startOffsetInDestBuffer += numToUse;
  154976. if (numSamples == 0)
  154977. break;
  154978. }
  154979. if (startSampleInFile < reservoirStart
  154980. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  154981. {
  154982. // buffer miss, so refill the reservoir
  154983. int bitStream = 0;
  154984. reservoirStart = jmax (0, (int) startSampleInFile);
  154985. samplesInReservoir = reservoir.getNumSamples();
  154986. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  154987. ov_pcm_seek (&ovFile, reservoirStart);
  154988. int offset = 0;
  154989. int numToRead = samplesInReservoir;
  154990. while (numToRead > 0)
  154991. {
  154992. float** dataIn = 0;
  154993. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  154994. if (samps == 0)
  154995. break;
  154996. jassert (samps <= numToRead);
  154997. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  154998. {
  154999. memcpy (reservoir.getSampleData (i, offset),
  155000. dataIn[i],
  155001. sizeof (float) * samps);
  155002. }
  155003. numToRead -= samps;
  155004. offset += samps;
  155005. }
  155006. if (numToRead > 0)
  155007. reservoir.clear (offset, numToRead);
  155008. }
  155009. }
  155010. if (numSamples > 0)
  155011. {
  155012. for (int i = numDestChannels; --i >= 0;)
  155013. if (destSamples[i] != 0)
  155014. zeromem (destSamples[i] + startOffsetInDestBuffer,
  155015. sizeof (int) * numSamples);
  155016. }
  155017. return true;
  155018. }
  155019. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  155020. {
  155021. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  155022. }
  155023. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  155024. {
  155025. InputStream* const in = (InputStream*) datasource;
  155026. if (whence == SEEK_CUR)
  155027. offset += in->getPosition();
  155028. else if (whence == SEEK_END)
  155029. offset += in->getTotalLength();
  155030. in->setPosition (offset);
  155031. return 0;
  155032. }
  155033. static int oggCloseCallback (void*)
  155034. {
  155035. return 0;
  155036. }
  155037. static long oggTellCallback (void* datasource)
  155038. {
  155039. return (long) ((InputStream*) datasource)->getPosition();
  155040. }
  155041. juce_UseDebuggingNewOperator
  155042. };
  155043. class OggWriter : public AudioFormatWriter
  155044. {
  155045. ogg_stream_state os;
  155046. ogg_page og;
  155047. ogg_packet op;
  155048. vorbis_info vi;
  155049. vorbis_comment vc;
  155050. vorbis_dsp_state vd;
  155051. vorbis_block vb;
  155052. public:
  155053. bool ok;
  155054. OggWriter (OutputStream* const out,
  155055. const double sampleRate,
  155056. const int numChannels,
  155057. const int bitsPerSample,
  155058. const int qualityIndex)
  155059. : AudioFormatWriter (out, oggFormatName,
  155060. sampleRate,
  155061. numChannels,
  155062. bitsPerSample)
  155063. {
  155064. ok = false;
  155065. vorbis_info_init (&vi);
  155066. if (vorbis_encode_init_vbr (&vi,
  155067. numChannels,
  155068. (int) sampleRate,
  155069. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  155070. {
  155071. vorbis_comment_init (&vc);
  155072. if (JUCEApplication::getInstance() != 0)
  155073. vorbis_comment_add_tag (&vc, "ENCODER",
  155074. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  155075. vorbis_analysis_init (&vd, &vi);
  155076. vorbis_block_init (&vd, &vb);
  155077. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  155078. ogg_packet header;
  155079. ogg_packet header_comm;
  155080. ogg_packet header_code;
  155081. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  155082. ogg_stream_packetin (&os, &header);
  155083. ogg_stream_packetin (&os, &header_comm);
  155084. ogg_stream_packetin (&os, &header_code);
  155085. for (;;)
  155086. {
  155087. if (ogg_stream_flush (&os, &og) == 0)
  155088. break;
  155089. output->write (og.header, og.header_len);
  155090. output->write (og.body, og.body_len);
  155091. }
  155092. ok = true;
  155093. }
  155094. }
  155095. ~OggWriter()
  155096. {
  155097. if (ok)
  155098. {
  155099. // write a zero-length packet to show ogg that we're finished..
  155100. write (0, 0);
  155101. ogg_stream_clear (&os);
  155102. vorbis_block_clear (&vb);
  155103. vorbis_dsp_clear (&vd);
  155104. vorbis_comment_clear (&vc);
  155105. vorbis_info_clear (&vi);
  155106. output->flush();
  155107. }
  155108. else
  155109. {
  155110. vorbis_info_clear (&vi);
  155111. output = 0; // to stop the base class deleting this, as it needs to be returned
  155112. // to the caller of createWriter()
  155113. }
  155114. }
  155115. bool write (const int** samplesToWrite, int numSamples)
  155116. {
  155117. if (! ok)
  155118. return false;
  155119. if (numSamples > 0)
  155120. {
  155121. const double gain = 1.0 / 0x80000000u;
  155122. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  155123. for (int i = numChannels; --i >= 0;)
  155124. {
  155125. float* const dst = vorbisBuffer[i];
  155126. const int* const src = samplesToWrite [i];
  155127. if (src != 0 && dst != 0)
  155128. {
  155129. for (int j = 0; j < numSamples; ++j)
  155130. dst[j] = (float) (src[j] * gain);
  155131. }
  155132. }
  155133. }
  155134. vorbis_analysis_wrote (&vd, numSamples);
  155135. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  155136. {
  155137. vorbis_analysis (&vb, 0);
  155138. vorbis_bitrate_addblock (&vb);
  155139. while (vorbis_bitrate_flushpacket (&vd, &op))
  155140. {
  155141. ogg_stream_packetin (&os, &op);
  155142. for (;;)
  155143. {
  155144. if (ogg_stream_pageout (&os, &og) == 0)
  155145. break;
  155146. output->write (og.header, og.header_len);
  155147. output->write (og.body, og.body_len);
  155148. if (ogg_page_eos (&og))
  155149. break;
  155150. }
  155151. }
  155152. }
  155153. return true;
  155154. }
  155155. juce_UseDebuggingNewOperator
  155156. };
  155157. OggVorbisAudioFormat::OggVorbisAudioFormat()
  155158. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  155159. {
  155160. }
  155161. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  155162. {
  155163. }
  155164. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  155165. {
  155166. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  155167. return Array <int> (rates);
  155168. }
  155169. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  155170. {
  155171. Array <int> depths;
  155172. depths.add (32);
  155173. return depths;
  155174. }
  155175. bool OggVorbisAudioFormat::canDoStereo()
  155176. {
  155177. return true;
  155178. }
  155179. bool OggVorbisAudioFormat::canDoMono()
  155180. {
  155181. return true;
  155182. }
  155183. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  155184. const bool deleteStreamIfOpeningFails)
  155185. {
  155186. OggReader* r = new OggReader (in);
  155187. if (r->sampleRate == 0)
  155188. {
  155189. if (! deleteStreamIfOpeningFails)
  155190. r->input = 0;
  155191. deleteAndZero (r);
  155192. }
  155193. return r;
  155194. }
  155195. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  155196. double sampleRate,
  155197. unsigned int numChannels,
  155198. int bitsPerSample,
  155199. const StringPairArray& /*metadataValues*/,
  155200. int qualityOptionIndex)
  155201. {
  155202. OggWriter* w = new OggWriter (out,
  155203. sampleRate,
  155204. numChannels,
  155205. bitsPerSample,
  155206. qualityOptionIndex);
  155207. if (! w->ok)
  155208. deleteAndZero (w);
  155209. return w;
  155210. }
  155211. bool OggVorbisAudioFormat::isCompressed()
  155212. {
  155213. return true;
  155214. }
  155215. const StringArray OggVorbisAudioFormat::getQualityOptions()
  155216. {
  155217. StringArray s;
  155218. s.add ("Low Quality");
  155219. s.add ("Medium Quality");
  155220. s.add ("High Quality");
  155221. return s;
  155222. }
  155223. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  155224. {
  155225. FileInputStream* const in = source.createInputStream();
  155226. if (in != 0)
  155227. {
  155228. AudioFormatReader* const r = createReaderFor (in, true);
  155229. if (r != 0)
  155230. {
  155231. const int64 numSamps = r->lengthInSamples;
  155232. delete r;
  155233. const int64 fileNumSamps = source.getSize() / 4;
  155234. const double ratio = numSamps / (double) fileNumSamps;
  155235. if (ratio > 12.0)
  155236. return 0;
  155237. else if (ratio > 6.0)
  155238. return 1;
  155239. else
  155240. return 2;
  155241. }
  155242. }
  155243. return 1;
  155244. }
  155245. END_JUCE_NAMESPACE
  155246. #endif
  155247. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  155248. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  155249. #if JUCE_MSVC
  155250. #pragma warning (push)
  155251. #endif
  155252. namespace jpeglibNamespace
  155253. {
  155254. #if JUCE_INCLUDE_JPEGLIB_CODE
  155255. extern "C"
  155256. {
  155257. #define JPEG_INTERNALS
  155258. #undef FAR
  155259. /********* Start of inlined file: jpeglib.h *********/
  155260. #ifndef JPEGLIB_H
  155261. #define JPEGLIB_H
  155262. /*
  155263. * First we include the configuration files that record how this
  155264. * installation of the JPEG library is set up. jconfig.h can be
  155265. * generated automatically for many systems. jmorecfg.h contains
  155266. * manual configuration options that most people need not worry about.
  155267. */
  155268. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  155269. /********* Start of inlined file: jconfig.h *********/
  155270. /* see jconfig.doc for explanations */
  155271. // disable all the warnings under MSVC
  155272. #ifdef _MSC_VER
  155273. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155274. #endif
  155275. #ifdef __BORLANDC__
  155276. #pragma warn -8057
  155277. #pragma warn -8019
  155278. #pragma warn -8004
  155279. #pragma warn -8008
  155280. #endif
  155281. #define HAVE_PROTOTYPES
  155282. #define HAVE_UNSIGNED_CHAR
  155283. #define HAVE_UNSIGNED_SHORT
  155284. /* #define void char */
  155285. /* #define const */
  155286. #undef CHAR_IS_UNSIGNED
  155287. #define HAVE_STDDEF_H
  155288. #define HAVE_STDLIB_H
  155289. #undef NEED_BSD_STRINGS
  155290. #undef NEED_SYS_TYPES_H
  155291. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155292. #undef NEED_SHORT_EXTERNAL_NAMES
  155293. #undef INCOMPLETE_TYPES_BROKEN
  155294. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155295. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155296. typedef unsigned char boolean;
  155297. #endif
  155298. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155299. #ifdef JPEG_INTERNALS
  155300. #undef RIGHT_SHIFT_IS_UNSIGNED
  155301. #endif /* JPEG_INTERNALS */
  155302. #ifdef JPEG_CJPEG_DJPEG
  155303. #define BMP_SUPPORTED /* BMP image file format */
  155304. #define GIF_SUPPORTED /* GIF image file format */
  155305. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155306. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155307. #define TARGA_SUPPORTED /* Targa image file format */
  155308. #define TWO_FILE_COMMANDLINE /* optional */
  155309. #define USE_SETMODE /* Microsoft has setmode() */
  155310. #undef NEED_SIGNAL_CATCHER
  155311. #undef DONT_USE_B_MODE
  155312. #undef PROGRESS_REPORT /* optional */
  155313. #endif /* JPEG_CJPEG_DJPEG */
  155314. /********* End of inlined file: jconfig.h *********/
  155315. /* widely used configuration options */
  155316. #endif
  155317. /********* Start of inlined file: jmorecfg.h *********/
  155318. /*
  155319. * Define BITS_IN_JSAMPLE as either
  155320. * 8 for 8-bit sample values (the usual setting)
  155321. * 12 for 12-bit sample values
  155322. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  155323. * JPEG standard, and the IJG code does not support anything else!
  155324. * We do not support run-time selection of data precision, sorry.
  155325. */
  155326. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  155327. /*
  155328. * Maximum number of components (color channels) allowed in JPEG image.
  155329. * To meet the letter of the JPEG spec, set this to 255. However, darn
  155330. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  155331. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  155332. * really short on memory. (Each allowed component costs a hundred or so
  155333. * bytes of storage, whether actually used in an image or not.)
  155334. */
  155335. #define MAX_COMPONENTS 10 /* maximum number of image components */
  155336. /*
  155337. * Basic data types.
  155338. * You may need to change these if you have a machine with unusual data
  155339. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  155340. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  155341. * but it had better be at least 16.
  155342. */
  155343. /* Representation of a single sample (pixel element value).
  155344. * We frequently allocate large arrays of these, so it's important to keep
  155345. * them small. But if you have memory to burn and access to char or short
  155346. * arrays is very slow on your hardware, you might want to change these.
  155347. */
  155348. #if BITS_IN_JSAMPLE == 8
  155349. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  155350. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  155351. */
  155352. #ifdef HAVE_UNSIGNED_CHAR
  155353. typedef unsigned char JSAMPLE;
  155354. #define GETJSAMPLE(value) ((int) (value))
  155355. #else /* not HAVE_UNSIGNED_CHAR */
  155356. typedef char JSAMPLE;
  155357. #ifdef CHAR_IS_UNSIGNED
  155358. #define GETJSAMPLE(value) ((int) (value))
  155359. #else
  155360. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  155361. #endif /* CHAR_IS_UNSIGNED */
  155362. #endif /* HAVE_UNSIGNED_CHAR */
  155363. #define MAXJSAMPLE 255
  155364. #define CENTERJSAMPLE 128
  155365. #endif /* BITS_IN_JSAMPLE == 8 */
  155366. #if BITS_IN_JSAMPLE == 12
  155367. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  155368. * On nearly all machines "short" will do nicely.
  155369. */
  155370. typedef short JSAMPLE;
  155371. #define GETJSAMPLE(value) ((int) (value))
  155372. #define MAXJSAMPLE 4095
  155373. #define CENTERJSAMPLE 2048
  155374. #endif /* BITS_IN_JSAMPLE == 12 */
  155375. /* Representation of a DCT frequency coefficient.
  155376. * This should be a signed value of at least 16 bits; "short" is usually OK.
  155377. * Again, we allocate large arrays of these, but you can change to int
  155378. * if you have memory to burn and "short" is really slow.
  155379. */
  155380. typedef short JCOEF;
  155381. /* Compressed datastreams are represented as arrays of JOCTET.
  155382. * These must be EXACTLY 8 bits wide, at least once they are written to
  155383. * external storage. Note that when using the stdio data source/destination
  155384. * managers, this is also the data type passed to fread/fwrite.
  155385. */
  155386. #ifdef HAVE_UNSIGNED_CHAR
  155387. typedef unsigned char JOCTET;
  155388. #define GETJOCTET(value) (value)
  155389. #else /* not HAVE_UNSIGNED_CHAR */
  155390. typedef char JOCTET;
  155391. #ifdef CHAR_IS_UNSIGNED
  155392. #define GETJOCTET(value) (value)
  155393. #else
  155394. #define GETJOCTET(value) ((value) & 0xFF)
  155395. #endif /* CHAR_IS_UNSIGNED */
  155396. #endif /* HAVE_UNSIGNED_CHAR */
  155397. /* These typedefs are used for various table entries and so forth.
  155398. * They must be at least as wide as specified; but making them too big
  155399. * won't cost a huge amount of memory, so we don't provide special
  155400. * extraction code like we did for JSAMPLE. (In other words, these
  155401. * typedefs live at a different point on the speed/space tradeoff curve.)
  155402. */
  155403. /* UINT8 must hold at least the values 0..255. */
  155404. #ifdef HAVE_UNSIGNED_CHAR
  155405. typedef unsigned char UINT8;
  155406. #else /* not HAVE_UNSIGNED_CHAR */
  155407. #ifdef CHAR_IS_UNSIGNED
  155408. typedef char UINT8;
  155409. #else /* not CHAR_IS_UNSIGNED */
  155410. typedef short UINT8;
  155411. #endif /* CHAR_IS_UNSIGNED */
  155412. #endif /* HAVE_UNSIGNED_CHAR */
  155413. /* UINT16 must hold at least the values 0..65535. */
  155414. #ifdef HAVE_UNSIGNED_SHORT
  155415. typedef unsigned short UINT16;
  155416. #else /* not HAVE_UNSIGNED_SHORT */
  155417. typedef unsigned int UINT16;
  155418. #endif /* HAVE_UNSIGNED_SHORT */
  155419. /* INT16 must hold at least the values -32768..32767. */
  155420. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  155421. typedef short INT16;
  155422. #endif
  155423. /* INT32 must hold at least signed 32-bit values. */
  155424. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  155425. typedef long INT32;
  155426. #endif
  155427. /* Datatype used for image dimensions. The JPEG standard only supports
  155428. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  155429. * "unsigned int" is sufficient on all machines. However, if you need to
  155430. * handle larger images and you don't mind deviating from the spec, you
  155431. * can change this datatype.
  155432. */
  155433. typedef unsigned int JDIMENSION;
  155434. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  155435. /* These macros are used in all function definitions and extern declarations.
  155436. * You could modify them if you need to change function linkage conventions;
  155437. * in particular, you'll need to do that to make the library a Windows DLL.
  155438. * Another application is to make all functions global for use with debuggers
  155439. * or code profilers that require it.
  155440. */
  155441. /* a function called through method pointers: */
  155442. #define METHODDEF(type) static type
  155443. /* a function used only in its module: */
  155444. #define LOCAL(type) static type
  155445. /* a function referenced thru EXTERNs: */
  155446. #define GLOBAL(type) type
  155447. /* a reference to a GLOBAL function: */
  155448. #define EXTERN(type) extern type
  155449. /* This macro is used to declare a "method", that is, a function pointer.
  155450. * We want to supply prototype parameters if the compiler can cope.
  155451. * Note that the arglist parameter must be parenthesized!
  155452. * Again, you can customize this if you need special linkage keywords.
  155453. */
  155454. #ifdef HAVE_PROTOTYPES
  155455. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  155456. #else
  155457. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  155458. #endif
  155459. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  155460. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  155461. * by just saying "FAR *" where such a pointer is needed. In a few places
  155462. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  155463. */
  155464. #ifdef NEED_FAR_POINTERS
  155465. #define FAR far
  155466. #else
  155467. #define FAR
  155468. #endif
  155469. /*
  155470. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  155471. * in standard header files. Or you may have conflicts with application-
  155472. * specific header files that you want to include together with these files.
  155473. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  155474. */
  155475. #ifndef HAVE_BOOLEAN
  155476. typedef int boolean;
  155477. #endif
  155478. #ifndef FALSE /* in case these macros already exist */
  155479. #define FALSE 0 /* values of boolean */
  155480. #endif
  155481. #ifndef TRUE
  155482. #define TRUE 1
  155483. #endif
  155484. /*
  155485. * The remaining options affect code selection within the JPEG library,
  155486. * but they don't need to be visible to most applications using the library.
  155487. * To minimize application namespace pollution, the symbols won't be
  155488. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  155489. */
  155490. #ifdef JPEG_INTERNALS
  155491. #define JPEG_INTERNAL_OPTIONS
  155492. #endif
  155493. #ifdef JPEG_INTERNAL_OPTIONS
  155494. /*
  155495. * These defines indicate whether to include various optional functions.
  155496. * Undefining some of these symbols will produce a smaller but less capable
  155497. * library. Note that you can leave certain source files out of the
  155498. * compilation/linking process if you've #undef'd the corresponding symbols.
  155499. * (You may HAVE to do that if your compiler doesn't like null source files.)
  155500. */
  155501. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  155502. /* Capability options common to encoder and decoder: */
  155503. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  155504. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  155505. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  155506. /* Encoder capability options: */
  155507. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155508. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155509. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155510. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  155511. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  155512. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  155513. * precision, so jchuff.c normally uses entropy optimization to compute
  155514. * usable tables for higher precision. If you don't want to do optimization,
  155515. * you'll have to supply different default Huffman tables.
  155516. * The exact same statements apply for progressive JPEG: the default tables
  155517. * don't work for progressive mode. (This may get fixed, however.)
  155518. */
  155519. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  155520. /* Decoder capability options: */
  155521. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155522. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155523. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155524. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  155525. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  155526. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  155527. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  155528. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  155529. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  155530. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  155531. /* more capability options later, no doubt */
  155532. /*
  155533. * Ordering of RGB data in scanlines passed to or from the application.
  155534. * If your application wants to deal with data in the order B,G,R, just
  155535. * change these macros. You can also deal with formats such as R,G,B,X
  155536. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  155537. * the offsets will also change the order in which colormap data is organized.
  155538. * RESTRICTIONS:
  155539. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  155540. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  155541. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  155542. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  155543. * is not 3 (they don't understand about dummy color components!). So you
  155544. * can't use color quantization if you change that value.
  155545. */
  155546. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  155547. #define RGB_GREEN 1 /* Offset of Green */
  155548. #define RGB_BLUE 2 /* Offset of Blue */
  155549. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  155550. /* Definitions for speed-related optimizations. */
  155551. /* If your compiler supports inline functions, define INLINE
  155552. * as the inline keyword; otherwise define it as empty.
  155553. */
  155554. #ifndef INLINE
  155555. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  155556. #define INLINE __inline__
  155557. #endif
  155558. #ifndef INLINE
  155559. #define INLINE /* default is to define it as empty */
  155560. #endif
  155561. #endif
  155562. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  155563. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  155564. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  155565. */
  155566. #ifndef MULTIPLIER
  155567. #define MULTIPLIER int /* type for fastest integer multiply */
  155568. #endif
  155569. /* FAST_FLOAT should be either float or double, whichever is done faster
  155570. * by your compiler. (Note that this type is only used in the floating point
  155571. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  155572. * Typically, float is faster in ANSI C compilers, while double is faster in
  155573. * pre-ANSI compilers (because they insist on converting to double anyway).
  155574. * The code below therefore chooses float if we have ANSI-style prototypes.
  155575. */
  155576. #ifndef FAST_FLOAT
  155577. #ifdef HAVE_PROTOTYPES
  155578. #define FAST_FLOAT float
  155579. #else
  155580. #define FAST_FLOAT double
  155581. #endif
  155582. #endif
  155583. #endif /* JPEG_INTERNAL_OPTIONS */
  155584. /********* End of inlined file: jmorecfg.h *********/
  155585. /* seldom changed options */
  155586. /* Version ID for the JPEG library.
  155587. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  155588. */
  155589. #define JPEG_LIB_VERSION 62 /* Version 6b */
  155590. /* Various constants determining the sizes of things.
  155591. * All of these are specified by the JPEG standard, so don't change them
  155592. * if you want to be compatible.
  155593. */
  155594. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  155595. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  155596. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  155597. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  155598. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  155599. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  155600. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  155601. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  155602. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  155603. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  155604. * to handle it. We even let you do this from the jconfig.h file. However,
  155605. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  155606. * sometimes emits noncompliant files doesn't mean you should too.
  155607. */
  155608. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  155609. #ifndef D_MAX_BLOCKS_IN_MCU
  155610. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  155611. #endif
  155612. /* Data structures for images (arrays of samples and of DCT coefficients).
  155613. * On 80x86 machines, the image arrays are too big for near pointers,
  155614. * but the pointer arrays can fit in near memory.
  155615. */
  155616. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  155617. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  155618. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  155619. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  155620. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  155621. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  155622. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  155623. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  155624. /* Types for JPEG compression parameters and working tables. */
  155625. /* DCT coefficient quantization tables. */
  155626. typedef struct {
  155627. /* This array gives the coefficient quantizers in natural array order
  155628. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  155629. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  155630. */
  155631. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  155632. /* This field is used only during compression. It's initialized FALSE when
  155633. * the table is created, and set TRUE when it's been output to the file.
  155634. * You could suppress output of a table by setting this to TRUE.
  155635. * (See jpeg_suppress_tables for an example.)
  155636. */
  155637. boolean sent_table; /* TRUE when table has been output */
  155638. } JQUANT_TBL;
  155639. /* Huffman coding tables. */
  155640. typedef struct {
  155641. /* These two fields directly represent the contents of a JPEG DHT marker */
  155642. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  155643. /* length k bits; bits[0] is unused */
  155644. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  155645. /* This field is used only during compression. It's initialized FALSE when
  155646. * the table is created, and set TRUE when it's been output to the file.
  155647. * You could suppress output of a table by setting this to TRUE.
  155648. * (See jpeg_suppress_tables for an example.)
  155649. */
  155650. boolean sent_table; /* TRUE when table has been output */
  155651. } JHUFF_TBL;
  155652. /* Basic info about one component (color channel). */
  155653. typedef struct {
  155654. /* These values are fixed over the whole image. */
  155655. /* For compression, they must be supplied by parameter setup; */
  155656. /* for decompression, they are read from the SOF marker. */
  155657. int component_id; /* identifier for this component (0..255) */
  155658. int component_index; /* its index in SOF or cinfo->comp_info[] */
  155659. int h_samp_factor; /* horizontal sampling factor (1..4) */
  155660. int v_samp_factor; /* vertical sampling factor (1..4) */
  155661. int quant_tbl_no; /* quantization table selector (0..3) */
  155662. /* These values may vary between scans. */
  155663. /* For compression, they must be supplied by parameter setup; */
  155664. /* for decompression, they are read from the SOS marker. */
  155665. /* The decompressor output side may not use these variables. */
  155666. int dc_tbl_no; /* DC entropy table selector (0..3) */
  155667. int ac_tbl_no; /* AC entropy table selector (0..3) */
  155668. /* Remaining fields should be treated as private by applications. */
  155669. /* These values are computed during compression or decompression startup: */
  155670. /* Component's size in DCT blocks.
  155671. * Any dummy blocks added to complete an MCU are not counted; therefore
  155672. * these values do not depend on whether a scan is interleaved or not.
  155673. */
  155674. JDIMENSION width_in_blocks;
  155675. JDIMENSION height_in_blocks;
  155676. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  155677. * For decompression this is the size of the output from one DCT block,
  155678. * reflecting any scaling we choose to apply during the IDCT step.
  155679. * Values of 1,2,4,8 are likely to be supported. Note that different
  155680. * components may receive different IDCT scalings.
  155681. */
  155682. int DCT_scaled_size;
  155683. /* The downsampled dimensions are the component's actual, unpadded number
  155684. * of samples at the main buffer (preprocessing/compression interface), thus
  155685. * downsampled_width = ceil(image_width * Hi/Hmax)
  155686. * and similarly for height. For decompression, IDCT scaling is included, so
  155687. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  155688. */
  155689. JDIMENSION downsampled_width; /* actual width in samples */
  155690. JDIMENSION downsampled_height; /* actual height in samples */
  155691. /* This flag is used only for decompression. In cases where some of the
  155692. * components will be ignored (eg grayscale output from YCbCr image),
  155693. * we can skip most computations for the unused components.
  155694. */
  155695. boolean component_needed; /* do we need the value of this component? */
  155696. /* These values are computed before starting a scan of the component. */
  155697. /* The decompressor output side may not use these variables. */
  155698. int MCU_width; /* number of blocks per MCU, horizontally */
  155699. int MCU_height; /* number of blocks per MCU, vertically */
  155700. int MCU_blocks; /* MCU_width * MCU_height */
  155701. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  155702. int last_col_width; /* # of non-dummy blocks across in last MCU */
  155703. int last_row_height; /* # of non-dummy blocks down in last MCU */
  155704. /* Saved quantization table for component; NULL if none yet saved.
  155705. * See jdinput.c comments about the need for this information.
  155706. * This field is currently used only for decompression.
  155707. */
  155708. JQUANT_TBL * quant_table;
  155709. /* Private per-component storage for DCT or IDCT subsystem. */
  155710. void * dct_table;
  155711. } jpeg_component_info;
  155712. /* The script for encoding a multiple-scan file is an array of these: */
  155713. typedef struct {
  155714. int comps_in_scan; /* number of components encoded in this scan */
  155715. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  155716. int Ss, Se; /* progressive JPEG spectral selection parms */
  155717. int Ah, Al; /* progressive JPEG successive approx. parms */
  155718. } jpeg_scan_info;
  155719. /* The decompressor can save APPn and COM markers in a list of these: */
  155720. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  155721. struct jpeg_marker_struct {
  155722. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  155723. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  155724. unsigned int original_length; /* # bytes of data in the file */
  155725. unsigned int data_length; /* # bytes of data saved at data[] */
  155726. JOCTET FAR * data; /* the data contained in the marker */
  155727. /* the marker length word is not counted in data_length or original_length */
  155728. };
  155729. /* Known color spaces. */
  155730. typedef enum {
  155731. JCS_UNKNOWN, /* error/unspecified */
  155732. JCS_GRAYSCALE, /* monochrome */
  155733. JCS_RGB, /* red/green/blue */
  155734. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  155735. JCS_CMYK, /* C/M/Y/K */
  155736. JCS_YCCK /* Y/Cb/Cr/K */
  155737. } J_COLOR_SPACE;
  155738. /* DCT/IDCT algorithm options. */
  155739. typedef enum {
  155740. JDCT_ISLOW, /* slow but accurate integer algorithm */
  155741. JDCT_IFAST, /* faster, less accurate integer method */
  155742. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  155743. } J_DCT_METHOD;
  155744. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  155745. #define JDCT_DEFAULT JDCT_ISLOW
  155746. #endif
  155747. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  155748. #define JDCT_FASTEST JDCT_IFAST
  155749. #endif
  155750. /* Dithering options for decompression. */
  155751. typedef enum {
  155752. JDITHER_NONE, /* no dithering */
  155753. JDITHER_ORDERED, /* simple ordered dither */
  155754. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  155755. } J_DITHER_MODE;
  155756. /* Common fields between JPEG compression and decompression master structs. */
  155757. #define jpeg_common_fields \
  155758. struct jpeg_error_mgr * err; /* Error handler module */\
  155759. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  155760. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  155761. void * client_data; /* Available for use by application */\
  155762. boolean is_decompressor; /* So common code can tell which is which */\
  155763. int global_state /* For checking call sequence validity */
  155764. /* Routines that are to be used by both halves of the library are declared
  155765. * to receive a pointer to this structure. There are no actual instances of
  155766. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  155767. */
  155768. struct jpeg_common_struct {
  155769. jpeg_common_fields; /* Fields common to both master struct types */
  155770. /* Additional fields follow in an actual jpeg_compress_struct or
  155771. * jpeg_decompress_struct. All three structs must agree on these
  155772. * initial fields! (This would be a lot cleaner in C++.)
  155773. */
  155774. };
  155775. typedef struct jpeg_common_struct * j_common_ptr;
  155776. typedef struct jpeg_compress_struct * j_compress_ptr;
  155777. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  155778. /* Master record for a compression instance */
  155779. struct jpeg_compress_struct {
  155780. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  155781. /* Destination for compressed data */
  155782. struct jpeg_destination_mgr * dest;
  155783. /* Description of source image --- these fields must be filled in by
  155784. * outer application before starting compression. in_color_space must
  155785. * be correct before you can even call jpeg_set_defaults().
  155786. */
  155787. JDIMENSION image_width; /* input image width */
  155788. JDIMENSION image_height; /* input image height */
  155789. int input_components; /* # of color components in input image */
  155790. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  155791. double input_gamma; /* image gamma of input image */
  155792. /* Compression parameters --- these fields must be set before calling
  155793. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  155794. * initialize everything to reasonable defaults, then changing anything
  155795. * the application specifically wants to change. That way you won't get
  155796. * burnt when new parameters are added. Also note that there are several
  155797. * helper routines to simplify changing parameters.
  155798. */
  155799. int data_precision; /* bits of precision in image data */
  155800. int num_components; /* # of color components in JPEG image */
  155801. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155802. jpeg_component_info * comp_info;
  155803. /* comp_info[i] describes component that appears i'th in SOF */
  155804. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155805. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155806. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155807. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155808. /* ptrs to Huffman coding tables, or NULL if not defined */
  155809. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155810. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155811. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155812. int num_scans; /* # of entries in scan_info array */
  155813. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  155814. /* The default value of scan_info is NULL, which causes a single-scan
  155815. * sequential JPEG file to be emitted. To create a multi-scan file,
  155816. * set num_scans and scan_info to point to an array of scan definitions.
  155817. */
  155818. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  155819. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155820. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  155821. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155822. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  155823. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  155824. /* The restart interval can be specified in absolute MCUs by setting
  155825. * restart_interval, or in MCU rows by setting restart_in_rows
  155826. * (in which case the correct restart_interval will be figured
  155827. * for each scan).
  155828. */
  155829. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  155830. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  155831. /* Parameters controlling emission of special markers. */
  155832. boolean write_JFIF_header; /* should a JFIF marker be written? */
  155833. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  155834. UINT8 JFIF_minor_version;
  155835. /* These three values are not used by the JPEG code, merely copied */
  155836. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  155837. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  155838. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  155839. UINT8 density_unit; /* JFIF code for pixel size units */
  155840. UINT16 X_density; /* Horizontal pixel density */
  155841. UINT16 Y_density; /* Vertical pixel density */
  155842. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  155843. /* State variable: index of next scanline to be written to
  155844. * jpeg_write_scanlines(). Application may use this to control its
  155845. * processing loop, e.g., "while (next_scanline < image_height)".
  155846. */
  155847. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  155848. /* Remaining fields are known throughout compressor, but generally
  155849. * should not be touched by a surrounding application.
  155850. */
  155851. /*
  155852. * These fields are computed during compression startup
  155853. */
  155854. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  155855. int max_h_samp_factor; /* largest h_samp_factor */
  155856. int max_v_samp_factor; /* largest v_samp_factor */
  155857. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  155858. /* The coefficient controller receives data in units of MCU rows as defined
  155859. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  155860. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  155861. * "iMCU" (interleaved MCU) row.
  155862. */
  155863. /*
  155864. * These fields are valid during any one scan.
  155865. * They describe the components and MCUs actually appearing in the scan.
  155866. */
  155867. int comps_in_scan; /* # of JPEG components in this scan */
  155868. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155869. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155870. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155871. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155872. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155873. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  155874. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155875. /* i'th block in an MCU */
  155876. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155877. /*
  155878. * Links to compression subobjects (methods and private variables of modules)
  155879. */
  155880. struct jpeg_comp_master * master;
  155881. struct jpeg_c_main_controller * main;
  155882. struct jpeg_c_prep_controller * prep;
  155883. struct jpeg_c_coef_controller * coef;
  155884. struct jpeg_marker_writer * marker;
  155885. struct jpeg_color_converter * cconvert;
  155886. struct jpeg_downsampler * downsample;
  155887. struct jpeg_forward_dct * fdct;
  155888. struct jpeg_entropy_encoder * entropy;
  155889. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  155890. int script_space_size;
  155891. };
  155892. /* Master record for a decompression instance */
  155893. struct jpeg_decompress_struct {
  155894. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  155895. /* Source of compressed data */
  155896. struct jpeg_source_mgr * src;
  155897. /* Basic description of image --- filled in by jpeg_read_header(). */
  155898. /* Application may inspect these values to decide how to process image. */
  155899. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  155900. JDIMENSION image_height; /* nominal image height */
  155901. int num_components; /* # of color components in JPEG image */
  155902. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155903. /* Decompression processing parameters --- these fields must be set before
  155904. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  155905. * them to default values.
  155906. */
  155907. J_COLOR_SPACE out_color_space; /* colorspace for output */
  155908. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  155909. double output_gamma; /* image gamma wanted in output */
  155910. boolean buffered_image; /* TRUE=multiple output passes */
  155911. boolean raw_data_out; /* TRUE=downsampled data wanted */
  155912. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  155913. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  155914. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  155915. boolean quantize_colors; /* TRUE=colormapped output wanted */
  155916. /* the following are ignored if not quantize_colors: */
  155917. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  155918. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  155919. int desired_number_of_colors; /* max # colors to use in created colormap */
  155920. /* these are significant only in buffered-image mode: */
  155921. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  155922. boolean enable_external_quant;/* enable future use of external colormap */
  155923. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  155924. /* Description of actual output image that will be returned to application.
  155925. * These fields are computed by jpeg_start_decompress().
  155926. * You can also use jpeg_calc_output_dimensions() to determine these values
  155927. * in advance of calling jpeg_start_decompress().
  155928. */
  155929. JDIMENSION output_width; /* scaled image width */
  155930. JDIMENSION output_height; /* scaled image height */
  155931. int out_color_components; /* # of color components in out_color_space */
  155932. int output_components; /* # of color components returned */
  155933. /* output_components is 1 (a colormap index) when quantizing colors;
  155934. * otherwise it equals out_color_components.
  155935. */
  155936. int rec_outbuf_height; /* min recommended height of scanline buffer */
  155937. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  155938. * high, space and time will be wasted due to unnecessary data copying.
  155939. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  155940. */
  155941. /* When quantizing colors, the output colormap is described by these fields.
  155942. * The application can supply a colormap by setting colormap non-NULL before
  155943. * calling jpeg_start_decompress; otherwise a colormap is created during
  155944. * jpeg_start_decompress or jpeg_start_output.
  155945. * The map has out_color_components rows and actual_number_of_colors columns.
  155946. */
  155947. int actual_number_of_colors; /* number of entries in use */
  155948. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  155949. /* State variables: these variables indicate the progress of decompression.
  155950. * The application may examine these but must not modify them.
  155951. */
  155952. /* Row index of next scanline to be read from jpeg_read_scanlines().
  155953. * Application may use this to control its processing loop, e.g.,
  155954. * "while (output_scanline < output_height)".
  155955. */
  155956. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  155957. /* Current input scan number and number of iMCU rows completed in scan.
  155958. * These indicate the progress of the decompressor input side.
  155959. */
  155960. int input_scan_number; /* Number of SOS markers seen so far */
  155961. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  155962. /* The "output scan number" is the notional scan being displayed by the
  155963. * output side. The decompressor will not allow output scan/row number
  155964. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  155965. */
  155966. int output_scan_number; /* Nominal scan number being displayed */
  155967. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  155968. /* Current progression status. coef_bits[c][i] indicates the precision
  155969. * with which component c's DCT coefficient i (in zigzag order) is known.
  155970. * It is -1 when no data has yet been received, otherwise it is the point
  155971. * transform (shift) value for the most recent scan of the coefficient
  155972. * (thus, 0 at completion of the progression).
  155973. * This pointer is NULL when reading a non-progressive file.
  155974. */
  155975. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  155976. /* Internal JPEG parameters --- the application usually need not look at
  155977. * these fields. Note that the decompressor output side may not use
  155978. * any parameters that can change between scans.
  155979. */
  155980. /* Quantization and Huffman tables are carried forward across input
  155981. * datastreams when processing abbreviated JPEG datastreams.
  155982. */
  155983. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155984. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155985. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155986. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155987. /* ptrs to Huffman coding tables, or NULL if not defined */
  155988. /* These parameters are never carried across datastreams, since they
  155989. * are given in SOF/SOS markers or defined to be reset by SOI.
  155990. */
  155991. int data_precision; /* bits of precision in image data */
  155992. jpeg_component_info * comp_info;
  155993. /* comp_info[i] describes component that appears i'th in SOF */
  155994. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  155995. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155996. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155997. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155998. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155999. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  156000. /* These fields record data obtained from optional markers recognized by
  156001. * the JPEG library.
  156002. */
  156003. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  156004. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  156005. UINT8 JFIF_major_version; /* JFIF version number */
  156006. UINT8 JFIF_minor_version;
  156007. UINT8 density_unit; /* JFIF code for pixel size units */
  156008. UINT16 X_density; /* Horizontal pixel density */
  156009. UINT16 Y_density; /* Vertical pixel density */
  156010. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  156011. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  156012. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  156013. /* Aside from the specific data retained from APPn markers known to the
  156014. * library, the uninterpreted contents of any or all APPn and COM markers
  156015. * can be saved in a list for examination by the application.
  156016. */
  156017. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  156018. /* Remaining fields are known throughout decompressor, but generally
  156019. * should not be touched by a surrounding application.
  156020. */
  156021. /*
  156022. * These fields are computed during decompression startup
  156023. */
  156024. int max_h_samp_factor; /* largest h_samp_factor */
  156025. int max_v_samp_factor; /* largest v_samp_factor */
  156026. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  156027. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  156028. /* The coefficient controller's input and output progress is measured in
  156029. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  156030. * in fully interleaved JPEG scans, but are used whether the scan is
  156031. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  156032. * rows of each component. Therefore, the IDCT output contains
  156033. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  156034. */
  156035. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  156036. /*
  156037. * These fields are valid during any one scan.
  156038. * They describe the components and MCUs actually appearing in the scan.
  156039. * Note that the decompressor output side must not use these fields.
  156040. */
  156041. int comps_in_scan; /* # of JPEG components in this scan */
  156042. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  156043. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  156044. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  156045. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  156046. int blocks_in_MCU; /* # of DCT blocks per MCU */
  156047. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  156048. /* MCU_membership[i] is index in cur_comp_info of component owning */
  156049. /* i'th block in an MCU */
  156050. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  156051. /* This field is shared between entropy decoder and marker parser.
  156052. * It is either zero or the code of a JPEG marker that has been
  156053. * read from the data source, but has not yet been processed.
  156054. */
  156055. int unread_marker;
  156056. /*
  156057. * Links to decompression subobjects (methods, private variables of modules)
  156058. */
  156059. struct jpeg_decomp_master * master;
  156060. struct jpeg_d_main_controller * main;
  156061. struct jpeg_d_coef_controller * coef;
  156062. struct jpeg_d_post_controller * post;
  156063. struct jpeg_input_controller * inputctl;
  156064. struct jpeg_marker_reader * marker;
  156065. struct jpeg_entropy_decoder * entropy;
  156066. struct jpeg_inverse_dct * idct;
  156067. struct jpeg_upsampler * upsample;
  156068. struct jpeg_color_deconverter * cconvert;
  156069. struct jpeg_color_quantizer * cquantize;
  156070. };
  156071. /* "Object" declarations for JPEG modules that may be supplied or called
  156072. * directly by the surrounding application.
  156073. * As with all objects in the JPEG library, these structs only define the
  156074. * publicly visible methods and state variables of a module. Additional
  156075. * private fields may exist after the public ones.
  156076. */
  156077. /* Error handler object */
  156078. struct jpeg_error_mgr {
  156079. /* Error exit handler: does not return to caller */
  156080. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  156081. /* Conditionally emit a trace or warning message */
  156082. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  156083. /* Routine that actually outputs a trace or error message */
  156084. JMETHOD(void, output_message, (j_common_ptr cinfo));
  156085. /* Format a message string for the most recent JPEG error or message */
  156086. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  156087. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  156088. /* Reset error state variables at start of a new image */
  156089. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  156090. /* The message ID code and any parameters are saved here.
  156091. * A message can have one string parameter or up to 8 int parameters.
  156092. */
  156093. int msg_code;
  156094. #define JMSG_STR_PARM_MAX 80
  156095. union {
  156096. int i[8];
  156097. char s[JMSG_STR_PARM_MAX];
  156098. } msg_parm;
  156099. /* Standard state variables for error facility */
  156100. int trace_level; /* max msg_level that will be displayed */
  156101. /* For recoverable corrupt-data errors, we emit a warning message,
  156102. * but keep going unless emit_message chooses to abort. emit_message
  156103. * should count warnings in num_warnings. The surrounding application
  156104. * can check for bad data by seeing if num_warnings is nonzero at the
  156105. * end of processing.
  156106. */
  156107. long num_warnings; /* number of corrupt-data warnings */
  156108. /* These fields point to the table(s) of error message strings.
  156109. * An application can change the table pointer to switch to a different
  156110. * message list (typically, to change the language in which errors are
  156111. * reported). Some applications may wish to add additional error codes
  156112. * that will be handled by the JPEG library error mechanism; the second
  156113. * table pointer is used for this purpose.
  156114. *
  156115. * First table includes all errors generated by JPEG library itself.
  156116. * Error code 0 is reserved for a "no such error string" message.
  156117. */
  156118. const char * const * jpeg_message_table; /* Library errors */
  156119. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  156120. /* Second table can be added by application (see cjpeg/djpeg for example).
  156121. * It contains strings numbered first_addon_message..last_addon_message.
  156122. */
  156123. const char * const * addon_message_table; /* Non-library errors */
  156124. int first_addon_message; /* code for first string in addon table */
  156125. int last_addon_message; /* code for last string in addon table */
  156126. };
  156127. /* Progress monitor object */
  156128. struct jpeg_progress_mgr {
  156129. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  156130. long pass_counter; /* work units completed in this pass */
  156131. long pass_limit; /* total number of work units in this pass */
  156132. int completed_passes; /* passes completed so far */
  156133. int total_passes; /* total number of passes expected */
  156134. };
  156135. /* Data destination object for compression */
  156136. struct jpeg_destination_mgr {
  156137. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156138. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156139. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  156140. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  156141. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  156142. };
  156143. /* Data source object for decompression */
  156144. struct jpeg_source_mgr {
  156145. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  156146. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  156147. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  156148. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  156149. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  156150. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  156151. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  156152. };
  156153. /* Memory manager object.
  156154. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  156155. * and "really big" objects (virtual arrays with backing store if needed).
  156156. * The memory manager does not allow individual objects to be freed; rather,
  156157. * each created object is assigned to a pool, and whole pools can be freed
  156158. * at once. This is faster and more convenient than remembering exactly what
  156159. * to free, especially where malloc()/free() are not too speedy.
  156160. * NB: alloc routines never return NULL. They exit to error_exit if not
  156161. * successful.
  156162. */
  156163. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  156164. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  156165. #define JPOOL_NUMPOOLS 2
  156166. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  156167. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  156168. struct jpeg_memory_mgr {
  156169. /* Method pointers */
  156170. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  156171. size_t sizeofobject));
  156172. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  156173. size_t sizeofobject));
  156174. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  156175. JDIMENSION samplesperrow,
  156176. JDIMENSION numrows));
  156177. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  156178. JDIMENSION blocksperrow,
  156179. JDIMENSION numrows));
  156180. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  156181. int pool_id,
  156182. boolean pre_zero,
  156183. JDIMENSION samplesperrow,
  156184. JDIMENSION numrows,
  156185. JDIMENSION maxaccess));
  156186. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  156187. int pool_id,
  156188. boolean pre_zero,
  156189. JDIMENSION blocksperrow,
  156190. JDIMENSION numrows,
  156191. JDIMENSION maxaccess));
  156192. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  156193. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  156194. jvirt_sarray_ptr ptr,
  156195. JDIMENSION start_row,
  156196. JDIMENSION num_rows,
  156197. boolean writable));
  156198. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  156199. jvirt_barray_ptr ptr,
  156200. JDIMENSION start_row,
  156201. JDIMENSION num_rows,
  156202. boolean writable));
  156203. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  156204. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  156205. /* Limit on memory allocation for this JPEG object. (Note that this is
  156206. * merely advisory, not a guaranteed maximum; it only affects the space
  156207. * used for virtual-array buffers.) May be changed by outer application
  156208. * after creating the JPEG object.
  156209. */
  156210. long max_memory_to_use;
  156211. /* Maximum allocation request accepted by alloc_large. */
  156212. long max_alloc_chunk;
  156213. };
  156214. /* Routine signature for application-supplied marker processing methods.
  156215. * Need not pass marker code since it is stored in cinfo->unread_marker.
  156216. */
  156217. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  156218. /* Declarations for routines called by application.
  156219. * The JPP macro hides prototype parameters from compilers that can't cope.
  156220. * Note JPP requires double parentheses.
  156221. */
  156222. #ifdef HAVE_PROTOTYPES
  156223. #define JPP(arglist) arglist
  156224. #else
  156225. #define JPP(arglist) ()
  156226. #endif
  156227. /* Short forms of external names for systems with brain-damaged linkers.
  156228. * We shorten external names to be unique in the first six letters, which
  156229. * is good enough for all known systems.
  156230. * (If your compiler itself needs names to be unique in less than 15
  156231. * characters, you are out of luck. Get a better compiler.)
  156232. */
  156233. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156234. #define jpeg_std_error jStdError
  156235. #define jpeg_CreateCompress jCreaCompress
  156236. #define jpeg_CreateDecompress jCreaDecompress
  156237. #define jpeg_destroy_compress jDestCompress
  156238. #define jpeg_destroy_decompress jDestDecompress
  156239. #define jpeg_stdio_dest jStdDest
  156240. #define jpeg_stdio_src jStdSrc
  156241. #define jpeg_set_defaults jSetDefaults
  156242. #define jpeg_set_colorspace jSetColorspace
  156243. #define jpeg_default_colorspace jDefColorspace
  156244. #define jpeg_set_quality jSetQuality
  156245. #define jpeg_set_linear_quality jSetLQuality
  156246. #define jpeg_add_quant_table jAddQuantTable
  156247. #define jpeg_quality_scaling jQualityScaling
  156248. #define jpeg_simple_progression jSimProgress
  156249. #define jpeg_suppress_tables jSuppressTables
  156250. #define jpeg_alloc_quant_table jAlcQTable
  156251. #define jpeg_alloc_huff_table jAlcHTable
  156252. #define jpeg_start_compress jStrtCompress
  156253. #define jpeg_write_scanlines jWrtScanlines
  156254. #define jpeg_finish_compress jFinCompress
  156255. #define jpeg_write_raw_data jWrtRawData
  156256. #define jpeg_write_marker jWrtMarker
  156257. #define jpeg_write_m_header jWrtMHeader
  156258. #define jpeg_write_m_byte jWrtMByte
  156259. #define jpeg_write_tables jWrtTables
  156260. #define jpeg_read_header jReadHeader
  156261. #define jpeg_start_decompress jStrtDecompress
  156262. #define jpeg_read_scanlines jReadScanlines
  156263. #define jpeg_finish_decompress jFinDecompress
  156264. #define jpeg_read_raw_data jReadRawData
  156265. #define jpeg_has_multiple_scans jHasMultScn
  156266. #define jpeg_start_output jStrtOutput
  156267. #define jpeg_finish_output jFinOutput
  156268. #define jpeg_input_complete jInComplete
  156269. #define jpeg_new_colormap jNewCMap
  156270. #define jpeg_consume_input jConsumeInput
  156271. #define jpeg_calc_output_dimensions jCalcDimensions
  156272. #define jpeg_save_markers jSaveMarkers
  156273. #define jpeg_set_marker_processor jSetMarker
  156274. #define jpeg_read_coefficients jReadCoefs
  156275. #define jpeg_write_coefficients jWrtCoefs
  156276. #define jpeg_copy_critical_parameters jCopyCrit
  156277. #define jpeg_abort_compress jAbrtCompress
  156278. #define jpeg_abort_decompress jAbrtDecompress
  156279. #define jpeg_abort jAbort
  156280. #define jpeg_destroy jDestroy
  156281. #define jpeg_resync_to_restart jResyncRestart
  156282. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156283. /* Default error-management setup */
  156284. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  156285. JPP((struct jpeg_error_mgr * err));
  156286. /* Initialization of JPEG compression objects.
  156287. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  156288. * names that applications should call. These expand to calls on
  156289. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  156290. * passed for version mismatch checking.
  156291. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  156292. */
  156293. #define jpeg_create_compress(cinfo) \
  156294. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  156295. (size_t) sizeof(struct jpeg_compress_struct))
  156296. #define jpeg_create_decompress(cinfo) \
  156297. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  156298. (size_t) sizeof(struct jpeg_decompress_struct))
  156299. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  156300. int version, size_t structsize));
  156301. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  156302. int version, size_t structsize));
  156303. /* Destruction of JPEG compression objects */
  156304. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  156305. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  156306. /* Standard data source and destination managers: stdio streams. */
  156307. /* Caller is responsible for opening the file before and closing after. */
  156308. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  156309. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  156310. /* Default parameter setup for compression */
  156311. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  156312. /* Compression parameter setup aids */
  156313. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  156314. J_COLOR_SPACE colorspace));
  156315. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  156316. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  156317. boolean force_baseline));
  156318. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  156319. int scale_factor,
  156320. boolean force_baseline));
  156321. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  156322. const unsigned int *basic_table,
  156323. int scale_factor,
  156324. boolean force_baseline));
  156325. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  156326. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  156327. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  156328. boolean suppress));
  156329. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  156330. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  156331. /* Main entry points for compression */
  156332. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  156333. boolean write_all_tables));
  156334. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  156335. JSAMPARRAY scanlines,
  156336. JDIMENSION num_lines));
  156337. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  156338. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  156339. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  156340. JSAMPIMAGE data,
  156341. JDIMENSION num_lines));
  156342. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  156343. EXTERN(void) jpeg_write_marker
  156344. JPP((j_compress_ptr cinfo, int marker,
  156345. const JOCTET * dataptr, unsigned int datalen));
  156346. /* Same, but piecemeal. */
  156347. EXTERN(void) jpeg_write_m_header
  156348. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  156349. EXTERN(void) jpeg_write_m_byte
  156350. JPP((j_compress_ptr cinfo, int val));
  156351. /* Alternate compression function: just write an abbreviated table file */
  156352. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  156353. /* Decompression startup: read start of JPEG datastream to see what's there */
  156354. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  156355. boolean require_image));
  156356. /* Return value is one of: */
  156357. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  156358. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  156359. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  156360. /* If you pass require_image = TRUE (normal case), you need not check for
  156361. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  156362. * JPEG_SUSPENDED is only possible if you use a data source module that can
  156363. * give a suspension return (the stdio source module doesn't).
  156364. */
  156365. /* Main entry points for decompression */
  156366. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  156367. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  156368. JSAMPARRAY scanlines,
  156369. JDIMENSION max_lines));
  156370. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  156371. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  156372. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  156373. JSAMPIMAGE data,
  156374. JDIMENSION max_lines));
  156375. /* Additional entry points for buffered-image mode. */
  156376. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  156377. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  156378. int scan_number));
  156379. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  156380. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  156381. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  156382. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  156383. /* Return value is one of: */
  156384. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  156385. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  156386. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  156387. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  156388. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  156389. /* Precalculate output dimensions for current decompression parameters. */
  156390. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  156391. /* Control saving of COM and APPn markers into marker_list. */
  156392. EXTERN(void) jpeg_save_markers
  156393. JPP((j_decompress_ptr cinfo, int marker_code,
  156394. unsigned int length_limit));
  156395. /* Install a special processing method for COM or APPn markers. */
  156396. EXTERN(void) jpeg_set_marker_processor
  156397. JPP((j_decompress_ptr cinfo, int marker_code,
  156398. jpeg_marker_parser_method routine));
  156399. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  156400. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  156401. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  156402. jvirt_barray_ptr * coef_arrays));
  156403. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  156404. j_compress_ptr dstinfo));
  156405. /* If you choose to abort compression or decompression before completing
  156406. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  156407. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  156408. * if you're done with the JPEG object, but if you want to clean it up and
  156409. * reuse it, call this:
  156410. */
  156411. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  156412. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  156413. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  156414. * flavor of JPEG object. These may be more convenient in some places.
  156415. */
  156416. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  156417. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  156418. /* Default restart-marker-resync procedure for use by data source modules */
  156419. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  156420. int desired));
  156421. /* These marker codes are exported since applications and data source modules
  156422. * are likely to want to use them.
  156423. */
  156424. #define JPEG_RST0 0xD0 /* RST0 marker code */
  156425. #define JPEG_EOI 0xD9 /* EOI marker code */
  156426. #define JPEG_APP0 0xE0 /* APP0 marker code */
  156427. #define JPEG_COM 0xFE /* COM marker code */
  156428. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  156429. * for structure definitions that are never filled in, keep it quiet by
  156430. * supplying dummy definitions for the various substructures.
  156431. */
  156432. #ifdef INCOMPLETE_TYPES_BROKEN
  156433. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  156434. struct jvirt_sarray_control { long dummy; };
  156435. struct jvirt_barray_control { long dummy; };
  156436. struct jpeg_comp_master { long dummy; };
  156437. struct jpeg_c_main_controller { long dummy; };
  156438. struct jpeg_c_prep_controller { long dummy; };
  156439. struct jpeg_c_coef_controller { long dummy; };
  156440. struct jpeg_marker_writer { long dummy; };
  156441. struct jpeg_color_converter { long dummy; };
  156442. struct jpeg_downsampler { long dummy; };
  156443. struct jpeg_forward_dct { long dummy; };
  156444. struct jpeg_entropy_encoder { long dummy; };
  156445. struct jpeg_decomp_master { long dummy; };
  156446. struct jpeg_d_main_controller { long dummy; };
  156447. struct jpeg_d_coef_controller { long dummy; };
  156448. struct jpeg_d_post_controller { long dummy; };
  156449. struct jpeg_input_controller { long dummy; };
  156450. struct jpeg_marker_reader { long dummy; };
  156451. struct jpeg_entropy_decoder { long dummy; };
  156452. struct jpeg_inverse_dct { long dummy; };
  156453. struct jpeg_upsampler { long dummy; };
  156454. struct jpeg_color_deconverter { long dummy; };
  156455. struct jpeg_color_quantizer { long dummy; };
  156456. #endif /* JPEG_INTERNALS */
  156457. #endif /* INCOMPLETE_TYPES_BROKEN */
  156458. /*
  156459. * The JPEG library modules define JPEG_INTERNALS before including this file.
  156460. * The internal structure declarations are read only when that is true.
  156461. * Applications using the library should not include jpegint.h, but may wish
  156462. * to include jerror.h.
  156463. */
  156464. #ifdef JPEG_INTERNALS
  156465. /********* Start of inlined file: jpegint.h *********/
  156466. /* Declarations for both compression & decompression */
  156467. typedef enum { /* Operating modes for buffer controllers */
  156468. JBUF_PASS_THRU, /* Plain stripwise operation */
  156469. /* Remaining modes require a full-image buffer to have been created */
  156470. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  156471. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  156472. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  156473. } J_BUF_MODE;
  156474. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  156475. #define CSTATE_START 100 /* after create_compress */
  156476. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  156477. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  156478. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  156479. #define DSTATE_START 200 /* after create_decompress */
  156480. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  156481. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  156482. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  156483. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  156484. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  156485. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  156486. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  156487. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  156488. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  156489. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  156490. /* Declarations for compression modules */
  156491. /* Master control module */
  156492. struct jpeg_comp_master {
  156493. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  156494. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  156495. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156496. /* State variables made visible to other modules */
  156497. boolean call_pass_startup; /* True if pass_startup must be called */
  156498. boolean is_last_pass; /* True during last pass */
  156499. };
  156500. /* Main buffer control (downsampled-data buffer) */
  156501. struct jpeg_c_main_controller {
  156502. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156503. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  156504. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  156505. JDIMENSION in_rows_avail));
  156506. };
  156507. /* Compression preprocessing (downsampling input buffer control) */
  156508. struct jpeg_c_prep_controller {
  156509. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156510. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  156511. JSAMPARRAY input_buf,
  156512. JDIMENSION *in_row_ctr,
  156513. JDIMENSION in_rows_avail,
  156514. JSAMPIMAGE output_buf,
  156515. JDIMENSION *out_row_group_ctr,
  156516. JDIMENSION out_row_groups_avail));
  156517. };
  156518. /* Coefficient buffer control */
  156519. struct jpeg_c_coef_controller {
  156520. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156521. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  156522. JSAMPIMAGE input_buf));
  156523. };
  156524. /* Colorspace conversion */
  156525. struct jpeg_color_converter {
  156526. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156527. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  156528. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156529. JDIMENSION output_row, int num_rows));
  156530. };
  156531. /* Downsampling */
  156532. struct jpeg_downsampler {
  156533. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156534. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  156535. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  156536. JSAMPIMAGE output_buf,
  156537. JDIMENSION out_row_group_index));
  156538. boolean need_context_rows; /* TRUE if need rows above & below */
  156539. };
  156540. /* Forward DCT (also controls coefficient quantization) */
  156541. struct jpeg_forward_dct {
  156542. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156543. /* perhaps this should be an array??? */
  156544. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  156545. jpeg_component_info * compptr,
  156546. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156547. JDIMENSION start_row, JDIMENSION start_col,
  156548. JDIMENSION num_blocks));
  156549. };
  156550. /* Entropy encoding */
  156551. struct jpeg_entropy_encoder {
  156552. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  156553. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  156554. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156555. };
  156556. /* Marker writing */
  156557. struct jpeg_marker_writer {
  156558. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  156559. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  156560. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  156561. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  156562. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  156563. /* These routines are exported to allow insertion of extra markers */
  156564. /* Probably only COM and APPn markers should be written this way */
  156565. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  156566. unsigned int datalen));
  156567. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  156568. };
  156569. /* Declarations for decompression modules */
  156570. /* Master control module */
  156571. struct jpeg_decomp_master {
  156572. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  156573. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  156574. /* State variables made visible to other modules */
  156575. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  156576. };
  156577. /* Input control module */
  156578. struct jpeg_input_controller {
  156579. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  156580. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  156581. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156582. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  156583. /* State variables made visible to other modules */
  156584. boolean has_multiple_scans; /* True if file has multiple scans */
  156585. boolean eoi_reached; /* True when EOI has been consumed */
  156586. };
  156587. /* Main buffer control (downsampled-data buffer) */
  156588. struct jpeg_d_main_controller {
  156589. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156590. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  156591. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  156592. JDIMENSION out_rows_avail));
  156593. };
  156594. /* Coefficient buffer control */
  156595. struct jpeg_d_coef_controller {
  156596. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156597. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  156598. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  156599. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  156600. JSAMPIMAGE output_buf));
  156601. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  156602. jvirt_barray_ptr *coef_arrays;
  156603. };
  156604. /* Decompression postprocessing (color quantization buffer control) */
  156605. struct jpeg_d_post_controller {
  156606. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156607. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  156608. JSAMPIMAGE input_buf,
  156609. JDIMENSION *in_row_group_ctr,
  156610. JDIMENSION in_row_groups_avail,
  156611. JSAMPARRAY output_buf,
  156612. JDIMENSION *out_row_ctr,
  156613. JDIMENSION out_rows_avail));
  156614. };
  156615. /* Marker reading & parsing */
  156616. struct jpeg_marker_reader {
  156617. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  156618. /* Read markers until SOS or EOI.
  156619. * Returns same codes as are defined for jpeg_consume_input:
  156620. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  156621. */
  156622. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  156623. /* Read a restart marker --- exported for use by entropy decoder only */
  156624. jpeg_marker_parser_method read_restart_marker;
  156625. /* State of marker reader --- nominally internal, but applications
  156626. * supplying COM or APPn handlers might like to know the state.
  156627. */
  156628. boolean saw_SOI; /* found SOI? */
  156629. boolean saw_SOF; /* found SOF? */
  156630. int next_restart_num; /* next restart number expected (0-7) */
  156631. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  156632. };
  156633. /* Entropy decoding */
  156634. struct jpeg_entropy_decoder {
  156635. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156636. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  156637. JBLOCKROW *MCU_data));
  156638. /* This is here to share code between baseline and progressive decoders; */
  156639. /* other modules probably should not use it */
  156640. boolean insufficient_data; /* set TRUE after emitting warning */
  156641. };
  156642. /* Inverse DCT (also performs dequantization) */
  156643. typedef JMETHOD(void, inverse_DCT_method_ptr,
  156644. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156645. JCOEFPTR coef_block,
  156646. JSAMPARRAY output_buf, JDIMENSION output_col));
  156647. struct jpeg_inverse_dct {
  156648. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156649. /* It is useful to allow each component to have a separate IDCT method. */
  156650. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  156651. };
  156652. /* Upsampling (note that upsampler must also call color converter) */
  156653. struct jpeg_upsampler {
  156654. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156655. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  156656. JSAMPIMAGE input_buf,
  156657. JDIMENSION *in_row_group_ctr,
  156658. JDIMENSION in_row_groups_avail,
  156659. JSAMPARRAY output_buf,
  156660. JDIMENSION *out_row_ctr,
  156661. JDIMENSION out_rows_avail));
  156662. boolean need_context_rows; /* TRUE if need rows above & below */
  156663. };
  156664. /* Colorspace conversion */
  156665. struct jpeg_color_deconverter {
  156666. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156667. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  156668. JSAMPIMAGE input_buf, JDIMENSION input_row,
  156669. JSAMPARRAY output_buf, int num_rows));
  156670. };
  156671. /* Color quantization or color precision reduction */
  156672. struct jpeg_color_quantizer {
  156673. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  156674. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  156675. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  156676. int num_rows));
  156677. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  156678. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  156679. };
  156680. /* Miscellaneous useful macros */
  156681. #undef MAX
  156682. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  156683. #undef MIN
  156684. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  156685. /* We assume that right shift corresponds to signed division by 2 with
  156686. * rounding towards minus infinity. This is correct for typical "arithmetic
  156687. * shift" instructions that shift in copies of the sign bit. But some
  156688. * C compilers implement >> with an unsigned shift. For these machines you
  156689. * must define RIGHT_SHIFT_IS_UNSIGNED.
  156690. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  156691. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  156692. * included in the variables of any routine using RIGHT_SHIFT.
  156693. */
  156694. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  156695. #define SHIFT_TEMPS INT32 shift_temp;
  156696. #define RIGHT_SHIFT(x,shft) \
  156697. ((shift_temp = (x)) < 0 ? \
  156698. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  156699. (shift_temp >> (shft)))
  156700. #else
  156701. #define SHIFT_TEMPS
  156702. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  156703. #endif
  156704. /* Short forms of external names for systems with brain-damaged linkers. */
  156705. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156706. #define jinit_compress_master jICompress
  156707. #define jinit_c_master_control jICMaster
  156708. #define jinit_c_main_controller jICMainC
  156709. #define jinit_c_prep_controller jICPrepC
  156710. #define jinit_c_coef_controller jICCoefC
  156711. #define jinit_color_converter jICColor
  156712. #define jinit_downsampler jIDownsampler
  156713. #define jinit_forward_dct jIFDCT
  156714. #define jinit_huff_encoder jIHEncoder
  156715. #define jinit_phuff_encoder jIPHEncoder
  156716. #define jinit_marker_writer jIMWriter
  156717. #define jinit_master_decompress jIDMaster
  156718. #define jinit_d_main_controller jIDMainC
  156719. #define jinit_d_coef_controller jIDCoefC
  156720. #define jinit_d_post_controller jIDPostC
  156721. #define jinit_input_controller jIInCtlr
  156722. #define jinit_marker_reader jIMReader
  156723. #define jinit_huff_decoder jIHDecoder
  156724. #define jinit_phuff_decoder jIPHDecoder
  156725. #define jinit_inverse_dct jIIDCT
  156726. #define jinit_upsampler jIUpsampler
  156727. #define jinit_color_deconverter jIDColor
  156728. #define jinit_1pass_quantizer jI1Quant
  156729. #define jinit_2pass_quantizer jI2Quant
  156730. #define jinit_merged_upsampler jIMUpsampler
  156731. #define jinit_memory_mgr jIMemMgr
  156732. #define jdiv_round_up jDivRound
  156733. #define jround_up jRound
  156734. #define jcopy_sample_rows jCopySamples
  156735. #define jcopy_block_row jCopyBlocks
  156736. #define jzero_far jZeroFar
  156737. #define jpeg_zigzag_order jZIGTable
  156738. #define jpeg_natural_order jZAGTable
  156739. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156740. /* Compression module initialization routines */
  156741. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  156742. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  156743. boolean transcode_only));
  156744. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  156745. boolean need_full_buffer));
  156746. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  156747. boolean need_full_buffer));
  156748. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  156749. boolean need_full_buffer));
  156750. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  156751. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  156752. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  156753. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  156754. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  156755. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  156756. /* Decompression module initialization routines */
  156757. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  156758. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  156759. boolean need_full_buffer));
  156760. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  156761. boolean need_full_buffer));
  156762. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  156763. boolean need_full_buffer));
  156764. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  156765. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  156766. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  156767. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  156768. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  156769. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  156770. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  156771. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  156772. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  156773. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  156774. /* Memory manager initialization */
  156775. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  156776. /* Utility routines in jutils.c */
  156777. EXTERN(long) jdiv_round_up JPP((long a, long b));
  156778. EXTERN(long) jround_up JPP((long a, long b));
  156779. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  156780. JSAMPARRAY output_array, int dest_row,
  156781. int num_rows, JDIMENSION num_cols));
  156782. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  156783. JDIMENSION num_blocks));
  156784. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  156785. /* Constant tables in jutils.c */
  156786. #if 0 /* This table is not actually needed in v6a */
  156787. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  156788. #endif
  156789. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  156790. /* Suppress undefined-structure complaints if necessary. */
  156791. #ifdef INCOMPLETE_TYPES_BROKEN
  156792. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  156793. struct jvirt_sarray_control { long dummy; };
  156794. struct jvirt_barray_control { long dummy; };
  156795. #endif
  156796. #endif /* INCOMPLETE_TYPES_BROKEN */
  156797. /********* End of inlined file: jpegint.h *********/
  156798. /* fetch private declarations */
  156799. /********* Start of inlined file: jerror.h *********/
  156800. /*
  156801. * To define the enum list of message codes, include this file without
  156802. * defining macro JMESSAGE. To create a message string table, include it
  156803. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  156804. */
  156805. #ifndef JMESSAGE
  156806. #ifndef JERROR_H
  156807. /* First time through, define the enum list */
  156808. #define JMAKE_ENUM_LIST
  156809. #else
  156810. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  156811. #define JMESSAGE(code,string)
  156812. #endif /* JERROR_H */
  156813. #endif /* JMESSAGE */
  156814. #ifdef JMAKE_ENUM_LIST
  156815. typedef enum {
  156816. #define JMESSAGE(code,string) code ,
  156817. #endif /* JMAKE_ENUM_LIST */
  156818. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  156819. /* For maintenance convenience, list is alphabetical by message code name */
  156820. JMESSAGE(JERR_ARITH_NOTIMPL,
  156821. "Sorry, there are legal restrictions on arithmetic coding")
  156822. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  156823. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  156824. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  156825. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  156826. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  156827. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  156828. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  156829. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  156830. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  156831. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  156832. JMESSAGE(JERR_BAD_LIB_VERSION,
  156833. "Wrong JPEG library version: library is %d, caller expects %d")
  156834. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  156835. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  156836. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  156837. JMESSAGE(JERR_BAD_PROGRESSION,
  156838. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  156839. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  156840. "Invalid progressive parameters at scan script entry %d")
  156841. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  156842. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  156843. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  156844. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  156845. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  156846. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  156847. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  156848. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  156849. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  156850. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  156851. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  156852. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  156853. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  156854. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  156855. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  156856. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  156857. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  156858. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  156859. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  156860. JMESSAGE(JERR_FILE_READ, "Input file read error")
  156861. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  156862. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  156863. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  156864. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  156865. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  156866. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  156867. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  156868. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  156869. "Cannot transcode due to multiple use of quantization table %d")
  156870. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  156871. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  156872. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  156873. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  156874. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  156875. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  156876. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  156877. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  156878. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  156879. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  156880. JMESSAGE(JERR_QUANT_COMPONENTS,
  156881. "Cannot quantize more than %d color components")
  156882. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  156883. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  156884. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  156885. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  156886. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  156887. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  156888. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  156889. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  156890. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  156891. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  156892. JMESSAGE(JERR_TFILE_WRITE,
  156893. "Write failed on temporary file --- out of disk space?")
  156894. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  156895. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  156896. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  156897. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  156898. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  156899. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  156900. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  156901. JMESSAGE(JMSG_VERSION, JVERSION)
  156902. JMESSAGE(JTRC_16BIT_TABLES,
  156903. "Caution: quantization tables are too coarse for baseline JPEG")
  156904. JMESSAGE(JTRC_ADOBE,
  156905. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  156906. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  156907. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  156908. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  156909. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  156910. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  156911. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  156912. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  156913. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  156914. JMESSAGE(JTRC_EOI, "End Of Image")
  156915. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  156916. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  156917. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  156918. "Warning: thumbnail image size does not match data length %u")
  156919. JMESSAGE(JTRC_JFIF_EXTENSION,
  156920. "JFIF extension marker: type 0x%02x, length %u")
  156921. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  156922. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  156923. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  156924. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  156925. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  156926. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  156927. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  156928. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  156929. JMESSAGE(JTRC_RST, "RST%d")
  156930. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  156931. "Smoothing not supported with nonstandard sampling ratios")
  156932. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  156933. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  156934. JMESSAGE(JTRC_SOI, "Start of Image")
  156935. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  156936. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  156937. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  156938. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  156939. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  156940. JMESSAGE(JTRC_THUMB_JPEG,
  156941. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  156942. JMESSAGE(JTRC_THUMB_PALETTE,
  156943. "JFIF extension marker: palette thumbnail image, length %u")
  156944. JMESSAGE(JTRC_THUMB_RGB,
  156945. "JFIF extension marker: RGB thumbnail image, length %u")
  156946. JMESSAGE(JTRC_UNKNOWN_IDS,
  156947. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  156948. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  156949. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  156950. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  156951. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  156952. "Inconsistent progression sequence for component %d coefficient %d")
  156953. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  156954. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  156955. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  156956. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  156957. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  156958. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  156959. JMESSAGE(JWRN_MUST_RESYNC,
  156960. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  156961. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  156962. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  156963. #ifdef JMAKE_ENUM_LIST
  156964. JMSG_LASTMSGCODE
  156965. } J_MESSAGE_CODE;
  156966. #undef JMAKE_ENUM_LIST
  156967. #endif /* JMAKE_ENUM_LIST */
  156968. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  156969. #undef JMESSAGE
  156970. #ifndef JERROR_H
  156971. #define JERROR_H
  156972. /* Macros to simplify using the error and trace message stuff */
  156973. /* The first parameter is either type of cinfo pointer */
  156974. /* Fatal errors (print message and exit) */
  156975. #define ERREXIT(cinfo,code) \
  156976. ((cinfo)->err->msg_code = (code), \
  156977. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156978. #define ERREXIT1(cinfo,code,p1) \
  156979. ((cinfo)->err->msg_code = (code), \
  156980. (cinfo)->err->msg_parm.i[0] = (p1), \
  156981. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156982. #define ERREXIT2(cinfo,code,p1,p2) \
  156983. ((cinfo)->err->msg_code = (code), \
  156984. (cinfo)->err->msg_parm.i[0] = (p1), \
  156985. (cinfo)->err->msg_parm.i[1] = (p2), \
  156986. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156987. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  156988. ((cinfo)->err->msg_code = (code), \
  156989. (cinfo)->err->msg_parm.i[0] = (p1), \
  156990. (cinfo)->err->msg_parm.i[1] = (p2), \
  156991. (cinfo)->err->msg_parm.i[2] = (p3), \
  156992. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156993. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  156994. ((cinfo)->err->msg_code = (code), \
  156995. (cinfo)->err->msg_parm.i[0] = (p1), \
  156996. (cinfo)->err->msg_parm.i[1] = (p2), \
  156997. (cinfo)->err->msg_parm.i[2] = (p3), \
  156998. (cinfo)->err->msg_parm.i[3] = (p4), \
  156999. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157000. #define ERREXITS(cinfo,code,str) \
  157001. ((cinfo)->err->msg_code = (code), \
  157002. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157003. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157004. #define MAKESTMT(stuff) do { stuff } while (0)
  157005. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  157006. #define WARNMS(cinfo,code) \
  157007. ((cinfo)->err->msg_code = (code), \
  157008. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157009. #define WARNMS1(cinfo,code,p1) \
  157010. ((cinfo)->err->msg_code = (code), \
  157011. (cinfo)->err->msg_parm.i[0] = (p1), \
  157012. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157013. #define WARNMS2(cinfo,code,p1,p2) \
  157014. ((cinfo)->err->msg_code = (code), \
  157015. (cinfo)->err->msg_parm.i[0] = (p1), \
  157016. (cinfo)->err->msg_parm.i[1] = (p2), \
  157017. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157018. /* Informational/debugging messages */
  157019. #define TRACEMS(cinfo,lvl,code) \
  157020. ((cinfo)->err->msg_code = (code), \
  157021. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157022. #define TRACEMS1(cinfo,lvl,code,p1) \
  157023. ((cinfo)->err->msg_code = (code), \
  157024. (cinfo)->err->msg_parm.i[0] = (p1), \
  157025. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157026. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  157027. ((cinfo)->err->msg_code = (code), \
  157028. (cinfo)->err->msg_parm.i[0] = (p1), \
  157029. (cinfo)->err->msg_parm.i[1] = (p2), \
  157030. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157031. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  157032. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157033. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  157034. (cinfo)->err->msg_code = (code); \
  157035. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157036. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  157037. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157038. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157039. (cinfo)->err->msg_code = (code); \
  157040. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157041. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  157042. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157043. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157044. _mp[4] = (p5); \
  157045. (cinfo)->err->msg_code = (code); \
  157046. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157047. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  157048. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157049. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157050. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  157051. (cinfo)->err->msg_code = (code); \
  157052. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157053. #define TRACEMSS(cinfo,lvl,code,str) \
  157054. ((cinfo)->err->msg_code = (code), \
  157055. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157056. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157057. #endif /* JERROR_H */
  157058. /********* End of inlined file: jerror.h *********/
  157059. /* fetch error codes too */
  157060. #endif
  157061. #endif /* JPEGLIB_H */
  157062. /********* End of inlined file: jpeglib.h *********/
  157063. /********* Start of inlined file: jcapimin.c *********/
  157064. #define JPEG_INTERNALS
  157065. /********* Start of inlined file: jinclude.h *********/
  157066. /* Include auto-config file to find out which system include files we need. */
  157067. #ifndef __jinclude_h__
  157068. #define __jinclude_h__
  157069. /********* Start of inlined file: jconfig.h *********/
  157070. /* see jconfig.doc for explanations */
  157071. // disable all the warnings under MSVC
  157072. #ifdef _MSC_VER
  157073. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  157074. #endif
  157075. #ifdef __BORLANDC__
  157076. #pragma warn -8057
  157077. #pragma warn -8019
  157078. #pragma warn -8004
  157079. #pragma warn -8008
  157080. #endif
  157081. #define HAVE_PROTOTYPES
  157082. #define HAVE_UNSIGNED_CHAR
  157083. #define HAVE_UNSIGNED_SHORT
  157084. /* #define void char */
  157085. /* #define const */
  157086. #undef CHAR_IS_UNSIGNED
  157087. #define HAVE_STDDEF_H
  157088. #define HAVE_STDLIB_H
  157089. #undef NEED_BSD_STRINGS
  157090. #undef NEED_SYS_TYPES_H
  157091. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  157092. #undef NEED_SHORT_EXTERNAL_NAMES
  157093. #undef INCOMPLETE_TYPES_BROKEN
  157094. /* Define "boolean" as unsigned char, not int, per Windows custom */
  157095. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  157096. typedef unsigned char boolean;
  157097. #endif
  157098. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  157099. #ifdef JPEG_INTERNALS
  157100. #undef RIGHT_SHIFT_IS_UNSIGNED
  157101. #endif /* JPEG_INTERNALS */
  157102. #ifdef JPEG_CJPEG_DJPEG
  157103. #define BMP_SUPPORTED /* BMP image file format */
  157104. #define GIF_SUPPORTED /* GIF image file format */
  157105. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  157106. #undef RLE_SUPPORTED /* Utah RLE image file format */
  157107. #define TARGA_SUPPORTED /* Targa image file format */
  157108. #define TWO_FILE_COMMANDLINE /* optional */
  157109. #define USE_SETMODE /* Microsoft has setmode() */
  157110. #undef NEED_SIGNAL_CATCHER
  157111. #undef DONT_USE_B_MODE
  157112. #undef PROGRESS_REPORT /* optional */
  157113. #endif /* JPEG_CJPEG_DJPEG */
  157114. /********* End of inlined file: jconfig.h *********/
  157115. /* auto configuration options */
  157116. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  157117. /*
  157118. * We need the NULL macro and size_t typedef.
  157119. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  157120. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  157121. * pull in <sys/types.h> as well.
  157122. * Note that the core JPEG library does not require <stdio.h>;
  157123. * only the default error handler and data source/destination modules do.
  157124. * But we must pull it in because of the references to FILE in jpeglib.h.
  157125. * You can remove those references if you want to compile without <stdio.h>.
  157126. */
  157127. #ifdef HAVE_STDDEF_H
  157128. #include <stddef.h>
  157129. #endif
  157130. #ifdef HAVE_STDLIB_H
  157131. #include <stdlib.h>
  157132. #endif
  157133. #ifdef NEED_SYS_TYPES_H
  157134. #include <sys/types.h>
  157135. #endif
  157136. #include <stdio.h>
  157137. /*
  157138. * We need memory copying and zeroing functions, plus strncpy().
  157139. * ANSI and System V implementations declare these in <string.h>.
  157140. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  157141. * Some systems may declare memset and memcpy in <memory.h>.
  157142. *
  157143. * NOTE: we assume the size parameters to these functions are of type size_t.
  157144. * Change the casts in these macros if not!
  157145. */
  157146. #ifdef NEED_BSD_STRINGS
  157147. #include <strings.h>
  157148. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  157149. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  157150. #else /* not BSD, assume ANSI/SysV string lib */
  157151. #include <string.h>
  157152. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  157153. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  157154. #endif
  157155. /*
  157156. * In ANSI C, and indeed any rational implementation, size_t is also the
  157157. * type returned by sizeof(). However, it seems there are some irrational
  157158. * implementations out there, in which sizeof() returns an int even though
  157159. * size_t is defined as long or unsigned long. To ensure consistent results
  157160. * we always use this SIZEOF() macro in place of using sizeof() directly.
  157161. */
  157162. #define SIZEOF(object) ((size_t) sizeof(object))
  157163. /*
  157164. * The modules that use fread() and fwrite() always invoke them through
  157165. * these macros. On some systems you may need to twiddle the argument casts.
  157166. * CAUTION: argument order is different from underlying functions!
  157167. */
  157168. #define JFREAD(file,buf,sizeofbuf) \
  157169. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157170. #define JFWRITE(file,buf,sizeofbuf) \
  157171. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157172. typedef enum { /* JPEG marker codes */
  157173. M_SOF0 = 0xc0,
  157174. M_SOF1 = 0xc1,
  157175. M_SOF2 = 0xc2,
  157176. M_SOF3 = 0xc3,
  157177. M_SOF5 = 0xc5,
  157178. M_SOF6 = 0xc6,
  157179. M_SOF7 = 0xc7,
  157180. M_JPG = 0xc8,
  157181. M_SOF9 = 0xc9,
  157182. M_SOF10 = 0xca,
  157183. M_SOF11 = 0xcb,
  157184. M_SOF13 = 0xcd,
  157185. M_SOF14 = 0xce,
  157186. M_SOF15 = 0xcf,
  157187. M_DHT = 0xc4,
  157188. M_DAC = 0xcc,
  157189. M_RST0 = 0xd0,
  157190. M_RST1 = 0xd1,
  157191. M_RST2 = 0xd2,
  157192. M_RST3 = 0xd3,
  157193. M_RST4 = 0xd4,
  157194. M_RST5 = 0xd5,
  157195. M_RST6 = 0xd6,
  157196. M_RST7 = 0xd7,
  157197. M_SOI = 0xd8,
  157198. M_EOI = 0xd9,
  157199. M_SOS = 0xda,
  157200. M_DQT = 0xdb,
  157201. M_DNL = 0xdc,
  157202. M_DRI = 0xdd,
  157203. M_DHP = 0xde,
  157204. M_EXP = 0xdf,
  157205. M_APP0 = 0xe0,
  157206. M_APP1 = 0xe1,
  157207. M_APP2 = 0xe2,
  157208. M_APP3 = 0xe3,
  157209. M_APP4 = 0xe4,
  157210. M_APP5 = 0xe5,
  157211. M_APP6 = 0xe6,
  157212. M_APP7 = 0xe7,
  157213. M_APP8 = 0xe8,
  157214. M_APP9 = 0xe9,
  157215. M_APP10 = 0xea,
  157216. M_APP11 = 0xeb,
  157217. M_APP12 = 0xec,
  157218. M_APP13 = 0xed,
  157219. M_APP14 = 0xee,
  157220. M_APP15 = 0xef,
  157221. M_JPG0 = 0xf0,
  157222. M_JPG13 = 0xfd,
  157223. M_COM = 0xfe,
  157224. M_TEM = 0x01,
  157225. M_ERROR = 0x100
  157226. } JPEG_MARKER;
  157227. /*
  157228. * Figure F.12: extend sign bit.
  157229. * On some machines, a shift and add will be faster than a table lookup.
  157230. */
  157231. #ifdef AVOID_TABLES
  157232. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  157233. #else
  157234. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  157235. static const int extend_test[16] = /* entry n is 2**(n-1) */
  157236. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  157237. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  157238. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  157239. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  157240. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  157241. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  157242. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  157243. #endif /* AVOID_TABLES */
  157244. #endif
  157245. /********* End of inlined file: jinclude.h *********/
  157246. /*
  157247. * Initialization of a JPEG compression object.
  157248. * The error manager must already be set up (in case memory manager fails).
  157249. */
  157250. GLOBAL(void)
  157251. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  157252. {
  157253. int i;
  157254. /* Guard against version mismatches between library and caller. */
  157255. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  157256. if (version != JPEG_LIB_VERSION)
  157257. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  157258. if (structsize != SIZEOF(struct jpeg_compress_struct))
  157259. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  157260. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  157261. /* For debugging purposes, we zero the whole master structure.
  157262. * But the application has already set the err pointer, and may have set
  157263. * client_data, so we have to save and restore those fields.
  157264. * Note: if application hasn't set client_data, tools like Purify may
  157265. * complain here.
  157266. */
  157267. {
  157268. struct jpeg_error_mgr * err = cinfo->err;
  157269. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  157270. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  157271. cinfo->err = err;
  157272. cinfo->client_data = client_data;
  157273. }
  157274. cinfo->is_decompressor = FALSE;
  157275. /* Initialize a memory manager instance for this object */
  157276. jinit_memory_mgr((j_common_ptr) cinfo);
  157277. /* Zero out pointers to permanent structures. */
  157278. cinfo->progress = NULL;
  157279. cinfo->dest = NULL;
  157280. cinfo->comp_info = NULL;
  157281. for (i = 0; i < NUM_QUANT_TBLS; i++)
  157282. cinfo->quant_tbl_ptrs[i] = NULL;
  157283. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157284. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  157285. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  157286. }
  157287. cinfo->script_space = NULL;
  157288. cinfo->input_gamma = 1.0; /* in case application forgets */
  157289. /* OK, I'm ready */
  157290. cinfo->global_state = CSTATE_START;
  157291. }
  157292. /*
  157293. * Destruction of a JPEG compression object
  157294. */
  157295. GLOBAL(void)
  157296. jpeg_destroy_compress (j_compress_ptr cinfo)
  157297. {
  157298. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  157299. }
  157300. /*
  157301. * Abort processing of a JPEG compression operation,
  157302. * but don't destroy the object itself.
  157303. */
  157304. GLOBAL(void)
  157305. jpeg_abort_compress (j_compress_ptr cinfo)
  157306. {
  157307. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  157308. }
  157309. /*
  157310. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  157311. * Marks all currently defined tables as already written (if suppress)
  157312. * or not written (if !suppress). This will control whether they get emitted
  157313. * by a subsequent jpeg_start_compress call.
  157314. *
  157315. * This routine is exported for use by applications that want to produce
  157316. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  157317. * since it is called by jpeg_start_compress, we put it here --- otherwise
  157318. * jcparam.o would be linked whether the application used it or not.
  157319. */
  157320. GLOBAL(void)
  157321. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  157322. {
  157323. int i;
  157324. JQUANT_TBL * qtbl;
  157325. JHUFF_TBL * htbl;
  157326. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157327. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  157328. qtbl->sent_table = suppress;
  157329. }
  157330. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157331. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  157332. htbl->sent_table = suppress;
  157333. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  157334. htbl->sent_table = suppress;
  157335. }
  157336. }
  157337. /*
  157338. * Finish JPEG compression.
  157339. *
  157340. * If a multipass operating mode was selected, this may do a great deal of
  157341. * work including most of the actual output.
  157342. */
  157343. GLOBAL(void)
  157344. jpeg_finish_compress (j_compress_ptr cinfo)
  157345. {
  157346. JDIMENSION iMCU_row;
  157347. if (cinfo->global_state == CSTATE_SCANNING ||
  157348. cinfo->global_state == CSTATE_RAW_OK) {
  157349. /* Terminate first pass */
  157350. if (cinfo->next_scanline < cinfo->image_height)
  157351. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  157352. (*cinfo->master->finish_pass) (cinfo);
  157353. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  157354. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157355. /* Perform any remaining passes */
  157356. while (! cinfo->master->is_last_pass) {
  157357. (*cinfo->master->prepare_for_pass) (cinfo);
  157358. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  157359. if (cinfo->progress != NULL) {
  157360. cinfo->progress->pass_counter = (long) iMCU_row;
  157361. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  157362. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157363. }
  157364. /* We bypass the main controller and invoke coef controller directly;
  157365. * all work is being done from the coefficient buffer.
  157366. */
  157367. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  157368. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157369. }
  157370. (*cinfo->master->finish_pass) (cinfo);
  157371. }
  157372. /* Write EOI, do final cleanup */
  157373. (*cinfo->marker->write_file_trailer) (cinfo);
  157374. (*cinfo->dest->term_destination) (cinfo);
  157375. /* We can use jpeg_abort to release memory and reset global_state */
  157376. jpeg_abort((j_common_ptr) cinfo);
  157377. }
  157378. /*
  157379. * Write a special marker.
  157380. * This is only recommended for writing COM or APPn markers.
  157381. * Must be called after jpeg_start_compress() and before
  157382. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  157383. */
  157384. GLOBAL(void)
  157385. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  157386. const JOCTET *dataptr, unsigned int datalen)
  157387. {
  157388. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  157389. if (cinfo->next_scanline != 0 ||
  157390. (cinfo->global_state != CSTATE_SCANNING &&
  157391. cinfo->global_state != CSTATE_RAW_OK &&
  157392. cinfo->global_state != CSTATE_WRCOEFS))
  157393. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157394. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157395. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  157396. while (datalen--) {
  157397. (*write_marker_byte) (cinfo, *dataptr);
  157398. dataptr++;
  157399. }
  157400. }
  157401. /* Same, but piecemeal. */
  157402. GLOBAL(void)
  157403. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  157404. {
  157405. if (cinfo->next_scanline != 0 ||
  157406. (cinfo->global_state != CSTATE_SCANNING &&
  157407. cinfo->global_state != CSTATE_RAW_OK &&
  157408. cinfo->global_state != CSTATE_WRCOEFS))
  157409. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157410. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157411. }
  157412. GLOBAL(void)
  157413. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  157414. {
  157415. (*cinfo->marker->write_marker_byte) (cinfo, val);
  157416. }
  157417. /*
  157418. * Alternate compression function: just write an abbreviated table file.
  157419. * Before calling this, all parameters and a data destination must be set up.
  157420. *
  157421. * To produce a pair of files containing abbreviated tables and abbreviated
  157422. * image data, one would proceed as follows:
  157423. *
  157424. * initialize JPEG object
  157425. * set JPEG parameters
  157426. * set destination to table file
  157427. * jpeg_write_tables(cinfo);
  157428. * set destination to image file
  157429. * jpeg_start_compress(cinfo, FALSE);
  157430. * write data...
  157431. * jpeg_finish_compress(cinfo);
  157432. *
  157433. * jpeg_write_tables has the side effect of marking all tables written
  157434. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  157435. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  157436. */
  157437. GLOBAL(void)
  157438. jpeg_write_tables (j_compress_ptr cinfo)
  157439. {
  157440. if (cinfo->global_state != CSTATE_START)
  157441. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157442. /* (Re)initialize error mgr and destination modules */
  157443. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157444. (*cinfo->dest->init_destination) (cinfo);
  157445. /* Initialize the marker writer ... bit of a crock to do it here. */
  157446. jinit_marker_writer(cinfo);
  157447. /* Write them tables! */
  157448. (*cinfo->marker->write_tables_only) (cinfo);
  157449. /* And clean up. */
  157450. (*cinfo->dest->term_destination) (cinfo);
  157451. /*
  157452. * In library releases up through v6a, we called jpeg_abort() here to free
  157453. * any working memory allocated by the destination manager and marker
  157454. * writer. Some applications had a problem with that: they allocated space
  157455. * of their own from the library memory manager, and didn't want it to go
  157456. * away during write_tables. So now we do nothing. This will cause a
  157457. * memory leak if an app calls write_tables repeatedly without doing a full
  157458. * compression cycle or otherwise resetting the JPEG object. However, that
  157459. * seems less bad than unexpectedly freeing memory in the normal case.
  157460. * An app that prefers the old behavior can call jpeg_abort for itself after
  157461. * each call to jpeg_write_tables().
  157462. */
  157463. }
  157464. /********* End of inlined file: jcapimin.c *********/
  157465. /********* Start of inlined file: jcapistd.c *********/
  157466. #define JPEG_INTERNALS
  157467. /*
  157468. * Compression initialization.
  157469. * Before calling this, all parameters and a data destination must be set up.
  157470. *
  157471. * We require a write_all_tables parameter as a failsafe check when writing
  157472. * multiple datastreams from the same compression object. Since prior runs
  157473. * will have left all the tables marked sent_table=TRUE, a subsequent run
  157474. * would emit an abbreviated stream (no tables) by default. This may be what
  157475. * is wanted, but for safety's sake it should not be the default behavior:
  157476. * programmers should have to make a deliberate choice to emit abbreviated
  157477. * images. Therefore the documentation and examples should encourage people
  157478. * to pass write_all_tables=TRUE; then it will take active thought to do the
  157479. * wrong thing.
  157480. */
  157481. GLOBAL(void)
  157482. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  157483. {
  157484. if (cinfo->global_state != CSTATE_START)
  157485. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157486. if (write_all_tables)
  157487. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  157488. /* (Re)initialize error mgr and destination modules */
  157489. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157490. (*cinfo->dest->init_destination) (cinfo);
  157491. /* Perform master selection of active modules */
  157492. jinit_compress_master(cinfo);
  157493. /* Set up for the first pass */
  157494. (*cinfo->master->prepare_for_pass) (cinfo);
  157495. /* Ready for application to drive first pass through jpeg_write_scanlines
  157496. * or jpeg_write_raw_data.
  157497. */
  157498. cinfo->next_scanline = 0;
  157499. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  157500. }
  157501. /*
  157502. * Write some scanlines of data to the JPEG compressor.
  157503. *
  157504. * The return value will be the number of lines actually written.
  157505. * This should be less than the supplied num_lines only in case that
  157506. * the data destination module has requested suspension of the compressor,
  157507. * or if more than image_height scanlines are passed in.
  157508. *
  157509. * Note: we warn about excess calls to jpeg_write_scanlines() since
  157510. * this likely signals an application programmer error. However,
  157511. * excess scanlines passed in the last valid call are *silently* ignored,
  157512. * so that the application need not adjust num_lines for end-of-image
  157513. * when using a multiple-scanline buffer.
  157514. */
  157515. GLOBAL(JDIMENSION)
  157516. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  157517. JDIMENSION num_lines)
  157518. {
  157519. JDIMENSION row_ctr, rows_left;
  157520. if (cinfo->global_state != CSTATE_SCANNING)
  157521. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157522. if (cinfo->next_scanline >= cinfo->image_height)
  157523. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157524. /* Call progress monitor hook if present */
  157525. if (cinfo->progress != NULL) {
  157526. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157527. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157528. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157529. }
  157530. /* Give master control module another chance if this is first call to
  157531. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  157532. * delayed so that application can write COM, etc, markers between
  157533. * jpeg_start_compress and jpeg_write_scanlines.
  157534. */
  157535. if (cinfo->master->call_pass_startup)
  157536. (*cinfo->master->pass_startup) (cinfo);
  157537. /* Ignore any extra scanlines at bottom of image. */
  157538. rows_left = cinfo->image_height - cinfo->next_scanline;
  157539. if (num_lines > rows_left)
  157540. num_lines = rows_left;
  157541. row_ctr = 0;
  157542. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  157543. cinfo->next_scanline += row_ctr;
  157544. return row_ctr;
  157545. }
  157546. /*
  157547. * Alternate entry point to write raw data.
  157548. * Processes exactly one iMCU row per call, unless suspended.
  157549. */
  157550. GLOBAL(JDIMENSION)
  157551. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  157552. JDIMENSION num_lines)
  157553. {
  157554. JDIMENSION lines_per_iMCU_row;
  157555. if (cinfo->global_state != CSTATE_RAW_OK)
  157556. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157557. if (cinfo->next_scanline >= cinfo->image_height) {
  157558. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157559. return 0;
  157560. }
  157561. /* Call progress monitor hook if present */
  157562. if (cinfo->progress != NULL) {
  157563. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157564. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157565. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157566. }
  157567. /* Give master control module another chance if this is first call to
  157568. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  157569. * delayed so that application can write COM, etc, markers between
  157570. * jpeg_start_compress and jpeg_write_raw_data.
  157571. */
  157572. if (cinfo->master->call_pass_startup)
  157573. (*cinfo->master->pass_startup) (cinfo);
  157574. /* Verify that at least one iMCU row has been passed. */
  157575. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  157576. if (num_lines < lines_per_iMCU_row)
  157577. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  157578. /* Directly compress the row. */
  157579. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  157580. /* If compressor did not consume the whole row, suspend processing. */
  157581. return 0;
  157582. }
  157583. /* OK, we processed one iMCU row. */
  157584. cinfo->next_scanline += lines_per_iMCU_row;
  157585. return lines_per_iMCU_row;
  157586. }
  157587. /********* End of inlined file: jcapistd.c *********/
  157588. /********* Start of inlined file: jccoefct.c *********/
  157589. #define JPEG_INTERNALS
  157590. /* We use a full-image coefficient buffer when doing Huffman optimization,
  157591. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  157592. * step is run during the first pass, and subsequent passes need only read
  157593. * the buffered coefficients.
  157594. */
  157595. #ifdef ENTROPY_OPT_SUPPORTED
  157596. #define FULL_COEF_BUFFER_SUPPORTED
  157597. #else
  157598. #ifdef C_MULTISCAN_FILES_SUPPORTED
  157599. #define FULL_COEF_BUFFER_SUPPORTED
  157600. #endif
  157601. #endif
  157602. /* Private buffer controller object */
  157603. typedef struct {
  157604. struct jpeg_c_coef_controller pub; /* public fields */
  157605. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  157606. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  157607. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  157608. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  157609. /* For single-pass compression, it's sufficient to buffer just one MCU
  157610. * (although this may prove a bit slow in practice). We allocate a
  157611. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  157612. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  157613. * it's not really very big; this is to keep the module interfaces unchanged
  157614. * when a large coefficient buffer is necessary.)
  157615. * In multi-pass modes, this array points to the current MCU's blocks
  157616. * within the virtual arrays.
  157617. */
  157618. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  157619. /* In multi-pass modes, we need a virtual block array for each component. */
  157620. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  157621. } my_coef_controller;
  157622. typedef my_coef_controller * my_coef_ptr;
  157623. /* Forward declarations */
  157624. METHODDEF(boolean) compress_data
  157625. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157626. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157627. METHODDEF(boolean) compress_first_pass
  157628. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157629. METHODDEF(boolean) compress_output
  157630. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157631. #endif
  157632. LOCAL(void)
  157633. start_iMCU_row (j_compress_ptr cinfo)
  157634. /* Reset within-iMCU-row counters for a new row */
  157635. {
  157636. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157637. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  157638. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  157639. * But at the bottom of the image, process only what's left.
  157640. */
  157641. if (cinfo->comps_in_scan > 1) {
  157642. coef->MCU_rows_per_iMCU_row = 1;
  157643. } else {
  157644. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  157645. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  157646. else
  157647. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  157648. }
  157649. coef->mcu_ctr = 0;
  157650. coef->MCU_vert_offset = 0;
  157651. }
  157652. /*
  157653. * Initialize for a processing pass.
  157654. */
  157655. METHODDEF(void)
  157656. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157657. {
  157658. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157659. coef->iMCU_row_num = 0;
  157660. start_iMCU_row(cinfo);
  157661. switch (pass_mode) {
  157662. case JBUF_PASS_THRU:
  157663. if (coef->whole_image[0] != NULL)
  157664. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157665. coef->pub.compress_data = compress_data;
  157666. break;
  157667. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157668. case JBUF_SAVE_AND_PASS:
  157669. if (coef->whole_image[0] == NULL)
  157670. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157671. coef->pub.compress_data = compress_first_pass;
  157672. break;
  157673. case JBUF_CRANK_DEST:
  157674. if (coef->whole_image[0] == NULL)
  157675. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157676. coef->pub.compress_data = compress_output;
  157677. break;
  157678. #endif
  157679. default:
  157680. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157681. break;
  157682. }
  157683. }
  157684. /*
  157685. * Process some data in the single-pass case.
  157686. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157687. * per call, ie, v_samp_factor block rows for each component in the image.
  157688. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157689. *
  157690. * NB: input_buf contains a plane for each component in image,
  157691. * which we index according to the component's SOF position.
  157692. */
  157693. METHODDEF(boolean)
  157694. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157695. {
  157696. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157697. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157698. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  157699. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157700. int blkn, bi, ci, yindex, yoffset, blockcnt;
  157701. JDIMENSION ypos, xpos;
  157702. jpeg_component_info *compptr;
  157703. /* Loop to write as much as one whole iMCU row */
  157704. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157705. yoffset++) {
  157706. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  157707. MCU_col_num++) {
  157708. /* Determine where data comes from in input_buf and do the DCT thing.
  157709. * Each call on forward_DCT processes a horizontal row of DCT blocks
  157710. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  157711. * sequentially. Dummy blocks at the right or bottom edge are filled in
  157712. * specially. The data in them does not matter for image reconstruction,
  157713. * so we fill them with values that will encode to the smallest amount of
  157714. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  157715. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  157716. */
  157717. blkn = 0;
  157718. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157719. compptr = cinfo->cur_comp_info[ci];
  157720. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  157721. : compptr->last_col_width;
  157722. xpos = MCU_col_num * compptr->MCU_sample_width;
  157723. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  157724. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157725. if (coef->iMCU_row_num < last_iMCU_row ||
  157726. yoffset+yindex < compptr->last_row_height) {
  157727. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157728. input_buf[compptr->component_index],
  157729. coef->MCU_buffer[blkn],
  157730. ypos, xpos, (JDIMENSION) blockcnt);
  157731. if (blockcnt < compptr->MCU_width) {
  157732. /* Create some dummy blocks at the right edge of the image. */
  157733. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  157734. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  157735. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  157736. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  157737. }
  157738. }
  157739. } else {
  157740. /* Create a row of dummy blocks at the bottom of the image. */
  157741. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  157742. compptr->MCU_width * SIZEOF(JBLOCK));
  157743. for (bi = 0; bi < compptr->MCU_width; bi++) {
  157744. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  157745. }
  157746. }
  157747. blkn += compptr->MCU_width;
  157748. ypos += DCTSIZE;
  157749. }
  157750. }
  157751. /* Try to write the MCU. In event of a suspension failure, we will
  157752. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  157753. */
  157754. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157755. /* Suspension forced; update state counters and exit */
  157756. coef->MCU_vert_offset = yoffset;
  157757. coef->mcu_ctr = MCU_col_num;
  157758. return FALSE;
  157759. }
  157760. }
  157761. /* Completed an MCU row, but perhaps not an iMCU row */
  157762. coef->mcu_ctr = 0;
  157763. }
  157764. /* Completed the iMCU row, advance counters for next one */
  157765. coef->iMCU_row_num++;
  157766. start_iMCU_row(cinfo);
  157767. return TRUE;
  157768. }
  157769. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157770. /*
  157771. * Process some data in the first pass of a multi-pass case.
  157772. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157773. * per call, ie, v_samp_factor block rows for each component in the image.
  157774. * This amount of data is read from the source buffer, DCT'd and quantized,
  157775. * and saved into the virtual arrays. We also generate suitable dummy blocks
  157776. * as needed at the right and lower edges. (The dummy blocks are constructed
  157777. * in the virtual arrays, which have been padded appropriately.) This makes
  157778. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  157779. *
  157780. * We must also emit the data to the entropy encoder. This is conveniently
  157781. * done by calling compress_output() after we've loaded the current strip
  157782. * of the virtual arrays.
  157783. *
  157784. * NB: input_buf contains a plane for each component in image. All
  157785. * components are DCT'd and loaded into the virtual arrays in this pass.
  157786. * However, it may be that only a subset of the components are emitted to
  157787. * the entropy encoder during this first pass; be careful about looking
  157788. * at the scan-dependent variables (MCU dimensions, etc).
  157789. */
  157790. METHODDEF(boolean)
  157791. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157792. {
  157793. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157794. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157795. JDIMENSION blocks_across, MCUs_across, MCUindex;
  157796. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  157797. JCOEF lastDC;
  157798. jpeg_component_info *compptr;
  157799. JBLOCKARRAY buffer;
  157800. JBLOCKROW thisblockrow, lastblockrow;
  157801. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157802. ci++, compptr++) {
  157803. /* Align the virtual buffer for this component. */
  157804. buffer = (*cinfo->mem->access_virt_barray)
  157805. ((j_common_ptr) cinfo, coef->whole_image[ci],
  157806. coef->iMCU_row_num * compptr->v_samp_factor,
  157807. (JDIMENSION) compptr->v_samp_factor, TRUE);
  157808. /* Count non-dummy DCT block rows in this iMCU row. */
  157809. if (coef->iMCU_row_num < last_iMCU_row)
  157810. block_rows = compptr->v_samp_factor;
  157811. else {
  157812. /* NB: can't use last_row_height here, since may not be set! */
  157813. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  157814. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  157815. }
  157816. blocks_across = compptr->width_in_blocks;
  157817. h_samp_factor = compptr->h_samp_factor;
  157818. /* Count number of dummy blocks to be added at the right margin. */
  157819. ndummy = (int) (blocks_across % h_samp_factor);
  157820. if (ndummy > 0)
  157821. ndummy = h_samp_factor - ndummy;
  157822. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  157823. * on forward_DCT processes a complete horizontal row of DCT blocks.
  157824. */
  157825. for (block_row = 0; block_row < block_rows; block_row++) {
  157826. thisblockrow = buffer[block_row];
  157827. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157828. input_buf[ci], thisblockrow,
  157829. (JDIMENSION) (block_row * DCTSIZE),
  157830. (JDIMENSION) 0, blocks_across);
  157831. if (ndummy > 0) {
  157832. /* Create dummy blocks at the right edge of the image. */
  157833. thisblockrow += blocks_across; /* => first dummy block */
  157834. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  157835. lastDC = thisblockrow[-1][0];
  157836. for (bi = 0; bi < ndummy; bi++) {
  157837. thisblockrow[bi][0] = lastDC;
  157838. }
  157839. }
  157840. }
  157841. /* If at end of image, create dummy block rows as needed.
  157842. * The tricky part here is that within each MCU, we want the DC values
  157843. * of the dummy blocks to match the last real block's DC value.
  157844. * This squeezes a few more bytes out of the resulting file...
  157845. */
  157846. if (coef->iMCU_row_num == last_iMCU_row) {
  157847. blocks_across += ndummy; /* include lower right corner */
  157848. MCUs_across = blocks_across / h_samp_factor;
  157849. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  157850. block_row++) {
  157851. thisblockrow = buffer[block_row];
  157852. lastblockrow = buffer[block_row-1];
  157853. jzero_far((void FAR *) thisblockrow,
  157854. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  157855. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  157856. lastDC = lastblockrow[h_samp_factor-1][0];
  157857. for (bi = 0; bi < h_samp_factor; bi++) {
  157858. thisblockrow[bi][0] = lastDC;
  157859. }
  157860. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  157861. lastblockrow += h_samp_factor;
  157862. }
  157863. }
  157864. }
  157865. }
  157866. /* NB: compress_output will increment iMCU_row_num if successful.
  157867. * A suspension return will result in redoing all the work above next time.
  157868. */
  157869. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  157870. return compress_output(cinfo, input_buf);
  157871. }
  157872. /*
  157873. * Process some data in subsequent passes of a multi-pass case.
  157874. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157875. * per call, ie, v_samp_factor block rows for each component in the scan.
  157876. * The data is obtained from the virtual arrays and fed to the entropy coder.
  157877. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157878. *
  157879. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  157880. */
  157881. METHODDEF(boolean)
  157882. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157883. {
  157884. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157885. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157886. int blkn, ci, xindex, yindex, yoffset;
  157887. JDIMENSION start_col;
  157888. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  157889. JBLOCKROW buffer_ptr;
  157890. jpeg_component_info *compptr;
  157891. /* Align the virtual buffers for the components used in this scan.
  157892. * NB: during first pass, this is safe only because the buffers will
  157893. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  157894. */
  157895. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157896. compptr = cinfo->cur_comp_info[ci];
  157897. buffer[ci] = (*cinfo->mem->access_virt_barray)
  157898. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  157899. coef->iMCU_row_num * compptr->v_samp_factor,
  157900. (JDIMENSION) compptr->v_samp_factor, FALSE);
  157901. }
  157902. /* Loop to process one whole iMCU row */
  157903. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157904. yoffset++) {
  157905. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  157906. MCU_col_num++) {
  157907. /* Construct list of pointers to DCT blocks belonging to this MCU */
  157908. blkn = 0; /* index of current DCT block within MCU */
  157909. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157910. compptr = cinfo->cur_comp_info[ci];
  157911. start_col = MCU_col_num * compptr->MCU_width;
  157912. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157913. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  157914. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  157915. coef->MCU_buffer[blkn++] = buffer_ptr++;
  157916. }
  157917. }
  157918. }
  157919. /* Try to write the MCU. */
  157920. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157921. /* Suspension forced; update state counters and exit */
  157922. coef->MCU_vert_offset = yoffset;
  157923. coef->mcu_ctr = MCU_col_num;
  157924. return FALSE;
  157925. }
  157926. }
  157927. /* Completed an MCU row, but perhaps not an iMCU row */
  157928. coef->mcu_ctr = 0;
  157929. }
  157930. /* Completed the iMCU row, advance counters for next one */
  157931. coef->iMCU_row_num++;
  157932. start_iMCU_row(cinfo);
  157933. return TRUE;
  157934. }
  157935. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  157936. /*
  157937. * Initialize coefficient buffer controller.
  157938. */
  157939. GLOBAL(void)
  157940. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157941. {
  157942. my_coef_ptr coef;
  157943. coef = (my_coef_ptr)
  157944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157945. SIZEOF(my_coef_controller));
  157946. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  157947. coef->pub.start_pass = start_pass_coef;
  157948. /* Create the coefficient buffer. */
  157949. if (need_full_buffer) {
  157950. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157951. /* Allocate a full-image virtual array for each component, */
  157952. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  157953. int ci;
  157954. jpeg_component_info *compptr;
  157955. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157956. ci++, compptr++) {
  157957. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  157958. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157959. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  157960. (long) compptr->h_samp_factor),
  157961. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157962. (long) compptr->v_samp_factor),
  157963. (JDIMENSION) compptr->v_samp_factor);
  157964. }
  157965. #else
  157966. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157967. #endif
  157968. } else {
  157969. /* We only need a single-MCU buffer. */
  157970. JBLOCKROW buffer;
  157971. int i;
  157972. buffer = (JBLOCKROW)
  157973. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157974. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  157975. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  157976. coef->MCU_buffer[i] = buffer + i;
  157977. }
  157978. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  157979. }
  157980. }
  157981. /********* End of inlined file: jccoefct.c *********/
  157982. /********* Start of inlined file: jccolor.c *********/
  157983. #define JPEG_INTERNALS
  157984. /* Private subobject */
  157985. typedef struct {
  157986. struct jpeg_color_converter pub; /* public fields */
  157987. /* Private state for RGB->YCC conversion */
  157988. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  157989. } my_color_converter;
  157990. typedef my_color_converter * my_cconvert_ptr;
  157991. /**************** RGB -> YCbCr conversion: most common case **************/
  157992. /*
  157993. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  157994. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  157995. * The conversion equations to be implemented are therefore
  157996. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  157997. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  157998. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  157999. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  158000. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  158001. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  158002. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  158003. * were not represented exactly. Now we sacrifice exact representation of
  158004. * maximum red and maximum blue in order to get exact grayscales.
  158005. *
  158006. * To avoid floating-point arithmetic, we represent the fractional constants
  158007. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  158008. * the products by 2^16, with appropriate rounding, to get the correct answer.
  158009. *
  158010. * For even more speed, we avoid doing any multiplications in the inner loop
  158011. * by precalculating the constants times R,G,B for all possible values.
  158012. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  158013. * for 12-bit samples it is still acceptable. It's not very reasonable for
  158014. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  158015. * colorspace anyway.
  158016. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  158017. * in the tables to save adding them separately in the inner loop.
  158018. */
  158019. #define SCALEBITS 16 /* speediest right-shift on some machines */
  158020. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  158021. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  158022. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  158023. /* We allocate one big table and divide it up into eight parts, instead of
  158024. * doing eight alloc_small requests. This lets us use a single table base
  158025. * address, which can be held in a register in the inner loops on many
  158026. * machines (more than can hold all eight addresses, anyway).
  158027. */
  158028. #define R_Y_OFF 0 /* offset to R => Y section */
  158029. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  158030. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  158031. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  158032. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  158033. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  158034. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  158035. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  158036. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  158037. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  158038. /*
  158039. * Initialize for RGB->YCC colorspace conversion.
  158040. */
  158041. METHODDEF(void)
  158042. rgb_ycc_start (j_compress_ptr cinfo)
  158043. {
  158044. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158045. INT32 * rgb_ycc_tab;
  158046. INT32 i;
  158047. /* Allocate and fill in the conversion tables. */
  158048. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  158049. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158050. (TABLE_SIZE * SIZEOF(INT32)));
  158051. for (i = 0; i <= MAXJSAMPLE; i++) {
  158052. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  158053. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  158054. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  158055. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  158056. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  158057. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  158058. * This ensures that the maximum output will round to MAXJSAMPLE
  158059. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  158060. */
  158061. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158062. /* B=>Cb and R=>Cr tables are the same
  158063. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158064. */
  158065. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  158066. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  158067. }
  158068. }
  158069. /*
  158070. * Convert some rows of samples to the JPEG colorspace.
  158071. *
  158072. * Note that we change from the application's interleaved-pixel format
  158073. * to our internal noninterleaved, one-plane-per-component format.
  158074. * The input buffer is therefore three times as wide as the output buffer.
  158075. *
  158076. * A starting row offset is provided only for the output buffer. The caller
  158077. * can easily adjust the passed input_buf value to accommodate any row
  158078. * offset required on that side.
  158079. */
  158080. METHODDEF(void)
  158081. rgb_ycc_convert (j_compress_ptr cinfo,
  158082. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158083. JDIMENSION output_row, int num_rows)
  158084. {
  158085. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158086. register int r, g, b;
  158087. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158088. register JSAMPROW inptr;
  158089. register JSAMPROW outptr0, outptr1, outptr2;
  158090. register JDIMENSION col;
  158091. JDIMENSION num_cols = cinfo->image_width;
  158092. while (--num_rows >= 0) {
  158093. inptr = *input_buf++;
  158094. outptr0 = output_buf[0][output_row];
  158095. outptr1 = output_buf[1][output_row];
  158096. outptr2 = output_buf[2][output_row];
  158097. output_row++;
  158098. for (col = 0; col < num_cols; col++) {
  158099. r = GETJSAMPLE(inptr[RGB_RED]);
  158100. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158101. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158102. inptr += RGB_PIXELSIZE;
  158103. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158104. * must be too; we do not need an explicit range-limiting operation.
  158105. * Hence the value being shifted is never negative, and we don't
  158106. * need the general RIGHT_SHIFT macro.
  158107. */
  158108. /* Y */
  158109. outptr0[col] = (JSAMPLE)
  158110. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158111. >> SCALEBITS);
  158112. /* Cb */
  158113. outptr1[col] = (JSAMPLE)
  158114. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158115. >> SCALEBITS);
  158116. /* Cr */
  158117. outptr2[col] = (JSAMPLE)
  158118. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158119. >> SCALEBITS);
  158120. }
  158121. }
  158122. }
  158123. /**************** Cases other than RGB -> YCbCr **************/
  158124. /*
  158125. * Convert some rows of samples to the JPEG colorspace.
  158126. * This version handles RGB->grayscale conversion, which is the same
  158127. * as the RGB->Y portion of RGB->YCbCr.
  158128. * We assume rgb_ycc_start has been called (we only use the Y tables).
  158129. */
  158130. METHODDEF(void)
  158131. rgb_gray_convert (j_compress_ptr cinfo,
  158132. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158133. JDIMENSION output_row, int num_rows)
  158134. {
  158135. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158136. register int r, g, b;
  158137. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158138. register JSAMPROW inptr;
  158139. register JSAMPROW outptr;
  158140. register JDIMENSION col;
  158141. JDIMENSION num_cols = cinfo->image_width;
  158142. while (--num_rows >= 0) {
  158143. inptr = *input_buf++;
  158144. outptr = output_buf[0][output_row];
  158145. output_row++;
  158146. for (col = 0; col < num_cols; col++) {
  158147. r = GETJSAMPLE(inptr[RGB_RED]);
  158148. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158149. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158150. inptr += RGB_PIXELSIZE;
  158151. /* Y */
  158152. outptr[col] = (JSAMPLE)
  158153. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158154. >> SCALEBITS);
  158155. }
  158156. }
  158157. }
  158158. /*
  158159. * Convert some rows of samples to the JPEG colorspace.
  158160. * This version handles Adobe-style CMYK->YCCK conversion,
  158161. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  158162. * conversion as above, while passing K (black) unchanged.
  158163. * We assume rgb_ycc_start has been called.
  158164. */
  158165. METHODDEF(void)
  158166. cmyk_ycck_convert (j_compress_ptr cinfo,
  158167. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158168. JDIMENSION output_row, int num_rows)
  158169. {
  158170. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158171. register int r, g, b;
  158172. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158173. register JSAMPROW inptr;
  158174. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  158175. register JDIMENSION col;
  158176. JDIMENSION num_cols = cinfo->image_width;
  158177. while (--num_rows >= 0) {
  158178. inptr = *input_buf++;
  158179. outptr0 = output_buf[0][output_row];
  158180. outptr1 = output_buf[1][output_row];
  158181. outptr2 = output_buf[2][output_row];
  158182. outptr3 = output_buf[3][output_row];
  158183. output_row++;
  158184. for (col = 0; col < num_cols; col++) {
  158185. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  158186. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  158187. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  158188. /* K passes through as-is */
  158189. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  158190. inptr += 4;
  158191. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158192. * must be too; we do not need an explicit range-limiting operation.
  158193. * Hence the value being shifted is never negative, and we don't
  158194. * need the general RIGHT_SHIFT macro.
  158195. */
  158196. /* Y */
  158197. outptr0[col] = (JSAMPLE)
  158198. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158199. >> SCALEBITS);
  158200. /* Cb */
  158201. outptr1[col] = (JSAMPLE)
  158202. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158203. >> SCALEBITS);
  158204. /* Cr */
  158205. outptr2[col] = (JSAMPLE)
  158206. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158207. >> SCALEBITS);
  158208. }
  158209. }
  158210. }
  158211. /*
  158212. * Convert some rows of samples to the JPEG colorspace.
  158213. * This version handles grayscale output with no conversion.
  158214. * The source can be either plain grayscale or YCbCr (since Y == gray).
  158215. */
  158216. METHODDEF(void)
  158217. grayscale_convert (j_compress_ptr cinfo,
  158218. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158219. JDIMENSION output_row, int num_rows)
  158220. {
  158221. register JSAMPROW inptr;
  158222. register JSAMPROW outptr;
  158223. register JDIMENSION col;
  158224. JDIMENSION num_cols = cinfo->image_width;
  158225. int instride = cinfo->input_components;
  158226. while (--num_rows >= 0) {
  158227. inptr = *input_buf++;
  158228. outptr = output_buf[0][output_row];
  158229. output_row++;
  158230. for (col = 0; col < num_cols; col++) {
  158231. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  158232. inptr += instride;
  158233. }
  158234. }
  158235. }
  158236. /*
  158237. * Convert some rows of samples to the JPEG colorspace.
  158238. * This version handles multi-component colorspaces without conversion.
  158239. * We assume input_components == num_components.
  158240. */
  158241. METHODDEF(void)
  158242. null_convert (j_compress_ptr cinfo,
  158243. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158244. JDIMENSION output_row, int num_rows)
  158245. {
  158246. register JSAMPROW inptr;
  158247. register JSAMPROW outptr;
  158248. register JDIMENSION col;
  158249. register int ci;
  158250. int nc = cinfo->num_components;
  158251. JDIMENSION num_cols = cinfo->image_width;
  158252. while (--num_rows >= 0) {
  158253. /* It seems fastest to make a separate pass for each component. */
  158254. for (ci = 0; ci < nc; ci++) {
  158255. inptr = *input_buf;
  158256. outptr = output_buf[ci][output_row];
  158257. for (col = 0; col < num_cols; col++) {
  158258. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  158259. inptr += nc;
  158260. }
  158261. }
  158262. input_buf++;
  158263. output_row++;
  158264. }
  158265. }
  158266. /*
  158267. * Empty method for start_pass.
  158268. */
  158269. METHODDEF(void)
  158270. null_method (j_compress_ptr cinfo)
  158271. {
  158272. /* no work needed */
  158273. }
  158274. /*
  158275. * Module initialization routine for input colorspace conversion.
  158276. */
  158277. GLOBAL(void)
  158278. jinit_color_converter (j_compress_ptr cinfo)
  158279. {
  158280. my_cconvert_ptr cconvert;
  158281. cconvert = (my_cconvert_ptr)
  158282. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158283. SIZEOF(my_color_converter));
  158284. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  158285. /* set start_pass to null method until we find out differently */
  158286. cconvert->pub.start_pass = null_method;
  158287. /* Make sure input_components agrees with in_color_space */
  158288. switch (cinfo->in_color_space) {
  158289. case JCS_GRAYSCALE:
  158290. if (cinfo->input_components != 1)
  158291. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158292. break;
  158293. case JCS_RGB:
  158294. #if RGB_PIXELSIZE != 3
  158295. if (cinfo->input_components != RGB_PIXELSIZE)
  158296. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158297. break;
  158298. #endif /* else share code with YCbCr */
  158299. case JCS_YCbCr:
  158300. if (cinfo->input_components != 3)
  158301. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158302. break;
  158303. case JCS_CMYK:
  158304. case JCS_YCCK:
  158305. if (cinfo->input_components != 4)
  158306. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158307. break;
  158308. default: /* JCS_UNKNOWN can be anything */
  158309. if (cinfo->input_components < 1)
  158310. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158311. break;
  158312. }
  158313. /* Check num_components, set conversion method based on requested space */
  158314. switch (cinfo->jpeg_color_space) {
  158315. case JCS_GRAYSCALE:
  158316. if (cinfo->num_components != 1)
  158317. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158318. if (cinfo->in_color_space == JCS_GRAYSCALE)
  158319. cconvert->pub.color_convert = grayscale_convert;
  158320. else if (cinfo->in_color_space == JCS_RGB) {
  158321. cconvert->pub.start_pass = rgb_ycc_start;
  158322. cconvert->pub.color_convert = rgb_gray_convert;
  158323. } else if (cinfo->in_color_space == JCS_YCbCr)
  158324. cconvert->pub.color_convert = grayscale_convert;
  158325. else
  158326. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158327. break;
  158328. case JCS_RGB:
  158329. if (cinfo->num_components != 3)
  158330. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158331. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  158332. cconvert->pub.color_convert = null_convert;
  158333. else
  158334. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158335. break;
  158336. case JCS_YCbCr:
  158337. if (cinfo->num_components != 3)
  158338. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158339. if (cinfo->in_color_space == JCS_RGB) {
  158340. cconvert->pub.start_pass = rgb_ycc_start;
  158341. cconvert->pub.color_convert = rgb_ycc_convert;
  158342. } else if (cinfo->in_color_space == JCS_YCbCr)
  158343. cconvert->pub.color_convert = null_convert;
  158344. else
  158345. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158346. break;
  158347. case JCS_CMYK:
  158348. if (cinfo->num_components != 4)
  158349. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158350. if (cinfo->in_color_space == JCS_CMYK)
  158351. cconvert->pub.color_convert = null_convert;
  158352. else
  158353. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158354. break;
  158355. case JCS_YCCK:
  158356. if (cinfo->num_components != 4)
  158357. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158358. if (cinfo->in_color_space == JCS_CMYK) {
  158359. cconvert->pub.start_pass = rgb_ycc_start;
  158360. cconvert->pub.color_convert = cmyk_ycck_convert;
  158361. } else if (cinfo->in_color_space == JCS_YCCK)
  158362. cconvert->pub.color_convert = null_convert;
  158363. else
  158364. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158365. break;
  158366. default: /* allow null conversion of JCS_UNKNOWN */
  158367. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  158368. cinfo->num_components != cinfo->input_components)
  158369. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158370. cconvert->pub.color_convert = null_convert;
  158371. break;
  158372. }
  158373. }
  158374. /********* End of inlined file: jccolor.c *********/
  158375. #undef FIX
  158376. /********* Start of inlined file: jcdctmgr.c *********/
  158377. #define JPEG_INTERNALS
  158378. /********* Start of inlined file: jdct.h *********/
  158379. /*
  158380. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  158381. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  158382. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  158383. * implementations use an array of type FAST_FLOAT, instead.)
  158384. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  158385. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  158386. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  158387. * convention improves accuracy in integer implementations and saves some
  158388. * work in floating-point ones.
  158389. * Quantization of the output coefficients is done by jcdctmgr.c.
  158390. */
  158391. #ifndef __jdct_h__
  158392. #define __jdct_h__
  158393. #if BITS_IN_JSAMPLE == 8
  158394. typedef int DCTELEM; /* 16 or 32 bits is fine */
  158395. #else
  158396. typedef INT32 DCTELEM; /* must have 32 bits */
  158397. #endif
  158398. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  158399. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  158400. /*
  158401. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  158402. * to an output sample array. The routine must dequantize the input data as
  158403. * well as perform the IDCT; for dequantization, it uses the multiplier table
  158404. * pointed to by compptr->dct_table. The output data is to be placed into the
  158405. * sample array starting at a specified column. (Any row offset needed will
  158406. * be applied to the array pointer before it is passed to the IDCT code.)
  158407. * Note that the number of samples emitted by the IDCT routine is
  158408. * DCT_scaled_size * DCT_scaled_size.
  158409. */
  158410. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  158411. /*
  158412. * Each IDCT routine has its own ideas about the best dct_table element type.
  158413. */
  158414. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  158415. #if BITS_IN_JSAMPLE == 8
  158416. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  158417. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  158418. #else
  158419. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  158420. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  158421. #endif
  158422. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  158423. /*
  158424. * Each IDCT routine is responsible for range-limiting its results and
  158425. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  158426. * be quite far out of range if the input data is corrupt, so a bulletproof
  158427. * range-limiting step is required. We use a mask-and-table-lookup method
  158428. * to do the combined operations quickly. See the comments with
  158429. * prepare_range_limit_table (in jdmaster.c) for more info.
  158430. */
  158431. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  158432. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  158433. /* Short forms of external names for systems with brain-damaged linkers. */
  158434. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158435. #define jpeg_fdct_islow jFDislow
  158436. #define jpeg_fdct_ifast jFDifast
  158437. #define jpeg_fdct_float jFDfloat
  158438. #define jpeg_idct_islow jRDislow
  158439. #define jpeg_idct_ifast jRDifast
  158440. #define jpeg_idct_float jRDfloat
  158441. #define jpeg_idct_4x4 jRD4x4
  158442. #define jpeg_idct_2x2 jRD2x2
  158443. #define jpeg_idct_1x1 jRD1x1
  158444. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158445. /* Extern declarations for the forward and inverse DCT routines. */
  158446. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  158447. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  158448. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  158449. EXTERN(void) jpeg_idct_islow
  158450. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158451. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158452. EXTERN(void) jpeg_idct_ifast
  158453. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158454. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158455. EXTERN(void) jpeg_idct_float
  158456. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158457. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158458. EXTERN(void) jpeg_idct_4x4
  158459. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158460. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158461. EXTERN(void) jpeg_idct_2x2
  158462. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158463. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158464. EXTERN(void) jpeg_idct_1x1
  158465. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158466. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158467. /*
  158468. * Macros for handling fixed-point arithmetic; these are used by many
  158469. * but not all of the DCT/IDCT modules.
  158470. *
  158471. * All values are expected to be of type INT32.
  158472. * Fractional constants are scaled left by CONST_BITS bits.
  158473. * CONST_BITS is defined within each module using these macros,
  158474. * and may differ from one module to the next.
  158475. */
  158476. #define ONE ((INT32) 1)
  158477. #define CONST_SCALE (ONE << CONST_BITS)
  158478. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  158479. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  158480. * thus causing a lot of useless floating-point operations at run time.
  158481. */
  158482. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  158483. /* Descale and correctly round an INT32 value that's scaled by N bits.
  158484. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  158485. * the fudge factor is correct for either sign of X.
  158486. */
  158487. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  158488. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  158489. * This macro is used only when the two inputs will actually be no more than
  158490. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  158491. * full 32x32 multiply. This provides a useful speedup on many machines.
  158492. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  158493. * in C, but some C compilers will do the right thing if you provide the
  158494. * correct combination of casts.
  158495. */
  158496. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158497. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  158498. #endif
  158499. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  158500. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  158501. #endif
  158502. #ifndef MULTIPLY16C16 /* default definition */
  158503. #define MULTIPLY16C16(var,const) ((var) * (const))
  158504. #endif
  158505. /* Same except both inputs are variables. */
  158506. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158507. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  158508. #endif
  158509. #ifndef MULTIPLY16V16 /* default definition */
  158510. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  158511. #endif
  158512. #endif
  158513. /********* End of inlined file: jdct.h *********/
  158514. /* Private declarations for DCT subsystem */
  158515. /* Private subobject for this module */
  158516. typedef struct {
  158517. struct jpeg_forward_dct pub; /* public fields */
  158518. /* Pointer to the DCT routine actually in use */
  158519. forward_DCT_method_ptr do_dct;
  158520. /* The actual post-DCT divisors --- not identical to the quant table
  158521. * entries, because of scaling (especially for an unnormalized DCT).
  158522. * Each table is given in normal array order.
  158523. */
  158524. DCTELEM * divisors[NUM_QUANT_TBLS];
  158525. #ifdef DCT_FLOAT_SUPPORTED
  158526. /* Same as above for the floating-point case. */
  158527. float_DCT_method_ptr do_float_dct;
  158528. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  158529. #endif
  158530. } my_fdct_controller;
  158531. typedef my_fdct_controller * my_fdct_ptr;
  158532. /*
  158533. * Initialize for a processing pass.
  158534. * Verify that all referenced Q-tables are present, and set up
  158535. * the divisor table for each one.
  158536. * In the current implementation, DCT of all components is done during
  158537. * the first pass, even if only some components will be output in the
  158538. * first scan. Hence all components should be examined here.
  158539. */
  158540. METHODDEF(void)
  158541. start_pass_fdctmgr (j_compress_ptr cinfo)
  158542. {
  158543. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158544. int ci, qtblno, i;
  158545. jpeg_component_info *compptr;
  158546. JQUANT_TBL * qtbl;
  158547. DCTELEM * dtbl;
  158548. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158549. ci++, compptr++) {
  158550. qtblno = compptr->quant_tbl_no;
  158551. /* Make sure specified quantization table is present */
  158552. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  158553. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  158554. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  158555. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  158556. /* Compute divisors for this quant table */
  158557. /* We may do this more than once for same table, but it's not a big deal */
  158558. switch (cinfo->dct_method) {
  158559. #ifdef DCT_ISLOW_SUPPORTED
  158560. case JDCT_ISLOW:
  158561. /* For LL&M IDCT method, divisors are equal to raw quantization
  158562. * coefficients multiplied by 8 (to counteract scaling).
  158563. */
  158564. if (fdct->divisors[qtblno] == NULL) {
  158565. fdct->divisors[qtblno] = (DCTELEM *)
  158566. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158567. DCTSIZE2 * SIZEOF(DCTELEM));
  158568. }
  158569. dtbl = fdct->divisors[qtblno];
  158570. for (i = 0; i < DCTSIZE2; i++) {
  158571. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  158572. }
  158573. break;
  158574. #endif
  158575. #ifdef DCT_IFAST_SUPPORTED
  158576. case JDCT_IFAST:
  158577. {
  158578. /* For AA&N IDCT method, divisors are equal to quantization
  158579. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158580. * scalefactor[0] = 1
  158581. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158582. * We apply a further scale factor of 8.
  158583. */
  158584. #define CONST_BITS 14
  158585. static const INT16 aanscales[DCTSIZE2] = {
  158586. /* precomputed values scaled up by 14 bits */
  158587. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158588. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  158589. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  158590. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  158591. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158592. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  158593. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  158594. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  158595. };
  158596. SHIFT_TEMPS
  158597. if (fdct->divisors[qtblno] == NULL) {
  158598. fdct->divisors[qtblno] = (DCTELEM *)
  158599. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158600. DCTSIZE2 * SIZEOF(DCTELEM));
  158601. }
  158602. dtbl = fdct->divisors[qtblno];
  158603. for (i = 0; i < DCTSIZE2; i++) {
  158604. dtbl[i] = (DCTELEM)
  158605. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  158606. (INT32) aanscales[i]),
  158607. CONST_BITS-3);
  158608. }
  158609. }
  158610. break;
  158611. #endif
  158612. #ifdef DCT_FLOAT_SUPPORTED
  158613. case JDCT_FLOAT:
  158614. {
  158615. /* For float AA&N IDCT method, divisors are equal to quantization
  158616. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158617. * scalefactor[0] = 1
  158618. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158619. * We apply a further scale factor of 8.
  158620. * What's actually stored is 1/divisor so that the inner loop can
  158621. * use a multiplication rather than a division.
  158622. */
  158623. FAST_FLOAT * fdtbl;
  158624. int row, col;
  158625. static const double aanscalefactor[DCTSIZE] = {
  158626. 1.0, 1.387039845, 1.306562965, 1.175875602,
  158627. 1.0, 0.785694958, 0.541196100, 0.275899379
  158628. };
  158629. if (fdct->float_divisors[qtblno] == NULL) {
  158630. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  158631. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158632. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  158633. }
  158634. fdtbl = fdct->float_divisors[qtblno];
  158635. i = 0;
  158636. for (row = 0; row < DCTSIZE; row++) {
  158637. for (col = 0; col < DCTSIZE; col++) {
  158638. fdtbl[i] = (FAST_FLOAT)
  158639. (1.0 / (((double) qtbl->quantval[i] *
  158640. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  158641. i++;
  158642. }
  158643. }
  158644. }
  158645. break;
  158646. #endif
  158647. default:
  158648. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158649. break;
  158650. }
  158651. }
  158652. }
  158653. /*
  158654. * Perform forward DCT on one or more blocks of a component.
  158655. *
  158656. * The input samples are taken from the sample_data[] array starting at
  158657. * position start_row/start_col, and moving to the right for any additional
  158658. * blocks. The quantized coefficients are returned in coef_blocks[].
  158659. */
  158660. METHODDEF(void)
  158661. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158662. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158663. JDIMENSION start_row, JDIMENSION start_col,
  158664. JDIMENSION num_blocks)
  158665. /* This version is used for integer DCT implementations. */
  158666. {
  158667. /* This routine is heavily used, so it's worth coding it tightly. */
  158668. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158669. forward_DCT_method_ptr do_dct = fdct->do_dct;
  158670. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  158671. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158672. JDIMENSION bi;
  158673. sample_data += start_row; /* fold in the vertical offset once */
  158674. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158675. /* Load data into workspace, applying unsigned->signed conversion */
  158676. { register DCTELEM *workspaceptr;
  158677. register JSAMPROW elemptr;
  158678. register int elemr;
  158679. workspaceptr = workspace;
  158680. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158681. elemptr = sample_data[elemr] + start_col;
  158682. #if DCTSIZE == 8 /* unroll the inner loop */
  158683. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158684. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158685. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158686. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158687. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158688. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158689. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158690. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158691. #else
  158692. { register int elemc;
  158693. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158694. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158695. }
  158696. }
  158697. #endif
  158698. }
  158699. }
  158700. /* Perform the DCT */
  158701. (*do_dct) (workspace);
  158702. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158703. { register DCTELEM temp, qval;
  158704. register int i;
  158705. register JCOEFPTR output_ptr = coef_blocks[bi];
  158706. for (i = 0; i < DCTSIZE2; i++) {
  158707. qval = divisors[i];
  158708. temp = workspace[i];
  158709. /* Divide the coefficient value by qval, ensuring proper rounding.
  158710. * Since C does not specify the direction of rounding for negative
  158711. * quotients, we have to force the dividend positive for portability.
  158712. *
  158713. * In most files, at least half of the output values will be zero
  158714. * (at default quantization settings, more like three-quarters...)
  158715. * so we should ensure that this case is fast. On many machines,
  158716. * a comparison is enough cheaper than a divide to make a special test
  158717. * a win. Since both inputs will be nonnegative, we need only test
  158718. * for a < b to discover whether a/b is 0.
  158719. * If your machine's division is fast enough, define FAST_DIVIDE.
  158720. */
  158721. #ifdef FAST_DIVIDE
  158722. #define DIVIDE_BY(a,b) a /= b
  158723. #else
  158724. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  158725. #endif
  158726. if (temp < 0) {
  158727. temp = -temp;
  158728. temp += qval>>1; /* for rounding */
  158729. DIVIDE_BY(temp, qval);
  158730. temp = -temp;
  158731. } else {
  158732. temp += qval>>1; /* for rounding */
  158733. DIVIDE_BY(temp, qval);
  158734. }
  158735. output_ptr[i] = (JCOEF) temp;
  158736. }
  158737. }
  158738. }
  158739. }
  158740. #ifdef DCT_FLOAT_SUPPORTED
  158741. METHODDEF(void)
  158742. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158743. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158744. JDIMENSION start_row, JDIMENSION start_col,
  158745. JDIMENSION num_blocks)
  158746. /* This version is used for floating-point DCT implementations. */
  158747. {
  158748. /* This routine is heavily used, so it's worth coding it tightly. */
  158749. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158750. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  158751. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  158752. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158753. JDIMENSION bi;
  158754. sample_data += start_row; /* fold in the vertical offset once */
  158755. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158756. /* Load data into workspace, applying unsigned->signed conversion */
  158757. { register FAST_FLOAT *workspaceptr;
  158758. register JSAMPROW elemptr;
  158759. register int elemr;
  158760. workspaceptr = workspace;
  158761. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158762. elemptr = sample_data[elemr] + start_col;
  158763. #if DCTSIZE == 8 /* unroll the inner loop */
  158764. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158765. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158766. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158767. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158768. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158769. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158770. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158771. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158772. #else
  158773. { register int elemc;
  158774. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158775. *workspaceptr++ = (FAST_FLOAT)
  158776. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158777. }
  158778. }
  158779. #endif
  158780. }
  158781. }
  158782. /* Perform the DCT */
  158783. (*do_dct) (workspace);
  158784. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158785. { register FAST_FLOAT temp;
  158786. register int i;
  158787. register JCOEFPTR output_ptr = coef_blocks[bi];
  158788. for (i = 0; i < DCTSIZE2; i++) {
  158789. /* Apply the quantization and scaling factor */
  158790. temp = workspace[i] * divisors[i];
  158791. /* Round to nearest integer.
  158792. * Since C does not specify the direction of rounding for negative
  158793. * quotients, we have to force the dividend positive for portability.
  158794. * The maximum coefficient size is +-16K (for 12-bit data), so this
  158795. * code should work for either 16-bit or 32-bit ints.
  158796. */
  158797. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  158798. }
  158799. }
  158800. }
  158801. }
  158802. #endif /* DCT_FLOAT_SUPPORTED */
  158803. /*
  158804. * Initialize FDCT manager.
  158805. */
  158806. GLOBAL(void)
  158807. jinit_forward_dct (j_compress_ptr cinfo)
  158808. {
  158809. my_fdct_ptr fdct;
  158810. int i;
  158811. fdct = (my_fdct_ptr)
  158812. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158813. SIZEOF(my_fdct_controller));
  158814. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  158815. fdct->pub.start_pass = start_pass_fdctmgr;
  158816. switch (cinfo->dct_method) {
  158817. #ifdef DCT_ISLOW_SUPPORTED
  158818. case JDCT_ISLOW:
  158819. fdct->pub.forward_DCT = forward_DCT;
  158820. fdct->do_dct = jpeg_fdct_islow;
  158821. break;
  158822. #endif
  158823. #ifdef DCT_IFAST_SUPPORTED
  158824. case JDCT_IFAST:
  158825. fdct->pub.forward_DCT = forward_DCT;
  158826. fdct->do_dct = jpeg_fdct_ifast;
  158827. break;
  158828. #endif
  158829. #ifdef DCT_FLOAT_SUPPORTED
  158830. case JDCT_FLOAT:
  158831. fdct->pub.forward_DCT = forward_DCT_float;
  158832. fdct->do_float_dct = jpeg_fdct_float;
  158833. break;
  158834. #endif
  158835. default:
  158836. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158837. break;
  158838. }
  158839. /* Mark divisor tables unallocated */
  158840. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158841. fdct->divisors[i] = NULL;
  158842. #ifdef DCT_FLOAT_SUPPORTED
  158843. fdct->float_divisors[i] = NULL;
  158844. #endif
  158845. }
  158846. }
  158847. /********* End of inlined file: jcdctmgr.c *********/
  158848. #undef CONST_BITS
  158849. /********* Start of inlined file: jchuff.c *********/
  158850. #define JPEG_INTERNALS
  158851. /********* Start of inlined file: jchuff.h *********/
  158852. /* The legal range of a DCT coefficient is
  158853. * -1024 .. +1023 for 8-bit data;
  158854. * -16384 .. +16383 for 12-bit data.
  158855. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  158856. */
  158857. #ifndef _jchuff_h_
  158858. #define _jchuff_h_
  158859. #if BITS_IN_JSAMPLE == 8
  158860. #define MAX_COEF_BITS 10
  158861. #else
  158862. #define MAX_COEF_BITS 14
  158863. #endif
  158864. /* Derived data constructed for each Huffman table */
  158865. typedef struct {
  158866. unsigned int ehufco[256]; /* code for each symbol */
  158867. char ehufsi[256]; /* length of code for each symbol */
  158868. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  158869. } c_derived_tbl;
  158870. /* Short forms of external names for systems with brain-damaged linkers. */
  158871. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158872. #define jpeg_make_c_derived_tbl jMkCDerived
  158873. #define jpeg_gen_optimal_table jGenOptTbl
  158874. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158875. /* Expand a Huffman table definition into the derived format */
  158876. EXTERN(void) jpeg_make_c_derived_tbl
  158877. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  158878. c_derived_tbl ** pdtbl));
  158879. /* Generate an optimal table definition given the specified counts */
  158880. EXTERN(void) jpeg_gen_optimal_table
  158881. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  158882. #endif
  158883. /********* End of inlined file: jchuff.h *********/
  158884. /* Declarations shared with jcphuff.c */
  158885. /* Expanded entropy encoder object for Huffman encoding.
  158886. *
  158887. * The savable_state subrecord contains fields that change within an MCU,
  158888. * but must not be updated permanently until we complete the MCU.
  158889. */
  158890. typedef struct {
  158891. INT32 put_buffer; /* current bit-accumulation buffer */
  158892. int put_bits; /* # of bits now in it */
  158893. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  158894. } savable_state;
  158895. /* This macro is to work around compilers with missing or broken
  158896. * structure assignment. You'll need to fix this code if you have
  158897. * such a compiler and you change MAX_COMPS_IN_SCAN.
  158898. */
  158899. #ifndef NO_STRUCT_ASSIGN
  158900. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  158901. #else
  158902. #if MAX_COMPS_IN_SCAN == 4
  158903. #define ASSIGN_STATE(dest,src) \
  158904. ((dest).put_buffer = (src).put_buffer, \
  158905. (dest).put_bits = (src).put_bits, \
  158906. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  158907. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  158908. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  158909. (dest).last_dc_val[3] = (src).last_dc_val[3])
  158910. #endif
  158911. #endif
  158912. typedef struct {
  158913. struct jpeg_entropy_encoder pub; /* public fields */
  158914. savable_state saved; /* Bit buffer & DC state at start of MCU */
  158915. /* These fields are NOT loaded into local working state. */
  158916. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  158917. int next_restart_num; /* next restart number to write (0-7) */
  158918. /* Pointers to derived tables (these workspaces have image lifespan) */
  158919. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  158920. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  158921. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  158922. long * dc_count_ptrs[NUM_HUFF_TBLS];
  158923. long * ac_count_ptrs[NUM_HUFF_TBLS];
  158924. #endif
  158925. } huff_entropy_encoder;
  158926. typedef huff_entropy_encoder * huff_entropy_ptr;
  158927. /* Working state while writing an MCU.
  158928. * This struct contains all the fields that are needed by subroutines.
  158929. */
  158930. typedef struct {
  158931. JOCTET * next_output_byte; /* => next byte to write in buffer */
  158932. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  158933. savable_state cur; /* Current bit buffer & DC state */
  158934. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  158935. } working_state;
  158936. /* Forward declarations */
  158937. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  158938. JBLOCKROW *MCU_data));
  158939. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  158940. #ifdef ENTROPY_OPT_SUPPORTED
  158941. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  158942. JBLOCKROW *MCU_data));
  158943. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  158944. #endif
  158945. /*
  158946. * Initialize for a Huffman-compressed scan.
  158947. * If gather_statistics is TRUE, we do not output anything during the scan,
  158948. * just count the Huffman symbols used and generate Huffman code tables.
  158949. */
  158950. METHODDEF(void)
  158951. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  158952. {
  158953. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158954. int ci, dctbl, actbl;
  158955. jpeg_component_info * compptr;
  158956. if (gather_statistics) {
  158957. #ifdef ENTROPY_OPT_SUPPORTED
  158958. entropy->pub.encode_mcu = encode_mcu_gather;
  158959. entropy->pub.finish_pass = finish_pass_gather;
  158960. #else
  158961. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158962. #endif
  158963. } else {
  158964. entropy->pub.encode_mcu = encode_mcu_huff;
  158965. entropy->pub.finish_pass = finish_pass_huff;
  158966. }
  158967. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158968. compptr = cinfo->cur_comp_info[ci];
  158969. dctbl = compptr->dc_tbl_no;
  158970. actbl = compptr->ac_tbl_no;
  158971. if (gather_statistics) {
  158972. #ifdef ENTROPY_OPT_SUPPORTED
  158973. /* Check for invalid table indexes */
  158974. /* (make_c_derived_tbl does this in the other path) */
  158975. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  158976. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  158977. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  158978. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  158979. /* Allocate and zero the statistics tables */
  158980. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  158981. if (entropy->dc_count_ptrs[dctbl] == NULL)
  158982. entropy->dc_count_ptrs[dctbl] = (long *)
  158983. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158984. 257 * SIZEOF(long));
  158985. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  158986. if (entropy->ac_count_ptrs[actbl] == NULL)
  158987. entropy->ac_count_ptrs[actbl] = (long *)
  158988. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158989. 257 * SIZEOF(long));
  158990. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  158991. #endif
  158992. } else {
  158993. /* Compute derived values for Huffman tables */
  158994. /* We may do this more than once for a table, but it's not expensive */
  158995. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  158996. & entropy->dc_derived_tbls[dctbl]);
  158997. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  158998. & entropy->ac_derived_tbls[actbl]);
  158999. }
  159000. /* Initialize DC predictions to 0 */
  159001. entropy->saved.last_dc_val[ci] = 0;
  159002. }
  159003. /* Initialize bit buffer to empty */
  159004. entropy->saved.put_buffer = 0;
  159005. entropy->saved.put_bits = 0;
  159006. /* Initialize restart stuff */
  159007. entropy->restarts_to_go = cinfo->restart_interval;
  159008. entropy->next_restart_num = 0;
  159009. }
  159010. /*
  159011. * Compute the derived values for a Huffman table.
  159012. * This routine also performs some validation checks on the table.
  159013. *
  159014. * Note this is also used by jcphuff.c.
  159015. */
  159016. GLOBAL(void)
  159017. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  159018. c_derived_tbl ** pdtbl)
  159019. {
  159020. JHUFF_TBL *htbl;
  159021. c_derived_tbl *dtbl;
  159022. int p, i, l, lastp, si, maxsymbol;
  159023. char huffsize[257];
  159024. unsigned int huffcode[257];
  159025. unsigned int code;
  159026. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  159027. * paralleling the order of the symbols themselves in htbl->huffval[].
  159028. */
  159029. /* Find the input Huffman table */
  159030. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  159031. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159032. htbl =
  159033. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  159034. if (htbl == NULL)
  159035. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159036. /* Allocate a workspace if we haven't already done so. */
  159037. if (*pdtbl == NULL)
  159038. *pdtbl = (c_derived_tbl *)
  159039. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159040. SIZEOF(c_derived_tbl));
  159041. dtbl = *pdtbl;
  159042. /* Figure C.1: make table of Huffman code length for each symbol */
  159043. p = 0;
  159044. for (l = 1; l <= 16; l++) {
  159045. i = (int) htbl->bits[l];
  159046. if (i < 0 || p + i > 256) /* protect against table overrun */
  159047. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159048. while (i--)
  159049. huffsize[p++] = (char) l;
  159050. }
  159051. huffsize[p] = 0;
  159052. lastp = p;
  159053. /* Figure C.2: generate the codes themselves */
  159054. /* We also validate that the counts represent a legal Huffman code tree. */
  159055. code = 0;
  159056. si = huffsize[0];
  159057. p = 0;
  159058. while (huffsize[p]) {
  159059. while (((int) huffsize[p]) == si) {
  159060. huffcode[p++] = code;
  159061. code++;
  159062. }
  159063. /* code is now 1 more than the last code used for codelength si; but
  159064. * it must still fit in si bits, since no code is allowed to be all ones.
  159065. */
  159066. if (((INT32) code) >= (((INT32) 1) << si))
  159067. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159068. code <<= 1;
  159069. si++;
  159070. }
  159071. /* Figure C.3: generate encoding tables */
  159072. /* These are code and size indexed by symbol value */
  159073. /* Set all codeless symbols to have code length 0;
  159074. * this lets us detect duplicate VAL entries here, and later
  159075. * allows emit_bits to detect any attempt to emit such symbols.
  159076. */
  159077. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  159078. /* This is also a convenient place to check for out-of-range
  159079. * and duplicated VAL entries. We allow 0..255 for AC symbols
  159080. * but only 0..15 for DC. (We could constrain them further
  159081. * based on data depth and mode, but this seems enough.)
  159082. */
  159083. maxsymbol = isDC ? 15 : 255;
  159084. for (p = 0; p < lastp; p++) {
  159085. i = htbl->huffval[p];
  159086. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  159087. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159088. dtbl->ehufco[i] = huffcode[p];
  159089. dtbl->ehufsi[i] = huffsize[p];
  159090. }
  159091. }
  159092. /* Outputting bytes to the file */
  159093. /* Emit a byte, taking 'action' if must suspend. */
  159094. #define emit_byte(state,val,action) \
  159095. { *(state)->next_output_byte++ = (JOCTET) (val); \
  159096. if (--(state)->free_in_buffer == 0) \
  159097. if (! dump_buffer(state)) \
  159098. { action; } }
  159099. LOCAL(boolean)
  159100. dump_buffer (working_state * state)
  159101. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  159102. {
  159103. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  159104. if (! (*dest->empty_output_buffer) (state->cinfo))
  159105. return FALSE;
  159106. /* After a successful buffer dump, must reset buffer pointers */
  159107. state->next_output_byte = dest->next_output_byte;
  159108. state->free_in_buffer = dest->free_in_buffer;
  159109. return TRUE;
  159110. }
  159111. /* Outputting bits to the file */
  159112. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159113. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159114. * in one call, and we never retain more than 7 bits in put_buffer
  159115. * between calls, so 24 bits are sufficient.
  159116. */
  159117. INLINE
  159118. LOCAL(boolean)
  159119. emit_bits (working_state * state, unsigned int code, int size)
  159120. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  159121. {
  159122. /* This routine is heavily used, so it's worth coding tightly. */
  159123. register INT32 put_buffer = (INT32) code;
  159124. register int put_bits = state->cur.put_bits;
  159125. /* if size is 0, caller used an invalid Huffman table entry */
  159126. if (size == 0)
  159127. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  159128. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159129. put_bits += size; /* new number of bits in buffer */
  159130. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159131. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  159132. while (put_bits >= 8) {
  159133. int c = (int) ((put_buffer >> 16) & 0xFF);
  159134. emit_byte(state, c, return FALSE);
  159135. if (c == 0xFF) { /* need to stuff a zero byte? */
  159136. emit_byte(state, 0, return FALSE);
  159137. }
  159138. put_buffer <<= 8;
  159139. put_bits -= 8;
  159140. }
  159141. state->cur.put_buffer = put_buffer; /* update state variables */
  159142. state->cur.put_bits = put_bits;
  159143. return TRUE;
  159144. }
  159145. LOCAL(boolean)
  159146. flush_bits (working_state * state)
  159147. {
  159148. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  159149. return FALSE;
  159150. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  159151. state->cur.put_bits = 0;
  159152. return TRUE;
  159153. }
  159154. /* Encode a single block's worth of coefficients */
  159155. LOCAL(boolean)
  159156. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  159157. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  159158. {
  159159. register int temp, temp2;
  159160. register int nbits;
  159161. register int k, r, i;
  159162. /* Encode the DC coefficient difference per section F.1.2.1 */
  159163. temp = temp2 = block[0] - last_dc_val;
  159164. if (temp < 0) {
  159165. temp = -temp; /* temp is abs value of input */
  159166. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159167. /* This code assumes we are on a two's complement machine */
  159168. temp2--;
  159169. }
  159170. /* Find the number of bits needed for the magnitude of the coefficient */
  159171. nbits = 0;
  159172. while (temp) {
  159173. nbits++;
  159174. temp >>= 1;
  159175. }
  159176. /* Check for out-of-range coefficient values.
  159177. * Since we're encoding a difference, the range limit is twice as much.
  159178. */
  159179. if (nbits > MAX_COEF_BITS+1)
  159180. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159181. /* Emit the Huffman-coded symbol for the number of bits */
  159182. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  159183. return FALSE;
  159184. /* Emit that number of bits of the value, if positive, */
  159185. /* or the complement of its magnitude, if negative. */
  159186. if (nbits) /* emit_bits rejects calls with size 0 */
  159187. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159188. return FALSE;
  159189. /* Encode the AC coefficients per section F.1.2.2 */
  159190. r = 0; /* r = run length of zeros */
  159191. for (k = 1; k < DCTSIZE2; k++) {
  159192. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159193. r++;
  159194. } else {
  159195. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159196. while (r > 15) {
  159197. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  159198. return FALSE;
  159199. r -= 16;
  159200. }
  159201. temp2 = temp;
  159202. if (temp < 0) {
  159203. temp = -temp; /* temp is abs value of input */
  159204. /* This code assumes we are on a two's complement machine */
  159205. temp2--;
  159206. }
  159207. /* Find the number of bits needed for the magnitude of the coefficient */
  159208. nbits = 1; /* there must be at least one 1 bit */
  159209. while ((temp >>= 1))
  159210. nbits++;
  159211. /* Check for out-of-range coefficient values */
  159212. if (nbits > MAX_COEF_BITS)
  159213. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159214. /* Emit Huffman symbol for run length / number of bits */
  159215. i = (r << 4) + nbits;
  159216. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  159217. return FALSE;
  159218. /* Emit that number of bits of the value, if positive, */
  159219. /* or the complement of its magnitude, if negative. */
  159220. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159221. return FALSE;
  159222. r = 0;
  159223. }
  159224. }
  159225. /* If the last coef(s) were zero, emit an end-of-block code */
  159226. if (r > 0)
  159227. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  159228. return FALSE;
  159229. return TRUE;
  159230. }
  159231. /*
  159232. * Emit a restart marker & resynchronize predictions.
  159233. */
  159234. LOCAL(boolean)
  159235. emit_restart (working_state * state, int restart_num)
  159236. {
  159237. int ci;
  159238. if (! flush_bits(state))
  159239. return FALSE;
  159240. emit_byte(state, 0xFF, return FALSE);
  159241. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  159242. /* Re-initialize DC predictions to 0 */
  159243. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  159244. state->cur.last_dc_val[ci] = 0;
  159245. /* The restart counter is not updated until we successfully write the MCU. */
  159246. return TRUE;
  159247. }
  159248. /*
  159249. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  159250. */
  159251. METHODDEF(boolean)
  159252. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159253. {
  159254. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159255. working_state state;
  159256. int blkn, ci;
  159257. jpeg_component_info * compptr;
  159258. /* Load up working state */
  159259. state.next_output_byte = cinfo->dest->next_output_byte;
  159260. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159261. ASSIGN_STATE(state.cur, entropy->saved);
  159262. state.cinfo = cinfo;
  159263. /* Emit restart marker if needed */
  159264. if (cinfo->restart_interval) {
  159265. if (entropy->restarts_to_go == 0)
  159266. if (! emit_restart(&state, entropy->next_restart_num))
  159267. return FALSE;
  159268. }
  159269. /* Encode the MCU data blocks */
  159270. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159271. ci = cinfo->MCU_membership[blkn];
  159272. compptr = cinfo->cur_comp_info[ci];
  159273. if (! encode_one_block(&state,
  159274. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  159275. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  159276. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  159277. return FALSE;
  159278. /* Update last_dc_val */
  159279. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  159280. }
  159281. /* Completed MCU, so update state */
  159282. cinfo->dest->next_output_byte = state.next_output_byte;
  159283. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159284. ASSIGN_STATE(entropy->saved, state.cur);
  159285. /* Update restart-interval state too */
  159286. if (cinfo->restart_interval) {
  159287. if (entropy->restarts_to_go == 0) {
  159288. entropy->restarts_to_go = cinfo->restart_interval;
  159289. entropy->next_restart_num++;
  159290. entropy->next_restart_num &= 7;
  159291. }
  159292. entropy->restarts_to_go--;
  159293. }
  159294. return TRUE;
  159295. }
  159296. /*
  159297. * Finish up at the end of a Huffman-compressed scan.
  159298. */
  159299. METHODDEF(void)
  159300. finish_pass_huff (j_compress_ptr cinfo)
  159301. {
  159302. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159303. working_state state;
  159304. /* Load up working state ... flush_bits needs it */
  159305. state.next_output_byte = cinfo->dest->next_output_byte;
  159306. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159307. ASSIGN_STATE(state.cur, entropy->saved);
  159308. state.cinfo = cinfo;
  159309. /* Flush out the last data */
  159310. if (! flush_bits(&state))
  159311. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159312. /* Update state */
  159313. cinfo->dest->next_output_byte = state.next_output_byte;
  159314. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159315. ASSIGN_STATE(entropy->saved, state.cur);
  159316. }
  159317. /*
  159318. * Huffman coding optimization.
  159319. *
  159320. * We first scan the supplied data and count the number of uses of each symbol
  159321. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  159322. * Then we build a Huffman coding tree for the observed counts.
  159323. * Symbols which are not needed at all for the particular image are not
  159324. * assigned any code, which saves space in the DHT marker as well as in
  159325. * the compressed data.
  159326. */
  159327. #ifdef ENTROPY_OPT_SUPPORTED
  159328. /* Process a single block's worth of coefficients */
  159329. LOCAL(void)
  159330. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  159331. long dc_counts[], long ac_counts[])
  159332. {
  159333. register int temp;
  159334. register int nbits;
  159335. register int k, r;
  159336. /* Encode the DC coefficient difference per section F.1.2.1 */
  159337. temp = block[0] - last_dc_val;
  159338. if (temp < 0)
  159339. temp = -temp;
  159340. /* Find the number of bits needed for the magnitude of the coefficient */
  159341. nbits = 0;
  159342. while (temp) {
  159343. nbits++;
  159344. temp >>= 1;
  159345. }
  159346. /* Check for out-of-range coefficient values.
  159347. * Since we're encoding a difference, the range limit is twice as much.
  159348. */
  159349. if (nbits > MAX_COEF_BITS+1)
  159350. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159351. /* Count the Huffman symbol for the number of bits */
  159352. dc_counts[nbits]++;
  159353. /* Encode the AC coefficients per section F.1.2.2 */
  159354. r = 0; /* r = run length of zeros */
  159355. for (k = 1; k < DCTSIZE2; k++) {
  159356. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159357. r++;
  159358. } else {
  159359. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159360. while (r > 15) {
  159361. ac_counts[0xF0]++;
  159362. r -= 16;
  159363. }
  159364. /* Find the number of bits needed for the magnitude of the coefficient */
  159365. if (temp < 0)
  159366. temp = -temp;
  159367. /* Find the number of bits needed for the magnitude of the coefficient */
  159368. nbits = 1; /* there must be at least one 1 bit */
  159369. while ((temp >>= 1))
  159370. nbits++;
  159371. /* Check for out-of-range coefficient values */
  159372. if (nbits > MAX_COEF_BITS)
  159373. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159374. /* Count Huffman symbol for run length / number of bits */
  159375. ac_counts[(r << 4) + nbits]++;
  159376. r = 0;
  159377. }
  159378. }
  159379. /* If the last coef(s) were zero, emit an end-of-block code */
  159380. if (r > 0)
  159381. ac_counts[0]++;
  159382. }
  159383. /*
  159384. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  159385. * No data is actually output, so no suspension return is possible.
  159386. */
  159387. METHODDEF(boolean)
  159388. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159389. {
  159390. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159391. int blkn, ci;
  159392. jpeg_component_info * compptr;
  159393. /* Take care of restart intervals if needed */
  159394. if (cinfo->restart_interval) {
  159395. if (entropy->restarts_to_go == 0) {
  159396. /* Re-initialize DC predictions to 0 */
  159397. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  159398. entropy->saved.last_dc_val[ci] = 0;
  159399. /* Update restart state */
  159400. entropy->restarts_to_go = cinfo->restart_interval;
  159401. }
  159402. entropy->restarts_to_go--;
  159403. }
  159404. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159405. ci = cinfo->MCU_membership[blkn];
  159406. compptr = cinfo->cur_comp_info[ci];
  159407. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  159408. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  159409. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  159410. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  159411. }
  159412. return TRUE;
  159413. }
  159414. /*
  159415. * Generate the best Huffman code table for the given counts, fill htbl.
  159416. * Note this is also used by jcphuff.c.
  159417. *
  159418. * The JPEG standard requires that no symbol be assigned a codeword of all
  159419. * one bits (so that padding bits added at the end of a compressed segment
  159420. * can't look like a valid code). Because of the canonical ordering of
  159421. * codewords, this just means that there must be an unused slot in the
  159422. * longest codeword length category. Section K.2 of the JPEG spec suggests
  159423. * reserving such a slot by pretending that symbol 256 is a valid symbol
  159424. * with count 1. In theory that's not optimal; giving it count zero but
  159425. * including it in the symbol set anyway should give a better Huffman code.
  159426. * But the theoretically better code actually seems to come out worse in
  159427. * practice, because it produces more all-ones bytes (which incur stuffed
  159428. * zero bytes in the final file). In any case the difference is tiny.
  159429. *
  159430. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  159431. * If some symbols have a very small but nonzero probability, the Huffman tree
  159432. * must be adjusted to meet the code length restriction. We currently use
  159433. * the adjustment method suggested in JPEG section K.2. This method is *not*
  159434. * optimal; it may not choose the best possible limited-length code. But
  159435. * typically only very-low-frequency symbols will be given less-than-optimal
  159436. * lengths, so the code is almost optimal. Experimental comparisons against
  159437. * an optimal limited-length-code algorithm indicate that the difference is
  159438. * microscopic --- usually less than a hundredth of a percent of total size.
  159439. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  159440. */
  159441. GLOBAL(void)
  159442. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  159443. {
  159444. #define MAX_CLEN 32 /* assumed maximum initial code length */
  159445. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  159446. int codesize[257]; /* codesize[k] = code length of symbol k */
  159447. int others[257]; /* next symbol in current branch of tree */
  159448. int c1, c2;
  159449. int p, i, j;
  159450. long v;
  159451. /* This algorithm is explained in section K.2 of the JPEG standard */
  159452. MEMZERO(bits, SIZEOF(bits));
  159453. MEMZERO(codesize, SIZEOF(codesize));
  159454. for (i = 0; i < 257; i++)
  159455. others[i] = -1; /* init links to empty */
  159456. freq[256] = 1; /* make sure 256 has a nonzero count */
  159457. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  159458. * that no real symbol is given code-value of all ones, because 256
  159459. * will be placed last in the largest codeword category.
  159460. */
  159461. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  159462. for (;;) {
  159463. /* Find the smallest nonzero frequency, set c1 = its symbol */
  159464. /* In case of ties, take the larger symbol number */
  159465. c1 = -1;
  159466. v = 1000000000L;
  159467. for (i = 0; i <= 256; i++) {
  159468. if (freq[i] && freq[i] <= v) {
  159469. v = freq[i];
  159470. c1 = i;
  159471. }
  159472. }
  159473. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  159474. /* In case of ties, take the larger symbol number */
  159475. c2 = -1;
  159476. v = 1000000000L;
  159477. for (i = 0; i <= 256; i++) {
  159478. if (freq[i] && freq[i] <= v && i != c1) {
  159479. v = freq[i];
  159480. c2 = i;
  159481. }
  159482. }
  159483. /* Done if we've merged everything into one frequency */
  159484. if (c2 < 0)
  159485. break;
  159486. /* Else merge the two counts/trees */
  159487. freq[c1] += freq[c2];
  159488. freq[c2] = 0;
  159489. /* Increment the codesize of everything in c1's tree branch */
  159490. codesize[c1]++;
  159491. while (others[c1] >= 0) {
  159492. c1 = others[c1];
  159493. codesize[c1]++;
  159494. }
  159495. others[c1] = c2; /* chain c2 onto c1's tree branch */
  159496. /* Increment the codesize of everything in c2's tree branch */
  159497. codesize[c2]++;
  159498. while (others[c2] >= 0) {
  159499. c2 = others[c2];
  159500. codesize[c2]++;
  159501. }
  159502. }
  159503. /* Now count the number of symbols of each code length */
  159504. for (i = 0; i <= 256; i++) {
  159505. if (codesize[i]) {
  159506. /* The JPEG standard seems to think that this can't happen, */
  159507. /* but I'm paranoid... */
  159508. if (codesize[i] > MAX_CLEN)
  159509. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  159510. bits[codesize[i]]++;
  159511. }
  159512. }
  159513. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  159514. * Huffman procedure assigned any such lengths, we must adjust the coding.
  159515. * Here is what the JPEG spec says about how this next bit works:
  159516. * Since symbols are paired for the longest Huffman code, the symbols are
  159517. * removed from this length category two at a time. The prefix for the pair
  159518. * (which is one bit shorter) is allocated to one of the pair; then,
  159519. * skipping the BITS entry for that prefix length, a code word from the next
  159520. * shortest nonzero BITS entry is converted into a prefix for two code words
  159521. * one bit longer.
  159522. */
  159523. for (i = MAX_CLEN; i > 16; i--) {
  159524. while (bits[i] > 0) {
  159525. j = i - 2; /* find length of new prefix to be used */
  159526. while (bits[j] == 0)
  159527. j--;
  159528. bits[i] -= 2; /* remove two symbols */
  159529. bits[i-1]++; /* one goes in this length */
  159530. bits[j+1] += 2; /* two new symbols in this length */
  159531. bits[j]--; /* symbol of this length is now a prefix */
  159532. }
  159533. }
  159534. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  159535. while (bits[i] == 0) /* find largest codelength still in use */
  159536. i--;
  159537. bits[i]--;
  159538. /* Return final symbol counts (only for lengths 0..16) */
  159539. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  159540. /* Return a list of the symbols sorted by code length */
  159541. /* It's not real clear to me why we don't need to consider the codelength
  159542. * changes made above, but the JPEG spec seems to think this works.
  159543. */
  159544. p = 0;
  159545. for (i = 1; i <= MAX_CLEN; i++) {
  159546. for (j = 0; j <= 255; j++) {
  159547. if (codesize[j] == i) {
  159548. htbl->huffval[p] = (UINT8) j;
  159549. p++;
  159550. }
  159551. }
  159552. }
  159553. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  159554. htbl->sent_table = FALSE;
  159555. }
  159556. /*
  159557. * Finish up a statistics-gathering pass and create the new Huffman tables.
  159558. */
  159559. METHODDEF(void)
  159560. finish_pass_gather (j_compress_ptr cinfo)
  159561. {
  159562. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159563. int ci, dctbl, actbl;
  159564. jpeg_component_info * compptr;
  159565. JHUFF_TBL **htblptr;
  159566. boolean did_dc[NUM_HUFF_TBLS];
  159567. boolean did_ac[NUM_HUFF_TBLS];
  159568. /* It's important not to apply jpeg_gen_optimal_table more than once
  159569. * per table, because it clobbers the input frequency counts!
  159570. */
  159571. MEMZERO(did_dc, SIZEOF(did_dc));
  159572. MEMZERO(did_ac, SIZEOF(did_ac));
  159573. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159574. compptr = cinfo->cur_comp_info[ci];
  159575. dctbl = compptr->dc_tbl_no;
  159576. actbl = compptr->ac_tbl_no;
  159577. if (! did_dc[dctbl]) {
  159578. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  159579. if (*htblptr == NULL)
  159580. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159581. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  159582. did_dc[dctbl] = TRUE;
  159583. }
  159584. if (! did_ac[actbl]) {
  159585. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  159586. if (*htblptr == NULL)
  159587. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159588. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  159589. did_ac[actbl] = TRUE;
  159590. }
  159591. }
  159592. }
  159593. #endif /* ENTROPY_OPT_SUPPORTED */
  159594. /*
  159595. * Module initialization routine for Huffman entropy encoding.
  159596. */
  159597. GLOBAL(void)
  159598. jinit_huff_encoder (j_compress_ptr cinfo)
  159599. {
  159600. huff_entropy_ptr entropy;
  159601. int i;
  159602. entropy = (huff_entropy_ptr)
  159603. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159604. SIZEOF(huff_entropy_encoder));
  159605. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  159606. entropy->pub.start_pass = start_pass_huff;
  159607. /* Mark tables unallocated */
  159608. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159609. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  159610. #ifdef ENTROPY_OPT_SUPPORTED
  159611. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  159612. #endif
  159613. }
  159614. }
  159615. /********* End of inlined file: jchuff.c *********/
  159616. #undef emit_byte
  159617. /********* Start of inlined file: jcinit.c *********/
  159618. #define JPEG_INTERNALS
  159619. /*
  159620. * Master selection of compression modules.
  159621. * This is done once at the start of processing an image. We determine
  159622. * which modules will be used and give them appropriate initialization calls.
  159623. */
  159624. GLOBAL(void)
  159625. jinit_compress_master (j_compress_ptr cinfo)
  159626. {
  159627. /* Initialize master control (includes parameter checking/processing) */
  159628. jinit_c_master_control(cinfo, FALSE /* full compression */);
  159629. /* Preprocessing */
  159630. if (! cinfo->raw_data_in) {
  159631. jinit_color_converter(cinfo);
  159632. jinit_downsampler(cinfo);
  159633. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  159634. }
  159635. /* Forward DCT */
  159636. jinit_forward_dct(cinfo);
  159637. /* Entropy encoding: either Huffman or arithmetic coding. */
  159638. if (cinfo->arith_code) {
  159639. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  159640. } else {
  159641. if (cinfo->progressive_mode) {
  159642. #ifdef C_PROGRESSIVE_SUPPORTED
  159643. jinit_phuff_encoder(cinfo);
  159644. #else
  159645. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159646. #endif
  159647. } else
  159648. jinit_huff_encoder(cinfo);
  159649. }
  159650. /* Need a full-image coefficient buffer in any multi-pass mode. */
  159651. jinit_c_coef_controller(cinfo,
  159652. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  159653. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  159654. jinit_marker_writer(cinfo);
  159655. /* We can now tell the memory manager to allocate virtual arrays. */
  159656. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  159657. /* Write the datastream header (SOI) immediately.
  159658. * Frame and scan headers are postponed till later.
  159659. * This lets application insert special markers after the SOI.
  159660. */
  159661. (*cinfo->marker->write_file_header) (cinfo);
  159662. }
  159663. /********* End of inlined file: jcinit.c *********/
  159664. /********* Start of inlined file: jcmainct.c *********/
  159665. #define JPEG_INTERNALS
  159666. /* Note: currently, there is no operating mode in which a full-image buffer
  159667. * is needed at this step. If there were, that mode could not be used with
  159668. * "raw data" input, since this module is bypassed in that case. However,
  159669. * we've left the code here for possible use in special applications.
  159670. */
  159671. #undef FULL_MAIN_BUFFER_SUPPORTED
  159672. /* Private buffer controller object */
  159673. typedef struct {
  159674. struct jpeg_c_main_controller pub; /* public fields */
  159675. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  159676. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  159677. boolean suspended; /* remember if we suspended output */
  159678. J_BUF_MODE pass_mode; /* current operating mode */
  159679. /* If using just a strip buffer, this points to the entire set of buffers
  159680. * (we allocate one for each component). In the full-image case, this
  159681. * points to the currently accessible strips of the virtual arrays.
  159682. */
  159683. JSAMPARRAY buffer[MAX_COMPONENTS];
  159684. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159685. /* If using full-image storage, this array holds pointers to virtual-array
  159686. * control blocks for each component. Unused if not full-image storage.
  159687. */
  159688. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  159689. #endif
  159690. } my_main_controller;
  159691. typedef my_main_controller * my_main_ptr;
  159692. /* Forward declarations */
  159693. METHODDEF(void) process_data_simple_main
  159694. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159695. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159696. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159697. METHODDEF(void) process_data_buffer_main
  159698. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159699. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159700. #endif
  159701. /*
  159702. * Initialize for a processing pass.
  159703. */
  159704. METHODDEF(void)
  159705. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159706. {
  159707. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159708. /* Do nothing in raw-data mode. */
  159709. if (cinfo->raw_data_in)
  159710. return;
  159711. main_->cur_iMCU_row = 0; /* initialize counters */
  159712. main_->rowgroup_ctr = 0;
  159713. main_->suspended = FALSE;
  159714. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  159715. switch (pass_mode) {
  159716. case JBUF_PASS_THRU:
  159717. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159718. if (main_->whole_image[0] != NULL)
  159719. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159720. #endif
  159721. main_->pub.process_data = process_data_simple_main;
  159722. break;
  159723. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159724. case JBUF_SAVE_SOURCE:
  159725. case JBUF_CRANK_DEST:
  159726. case JBUF_SAVE_AND_PASS:
  159727. if (main_->whole_image[0] == NULL)
  159728. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159729. main_->pub.process_data = process_data_buffer_main;
  159730. break;
  159731. #endif
  159732. default:
  159733. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159734. break;
  159735. }
  159736. }
  159737. /*
  159738. * Process some data.
  159739. * This routine handles the simple pass-through mode,
  159740. * where we have only a strip buffer.
  159741. */
  159742. METHODDEF(void)
  159743. process_data_simple_main (j_compress_ptr cinfo,
  159744. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159745. JDIMENSION in_rows_avail)
  159746. {
  159747. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159748. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159749. /* Read input data if we haven't filled the main buffer yet */
  159750. if (main_->rowgroup_ctr < DCTSIZE)
  159751. (*cinfo->prep->pre_process_data) (cinfo,
  159752. input_buf, in_row_ctr, in_rows_avail,
  159753. main_->buffer, &main_->rowgroup_ctr,
  159754. (JDIMENSION) DCTSIZE);
  159755. /* If we don't have a full iMCU row buffered, return to application for
  159756. * more data. Note that preprocessor will always pad to fill the iMCU row
  159757. * at the bottom of the image.
  159758. */
  159759. if (main_->rowgroup_ctr != DCTSIZE)
  159760. return;
  159761. /* Send the completed row to the compressor */
  159762. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  159763. /* If compressor did not consume the whole row, then we must need to
  159764. * suspend processing and return to the application. In this situation
  159765. * we pretend we didn't yet consume the last input row; otherwise, if
  159766. * it happened to be the last row of the image, the application would
  159767. * think we were done.
  159768. */
  159769. if (! main_->suspended) {
  159770. (*in_row_ctr)--;
  159771. main_->suspended = TRUE;
  159772. }
  159773. return;
  159774. }
  159775. /* We did finish the row. Undo our little suspension hack if a previous
  159776. * call suspended; then mark the main buffer empty.
  159777. */
  159778. if (main_->suspended) {
  159779. (*in_row_ctr)++;
  159780. main_->suspended = FALSE;
  159781. }
  159782. main_->rowgroup_ctr = 0;
  159783. main_->cur_iMCU_row++;
  159784. }
  159785. }
  159786. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159787. /*
  159788. * Process some data.
  159789. * This routine handles all of the modes that use a full-size buffer.
  159790. */
  159791. METHODDEF(void)
  159792. process_data_buffer_main (j_compress_ptr cinfo,
  159793. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159794. JDIMENSION in_rows_avail)
  159795. {
  159796. my_main_ptr main = (my_main_ptr) cinfo->main;
  159797. int ci;
  159798. jpeg_component_info *compptr;
  159799. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  159800. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159801. /* Realign the virtual buffers if at the start of an iMCU row. */
  159802. if (main->rowgroup_ctr == 0) {
  159803. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159804. ci++, compptr++) {
  159805. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  159806. ((j_common_ptr) cinfo, main->whole_image[ci],
  159807. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  159808. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  159809. }
  159810. /* In a read pass, pretend we just read some source data. */
  159811. if (! writing) {
  159812. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  159813. main->rowgroup_ctr = DCTSIZE;
  159814. }
  159815. }
  159816. /* If a write pass, read input data until the current iMCU row is full. */
  159817. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  159818. if (writing) {
  159819. (*cinfo->prep->pre_process_data) (cinfo,
  159820. input_buf, in_row_ctr, in_rows_avail,
  159821. main->buffer, &main->rowgroup_ctr,
  159822. (JDIMENSION) DCTSIZE);
  159823. /* Return to application if we need more data to fill the iMCU row. */
  159824. if (main->rowgroup_ctr < DCTSIZE)
  159825. return;
  159826. }
  159827. /* Emit data, unless this is a sink-only pass. */
  159828. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  159829. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  159830. /* If compressor did not consume the whole row, then we must need to
  159831. * suspend processing and return to the application. In this situation
  159832. * we pretend we didn't yet consume the last input row; otherwise, if
  159833. * it happened to be the last row of the image, the application would
  159834. * think we were done.
  159835. */
  159836. if (! main->suspended) {
  159837. (*in_row_ctr)--;
  159838. main->suspended = TRUE;
  159839. }
  159840. return;
  159841. }
  159842. /* We did finish the row. Undo our little suspension hack if a previous
  159843. * call suspended; then mark the main buffer empty.
  159844. */
  159845. if (main->suspended) {
  159846. (*in_row_ctr)++;
  159847. main->suspended = FALSE;
  159848. }
  159849. }
  159850. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  159851. main->rowgroup_ctr = 0;
  159852. main->cur_iMCU_row++;
  159853. }
  159854. }
  159855. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  159856. /*
  159857. * Initialize main buffer controller.
  159858. */
  159859. GLOBAL(void)
  159860. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159861. {
  159862. my_main_ptr main_;
  159863. int ci;
  159864. jpeg_component_info *compptr;
  159865. main_ = (my_main_ptr)
  159866. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159867. SIZEOF(my_main_controller));
  159868. cinfo->main = (struct jpeg_c_main_controller *) main_;
  159869. main_->pub.start_pass = start_pass_main;
  159870. /* We don't need to create a buffer in raw-data mode. */
  159871. if (cinfo->raw_data_in)
  159872. return;
  159873. /* Create the buffer. It holds downsampled data, so each component
  159874. * may be of a different size.
  159875. */
  159876. if (need_full_buffer) {
  159877. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159878. /* Allocate a full-image virtual array for each component */
  159879. /* Note we pad the bottom to a multiple of the iMCU height */
  159880. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159881. ci++, compptr++) {
  159882. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  159883. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159884. compptr->width_in_blocks * DCTSIZE,
  159885. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159886. (long) compptr->v_samp_factor) * DCTSIZE,
  159887. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159888. }
  159889. #else
  159890. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159891. #endif
  159892. } else {
  159893. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159894. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  159895. #endif
  159896. /* Allocate a strip buffer for each component */
  159897. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159898. ci++, compptr++) {
  159899. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  159900. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159901. compptr->width_in_blocks * DCTSIZE,
  159902. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159903. }
  159904. }
  159905. }
  159906. /********* End of inlined file: jcmainct.c *********/
  159907. /********* Start of inlined file: jcmarker.c *********/
  159908. #define JPEG_INTERNALS
  159909. /* Private state */
  159910. typedef struct {
  159911. struct jpeg_marker_writer pub; /* public fields */
  159912. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  159913. } my_marker_writer;
  159914. typedef my_marker_writer * my_marker_ptr;
  159915. /*
  159916. * Basic output routines.
  159917. *
  159918. * Note that we do not support suspension while writing a marker.
  159919. * Therefore, an application using suspension must ensure that there is
  159920. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  159921. * calling jpeg_start_compress, and enough space to write the trailing EOI
  159922. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  159923. * modes are not supported at all with suspension, so those two are the only
  159924. * points where markers will be written.
  159925. */
  159926. LOCAL(void)
  159927. emit_byte (j_compress_ptr cinfo, int val)
  159928. /* Emit a byte */
  159929. {
  159930. struct jpeg_destination_mgr * dest = cinfo->dest;
  159931. *(dest->next_output_byte)++ = (JOCTET) val;
  159932. if (--dest->free_in_buffer == 0) {
  159933. if (! (*dest->empty_output_buffer) (cinfo))
  159934. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159935. }
  159936. }
  159937. LOCAL(void)
  159938. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  159939. /* Emit a marker code */
  159940. {
  159941. emit_byte(cinfo, 0xFF);
  159942. emit_byte(cinfo, (int) mark);
  159943. }
  159944. LOCAL(void)
  159945. emit_2bytes (j_compress_ptr cinfo, int value)
  159946. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  159947. {
  159948. emit_byte(cinfo, (value >> 8) & 0xFF);
  159949. emit_byte(cinfo, value & 0xFF);
  159950. }
  159951. /*
  159952. * Routines to write specific marker types.
  159953. */
  159954. LOCAL(int)
  159955. emit_dqt (j_compress_ptr cinfo, int index)
  159956. /* Emit a DQT marker */
  159957. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  159958. {
  159959. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  159960. int prec;
  159961. int i;
  159962. if (qtbl == NULL)
  159963. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  159964. prec = 0;
  159965. for (i = 0; i < DCTSIZE2; i++) {
  159966. if (qtbl->quantval[i] > 255)
  159967. prec = 1;
  159968. }
  159969. if (! qtbl->sent_table) {
  159970. emit_marker(cinfo, M_DQT);
  159971. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  159972. emit_byte(cinfo, index + (prec<<4));
  159973. for (i = 0; i < DCTSIZE2; i++) {
  159974. /* The table entries must be emitted in zigzag order. */
  159975. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  159976. if (prec)
  159977. emit_byte(cinfo, (int) (qval >> 8));
  159978. emit_byte(cinfo, (int) (qval & 0xFF));
  159979. }
  159980. qtbl->sent_table = TRUE;
  159981. }
  159982. return prec;
  159983. }
  159984. LOCAL(void)
  159985. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  159986. /* Emit a DHT marker */
  159987. {
  159988. JHUFF_TBL * htbl;
  159989. int length, i;
  159990. if (is_ac) {
  159991. htbl = cinfo->ac_huff_tbl_ptrs[index];
  159992. index += 0x10; /* output index has AC bit set */
  159993. } else {
  159994. htbl = cinfo->dc_huff_tbl_ptrs[index];
  159995. }
  159996. if (htbl == NULL)
  159997. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  159998. if (! htbl->sent_table) {
  159999. emit_marker(cinfo, M_DHT);
  160000. length = 0;
  160001. for (i = 1; i <= 16; i++)
  160002. length += htbl->bits[i];
  160003. emit_2bytes(cinfo, length + 2 + 1 + 16);
  160004. emit_byte(cinfo, index);
  160005. for (i = 1; i <= 16; i++)
  160006. emit_byte(cinfo, htbl->bits[i]);
  160007. for (i = 0; i < length; i++)
  160008. emit_byte(cinfo, htbl->huffval[i]);
  160009. htbl->sent_table = TRUE;
  160010. }
  160011. }
  160012. LOCAL(void)
  160013. emit_dac (j_compress_ptr cinfo)
  160014. /* Emit a DAC marker */
  160015. /* Since the useful info is so small, we want to emit all the tables in */
  160016. /* one DAC marker. Therefore this routine does its own scan of the table. */
  160017. {
  160018. #ifdef C_ARITH_CODING_SUPPORTED
  160019. char dc_in_use[NUM_ARITH_TBLS];
  160020. char ac_in_use[NUM_ARITH_TBLS];
  160021. int length, i;
  160022. jpeg_component_info *compptr;
  160023. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160024. dc_in_use[i] = ac_in_use[i] = 0;
  160025. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160026. compptr = cinfo->cur_comp_info[i];
  160027. dc_in_use[compptr->dc_tbl_no] = 1;
  160028. ac_in_use[compptr->ac_tbl_no] = 1;
  160029. }
  160030. length = 0;
  160031. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160032. length += dc_in_use[i] + ac_in_use[i];
  160033. emit_marker(cinfo, M_DAC);
  160034. emit_2bytes(cinfo, length*2 + 2);
  160035. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  160036. if (dc_in_use[i]) {
  160037. emit_byte(cinfo, i);
  160038. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  160039. }
  160040. if (ac_in_use[i]) {
  160041. emit_byte(cinfo, i + 0x10);
  160042. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  160043. }
  160044. }
  160045. #endif /* C_ARITH_CODING_SUPPORTED */
  160046. }
  160047. LOCAL(void)
  160048. emit_dri (j_compress_ptr cinfo)
  160049. /* Emit a DRI marker */
  160050. {
  160051. emit_marker(cinfo, M_DRI);
  160052. emit_2bytes(cinfo, 4); /* fixed length */
  160053. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  160054. }
  160055. LOCAL(void)
  160056. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  160057. /* Emit a SOF marker */
  160058. {
  160059. int ci;
  160060. jpeg_component_info *compptr;
  160061. emit_marker(cinfo, code);
  160062. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  160063. /* Make sure image isn't bigger than SOF field can handle */
  160064. if ((long) cinfo->image_height > 65535L ||
  160065. (long) cinfo->image_width > 65535L)
  160066. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  160067. emit_byte(cinfo, cinfo->data_precision);
  160068. emit_2bytes(cinfo, (int) cinfo->image_height);
  160069. emit_2bytes(cinfo, (int) cinfo->image_width);
  160070. emit_byte(cinfo, cinfo->num_components);
  160071. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160072. ci++, compptr++) {
  160073. emit_byte(cinfo, compptr->component_id);
  160074. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  160075. emit_byte(cinfo, compptr->quant_tbl_no);
  160076. }
  160077. }
  160078. LOCAL(void)
  160079. emit_sos (j_compress_ptr cinfo)
  160080. /* Emit a SOS marker */
  160081. {
  160082. int i, td, ta;
  160083. jpeg_component_info *compptr;
  160084. emit_marker(cinfo, M_SOS);
  160085. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  160086. emit_byte(cinfo, cinfo->comps_in_scan);
  160087. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160088. compptr = cinfo->cur_comp_info[i];
  160089. emit_byte(cinfo, compptr->component_id);
  160090. td = compptr->dc_tbl_no;
  160091. ta = compptr->ac_tbl_no;
  160092. if (cinfo->progressive_mode) {
  160093. /* Progressive mode: only DC or only AC tables are used in one scan;
  160094. * furthermore, Huffman coding of DC refinement uses no table at all.
  160095. * We emit 0 for unused field(s); this is recommended by the P&M text
  160096. * but does not seem to be specified in the standard.
  160097. */
  160098. if (cinfo->Ss == 0) {
  160099. ta = 0; /* DC scan */
  160100. if (cinfo->Ah != 0 && !cinfo->arith_code)
  160101. td = 0; /* no DC table either */
  160102. } else {
  160103. td = 0; /* AC scan */
  160104. }
  160105. }
  160106. emit_byte(cinfo, (td << 4) + ta);
  160107. }
  160108. emit_byte(cinfo, cinfo->Ss);
  160109. emit_byte(cinfo, cinfo->Se);
  160110. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  160111. }
  160112. LOCAL(void)
  160113. emit_jfif_app0 (j_compress_ptr cinfo)
  160114. /* Emit a JFIF-compliant APP0 marker */
  160115. {
  160116. /*
  160117. * Length of APP0 block (2 bytes)
  160118. * Block ID (4 bytes - ASCII "JFIF")
  160119. * Zero byte (1 byte to terminate the ID string)
  160120. * Version Major, Minor (2 bytes - major first)
  160121. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  160122. * Xdpu (2 bytes - dots per unit horizontal)
  160123. * Ydpu (2 bytes - dots per unit vertical)
  160124. * Thumbnail X size (1 byte)
  160125. * Thumbnail Y size (1 byte)
  160126. */
  160127. emit_marker(cinfo, M_APP0);
  160128. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  160129. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  160130. emit_byte(cinfo, 0x46);
  160131. emit_byte(cinfo, 0x49);
  160132. emit_byte(cinfo, 0x46);
  160133. emit_byte(cinfo, 0);
  160134. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  160135. emit_byte(cinfo, cinfo->JFIF_minor_version);
  160136. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  160137. emit_2bytes(cinfo, (int) cinfo->X_density);
  160138. emit_2bytes(cinfo, (int) cinfo->Y_density);
  160139. emit_byte(cinfo, 0); /* No thumbnail image */
  160140. emit_byte(cinfo, 0);
  160141. }
  160142. LOCAL(void)
  160143. emit_adobe_app14 (j_compress_ptr cinfo)
  160144. /* Emit an Adobe APP14 marker */
  160145. {
  160146. /*
  160147. * Length of APP14 block (2 bytes)
  160148. * Block ID (5 bytes - ASCII "Adobe")
  160149. * Version Number (2 bytes - currently 100)
  160150. * Flags0 (2 bytes - currently 0)
  160151. * Flags1 (2 bytes - currently 0)
  160152. * Color transform (1 byte)
  160153. *
  160154. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  160155. * now in circulation seem to use Version = 100, so that's what we write.
  160156. *
  160157. * We write the color transform byte as 1 if the JPEG color space is
  160158. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  160159. * whether the encoder performed a transformation, which is pretty useless.
  160160. */
  160161. emit_marker(cinfo, M_APP14);
  160162. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  160163. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  160164. emit_byte(cinfo, 0x64);
  160165. emit_byte(cinfo, 0x6F);
  160166. emit_byte(cinfo, 0x62);
  160167. emit_byte(cinfo, 0x65);
  160168. emit_2bytes(cinfo, 100); /* Version */
  160169. emit_2bytes(cinfo, 0); /* Flags0 */
  160170. emit_2bytes(cinfo, 0); /* Flags1 */
  160171. switch (cinfo->jpeg_color_space) {
  160172. case JCS_YCbCr:
  160173. emit_byte(cinfo, 1); /* Color transform = 1 */
  160174. break;
  160175. case JCS_YCCK:
  160176. emit_byte(cinfo, 2); /* Color transform = 2 */
  160177. break;
  160178. default:
  160179. emit_byte(cinfo, 0); /* Color transform = 0 */
  160180. break;
  160181. }
  160182. }
  160183. /*
  160184. * These routines allow writing an arbitrary marker with parameters.
  160185. * The only intended use is to emit COM or APPn markers after calling
  160186. * write_file_header and before calling write_frame_header.
  160187. * Other uses are not guaranteed to produce desirable results.
  160188. * Counting the parameter bytes properly is the caller's responsibility.
  160189. */
  160190. METHODDEF(void)
  160191. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160192. /* Emit an arbitrary marker header */
  160193. {
  160194. if (datalen > (unsigned int) 65533) /* safety check */
  160195. ERREXIT(cinfo, JERR_BAD_LENGTH);
  160196. emit_marker(cinfo, (JPEG_MARKER) marker);
  160197. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  160198. }
  160199. METHODDEF(void)
  160200. write_marker_byte (j_compress_ptr cinfo, int val)
  160201. /* Emit one byte of marker parameters following write_marker_header */
  160202. {
  160203. emit_byte(cinfo, val);
  160204. }
  160205. /*
  160206. * Write datastream header.
  160207. * This consists of an SOI and optional APPn markers.
  160208. * We recommend use of the JFIF marker, but not the Adobe marker,
  160209. * when using YCbCr or grayscale data. The JFIF marker should NOT
  160210. * be used for any other JPEG colorspace. The Adobe marker is helpful
  160211. * to distinguish RGB, CMYK, and YCCK colorspaces.
  160212. * Note that an application can write additional header markers after
  160213. * jpeg_start_compress returns.
  160214. */
  160215. METHODDEF(void)
  160216. write_file_header (j_compress_ptr cinfo)
  160217. {
  160218. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160219. emit_marker(cinfo, M_SOI); /* first the SOI */
  160220. /* SOI is defined to reset restart interval to 0 */
  160221. marker->last_restart_interval = 0;
  160222. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  160223. emit_jfif_app0(cinfo);
  160224. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  160225. emit_adobe_app14(cinfo);
  160226. }
  160227. /*
  160228. * Write frame header.
  160229. * This consists of DQT and SOFn markers.
  160230. * Note that we do not emit the SOF until we have emitted the DQT(s).
  160231. * This avoids compatibility problems with incorrect implementations that
  160232. * try to error-check the quant table numbers as soon as they see the SOF.
  160233. */
  160234. METHODDEF(void)
  160235. write_frame_header (j_compress_ptr cinfo)
  160236. {
  160237. int ci, prec;
  160238. boolean is_baseline;
  160239. jpeg_component_info *compptr;
  160240. /* Emit DQT for each quantization table.
  160241. * Note that emit_dqt() suppresses any duplicate tables.
  160242. */
  160243. prec = 0;
  160244. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160245. ci++, compptr++) {
  160246. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  160247. }
  160248. /* now prec is nonzero iff there are any 16-bit quant tables. */
  160249. /* Check for a non-baseline specification.
  160250. * Note we assume that Huffman table numbers won't be changed later.
  160251. */
  160252. if (cinfo->arith_code || cinfo->progressive_mode ||
  160253. cinfo->data_precision != 8) {
  160254. is_baseline = FALSE;
  160255. } else {
  160256. is_baseline = TRUE;
  160257. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160258. ci++, compptr++) {
  160259. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  160260. is_baseline = FALSE;
  160261. }
  160262. if (prec && is_baseline) {
  160263. is_baseline = FALSE;
  160264. /* If it's baseline except for quantizer size, warn the user */
  160265. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  160266. }
  160267. }
  160268. /* Emit the proper SOF marker */
  160269. if (cinfo->arith_code) {
  160270. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  160271. } else {
  160272. if (cinfo->progressive_mode)
  160273. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  160274. else if (is_baseline)
  160275. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  160276. else
  160277. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  160278. }
  160279. }
  160280. /*
  160281. * Write scan header.
  160282. * This consists of DHT or DAC markers, optional DRI, and SOS.
  160283. * Compressed data will be written following the SOS.
  160284. */
  160285. METHODDEF(void)
  160286. write_scan_header (j_compress_ptr cinfo)
  160287. {
  160288. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160289. int i;
  160290. jpeg_component_info *compptr;
  160291. if (cinfo->arith_code) {
  160292. /* Emit arith conditioning info. We may have some duplication
  160293. * if the file has multiple scans, but it's so small it's hardly
  160294. * worth worrying about.
  160295. */
  160296. emit_dac(cinfo);
  160297. } else {
  160298. /* Emit Huffman tables.
  160299. * Note that emit_dht() suppresses any duplicate tables.
  160300. */
  160301. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160302. compptr = cinfo->cur_comp_info[i];
  160303. if (cinfo->progressive_mode) {
  160304. /* Progressive mode: only DC or only AC tables are used in one scan */
  160305. if (cinfo->Ss == 0) {
  160306. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  160307. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160308. } else {
  160309. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160310. }
  160311. } else {
  160312. /* Sequential mode: need both DC and AC tables */
  160313. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160314. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160315. }
  160316. }
  160317. }
  160318. /* Emit DRI if required --- note that DRI value could change for each scan.
  160319. * We avoid wasting space with unnecessary DRIs, however.
  160320. */
  160321. if (cinfo->restart_interval != marker->last_restart_interval) {
  160322. emit_dri(cinfo);
  160323. marker->last_restart_interval = cinfo->restart_interval;
  160324. }
  160325. emit_sos(cinfo);
  160326. }
  160327. /*
  160328. * Write datastream trailer.
  160329. */
  160330. METHODDEF(void)
  160331. write_file_trailer (j_compress_ptr cinfo)
  160332. {
  160333. emit_marker(cinfo, M_EOI);
  160334. }
  160335. /*
  160336. * Write an abbreviated table-specification datastream.
  160337. * This consists of SOI, DQT and DHT tables, and EOI.
  160338. * Any table that is defined and not marked sent_table = TRUE will be
  160339. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  160340. */
  160341. METHODDEF(void)
  160342. write_tables_only (j_compress_ptr cinfo)
  160343. {
  160344. int i;
  160345. emit_marker(cinfo, M_SOI);
  160346. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160347. if (cinfo->quant_tbl_ptrs[i] != NULL)
  160348. (void) emit_dqt(cinfo, i);
  160349. }
  160350. if (! cinfo->arith_code) {
  160351. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160352. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  160353. emit_dht(cinfo, i, FALSE);
  160354. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  160355. emit_dht(cinfo, i, TRUE);
  160356. }
  160357. }
  160358. emit_marker(cinfo, M_EOI);
  160359. }
  160360. /*
  160361. * Initialize the marker writer module.
  160362. */
  160363. GLOBAL(void)
  160364. jinit_marker_writer (j_compress_ptr cinfo)
  160365. {
  160366. my_marker_ptr marker;
  160367. /* Create the subobject */
  160368. marker = (my_marker_ptr)
  160369. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160370. SIZEOF(my_marker_writer));
  160371. cinfo->marker = (struct jpeg_marker_writer *) marker;
  160372. /* Initialize method pointers */
  160373. marker->pub.write_file_header = write_file_header;
  160374. marker->pub.write_frame_header = write_frame_header;
  160375. marker->pub.write_scan_header = write_scan_header;
  160376. marker->pub.write_file_trailer = write_file_trailer;
  160377. marker->pub.write_tables_only = write_tables_only;
  160378. marker->pub.write_marker_header = write_marker_header;
  160379. marker->pub.write_marker_byte = write_marker_byte;
  160380. /* Initialize private state */
  160381. marker->last_restart_interval = 0;
  160382. }
  160383. /********* End of inlined file: jcmarker.c *********/
  160384. /********* Start of inlined file: jcmaster.c *********/
  160385. #define JPEG_INTERNALS
  160386. /* Private state */
  160387. typedef enum {
  160388. main_pass, /* input data, also do first output step */
  160389. huff_opt_pass, /* Huffman code optimization pass */
  160390. output_pass /* data output pass */
  160391. } c_pass_type;
  160392. typedef struct {
  160393. struct jpeg_comp_master pub; /* public fields */
  160394. c_pass_type pass_type; /* the type of the current pass */
  160395. int pass_number; /* # of passes completed */
  160396. int total_passes; /* total # of passes needed */
  160397. int scan_number; /* current index in scan_info[] */
  160398. } my_comp_master;
  160399. typedef my_comp_master * my_master_ptr;
  160400. /*
  160401. * Support routines that do various essential calculations.
  160402. */
  160403. LOCAL(void)
  160404. initial_setup (j_compress_ptr cinfo)
  160405. /* Do computations that are needed before master selection phase */
  160406. {
  160407. int ci;
  160408. jpeg_component_info *compptr;
  160409. long samplesperrow;
  160410. JDIMENSION jd_samplesperrow;
  160411. /* Sanity check on image dimensions */
  160412. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  160413. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  160414. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  160415. /* Make sure image isn't bigger than I can handle */
  160416. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  160417. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  160418. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  160419. /* Width of an input scanline must be representable as JDIMENSION. */
  160420. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  160421. jd_samplesperrow = (JDIMENSION) samplesperrow;
  160422. if ((long) jd_samplesperrow != samplesperrow)
  160423. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  160424. /* For now, precision must match compiled-in value... */
  160425. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  160426. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  160427. /* Check that number of components won't exceed internal array sizes */
  160428. if (cinfo->num_components > MAX_COMPONENTS)
  160429. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160430. MAX_COMPONENTS);
  160431. /* Compute maximum sampling factors; check factor validity */
  160432. cinfo->max_h_samp_factor = 1;
  160433. cinfo->max_v_samp_factor = 1;
  160434. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160435. ci++, compptr++) {
  160436. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  160437. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  160438. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  160439. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  160440. compptr->h_samp_factor);
  160441. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  160442. compptr->v_samp_factor);
  160443. }
  160444. /* Compute dimensions of components */
  160445. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160446. ci++, compptr++) {
  160447. /* Fill in the correct component_index value; don't rely on application */
  160448. compptr->component_index = ci;
  160449. /* For compression, we never do DCT scaling. */
  160450. compptr->DCT_scaled_size = DCTSIZE;
  160451. /* Size in DCT blocks */
  160452. compptr->width_in_blocks = (JDIMENSION)
  160453. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160454. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  160455. compptr->height_in_blocks = (JDIMENSION)
  160456. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160457. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  160458. /* Size in samples */
  160459. compptr->downsampled_width = (JDIMENSION)
  160460. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160461. (long) cinfo->max_h_samp_factor);
  160462. compptr->downsampled_height = (JDIMENSION)
  160463. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160464. (long) cinfo->max_v_samp_factor);
  160465. /* Mark component needed (this flag isn't actually used for compression) */
  160466. compptr->component_needed = TRUE;
  160467. }
  160468. /* Compute number of fully interleaved MCU rows (number of times that
  160469. * main controller will call coefficient controller).
  160470. */
  160471. cinfo->total_iMCU_rows = (JDIMENSION)
  160472. jdiv_round_up((long) cinfo->image_height,
  160473. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160474. }
  160475. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160476. LOCAL(void)
  160477. validate_script (j_compress_ptr cinfo)
  160478. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  160479. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  160480. */
  160481. {
  160482. const jpeg_scan_info * scanptr;
  160483. int scanno, ncomps, ci, coefi, thisi;
  160484. int Ss, Se, Ah, Al;
  160485. boolean component_sent[MAX_COMPONENTS];
  160486. #ifdef C_PROGRESSIVE_SUPPORTED
  160487. int * last_bitpos_ptr;
  160488. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  160489. /* -1 until that coefficient has been seen; then last Al for it */
  160490. #endif
  160491. if (cinfo->num_scans <= 0)
  160492. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  160493. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  160494. * for progressive JPEG, no scan can have this.
  160495. */
  160496. scanptr = cinfo->scan_info;
  160497. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  160498. #ifdef C_PROGRESSIVE_SUPPORTED
  160499. cinfo->progressive_mode = TRUE;
  160500. last_bitpos_ptr = & last_bitpos[0][0];
  160501. for (ci = 0; ci < cinfo->num_components; ci++)
  160502. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  160503. *last_bitpos_ptr++ = -1;
  160504. #else
  160505. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160506. #endif
  160507. } else {
  160508. cinfo->progressive_mode = FALSE;
  160509. for (ci = 0; ci < cinfo->num_components; ci++)
  160510. component_sent[ci] = FALSE;
  160511. }
  160512. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  160513. /* Validate component indexes */
  160514. ncomps = scanptr->comps_in_scan;
  160515. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  160516. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  160517. for (ci = 0; ci < ncomps; ci++) {
  160518. thisi = scanptr->component_index[ci];
  160519. if (thisi < 0 || thisi >= cinfo->num_components)
  160520. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160521. /* Components must appear in SOF order within each scan */
  160522. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  160523. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160524. }
  160525. /* Validate progression parameters */
  160526. Ss = scanptr->Ss;
  160527. Se = scanptr->Se;
  160528. Ah = scanptr->Ah;
  160529. Al = scanptr->Al;
  160530. if (cinfo->progressive_mode) {
  160531. #ifdef C_PROGRESSIVE_SUPPORTED
  160532. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  160533. * seems wrong: the upper bound ought to depend on data precision.
  160534. * Perhaps they really meant 0..N+1 for N-bit precision.
  160535. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  160536. * out-of-range reconstructed DC values during the first DC scan,
  160537. * which might cause problems for some decoders.
  160538. */
  160539. #if BITS_IN_JSAMPLE == 8
  160540. #define MAX_AH_AL 10
  160541. #else
  160542. #define MAX_AH_AL 13
  160543. #endif
  160544. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  160545. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  160546. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160547. if (Ss == 0) {
  160548. if (Se != 0) /* DC and AC together not OK */
  160549. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160550. } else {
  160551. if (ncomps != 1) /* AC scans must be for only one component */
  160552. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160553. }
  160554. for (ci = 0; ci < ncomps; ci++) {
  160555. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  160556. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  160557. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160558. for (coefi = Ss; coefi <= Se; coefi++) {
  160559. if (last_bitpos_ptr[coefi] < 0) {
  160560. /* first scan of this coefficient */
  160561. if (Ah != 0)
  160562. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160563. } else {
  160564. /* not first scan */
  160565. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  160566. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160567. }
  160568. last_bitpos_ptr[coefi] = Al;
  160569. }
  160570. }
  160571. #endif
  160572. } else {
  160573. /* For sequential JPEG, all progression parameters must be these: */
  160574. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  160575. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160576. /* Make sure components are not sent twice */
  160577. for (ci = 0; ci < ncomps; ci++) {
  160578. thisi = scanptr->component_index[ci];
  160579. if (component_sent[thisi])
  160580. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160581. component_sent[thisi] = TRUE;
  160582. }
  160583. }
  160584. }
  160585. /* Now verify that everything got sent. */
  160586. if (cinfo->progressive_mode) {
  160587. #ifdef C_PROGRESSIVE_SUPPORTED
  160588. /* For progressive mode, we only check that at least some DC data
  160589. * got sent for each component; the spec does not require that all bits
  160590. * of all coefficients be transmitted. Would it be wiser to enforce
  160591. * transmission of all coefficient bits??
  160592. */
  160593. for (ci = 0; ci < cinfo->num_components; ci++) {
  160594. if (last_bitpos[ci][0] < 0)
  160595. ERREXIT(cinfo, JERR_MISSING_DATA);
  160596. }
  160597. #endif
  160598. } else {
  160599. for (ci = 0; ci < cinfo->num_components; ci++) {
  160600. if (! component_sent[ci])
  160601. ERREXIT(cinfo, JERR_MISSING_DATA);
  160602. }
  160603. }
  160604. }
  160605. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  160606. LOCAL(void)
  160607. select_scan_parameters (j_compress_ptr cinfo)
  160608. /* Set up the scan parameters for the current scan */
  160609. {
  160610. int ci;
  160611. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160612. if (cinfo->scan_info != NULL) {
  160613. /* Prepare for current scan --- the script is already validated */
  160614. my_master_ptr master = (my_master_ptr) cinfo->master;
  160615. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  160616. cinfo->comps_in_scan = scanptr->comps_in_scan;
  160617. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  160618. cinfo->cur_comp_info[ci] =
  160619. &cinfo->comp_info[scanptr->component_index[ci]];
  160620. }
  160621. cinfo->Ss = scanptr->Ss;
  160622. cinfo->Se = scanptr->Se;
  160623. cinfo->Ah = scanptr->Ah;
  160624. cinfo->Al = scanptr->Al;
  160625. }
  160626. else
  160627. #endif
  160628. {
  160629. /* Prepare for single sequential-JPEG scan containing all components */
  160630. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  160631. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160632. MAX_COMPS_IN_SCAN);
  160633. cinfo->comps_in_scan = cinfo->num_components;
  160634. for (ci = 0; ci < cinfo->num_components; ci++) {
  160635. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  160636. }
  160637. cinfo->Ss = 0;
  160638. cinfo->Se = DCTSIZE2-1;
  160639. cinfo->Ah = 0;
  160640. cinfo->Al = 0;
  160641. }
  160642. }
  160643. LOCAL(void)
  160644. per_scan_setup (j_compress_ptr cinfo)
  160645. /* Do computations that are needed before processing a JPEG scan */
  160646. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  160647. {
  160648. int ci, mcublks, tmp;
  160649. jpeg_component_info *compptr;
  160650. if (cinfo->comps_in_scan == 1) {
  160651. /* Noninterleaved (single-component) scan */
  160652. compptr = cinfo->cur_comp_info[0];
  160653. /* Overall image size in MCUs */
  160654. cinfo->MCUs_per_row = compptr->width_in_blocks;
  160655. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  160656. /* For noninterleaved scan, always one block per MCU */
  160657. compptr->MCU_width = 1;
  160658. compptr->MCU_height = 1;
  160659. compptr->MCU_blocks = 1;
  160660. compptr->MCU_sample_width = DCTSIZE;
  160661. compptr->last_col_width = 1;
  160662. /* For noninterleaved scans, it is convenient to define last_row_height
  160663. * as the number of block rows present in the last iMCU row.
  160664. */
  160665. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  160666. if (tmp == 0) tmp = compptr->v_samp_factor;
  160667. compptr->last_row_height = tmp;
  160668. /* Prepare array describing MCU composition */
  160669. cinfo->blocks_in_MCU = 1;
  160670. cinfo->MCU_membership[0] = 0;
  160671. } else {
  160672. /* Interleaved (multi-component) scan */
  160673. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  160674. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  160675. MAX_COMPS_IN_SCAN);
  160676. /* Overall image size in MCUs */
  160677. cinfo->MCUs_per_row = (JDIMENSION)
  160678. jdiv_round_up((long) cinfo->image_width,
  160679. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  160680. cinfo->MCU_rows_in_scan = (JDIMENSION)
  160681. jdiv_round_up((long) cinfo->image_height,
  160682. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160683. cinfo->blocks_in_MCU = 0;
  160684. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160685. compptr = cinfo->cur_comp_info[ci];
  160686. /* Sampling factors give # of blocks of component in each MCU */
  160687. compptr->MCU_width = compptr->h_samp_factor;
  160688. compptr->MCU_height = compptr->v_samp_factor;
  160689. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  160690. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  160691. /* Figure number of non-dummy blocks in last MCU column & row */
  160692. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  160693. if (tmp == 0) tmp = compptr->MCU_width;
  160694. compptr->last_col_width = tmp;
  160695. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  160696. if (tmp == 0) tmp = compptr->MCU_height;
  160697. compptr->last_row_height = tmp;
  160698. /* Prepare array describing MCU composition */
  160699. mcublks = compptr->MCU_blocks;
  160700. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  160701. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  160702. while (mcublks-- > 0) {
  160703. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  160704. }
  160705. }
  160706. }
  160707. /* Convert restart specified in rows to actual MCU count. */
  160708. /* Note that count must fit in 16 bits, so we provide limiting. */
  160709. if (cinfo->restart_in_rows > 0) {
  160710. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  160711. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  160712. }
  160713. }
  160714. /*
  160715. * Per-pass setup.
  160716. * This is called at the beginning of each pass. We determine which modules
  160717. * will be active during this pass and give them appropriate start_pass calls.
  160718. * We also set is_last_pass to indicate whether any more passes will be
  160719. * required.
  160720. */
  160721. METHODDEF(void)
  160722. prepare_for_pass (j_compress_ptr cinfo)
  160723. {
  160724. my_master_ptr master = (my_master_ptr) cinfo->master;
  160725. switch (master->pass_type) {
  160726. case main_pass:
  160727. /* Initial pass: will collect input data, and do either Huffman
  160728. * optimization or data output for the first scan.
  160729. */
  160730. select_scan_parameters(cinfo);
  160731. per_scan_setup(cinfo);
  160732. if (! cinfo->raw_data_in) {
  160733. (*cinfo->cconvert->start_pass) (cinfo);
  160734. (*cinfo->downsample->start_pass) (cinfo);
  160735. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  160736. }
  160737. (*cinfo->fdct->start_pass) (cinfo);
  160738. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  160739. (*cinfo->coef->start_pass) (cinfo,
  160740. (master->total_passes > 1 ?
  160741. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  160742. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  160743. if (cinfo->optimize_coding) {
  160744. /* No immediate data output; postpone writing frame/scan headers */
  160745. master->pub.call_pass_startup = FALSE;
  160746. } else {
  160747. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  160748. master->pub.call_pass_startup = TRUE;
  160749. }
  160750. break;
  160751. #ifdef ENTROPY_OPT_SUPPORTED
  160752. case huff_opt_pass:
  160753. /* Do Huffman optimization for a scan after the first one. */
  160754. select_scan_parameters(cinfo);
  160755. per_scan_setup(cinfo);
  160756. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  160757. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  160758. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160759. master->pub.call_pass_startup = FALSE;
  160760. break;
  160761. }
  160762. /* Special case: Huffman DC refinement scans need no Huffman table
  160763. * and therefore we can skip the optimization pass for them.
  160764. */
  160765. master->pass_type = output_pass;
  160766. master->pass_number++;
  160767. /*FALLTHROUGH*/
  160768. #endif
  160769. case output_pass:
  160770. /* Do a data-output pass. */
  160771. /* We need not repeat per-scan setup if prior optimization pass did it. */
  160772. if (! cinfo->optimize_coding) {
  160773. select_scan_parameters(cinfo);
  160774. per_scan_setup(cinfo);
  160775. }
  160776. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  160777. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160778. /* We emit frame/scan headers now */
  160779. if (master->scan_number == 0)
  160780. (*cinfo->marker->write_frame_header) (cinfo);
  160781. (*cinfo->marker->write_scan_header) (cinfo);
  160782. master->pub.call_pass_startup = FALSE;
  160783. break;
  160784. default:
  160785. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160786. }
  160787. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  160788. /* Set up progress monitor's pass info if present */
  160789. if (cinfo->progress != NULL) {
  160790. cinfo->progress->completed_passes = master->pass_number;
  160791. cinfo->progress->total_passes = master->total_passes;
  160792. }
  160793. }
  160794. /*
  160795. * Special start-of-pass hook.
  160796. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  160797. * In single-pass processing, we need this hook because we don't want to
  160798. * write frame/scan headers during jpeg_start_compress; we want to let the
  160799. * application write COM markers etc. between jpeg_start_compress and the
  160800. * jpeg_write_scanlines loop.
  160801. * In multi-pass processing, this routine is not used.
  160802. */
  160803. METHODDEF(void)
  160804. pass_startup (j_compress_ptr cinfo)
  160805. {
  160806. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  160807. (*cinfo->marker->write_frame_header) (cinfo);
  160808. (*cinfo->marker->write_scan_header) (cinfo);
  160809. }
  160810. /*
  160811. * Finish up at end of pass.
  160812. */
  160813. METHODDEF(void)
  160814. finish_pass_master (j_compress_ptr cinfo)
  160815. {
  160816. my_master_ptr master = (my_master_ptr) cinfo->master;
  160817. /* The entropy coder always needs an end-of-pass call,
  160818. * either to analyze statistics or to flush its output buffer.
  160819. */
  160820. (*cinfo->entropy->finish_pass) (cinfo);
  160821. /* Update state for next pass */
  160822. switch (master->pass_type) {
  160823. case main_pass:
  160824. /* next pass is either output of scan 0 (after optimization)
  160825. * or output of scan 1 (if no optimization).
  160826. */
  160827. master->pass_type = output_pass;
  160828. if (! cinfo->optimize_coding)
  160829. master->scan_number++;
  160830. break;
  160831. case huff_opt_pass:
  160832. /* next pass is always output of current scan */
  160833. master->pass_type = output_pass;
  160834. break;
  160835. case output_pass:
  160836. /* next pass is either optimization or output of next scan */
  160837. if (cinfo->optimize_coding)
  160838. master->pass_type = huff_opt_pass;
  160839. master->scan_number++;
  160840. break;
  160841. }
  160842. master->pass_number++;
  160843. }
  160844. /*
  160845. * Initialize master compression control.
  160846. */
  160847. GLOBAL(void)
  160848. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  160849. {
  160850. my_master_ptr master;
  160851. master = (my_master_ptr)
  160852. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160853. SIZEOF(my_comp_master));
  160854. cinfo->master = (struct jpeg_comp_master *) master;
  160855. master->pub.prepare_for_pass = prepare_for_pass;
  160856. master->pub.pass_startup = pass_startup;
  160857. master->pub.finish_pass = finish_pass_master;
  160858. master->pub.is_last_pass = FALSE;
  160859. /* Validate parameters, determine derived values */
  160860. initial_setup(cinfo);
  160861. if (cinfo->scan_info != NULL) {
  160862. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160863. validate_script(cinfo);
  160864. #else
  160865. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160866. #endif
  160867. } else {
  160868. cinfo->progressive_mode = FALSE;
  160869. cinfo->num_scans = 1;
  160870. }
  160871. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  160872. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  160873. /* Initialize my private state */
  160874. if (transcode_only) {
  160875. /* no main pass in transcoding */
  160876. if (cinfo->optimize_coding)
  160877. master->pass_type = huff_opt_pass;
  160878. else
  160879. master->pass_type = output_pass;
  160880. } else {
  160881. /* for normal compression, first pass is always this type: */
  160882. master->pass_type = main_pass;
  160883. }
  160884. master->scan_number = 0;
  160885. master->pass_number = 0;
  160886. if (cinfo->optimize_coding)
  160887. master->total_passes = cinfo->num_scans * 2;
  160888. else
  160889. master->total_passes = cinfo->num_scans;
  160890. }
  160891. /********* End of inlined file: jcmaster.c *********/
  160892. /********* Start of inlined file: jcomapi.c *********/
  160893. #define JPEG_INTERNALS
  160894. /*
  160895. * Abort processing of a JPEG compression or decompression operation,
  160896. * but don't destroy the object itself.
  160897. *
  160898. * For this, we merely clean up all the nonpermanent memory pools.
  160899. * Note that temp files (virtual arrays) are not allowed to belong to
  160900. * the permanent pool, so we will be able to close all temp files here.
  160901. * Closing a data source or destination, if necessary, is the application's
  160902. * responsibility.
  160903. */
  160904. GLOBAL(void)
  160905. jpeg_abort (j_common_ptr cinfo)
  160906. {
  160907. int pool;
  160908. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  160909. if (cinfo->mem == NULL)
  160910. return;
  160911. /* Releasing pools in reverse order might help avoid fragmentation
  160912. * with some (brain-damaged) malloc libraries.
  160913. */
  160914. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  160915. (*cinfo->mem->free_pool) (cinfo, pool);
  160916. }
  160917. /* Reset overall state for possible reuse of object */
  160918. if (cinfo->is_decompressor) {
  160919. cinfo->global_state = DSTATE_START;
  160920. /* Try to keep application from accessing now-deleted marker list.
  160921. * A bit kludgy to do it here, but this is the most central place.
  160922. */
  160923. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  160924. } else {
  160925. cinfo->global_state = CSTATE_START;
  160926. }
  160927. }
  160928. /*
  160929. * Destruction of a JPEG object.
  160930. *
  160931. * Everything gets deallocated except the master jpeg_compress_struct itself
  160932. * and the error manager struct. Both of these are supplied by the application
  160933. * and must be freed, if necessary, by the application. (Often they are on
  160934. * the stack and so don't need to be freed anyway.)
  160935. * Closing a data source or destination, if necessary, is the application's
  160936. * responsibility.
  160937. */
  160938. GLOBAL(void)
  160939. jpeg_destroy (j_common_ptr cinfo)
  160940. {
  160941. /* We need only tell the memory manager to release everything. */
  160942. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  160943. if (cinfo->mem != NULL)
  160944. (*cinfo->mem->self_destruct) (cinfo);
  160945. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  160946. cinfo->global_state = 0; /* mark it destroyed */
  160947. }
  160948. /*
  160949. * Convenience routines for allocating quantization and Huffman tables.
  160950. * (Would jutils.c be a more reasonable place to put these?)
  160951. */
  160952. GLOBAL(JQUANT_TBL *)
  160953. jpeg_alloc_quant_table (j_common_ptr cinfo)
  160954. {
  160955. JQUANT_TBL *tbl;
  160956. tbl = (JQUANT_TBL *)
  160957. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  160958. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160959. return tbl;
  160960. }
  160961. GLOBAL(JHUFF_TBL *)
  160962. jpeg_alloc_huff_table (j_common_ptr cinfo)
  160963. {
  160964. JHUFF_TBL *tbl;
  160965. tbl = (JHUFF_TBL *)
  160966. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  160967. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160968. return tbl;
  160969. }
  160970. /********* End of inlined file: jcomapi.c *********/
  160971. /********* Start of inlined file: jcparam.c *********/
  160972. #define JPEG_INTERNALS
  160973. /*
  160974. * Quantization table setup routines
  160975. */
  160976. GLOBAL(void)
  160977. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  160978. const unsigned int *basic_table,
  160979. int scale_factor, boolean force_baseline)
  160980. /* Define a quantization table equal to the basic_table times
  160981. * a scale factor (given as a percentage).
  160982. * If force_baseline is TRUE, the computed quantization table entries
  160983. * are limited to 1..255 for JPEG baseline compatibility.
  160984. */
  160985. {
  160986. JQUANT_TBL ** qtblptr;
  160987. int i;
  160988. long temp;
  160989. /* Safety check to ensure start_compress not called yet. */
  160990. if (cinfo->global_state != CSTATE_START)
  160991. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160992. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  160993. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  160994. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  160995. if (*qtblptr == NULL)
  160996. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  160997. for (i = 0; i < DCTSIZE2; i++) {
  160998. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  160999. /* limit the values to the valid range */
  161000. if (temp <= 0L) temp = 1L;
  161001. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  161002. if (force_baseline && temp > 255L)
  161003. temp = 255L; /* limit to baseline range if requested */
  161004. (*qtblptr)->quantval[i] = (UINT16) temp;
  161005. }
  161006. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161007. (*qtblptr)->sent_table = FALSE;
  161008. }
  161009. GLOBAL(void)
  161010. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  161011. boolean force_baseline)
  161012. /* Set or change the 'quality' (quantization) setting, using default tables
  161013. * and a straight percentage-scaling quality scale. In most cases it's better
  161014. * to use jpeg_set_quality (below); this entry point is provided for
  161015. * applications that insist on a linear percentage scaling.
  161016. */
  161017. {
  161018. /* These are the sample quantization tables given in JPEG spec section K.1.
  161019. * The spec says that the values given produce "good" quality, and
  161020. * when divided by 2, "very good" quality.
  161021. */
  161022. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  161023. 16, 11, 10, 16, 24, 40, 51, 61,
  161024. 12, 12, 14, 19, 26, 58, 60, 55,
  161025. 14, 13, 16, 24, 40, 57, 69, 56,
  161026. 14, 17, 22, 29, 51, 87, 80, 62,
  161027. 18, 22, 37, 56, 68, 109, 103, 77,
  161028. 24, 35, 55, 64, 81, 104, 113, 92,
  161029. 49, 64, 78, 87, 103, 121, 120, 101,
  161030. 72, 92, 95, 98, 112, 100, 103, 99
  161031. };
  161032. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  161033. 17, 18, 24, 47, 99, 99, 99, 99,
  161034. 18, 21, 26, 66, 99, 99, 99, 99,
  161035. 24, 26, 56, 99, 99, 99, 99, 99,
  161036. 47, 66, 99, 99, 99, 99, 99, 99,
  161037. 99, 99, 99, 99, 99, 99, 99, 99,
  161038. 99, 99, 99, 99, 99, 99, 99, 99,
  161039. 99, 99, 99, 99, 99, 99, 99, 99,
  161040. 99, 99, 99, 99, 99, 99, 99, 99
  161041. };
  161042. /* Set up two quantization tables using the specified scaling */
  161043. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  161044. scale_factor, force_baseline);
  161045. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  161046. scale_factor, force_baseline);
  161047. }
  161048. GLOBAL(int)
  161049. jpeg_quality_scaling (int quality)
  161050. /* Convert a user-specified quality rating to a percentage scaling factor
  161051. * for an underlying quantization table, using our recommended scaling curve.
  161052. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  161053. */
  161054. {
  161055. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  161056. if (quality <= 0) quality = 1;
  161057. if (quality > 100) quality = 100;
  161058. /* The basic table is used as-is (scaling 100) for a quality of 50.
  161059. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  161060. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  161061. * to make all the table entries 1 (hence, minimum quantization loss).
  161062. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  161063. */
  161064. if (quality < 50)
  161065. quality = 5000 / quality;
  161066. else
  161067. quality = 200 - quality*2;
  161068. return quality;
  161069. }
  161070. GLOBAL(void)
  161071. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  161072. /* Set or change the 'quality' (quantization) setting, using default tables.
  161073. * This is the standard quality-adjusting entry point for typical user
  161074. * interfaces; only those who want detailed control over quantization tables
  161075. * would use the preceding three routines directly.
  161076. */
  161077. {
  161078. /* Convert user 0-100 rating to percentage scaling */
  161079. quality = jpeg_quality_scaling(quality);
  161080. /* Set up standard quality tables */
  161081. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  161082. }
  161083. /*
  161084. * Huffman table setup routines
  161085. */
  161086. LOCAL(void)
  161087. add_huff_table (j_compress_ptr cinfo,
  161088. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  161089. /* Define a Huffman table */
  161090. {
  161091. int nsymbols, len;
  161092. if (*htblptr == NULL)
  161093. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161094. /* Copy the number-of-symbols-of-each-code-length counts */
  161095. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  161096. /* Validate the counts. We do this here mainly so we can copy the right
  161097. * number of symbols from the val[] array, without risking marching off
  161098. * the end of memory. jchuff.c will do a more thorough test later.
  161099. */
  161100. nsymbols = 0;
  161101. for (len = 1; len <= 16; len++)
  161102. nsymbols += bits[len];
  161103. if (nsymbols < 1 || nsymbols > 256)
  161104. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  161105. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  161106. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161107. (*htblptr)->sent_table = FALSE;
  161108. }
  161109. LOCAL(void)
  161110. std_huff_tables (j_compress_ptr cinfo)
  161111. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  161112. /* IMPORTANT: these are only valid for 8-bit data precision! */
  161113. {
  161114. static const UINT8 bits_dc_luminance[17] =
  161115. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  161116. static const UINT8 val_dc_luminance[] =
  161117. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161118. static const UINT8 bits_dc_chrominance[17] =
  161119. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  161120. static const UINT8 val_dc_chrominance[] =
  161121. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161122. static const UINT8 bits_ac_luminance[17] =
  161123. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  161124. static const UINT8 val_ac_luminance[] =
  161125. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  161126. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  161127. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  161128. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  161129. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  161130. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  161131. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  161132. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  161133. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  161134. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  161135. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  161136. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  161137. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  161138. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  161139. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  161140. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  161141. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  161142. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  161143. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  161144. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161145. 0xf9, 0xfa };
  161146. static const UINT8 bits_ac_chrominance[17] =
  161147. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  161148. static const UINT8 val_ac_chrominance[] =
  161149. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  161150. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  161151. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  161152. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  161153. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  161154. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  161155. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  161156. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  161157. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  161158. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  161159. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  161160. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  161161. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  161162. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  161163. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  161164. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  161165. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  161166. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  161167. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  161168. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161169. 0xf9, 0xfa };
  161170. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  161171. bits_dc_luminance, val_dc_luminance);
  161172. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  161173. bits_ac_luminance, val_ac_luminance);
  161174. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  161175. bits_dc_chrominance, val_dc_chrominance);
  161176. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  161177. bits_ac_chrominance, val_ac_chrominance);
  161178. }
  161179. /*
  161180. * Default parameter setup for compression.
  161181. *
  161182. * Applications that don't choose to use this routine must do their
  161183. * own setup of all these parameters. Alternately, you can call this
  161184. * to establish defaults and then alter parameters selectively. This
  161185. * is the recommended approach since, if we add any new parameters,
  161186. * your code will still work (they'll be set to reasonable defaults).
  161187. */
  161188. GLOBAL(void)
  161189. jpeg_set_defaults (j_compress_ptr cinfo)
  161190. {
  161191. int i;
  161192. /* Safety check to ensure start_compress not called yet. */
  161193. if (cinfo->global_state != CSTATE_START)
  161194. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161195. /* Allocate comp_info array large enough for maximum component count.
  161196. * Array is made permanent in case application wants to compress
  161197. * multiple images at same param settings.
  161198. */
  161199. if (cinfo->comp_info == NULL)
  161200. cinfo->comp_info = (jpeg_component_info *)
  161201. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161202. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  161203. /* Initialize everything not dependent on the color space */
  161204. cinfo->data_precision = BITS_IN_JSAMPLE;
  161205. /* Set up two quantization tables using default quality of 75 */
  161206. jpeg_set_quality(cinfo, 75, TRUE);
  161207. /* Set up two Huffman tables */
  161208. std_huff_tables(cinfo);
  161209. /* Initialize default arithmetic coding conditioning */
  161210. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161211. cinfo->arith_dc_L[i] = 0;
  161212. cinfo->arith_dc_U[i] = 1;
  161213. cinfo->arith_ac_K[i] = 5;
  161214. }
  161215. /* Default is no multiple-scan output */
  161216. cinfo->scan_info = NULL;
  161217. cinfo->num_scans = 0;
  161218. /* Expect normal source image, not raw downsampled data */
  161219. cinfo->raw_data_in = FALSE;
  161220. /* Use Huffman coding, not arithmetic coding, by default */
  161221. cinfo->arith_code = FALSE;
  161222. /* By default, don't do extra passes to optimize entropy coding */
  161223. cinfo->optimize_coding = FALSE;
  161224. /* The standard Huffman tables are only valid for 8-bit data precision.
  161225. * If the precision is higher, force optimization on so that usable
  161226. * tables will be computed. This test can be removed if default tables
  161227. * are supplied that are valid for the desired precision.
  161228. */
  161229. if (cinfo->data_precision > 8)
  161230. cinfo->optimize_coding = TRUE;
  161231. /* By default, use the simpler non-cosited sampling alignment */
  161232. cinfo->CCIR601_sampling = FALSE;
  161233. /* No input smoothing */
  161234. cinfo->smoothing_factor = 0;
  161235. /* DCT algorithm preference */
  161236. cinfo->dct_method = JDCT_DEFAULT;
  161237. /* No restart markers */
  161238. cinfo->restart_interval = 0;
  161239. cinfo->restart_in_rows = 0;
  161240. /* Fill in default JFIF marker parameters. Note that whether the marker
  161241. * will actually be written is determined by jpeg_set_colorspace.
  161242. *
  161243. * By default, the library emits JFIF version code 1.01.
  161244. * An application that wants to emit JFIF 1.02 extension markers should set
  161245. * JFIF_minor_version to 2. We could probably get away with just defaulting
  161246. * to 1.02, but there may still be some decoders in use that will complain
  161247. * about that; saying 1.01 should minimize compatibility problems.
  161248. */
  161249. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  161250. cinfo->JFIF_minor_version = 1;
  161251. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  161252. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  161253. cinfo->Y_density = 1;
  161254. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  161255. jpeg_default_colorspace(cinfo);
  161256. }
  161257. /*
  161258. * Select an appropriate JPEG colorspace for in_color_space.
  161259. */
  161260. GLOBAL(void)
  161261. jpeg_default_colorspace (j_compress_ptr cinfo)
  161262. {
  161263. switch (cinfo->in_color_space) {
  161264. case JCS_GRAYSCALE:
  161265. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  161266. break;
  161267. case JCS_RGB:
  161268. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161269. break;
  161270. case JCS_YCbCr:
  161271. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161272. break;
  161273. case JCS_CMYK:
  161274. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  161275. break;
  161276. case JCS_YCCK:
  161277. jpeg_set_colorspace(cinfo, JCS_YCCK);
  161278. break;
  161279. case JCS_UNKNOWN:
  161280. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  161281. break;
  161282. default:
  161283. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161284. }
  161285. }
  161286. /*
  161287. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  161288. */
  161289. GLOBAL(void)
  161290. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  161291. {
  161292. jpeg_component_info * compptr;
  161293. int ci;
  161294. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  161295. (compptr = &cinfo->comp_info[index], \
  161296. compptr->component_id = (id), \
  161297. compptr->h_samp_factor = (hsamp), \
  161298. compptr->v_samp_factor = (vsamp), \
  161299. compptr->quant_tbl_no = (quant), \
  161300. compptr->dc_tbl_no = (dctbl), \
  161301. compptr->ac_tbl_no = (actbl) )
  161302. /* Safety check to ensure start_compress not called yet. */
  161303. if (cinfo->global_state != CSTATE_START)
  161304. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161305. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  161306. * tables 1 for chrominance components.
  161307. */
  161308. cinfo->jpeg_color_space = colorspace;
  161309. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  161310. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  161311. switch (colorspace) {
  161312. case JCS_GRAYSCALE:
  161313. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161314. cinfo->num_components = 1;
  161315. /* JFIF specifies component ID 1 */
  161316. SET_COMP(0, 1, 1,1, 0, 0,0);
  161317. break;
  161318. case JCS_RGB:
  161319. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  161320. cinfo->num_components = 3;
  161321. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  161322. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  161323. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  161324. break;
  161325. case JCS_YCbCr:
  161326. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161327. cinfo->num_components = 3;
  161328. /* JFIF specifies component IDs 1,2,3 */
  161329. /* We default to 2x2 subsamples of chrominance */
  161330. SET_COMP(0, 1, 2,2, 0, 0,0);
  161331. SET_COMP(1, 2, 1,1, 1, 1,1);
  161332. SET_COMP(2, 3, 1,1, 1, 1,1);
  161333. break;
  161334. case JCS_CMYK:
  161335. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  161336. cinfo->num_components = 4;
  161337. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  161338. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  161339. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  161340. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  161341. break;
  161342. case JCS_YCCK:
  161343. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  161344. cinfo->num_components = 4;
  161345. SET_COMP(0, 1, 2,2, 0, 0,0);
  161346. SET_COMP(1, 2, 1,1, 1, 1,1);
  161347. SET_COMP(2, 3, 1,1, 1, 1,1);
  161348. SET_COMP(3, 4, 2,2, 0, 0,0);
  161349. break;
  161350. case JCS_UNKNOWN:
  161351. cinfo->num_components = cinfo->input_components;
  161352. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  161353. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161354. MAX_COMPONENTS);
  161355. for (ci = 0; ci < cinfo->num_components; ci++) {
  161356. SET_COMP(ci, ci, 1,1, 0, 0,0);
  161357. }
  161358. break;
  161359. default:
  161360. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161361. }
  161362. }
  161363. #ifdef C_PROGRESSIVE_SUPPORTED
  161364. LOCAL(jpeg_scan_info *)
  161365. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  161366. int Ss, int Se, int Ah, int Al)
  161367. /* Support routine: generate one scan for specified component */
  161368. {
  161369. scanptr->comps_in_scan = 1;
  161370. scanptr->component_index[0] = ci;
  161371. scanptr->Ss = Ss;
  161372. scanptr->Se = Se;
  161373. scanptr->Ah = Ah;
  161374. scanptr->Al = Al;
  161375. scanptr++;
  161376. return scanptr;
  161377. }
  161378. LOCAL(jpeg_scan_info *)
  161379. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  161380. int Ss, int Se, int Ah, int Al)
  161381. /* Support routine: generate one scan for each component */
  161382. {
  161383. int ci;
  161384. for (ci = 0; ci < ncomps; ci++) {
  161385. scanptr->comps_in_scan = 1;
  161386. scanptr->component_index[0] = ci;
  161387. scanptr->Ss = Ss;
  161388. scanptr->Se = Se;
  161389. scanptr->Ah = Ah;
  161390. scanptr->Al = Al;
  161391. scanptr++;
  161392. }
  161393. return scanptr;
  161394. }
  161395. LOCAL(jpeg_scan_info *)
  161396. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  161397. /* Support routine: generate interleaved DC scan if possible, else N scans */
  161398. {
  161399. int ci;
  161400. if (ncomps <= MAX_COMPS_IN_SCAN) {
  161401. /* Single interleaved DC scan */
  161402. scanptr->comps_in_scan = ncomps;
  161403. for (ci = 0; ci < ncomps; ci++)
  161404. scanptr->component_index[ci] = ci;
  161405. scanptr->Ss = scanptr->Se = 0;
  161406. scanptr->Ah = Ah;
  161407. scanptr->Al = Al;
  161408. scanptr++;
  161409. } else {
  161410. /* Noninterleaved DC scan for each component */
  161411. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  161412. }
  161413. return scanptr;
  161414. }
  161415. /*
  161416. * Create a recommended progressive-JPEG script.
  161417. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  161418. */
  161419. GLOBAL(void)
  161420. jpeg_simple_progression (j_compress_ptr cinfo)
  161421. {
  161422. int ncomps = cinfo->num_components;
  161423. int nscans;
  161424. jpeg_scan_info * scanptr;
  161425. /* Safety check to ensure start_compress not called yet. */
  161426. if (cinfo->global_state != CSTATE_START)
  161427. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161428. /* Figure space needed for script. Calculation must match code below! */
  161429. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161430. /* Custom script for YCbCr color images. */
  161431. nscans = 10;
  161432. } else {
  161433. /* All-purpose script for other color spaces. */
  161434. if (ncomps > MAX_COMPS_IN_SCAN)
  161435. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  161436. else
  161437. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  161438. }
  161439. /* Allocate space for script.
  161440. * We need to put it in the permanent pool in case the application performs
  161441. * multiple compressions without changing the settings. To avoid a memory
  161442. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  161443. * object, we try to re-use previously allocated space, and we allocate
  161444. * enough space to handle YCbCr even if initially asked for grayscale.
  161445. */
  161446. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  161447. cinfo->script_space_size = MAX(nscans, 10);
  161448. cinfo->script_space = (jpeg_scan_info *)
  161449. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161450. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  161451. }
  161452. scanptr = cinfo->script_space;
  161453. cinfo->scan_info = scanptr;
  161454. cinfo->num_scans = nscans;
  161455. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161456. /* Custom script for YCbCr color images. */
  161457. /* Initial DC scan */
  161458. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161459. /* Initial AC scan: get some luma data out in a hurry */
  161460. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  161461. /* Chroma data is too small to be worth expending many scans on */
  161462. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  161463. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  161464. /* Complete spectral selection for luma AC */
  161465. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  161466. /* Refine next bit of luma AC */
  161467. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  161468. /* Finish DC successive approximation */
  161469. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161470. /* Finish AC successive approximation */
  161471. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  161472. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  161473. /* Luma bottom bit comes last since it's usually largest scan */
  161474. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  161475. } else {
  161476. /* All-purpose script for other color spaces. */
  161477. /* Successive approximation first pass */
  161478. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161479. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  161480. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  161481. /* Successive approximation second pass */
  161482. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  161483. /* Successive approximation final pass */
  161484. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161485. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  161486. }
  161487. }
  161488. #endif /* C_PROGRESSIVE_SUPPORTED */
  161489. /********* End of inlined file: jcparam.c *********/
  161490. /********* Start of inlined file: jcphuff.c *********/
  161491. #define JPEG_INTERNALS
  161492. #ifdef C_PROGRESSIVE_SUPPORTED
  161493. /* Expanded entropy encoder object for progressive Huffman encoding. */
  161494. typedef struct {
  161495. struct jpeg_entropy_encoder pub; /* public fields */
  161496. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  161497. boolean gather_statistics;
  161498. /* Bit-level coding status.
  161499. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  161500. */
  161501. JOCTET * next_output_byte; /* => next byte to write in buffer */
  161502. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  161503. INT32 put_buffer; /* current bit-accumulation buffer */
  161504. int put_bits; /* # of bits now in it */
  161505. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  161506. /* Coding status for DC components */
  161507. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  161508. /* Coding status for AC components */
  161509. int ac_tbl_no; /* the table number of the single component */
  161510. unsigned int EOBRUN; /* run length of EOBs */
  161511. unsigned int BE; /* # of buffered correction bits before MCU */
  161512. char * bit_buffer; /* buffer for correction bits (1 per char) */
  161513. /* packing correction bits tightly would save some space but cost time... */
  161514. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  161515. int next_restart_num; /* next restart number to write (0-7) */
  161516. /* Pointers to derived tables (these workspaces have image lifespan).
  161517. * Since any one scan codes only DC or only AC, we only need one set
  161518. * of tables, not one for DC and one for AC.
  161519. */
  161520. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  161521. /* Statistics tables for optimization; again, one set is enough */
  161522. long * count_ptrs[NUM_HUFF_TBLS];
  161523. } phuff_entropy_encoder;
  161524. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  161525. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  161526. * buffer can hold. Larger sizes may slightly improve compression, but
  161527. * 1000 is already well into the realm of overkill.
  161528. * The minimum safe size is 64 bits.
  161529. */
  161530. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  161531. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  161532. * We assume that int right shift is unsigned if INT32 right shift is,
  161533. * which should be safe.
  161534. */
  161535. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161536. #define ISHIFT_TEMPS int ishift_temp;
  161537. #define IRIGHT_SHIFT(x,shft) \
  161538. ((ishift_temp = (x)) < 0 ? \
  161539. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  161540. (ishift_temp >> (shft)))
  161541. #else
  161542. #define ISHIFT_TEMPS
  161543. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  161544. #endif
  161545. /* Forward declarations */
  161546. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  161547. JBLOCKROW *MCU_data));
  161548. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  161549. JBLOCKROW *MCU_data));
  161550. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  161551. JBLOCKROW *MCU_data));
  161552. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  161553. JBLOCKROW *MCU_data));
  161554. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  161555. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  161556. /*
  161557. * Initialize for a Huffman-compressed scan using progressive JPEG.
  161558. */
  161559. METHODDEF(void)
  161560. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  161561. {
  161562. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161563. boolean is_DC_band;
  161564. int ci, tbl;
  161565. jpeg_component_info * compptr;
  161566. entropy->cinfo = cinfo;
  161567. entropy->gather_statistics = gather_statistics;
  161568. is_DC_band = (cinfo->Ss == 0);
  161569. /* We assume jcmaster.c already validated the scan parameters. */
  161570. /* Select execution routines */
  161571. if (cinfo->Ah == 0) {
  161572. if (is_DC_band)
  161573. entropy->pub.encode_mcu = encode_mcu_DC_first;
  161574. else
  161575. entropy->pub.encode_mcu = encode_mcu_AC_first;
  161576. } else {
  161577. if (is_DC_band)
  161578. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  161579. else {
  161580. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  161581. /* AC refinement needs a correction bit buffer */
  161582. if (entropy->bit_buffer == NULL)
  161583. entropy->bit_buffer = (char *)
  161584. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161585. MAX_CORR_BITS * SIZEOF(char));
  161586. }
  161587. }
  161588. if (gather_statistics)
  161589. entropy->pub.finish_pass = finish_pass_gather_phuff;
  161590. else
  161591. entropy->pub.finish_pass = finish_pass_phuff;
  161592. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  161593. * for AC coefficients.
  161594. */
  161595. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161596. compptr = cinfo->cur_comp_info[ci];
  161597. /* Initialize DC predictions to 0 */
  161598. entropy->last_dc_val[ci] = 0;
  161599. /* Get table index */
  161600. if (is_DC_band) {
  161601. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161602. continue;
  161603. tbl = compptr->dc_tbl_no;
  161604. } else {
  161605. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  161606. }
  161607. if (gather_statistics) {
  161608. /* Check for invalid table index */
  161609. /* (make_c_derived_tbl does this in the other path) */
  161610. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  161611. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  161612. /* Allocate and zero the statistics tables */
  161613. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  161614. if (entropy->count_ptrs[tbl] == NULL)
  161615. entropy->count_ptrs[tbl] = (long *)
  161616. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161617. 257 * SIZEOF(long));
  161618. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  161619. } else {
  161620. /* Compute derived values for Huffman table */
  161621. /* We may do this more than once for a table, but it's not expensive */
  161622. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  161623. & entropy->derived_tbls[tbl]);
  161624. }
  161625. }
  161626. /* Initialize AC stuff */
  161627. entropy->EOBRUN = 0;
  161628. entropy->BE = 0;
  161629. /* Initialize bit buffer to empty */
  161630. entropy->put_buffer = 0;
  161631. entropy->put_bits = 0;
  161632. /* Initialize restart stuff */
  161633. entropy->restarts_to_go = cinfo->restart_interval;
  161634. entropy->next_restart_num = 0;
  161635. }
  161636. /* Outputting bytes to the file.
  161637. * NB: these must be called only when actually outputting,
  161638. * that is, entropy->gather_statistics == FALSE.
  161639. */
  161640. /* Emit a byte */
  161641. #define emit_byte(entropy,val) \
  161642. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  161643. if (--(entropy)->free_in_buffer == 0) \
  161644. dump_buffer_p(entropy); }
  161645. LOCAL(void)
  161646. dump_buffer_p (phuff_entropy_ptr entropy)
  161647. /* Empty the output buffer; we do not support suspension in this module. */
  161648. {
  161649. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  161650. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  161651. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  161652. /* After a successful buffer dump, must reset buffer pointers */
  161653. entropy->next_output_byte = dest->next_output_byte;
  161654. entropy->free_in_buffer = dest->free_in_buffer;
  161655. }
  161656. /* Outputting bits to the file */
  161657. /* Only the right 24 bits of put_buffer are used; the valid bits are
  161658. * left-justified in this part. At most 16 bits can be passed to emit_bits
  161659. * in one call, and we never retain more than 7 bits in put_buffer
  161660. * between calls, so 24 bits are sufficient.
  161661. */
  161662. INLINE
  161663. LOCAL(void)
  161664. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  161665. /* Emit some bits, unless we are in gather mode */
  161666. {
  161667. /* This routine is heavily used, so it's worth coding tightly. */
  161668. register INT32 put_buffer = (INT32) code;
  161669. register int put_bits = entropy->put_bits;
  161670. /* if size is 0, caller used an invalid Huffman table entry */
  161671. if (size == 0)
  161672. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161673. if (entropy->gather_statistics)
  161674. return; /* do nothing if we're only getting stats */
  161675. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  161676. put_bits += size; /* new number of bits in buffer */
  161677. put_buffer <<= 24 - put_bits; /* align incoming bits */
  161678. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  161679. while (put_bits >= 8) {
  161680. int c = (int) ((put_buffer >> 16) & 0xFF);
  161681. emit_byte(entropy, c);
  161682. if (c == 0xFF) { /* need to stuff a zero byte? */
  161683. emit_byte(entropy, 0);
  161684. }
  161685. put_buffer <<= 8;
  161686. put_bits -= 8;
  161687. }
  161688. entropy->put_buffer = put_buffer; /* update variables */
  161689. entropy->put_bits = put_bits;
  161690. }
  161691. LOCAL(void)
  161692. flush_bits_p (phuff_entropy_ptr entropy)
  161693. {
  161694. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  161695. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  161696. entropy->put_bits = 0;
  161697. }
  161698. /*
  161699. * Emit (or just count) a Huffman symbol.
  161700. */
  161701. INLINE
  161702. LOCAL(void)
  161703. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  161704. {
  161705. if (entropy->gather_statistics)
  161706. entropy->count_ptrs[tbl_no][symbol]++;
  161707. else {
  161708. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  161709. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  161710. }
  161711. }
  161712. /*
  161713. * Emit bits from a correction bit buffer.
  161714. */
  161715. LOCAL(void)
  161716. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  161717. unsigned int nbits)
  161718. {
  161719. if (entropy->gather_statistics)
  161720. return; /* no real work */
  161721. while (nbits > 0) {
  161722. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  161723. bufstart++;
  161724. nbits--;
  161725. }
  161726. }
  161727. /*
  161728. * Emit any pending EOBRUN symbol.
  161729. */
  161730. LOCAL(void)
  161731. emit_eobrun (phuff_entropy_ptr entropy)
  161732. {
  161733. register int temp, nbits;
  161734. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  161735. temp = entropy->EOBRUN;
  161736. nbits = 0;
  161737. while ((temp >>= 1))
  161738. nbits++;
  161739. /* safety check: shouldn't happen given limited correction-bit buffer */
  161740. if (nbits > 14)
  161741. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161742. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  161743. if (nbits)
  161744. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  161745. entropy->EOBRUN = 0;
  161746. /* Emit any buffered correction bits */
  161747. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  161748. entropy->BE = 0;
  161749. }
  161750. }
  161751. /*
  161752. * Emit a restart marker & resynchronize predictions.
  161753. */
  161754. LOCAL(void)
  161755. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  161756. {
  161757. int ci;
  161758. emit_eobrun(entropy);
  161759. if (! entropy->gather_statistics) {
  161760. flush_bits_p(entropy);
  161761. emit_byte(entropy, 0xFF);
  161762. emit_byte(entropy, JPEG_RST0 + restart_num);
  161763. }
  161764. if (entropy->cinfo->Ss == 0) {
  161765. /* Re-initialize DC predictions to 0 */
  161766. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  161767. entropy->last_dc_val[ci] = 0;
  161768. } else {
  161769. /* Re-initialize all AC-related fields to 0 */
  161770. entropy->EOBRUN = 0;
  161771. entropy->BE = 0;
  161772. }
  161773. }
  161774. /*
  161775. * MCU encoding for DC initial scan (either spectral selection,
  161776. * or first pass of successive approximation).
  161777. */
  161778. METHODDEF(boolean)
  161779. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161780. {
  161781. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161782. register int temp, temp2;
  161783. register int nbits;
  161784. int blkn, ci;
  161785. int Al = cinfo->Al;
  161786. JBLOCKROW block;
  161787. jpeg_component_info * compptr;
  161788. ISHIFT_TEMPS
  161789. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161790. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161791. /* Emit restart marker if needed */
  161792. if (cinfo->restart_interval)
  161793. if (entropy->restarts_to_go == 0)
  161794. emit_restart_p(entropy, entropy->next_restart_num);
  161795. /* Encode the MCU data blocks */
  161796. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161797. block = MCU_data[blkn];
  161798. ci = cinfo->MCU_membership[blkn];
  161799. compptr = cinfo->cur_comp_info[ci];
  161800. /* Compute the DC value after the required point transform by Al.
  161801. * This is simply an arithmetic right shift.
  161802. */
  161803. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  161804. /* DC differences are figured on the point-transformed values. */
  161805. temp = temp2 - entropy->last_dc_val[ci];
  161806. entropy->last_dc_val[ci] = temp2;
  161807. /* Encode the DC coefficient difference per section G.1.2.1 */
  161808. temp2 = temp;
  161809. if (temp < 0) {
  161810. temp = -temp; /* temp is abs value of input */
  161811. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  161812. /* This code assumes we are on a two's complement machine */
  161813. temp2--;
  161814. }
  161815. /* Find the number of bits needed for the magnitude of the coefficient */
  161816. nbits = 0;
  161817. while (temp) {
  161818. nbits++;
  161819. temp >>= 1;
  161820. }
  161821. /* Check for out-of-range coefficient values.
  161822. * Since we're encoding a difference, the range limit is twice as much.
  161823. */
  161824. if (nbits > MAX_COEF_BITS+1)
  161825. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161826. /* Count/emit the Huffman-coded symbol for the number of bits */
  161827. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  161828. /* Emit that number of bits of the value, if positive, */
  161829. /* or the complement of its magnitude, if negative. */
  161830. if (nbits) /* emit_bits rejects calls with size 0 */
  161831. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161832. }
  161833. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161834. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161835. /* Update restart-interval state too */
  161836. if (cinfo->restart_interval) {
  161837. if (entropy->restarts_to_go == 0) {
  161838. entropy->restarts_to_go = cinfo->restart_interval;
  161839. entropy->next_restart_num++;
  161840. entropy->next_restart_num &= 7;
  161841. }
  161842. entropy->restarts_to_go--;
  161843. }
  161844. return TRUE;
  161845. }
  161846. /*
  161847. * MCU encoding for AC initial scan (either spectral selection,
  161848. * or first pass of successive approximation).
  161849. */
  161850. METHODDEF(boolean)
  161851. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161852. {
  161853. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161854. register int temp, temp2;
  161855. register int nbits;
  161856. register int r, k;
  161857. int Se = cinfo->Se;
  161858. int Al = cinfo->Al;
  161859. JBLOCKROW block;
  161860. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161861. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161862. /* Emit restart marker if needed */
  161863. if (cinfo->restart_interval)
  161864. if (entropy->restarts_to_go == 0)
  161865. emit_restart_p(entropy, entropy->next_restart_num);
  161866. /* Encode the MCU data block */
  161867. block = MCU_data[0];
  161868. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  161869. r = 0; /* r = run length of zeros */
  161870. for (k = cinfo->Ss; k <= Se; k++) {
  161871. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  161872. r++;
  161873. continue;
  161874. }
  161875. /* We must apply the point transform by Al. For AC coefficients this
  161876. * is an integer division with rounding towards 0. To do this portably
  161877. * in C, we shift after obtaining the absolute value; so the code is
  161878. * interwoven with finding the abs value (temp) and output bits (temp2).
  161879. */
  161880. if (temp < 0) {
  161881. temp = -temp; /* temp is abs value of input */
  161882. temp >>= Al; /* apply the point transform */
  161883. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  161884. temp2 = ~temp;
  161885. } else {
  161886. temp >>= Al; /* apply the point transform */
  161887. temp2 = temp;
  161888. }
  161889. /* Watch out for case that nonzero coef is zero after point transform */
  161890. if (temp == 0) {
  161891. r++;
  161892. continue;
  161893. }
  161894. /* Emit any pending EOBRUN */
  161895. if (entropy->EOBRUN > 0)
  161896. emit_eobrun(entropy);
  161897. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  161898. while (r > 15) {
  161899. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161900. r -= 16;
  161901. }
  161902. /* Find the number of bits needed for the magnitude of the coefficient */
  161903. nbits = 1; /* there must be at least one 1 bit */
  161904. while ((temp >>= 1))
  161905. nbits++;
  161906. /* Check for out-of-range coefficient values */
  161907. if (nbits > MAX_COEF_BITS)
  161908. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161909. /* Count/emit Huffman symbol for run length / number of bits */
  161910. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  161911. /* Emit that number of bits of the value, if positive, */
  161912. /* or the complement of its magnitude, if negative. */
  161913. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161914. r = 0; /* reset zero run length */
  161915. }
  161916. if (r > 0) { /* If there are trailing zeroes, */
  161917. entropy->EOBRUN++; /* count an EOB */
  161918. if (entropy->EOBRUN == 0x7FFF)
  161919. emit_eobrun(entropy); /* force it out to avoid overflow */
  161920. }
  161921. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161922. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161923. /* Update restart-interval state too */
  161924. if (cinfo->restart_interval) {
  161925. if (entropy->restarts_to_go == 0) {
  161926. entropy->restarts_to_go = cinfo->restart_interval;
  161927. entropy->next_restart_num++;
  161928. entropy->next_restart_num &= 7;
  161929. }
  161930. entropy->restarts_to_go--;
  161931. }
  161932. return TRUE;
  161933. }
  161934. /*
  161935. * MCU encoding for DC successive approximation refinement scan.
  161936. * Note: we assume such scans can be multi-component, although the spec
  161937. * is not very clear on the point.
  161938. */
  161939. METHODDEF(boolean)
  161940. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161941. {
  161942. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161943. register int temp;
  161944. int blkn;
  161945. int Al = cinfo->Al;
  161946. JBLOCKROW block;
  161947. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161948. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161949. /* Emit restart marker if needed */
  161950. if (cinfo->restart_interval)
  161951. if (entropy->restarts_to_go == 0)
  161952. emit_restart_p(entropy, entropy->next_restart_num);
  161953. /* Encode the MCU data blocks */
  161954. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161955. block = MCU_data[blkn];
  161956. /* We simply emit the Al'th bit of the DC coefficient value. */
  161957. temp = (*block)[0];
  161958. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  161959. }
  161960. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161961. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161962. /* Update restart-interval state too */
  161963. if (cinfo->restart_interval) {
  161964. if (entropy->restarts_to_go == 0) {
  161965. entropy->restarts_to_go = cinfo->restart_interval;
  161966. entropy->next_restart_num++;
  161967. entropy->next_restart_num &= 7;
  161968. }
  161969. entropy->restarts_to_go--;
  161970. }
  161971. return TRUE;
  161972. }
  161973. /*
  161974. * MCU encoding for AC successive approximation refinement scan.
  161975. */
  161976. METHODDEF(boolean)
  161977. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161978. {
  161979. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161980. register int temp;
  161981. register int r, k;
  161982. int EOB;
  161983. char *BR_buffer;
  161984. unsigned int BR;
  161985. int Se = cinfo->Se;
  161986. int Al = cinfo->Al;
  161987. JBLOCKROW block;
  161988. int absvalues[DCTSIZE2];
  161989. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161990. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161991. /* Emit restart marker if needed */
  161992. if (cinfo->restart_interval)
  161993. if (entropy->restarts_to_go == 0)
  161994. emit_restart_p(entropy, entropy->next_restart_num);
  161995. /* Encode the MCU data block */
  161996. block = MCU_data[0];
  161997. /* It is convenient to make a pre-pass to determine the transformed
  161998. * coefficients' absolute values and the EOB position.
  161999. */
  162000. EOB = 0;
  162001. for (k = cinfo->Ss; k <= Se; k++) {
  162002. temp = (*block)[jpeg_natural_order[k]];
  162003. /* We must apply the point transform by Al. For AC coefficients this
  162004. * is an integer division with rounding towards 0. To do this portably
  162005. * in C, we shift after obtaining the absolute value.
  162006. */
  162007. if (temp < 0)
  162008. temp = -temp; /* temp is abs value of input */
  162009. temp >>= Al; /* apply the point transform */
  162010. absvalues[k] = temp; /* save abs value for main pass */
  162011. if (temp == 1)
  162012. EOB = k; /* EOB = index of last newly-nonzero coef */
  162013. }
  162014. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  162015. r = 0; /* r = run length of zeros */
  162016. BR = 0; /* BR = count of buffered bits added now */
  162017. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  162018. for (k = cinfo->Ss; k <= Se; k++) {
  162019. if ((temp = absvalues[k]) == 0) {
  162020. r++;
  162021. continue;
  162022. }
  162023. /* Emit any required ZRLs, but not if they can be folded into EOB */
  162024. while (r > 15 && k <= EOB) {
  162025. /* emit any pending EOBRUN and the BE correction bits */
  162026. emit_eobrun(entropy);
  162027. /* Emit ZRL */
  162028. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  162029. r -= 16;
  162030. /* Emit buffered correction bits that must be associated with ZRL */
  162031. emit_buffered_bits(entropy, BR_buffer, BR);
  162032. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162033. BR = 0;
  162034. }
  162035. /* If the coef was previously nonzero, it only needs a correction bit.
  162036. * NOTE: a straight translation of the spec's figure G.7 would suggest
  162037. * that we also need to test r > 15. But if r > 15, we can only get here
  162038. * if k > EOB, which implies that this coefficient is not 1.
  162039. */
  162040. if (temp > 1) {
  162041. /* The correction bit is the next bit of the absolute value. */
  162042. BR_buffer[BR++] = (char) (temp & 1);
  162043. continue;
  162044. }
  162045. /* Emit any pending EOBRUN and the BE correction bits */
  162046. emit_eobrun(entropy);
  162047. /* Count/emit Huffman symbol for run length / number of bits */
  162048. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  162049. /* Emit output bit for newly-nonzero coef */
  162050. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  162051. emit_bits_p(entropy, (unsigned int) temp, 1);
  162052. /* Emit buffered correction bits that must be associated with this code */
  162053. emit_buffered_bits(entropy, BR_buffer, BR);
  162054. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162055. BR = 0;
  162056. r = 0; /* reset zero run length */
  162057. }
  162058. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  162059. entropy->EOBRUN++; /* count an EOB */
  162060. entropy->BE += BR; /* concat my correction bits to older ones */
  162061. /* We force out the EOB if we risk either:
  162062. * 1. overflow of the EOB counter;
  162063. * 2. overflow of the correction bit buffer during the next MCU.
  162064. */
  162065. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  162066. emit_eobrun(entropy);
  162067. }
  162068. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162069. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162070. /* Update restart-interval state too */
  162071. if (cinfo->restart_interval) {
  162072. if (entropy->restarts_to_go == 0) {
  162073. entropy->restarts_to_go = cinfo->restart_interval;
  162074. entropy->next_restart_num++;
  162075. entropy->next_restart_num &= 7;
  162076. }
  162077. entropy->restarts_to_go--;
  162078. }
  162079. return TRUE;
  162080. }
  162081. /*
  162082. * Finish up at the end of a Huffman-compressed progressive scan.
  162083. */
  162084. METHODDEF(void)
  162085. finish_pass_phuff (j_compress_ptr cinfo)
  162086. {
  162087. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162088. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162089. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162090. /* Flush out any buffered data */
  162091. emit_eobrun(entropy);
  162092. flush_bits_p(entropy);
  162093. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162094. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162095. }
  162096. /*
  162097. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162098. */
  162099. METHODDEF(void)
  162100. finish_pass_gather_phuff (j_compress_ptr cinfo)
  162101. {
  162102. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162103. boolean is_DC_band;
  162104. int ci, tbl;
  162105. jpeg_component_info * compptr;
  162106. JHUFF_TBL **htblptr;
  162107. boolean did[NUM_HUFF_TBLS];
  162108. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  162109. emit_eobrun(entropy);
  162110. is_DC_band = (cinfo->Ss == 0);
  162111. /* It's important not to apply jpeg_gen_optimal_table more than once
  162112. * per table, because it clobbers the input frequency counts!
  162113. */
  162114. MEMZERO(did, SIZEOF(did));
  162115. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162116. compptr = cinfo->cur_comp_info[ci];
  162117. if (is_DC_band) {
  162118. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162119. continue;
  162120. tbl = compptr->dc_tbl_no;
  162121. } else {
  162122. tbl = compptr->ac_tbl_no;
  162123. }
  162124. if (! did[tbl]) {
  162125. if (is_DC_band)
  162126. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  162127. else
  162128. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  162129. if (*htblptr == NULL)
  162130. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162131. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  162132. did[tbl] = TRUE;
  162133. }
  162134. }
  162135. }
  162136. /*
  162137. * Module initialization routine for progressive Huffman entropy encoding.
  162138. */
  162139. GLOBAL(void)
  162140. jinit_phuff_encoder (j_compress_ptr cinfo)
  162141. {
  162142. phuff_entropy_ptr entropy;
  162143. int i;
  162144. entropy = (phuff_entropy_ptr)
  162145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162146. SIZEOF(phuff_entropy_encoder));
  162147. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162148. entropy->pub.start_pass = start_pass_phuff;
  162149. /* Mark tables unallocated */
  162150. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162151. entropy->derived_tbls[i] = NULL;
  162152. entropy->count_ptrs[i] = NULL;
  162153. }
  162154. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  162155. }
  162156. #endif /* C_PROGRESSIVE_SUPPORTED */
  162157. /********* End of inlined file: jcphuff.c *********/
  162158. /********* Start of inlined file: jcprepct.c *********/
  162159. #define JPEG_INTERNALS
  162160. /* At present, jcsample.c can request context rows only for smoothing.
  162161. * In the future, we might also need context rows for CCIR601 sampling
  162162. * or other more-complex downsampling procedures. The code to support
  162163. * context rows should be compiled only if needed.
  162164. */
  162165. #ifdef INPUT_SMOOTHING_SUPPORTED
  162166. #define CONTEXT_ROWS_SUPPORTED
  162167. #endif
  162168. /*
  162169. * For the simple (no-context-row) case, we just need to buffer one
  162170. * row group's worth of pixels for the downsampling step. At the bottom of
  162171. * the image, we pad to a full row group by replicating the last pixel row.
  162172. * The downsampler's last output row is then replicated if needed to pad
  162173. * out to a full iMCU row.
  162174. *
  162175. * When providing context rows, we must buffer three row groups' worth of
  162176. * pixels. Three row groups are physically allocated, but the row pointer
  162177. * arrays are made five row groups high, with the extra pointers above and
  162178. * below "wrapping around" to point to the last and first real row groups.
  162179. * This allows the downsampler to access the proper context rows.
  162180. * At the top and bottom of the image, we create dummy context rows by
  162181. * copying the first or last real pixel row. This copying could be avoided
  162182. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  162183. * trouble on the compression side.
  162184. */
  162185. /* Private buffer controller object */
  162186. typedef struct {
  162187. struct jpeg_c_prep_controller pub; /* public fields */
  162188. /* Downsampling input buffer. This buffer holds color-converted data
  162189. * until we have enough to do a downsample step.
  162190. */
  162191. JSAMPARRAY color_buf[MAX_COMPONENTS];
  162192. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  162193. int next_buf_row; /* index of next row to store in color_buf */
  162194. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  162195. int this_row_group; /* starting row index of group to process */
  162196. int next_buf_stop; /* downsample when we reach this index */
  162197. #endif
  162198. } my_prep_controller;
  162199. typedef my_prep_controller * my_prep_ptr;
  162200. /*
  162201. * Initialize for a processing pass.
  162202. */
  162203. METHODDEF(void)
  162204. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162205. {
  162206. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162207. if (pass_mode != JBUF_PASS_THRU)
  162208. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162209. /* Initialize total-height counter for detecting bottom of image */
  162210. prep->rows_to_go = cinfo->image_height;
  162211. /* Mark the conversion buffer empty */
  162212. prep->next_buf_row = 0;
  162213. #ifdef CONTEXT_ROWS_SUPPORTED
  162214. /* Preset additional state variables for context mode.
  162215. * These aren't used in non-context mode, so we needn't test which mode.
  162216. */
  162217. prep->this_row_group = 0;
  162218. /* Set next_buf_stop to stop after two row groups have been read in. */
  162219. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  162220. #endif
  162221. }
  162222. /*
  162223. * Expand an image vertically from height input_rows to height output_rows,
  162224. * by duplicating the bottom row.
  162225. */
  162226. LOCAL(void)
  162227. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  162228. int input_rows, int output_rows)
  162229. {
  162230. register int row;
  162231. for (row = input_rows; row < output_rows; row++) {
  162232. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  162233. 1, num_cols);
  162234. }
  162235. }
  162236. /*
  162237. * Process some data in the simple no-context case.
  162238. *
  162239. * Preprocessor output data is counted in "row groups". A row group
  162240. * is defined to be v_samp_factor sample rows of each component.
  162241. * Downsampling will produce this much data from each max_v_samp_factor
  162242. * input rows.
  162243. */
  162244. METHODDEF(void)
  162245. pre_process_data (j_compress_ptr cinfo,
  162246. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162247. JDIMENSION in_rows_avail,
  162248. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162249. JDIMENSION out_row_groups_avail)
  162250. {
  162251. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162252. int numrows, ci;
  162253. JDIMENSION inrows;
  162254. jpeg_component_info * compptr;
  162255. while (*in_row_ctr < in_rows_avail &&
  162256. *out_row_group_ctr < out_row_groups_avail) {
  162257. /* Do color conversion to fill the conversion buffer. */
  162258. inrows = in_rows_avail - *in_row_ctr;
  162259. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  162260. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162261. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162262. prep->color_buf,
  162263. (JDIMENSION) prep->next_buf_row,
  162264. numrows);
  162265. *in_row_ctr += numrows;
  162266. prep->next_buf_row += numrows;
  162267. prep->rows_to_go -= numrows;
  162268. /* If at bottom of image, pad to fill the conversion buffer. */
  162269. if (prep->rows_to_go == 0 &&
  162270. prep->next_buf_row < cinfo->max_v_samp_factor) {
  162271. for (ci = 0; ci < cinfo->num_components; ci++) {
  162272. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162273. prep->next_buf_row, cinfo->max_v_samp_factor);
  162274. }
  162275. prep->next_buf_row = cinfo->max_v_samp_factor;
  162276. }
  162277. /* If we've filled the conversion buffer, empty it. */
  162278. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  162279. (*cinfo->downsample->downsample) (cinfo,
  162280. prep->color_buf, (JDIMENSION) 0,
  162281. output_buf, *out_row_group_ctr);
  162282. prep->next_buf_row = 0;
  162283. (*out_row_group_ctr)++;
  162284. }
  162285. /* If at bottom of image, pad the output to a full iMCU height.
  162286. * Note we assume the caller is providing a one-iMCU-height output buffer!
  162287. */
  162288. if (prep->rows_to_go == 0 &&
  162289. *out_row_group_ctr < out_row_groups_avail) {
  162290. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162291. ci++, compptr++) {
  162292. expand_bottom_edge(output_buf[ci],
  162293. compptr->width_in_blocks * DCTSIZE,
  162294. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  162295. (int) (out_row_groups_avail * compptr->v_samp_factor));
  162296. }
  162297. *out_row_group_ctr = out_row_groups_avail;
  162298. break; /* can exit outer loop without test */
  162299. }
  162300. }
  162301. }
  162302. #ifdef CONTEXT_ROWS_SUPPORTED
  162303. /*
  162304. * Process some data in the context case.
  162305. */
  162306. METHODDEF(void)
  162307. pre_process_context (j_compress_ptr cinfo,
  162308. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162309. JDIMENSION in_rows_avail,
  162310. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162311. JDIMENSION out_row_groups_avail)
  162312. {
  162313. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162314. int numrows, ci;
  162315. int buf_height = cinfo->max_v_samp_factor * 3;
  162316. JDIMENSION inrows;
  162317. while (*out_row_group_ctr < out_row_groups_avail) {
  162318. if (*in_row_ctr < in_rows_avail) {
  162319. /* Do color conversion to fill the conversion buffer. */
  162320. inrows = in_rows_avail - *in_row_ctr;
  162321. numrows = prep->next_buf_stop - prep->next_buf_row;
  162322. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162323. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162324. prep->color_buf,
  162325. (JDIMENSION) prep->next_buf_row,
  162326. numrows);
  162327. /* Pad at top of image, if first time through */
  162328. if (prep->rows_to_go == cinfo->image_height) {
  162329. for (ci = 0; ci < cinfo->num_components; ci++) {
  162330. int row;
  162331. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  162332. jcopy_sample_rows(prep->color_buf[ci], 0,
  162333. prep->color_buf[ci], -row,
  162334. 1, cinfo->image_width);
  162335. }
  162336. }
  162337. }
  162338. *in_row_ctr += numrows;
  162339. prep->next_buf_row += numrows;
  162340. prep->rows_to_go -= numrows;
  162341. } else {
  162342. /* Return for more data, unless we are at the bottom of the image. */
  162343. if (prep->rows_to_go != 0)
  162344. break;
  162345. /* When at bottom of image, pad to fill the conversion buffer. */
  162346. if (prep->next_buf_row < prep->next_buf_stop) {
  162347. for (ci = 0; ci < cinfo->num_components; ci++) {
  162348. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162349. prep->next_buf_row, prep->next_buf_stop);
  162350. }
  162351. prep->next_buf_row = prep->next_buf_stop;
  162352. }
  162353. }
  162354. /* If we've gotten enough data, downsample a row group. */
  162355. if (prep->next_buf_row == prep->next_buf_stop) {
  162356. (*cinfo->downsample->downsample) (cinfo,
  162357. prep->color_buf,
  162358. (JDIMENSION) prep->this_row_group,
  162359. output_buf, *out_row_group_ctr);
  162360. (*out_row_group_ctr)++;
  162361. /* Advance pointers with wraparound as necessary. */
  162362. prep->this_row_group += cinfo->max_v_samp_factor;
  162363. if (prep->this_row_group >= buf_height)
  162364. prep->this_row_group = 0;
  162365. if (prep->next_buf_row >= buf_height)
  162366. prep->next_buf_row = 0;
  162367. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  162368. }
  162369. }
  162370. }
  162371. /*
  162372. * Create the wrapped-around downsampling input buffer needed for context mode.
  162373. */
  162374. LOCAL(void)
  162375. create_context_buffer (j_compress_ptr cinfo)
  162376. {
  162377. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162378. int rgroup_height = cinfo->max_v_samp_factor;
  162379. int ci, i;
  162380. jpeg_component_info * compptr;
  162381. JSAMPARRAY true_buffer, fake_buffer;
  162382. /* Grab enough space for fake row pointers for all the components;
  162383. * we need five row groups' worth of pointers for each component.
  162384. */
  162385. fake_buffer = (JSAMPARRAY)
  162386. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162387. (cinfo->num_components * 5 * rgroup_height) *
  162388. SIZEOF(JSAMPROW));
  162389. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162390. ci++, compptr++) {
  162391. /* Allocate the actual buffer space (3 row groups) for this component.
  162392. * We make the buffer wide enough to allow the downsampler to edge-expand
  162393. * horizontally within the buffer, if it so chooses.
  162394. */
  162395. true_buffer = (*cinfo->mem->alloc_sarray)
  162396. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162397. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162398. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162399. (JDIMENSION) (3 * rgroup_height));
  162400. /* Copy true buffer row pointers into the middle of the fake row array */
  162401. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  162402. 3 * rgroup_height * SIZEOF(JSAMPROW));
  162403. /* Fill in the above and below wraparound pointers */
  162404. for (i = 0; i < rgroup_height; i++) {
  162405. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  162406. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  162407. }
  162408. prep->color_buf[ci] = fake_buffer + rgroup_height;
  162409. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  162410. }
  162411. }
  162412. #endif /* CONTEXT_ROWS_SUPPORTED */
  162413. /*
  162414. * Initialize preprocessing controller.
  162415. */
  162416. GLOBAL(void)
  162417. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162418. {
  162419. my_prep_ptr prep;
  162420. int ci;
  162421. jpeg_component_info * compptr;
  162422. if (need_full_buffer) /* safety check */
  162423. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162424. prep = (my_prep_ptr)
  162425. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162426. SIZEOF(my_prep_controller));
  162427. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  162428. prep->pub.start_pass = start_pass_prep;
  162429. /* Allocate the color conversion buffer.
  162430. * We make the buffer wide enough to allow the downsampler to edge-expand
  162431. * horizontally within the buffer, if it so chooses.
  162432. */
  162433. if (cinfo->downsample->need_context_rows) {
  162434. /* Set up to provide context rows */
  162435. #ifdef CONTEXT_ROWS_SUPPORTED
  162436. prep->pub.pre_process_data = pre_process_context;
  162437. create_context_buffer(cinfo);
  162438. #else
  162439. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162440. #endif
  162441. } else {
  162442. /* No context, just make it tall enough for one row group */
  162443. prep->pub.pre_process_data = pre_process_data;
  162444. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162445. ci++, compptr++) {
  162446. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  162447. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162448. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162449. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162450. (JDIMENSION) cinfo->max_v_samp_factor);
  162451. }
  162452. }
  162453. }
  162454. /********* End of inlined file: jcprepct.c *********/
  162455. /********* Start of inlined file: jcsample.c *********/
  162456. #define JPEG_INTERNALS
  162457. /* Pointer to routine to downsample a single component */
  162458. typedef JMETHOD(void, downsample1_ptr,
  162459. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162460. JSAMPARRAY input_data, JSAMPARRAY output_data));
  162461. /* Private subobject */
  162462. typedef struct {
  162463. struct jpeg_downsampler pub; /* public fields */
  162464. /* Downsampling method pointers, one per component */
  162465. downsample1_ptr methods[MAX_COMPONENTS];
  162466. } my_downsampler;
  162467. typedef my_downsampler * my_downsample_ptr;
  162468. /*
  162469. * Initialize for a downsampling pass.
  162470. */
  162471. METHODDEF(void)
  162472. start_pass_downsample (j_compress_ptr cinfo)
  162473. {
  162474. /* no work for now */
  162475. }
  162476. /*
  162477. * Expand a component horizontally from width input_cols to width output_cols,
  162478. * by duplicating the rightmost samples.
  162479. */
  162480. LOCAL(void)
  162481. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  162482. JDIMENSION input_cols, JDIMENSION output_cols)
  162483. {
  162484. register JSAMPROW ptr;
  162485. register JSAMPLE pixval;
  162486. register int count;
  162487. int row;
  162488. int numcols = (int) (output_cols - input_cols);
  162489. if (numcols > 0) {
  162490. for (row = 0; row < num_rows; row++) {
  162491. ptr = image_data[row] + input_cols;
  162492. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  162493. for (count = numcols; count > 0; count--)
  162494. *ptr++ = pixval;
  162495. }
  162496. }
  162497. }
  162498. /*
  162499. * Do downsampling for a whole row group (all components).
  162500. *
  162501. * In this version we simply downsample each component independently.
  162502. */
  162503. METHODDEF(void)
  162504. sep_downsample (j_compress_ptr cinfo,
  162505. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  162506. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  162507. {
  162508. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  162509. int ci;
  162510. jpeg_component_info * compptr;
  162511. JSAMPARRAY in_ptr, out_ptr;
  162512. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162513. ci++, compptr++) {
  162514. in_ptr = input_buf[ci] + in_row_index;
  162515. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  162516. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  162517. }
  162518. }
  162519. /*
  162520. * Downsample pixel values of a single component.
  162521. * One row group is processed per call.
  162522. * This version handles arbitrary integral sampling ratios, without smoothing.
  162523. * Note that this version is not actually used for customary sampling ratios.
  162524. */
  162525. METHODDEF(void)
  162526. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162527. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162528. {
  162529. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  162530. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  162531. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162532. JSAMPROW inptr, outptr;
  162533. INT32 outvalue;
  162534. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  162535. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  162536. numpix = h_expand * v_expand;
  162537. numpix2 = numpix/2;
  162538. /* Expand input data enough to let all the output samples be generated
  162539. * by the standard loop. Special-casing padded output would be more
  162540. * efficient.
  162541. */
  162542. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162543. cinfo->image_width, output_cols * h_expand);
  162544. inrow = 0;
  162545. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162546. outptr = output_data[outrow];
  162547. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  162548. outcol++, outcol_h += h_expand) {
  162549. outvalue = 0;
  162550. for (v = 0; v < v_expand; v++) {
  162551. inptr = input_data[inrow+v] + outcol_h;
  162552. for (h = 0; h < h_expand; h++) {
  162553. outvalue += (INT32) GETJSAMPLE(*inptr++);
  162554. }
  162555. }
  162556. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  162557. }
  162558. inrow += v_expand;
  162559. }
  162560. }
  162561. /*
  162562. * Downsample pixel values of a single component.
  162563. * This version handles the special case of a full-size component,
  162564. * without smoothing.
  162565. */
  162566. METHODDEF(void)
  162567. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162568. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162569. {
  162570. /* Copy the data */
  162571. jcopy_sample_rows(input_data, 0, output_data, 0,
  162572. cinfo->max_v_samp_factor, cinfo->image_width);
  162573. /* Edge-expand */
  162574. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  162575. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  162576. }
  162577. /*
  162578. * Downsample pixel values of a single component.
  162579. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  162580. * without smoothing.
  162581. *
  162582. * A note about the "bias" calculations: when rounding fractional values to
  162583. * integer, we do not want to always round 0.5 up to the next integer.
  162584. * If we did that, we'd introduce a noticeable bias towards larger values.
  162585. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  162586. * alternate pixel locations (a simple ordered dither pattern).
  162587. */
  162588. METHODDEF(void)
  162589. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162590. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162591. {
  162592. int outrow;
  162593. JDIMENSION outcol;
  162594. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162595. register JSAMPROW inptr, outptr;
  162596. register int bias;
  162597. /* Expand input data enough to let all the output samples be generated
  162598. * by the standard loop. Special-casing padded output would be more
  162599. * efficient.
  162600. */
  162601. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162602. cinfo->image_width, output_cols * 2);
  162603. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162604. outptr = output_data[outrow];
  162605. inptr = input_data[outrow];
  162606. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  162607. for (outcol = 0; outcol < output_cols; outcol++) {
  162608. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  162609. + bias) >> 1);
  162610. bias ^= 1; /* 0=>1, 1=>0 */
  162611. inptr += 2;
  162612. }
  162613. }
  162614. }
  162615. /*
  162616. * Downsample pixel values of a single component.
  162617. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162618. * without smoothing.
  162619. */
  162620. METHODDEF(void)
  162621. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162622. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162623. {
  162624. int inrow, outrow;
  162625. JDIMENSION outcol;
  162626. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162627. register JSAMPROW inptr0, inptr1, outptr;
  162628. register int bias;
  162629. /* Expand input data enough to let all the output samples be generated
  162630. * by the standard loop. Special-casing padded output would be more
  162631. * efficient.
  162632. */
  162633. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162634. cinfo->image_width, output_cols * 2);
  162635. inrow = 0;
  162636. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162637. outptr = output_data[outrow];
  162638. inptr0 = input_data[inrow];
  162639. inptr1 = input_data[inrow+1];
  162640. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  162641. for (outcol = 0; outcol < output_cols; outcol++) {
  162642. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162643. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  162644. + bias) >> 2);
  162645. bias ^= 3; /* 1=>2, 2=>1 */
  162646. inptr0 += 2; inptr1 += 2;
  162647. }
  162648. inrow += 2;
  162649. }
  162650. }
  162651. #ifdef INPUT_SMOOTHING_SUPPORTED
  162652. /*
  162653. * Downsample pixel values of a single component.
  162654. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162655. * with smoothing. One row of context is required.
  162656. */
  162657. METHODDEF(void)
  162658. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162659. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162660. {
  162661. int inrow, outrow;
  162662. JDIMENSION colctr;
  162663. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162664. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  162665. INT32 membersum, neighsum, memberscale, neighscale;
  162666. /* Expand input data enough to let all the output samples be generated
  162667. * by the standard loop. Special-casing padded output would be more
  162668. * efficient.
  162669. */
  162670. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162671. cinfo->image_width, output_cols * 2);
  162672. /* We don't bother to form the individual "smoothed" input pixel values;
  162673. * we can directly compute the output which is the average of the four
  162674. * smoothed values. Each of the four member pixels contributes a fraction
  162675. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  162676. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  162677. * output. The four corner-adjacent neighbor pixels contribute a fraction
  162678. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  162679. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  162680. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  162681. * factors are scaled by 2^16 = 65536.
  162682. * Also recall that SF = smoothing_factor / 1024.
  162683. */
  162684. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  162685. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  162686. inrow = 0;
  162687. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162688. outptr = output_data[outrow];
  162689. inptr0 = input_data[inrow];
  162690. inptr1 = input_data[inrow+1];
  162691. above_ptr = input_data[inrow-1];
  162692. below_ptr = input_data[inrow+2];
  162693. /* Special case for first column: pretend column -1 is same as column 0 */
  162694. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162695. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162696. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162697. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162698. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  162699. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  162700. neighsum += neighsum;
  162701. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  162702. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  162703. membersum = membersum * memberscale + neighsum * neighscale;
  162704. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162705. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162706. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162707. /* sum of pixels directly mapped to this output element */
  162708. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162709. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162710. /* sum of edge-neighbor pixels */
  162711. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162712. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162713. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  162714. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  162715. /* The edge-neighbors count twice as much as corner-neighbors */
  162716. neighsum += neighsum;
  162717. /* Add in the corner-neighbors */
  162718. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  162719. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  162720. /* form final output scaled up by 2^16 */
  162721. membersum = membersum * memberscale + neighsum * neighscale;
  162722. /* round, descale and output it */
  162723. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162724. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162725. }
  162726. /* Special case for last column */
  162727. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162728. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162729. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162730. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162731. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  162732. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  162733. neighsum += neighsum;
  162734. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  162735. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  162736. membersum = membersum * memberscale + neighsum * neighscale;
  162737. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162738. inrow += 2;
  162739. }
  162740. }
  162741. /*
  162742. * Downsample pixel values of a single component.
  162743. * This version handles the special case of a full-size component,
  162744. * with smoothing. One row of context is required.
  162745. */
  162746. METHODDEF(void)
  162747. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  162748. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162749. {
  162750. int outrow;
  162751. JDIMENSION colctr;
  162752. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162753. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  162754. INT32 membersum, neighsum, memberscale, neighscale;
  162755. int colsum, lastcolsum, nextcolsum;
  162756. /* Expand input data enough to let all the output samples be generated
  162757. * by the standard loop. Special-casing padded output would be more
  162758. * efficient.
  162759. */
  162760. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162761. cinfo->image_width, output_cols);
  162762. /* Each of the eight neighbor pixels contributes a fraction SF to the
  162763. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  162764. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  162765. * Also recall that SF = smoothing_factor / 1024.
  162766. */
  162767. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  162768. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  162769. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162770. outptr = output_data[outrow];
  162771. inptr = input_data[outrow];
  162772. above_ptr = input_data[outrow-1];
  162773. below_ptr = input_data[outrow+1];
  162774. /* Special case for first column */
  162775. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  162776. GETJSAMPLE(*inptr);
  162777. membersum = GETJSAMPLE(*inptr++);
  162778. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162779. GETJSAMPLE(*inptr);
  162780. neighsum = colsum + (colsum - membersum) + nextcolsum;
  162781. membersum = membersum * memberscale + neighsum * neighscale;
  162782. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162783. lastcolsum = colsum; colsum = nextcolsum;
  162784. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162785. membersum = GETJSAMPLE(*inptr++);
  162786. above_ptr++; below_ptr++;
  162787. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162788. GETJSAMPLE(*inptr);
  162789. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  162790. membersum = membersum * memberscale + neighsum * neighscale;
  162791. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162792. lastcolsum = colsum; colsum = nextcolsum;
  162793. }
  162794. /* Special case for last column */
  162795. membersum = GETJSAMPLE(*inptr);
  162796. neighsum = lastcolsum + (colsum - membersum) + colsum;
  162797. membersum = membersum * memberscale + neighsum * neighscale;
  162798. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162799. }
  162800. }
  162801. #endif /* INPUT_SMOOTHING_SUPPORTED */
  162802. /*
  162803. * Module initialization routine for downsampling.
  162804. * Note that we must select a routine for each component.
  162805. */
  162806. GLOBAL(void)
  162807. jinit_downsampler (j_compress_ptr cinfo)
  162808. {
  162809. my_downsample_ptr downsample;
  162810. int ci;
  162811. jpeg_component_info * compptr;
  162812. boolean smoothok = TRUE;
  162813. downsample = (my_downsample_ptr)
  162814. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162815. SIZEOF(my_downsampler));
  162816. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  162817. downsample->pub.start_pass = start_pass_downsample;
  162818. downsample->pub.downsample = sep_downsample;
  162819. downsample->pub.need_context_rows = FALSE;
  162820. if (cinfo->CCIR601_sampling)
  162821. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  162822. /* Verify we can handle the sampling factors, and set up method pointers */
  162823. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162824. ci++, compptr++) {
  162825. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  162826. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162827. #ifdef INPUT_SMOOTHING_SUPPORTED
  162828. if (cinfo->smoothing_factor) {
  162829. downsample->methods[ci] = fullsize_smooth_downsample;
  162830. downsample->pub.need_context_rows = TRUE;
  162831. } else
  162832. #endif
  162833. downsample->methods[ci] = fullsize_downsample;
  162834. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162835. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162836. smoothok = FALSE;
  162837. downsample->methods[ci] = h2v1_downsample;
  162838. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162839. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  162840. #ifdef INPUT_SMOOTHING_SUPPORTED
  162841. if (cinfo->smoothing_factor) {
  162842. downsample->methods[ci] = h2v2_smooth_downsample;
  162843. downsample->pub.need_context_rows = TRUE;
  162844. } else
  162845. #endif
  162846. downsample->methods[ci] = h2v2_downsample;
  162847. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  162848. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  162849. smoothok = FALSE;
  162850. downsample->methods[ci] = int_downsample;
  162851. } else
  162852. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  162853. }
  162854. #ifdef INPUT_SMOOTHING_SUPPORTED
  162855. if (cinfo->smoothing_factor && !smoothok)
  162856. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  162857. #endif
  162858. }
  162859. /********* End of inlined file: jcsample.c *********/
  162860. /********* Start of inlined file: jctrans.c *********/
  162861. #define JPEG_INTERNALS
  162862. /* Forward declarations */
  162863. LOCAL(void) transencode_master_selection
  162864. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162865. LOCAL(void) transencode_coef_controller
  162866. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162867. /*
  162868. * Compression initialization for writing raw-coefficient data.
  162869. * Before calling this, all parameters and a data destination must be set up.
  162870. * Call jpeg_finish_compress() to actually write the data.
  162871. *
  162872. * The number of passed virtual arrays must match cinfo->num_components.
  162873. * Note that the virtual arrays need not be filled or even realized at
  162874. * the time write_coefficients is called; indeed, if the virtual arrays
  162875. * were requested from this compression object's memory manager, they
  162876. * typically will be realized during this routine and filled afterwards.
  162877. */
  162878. GLOBAL(void)
  162879. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  162880. {
  162881. if (cinfo->global_state != CSTATE_START)
  162882. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162883. /* Mark all tables to be written */
  162884. jpeg_suppress_tables(cinfo, FALSE);
  162885. /* (Re)initialize error mgr and destination modules */
  162886. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162887. (*cinfo->dest->init_destination) (cinfo);
  162888. /* Perform master selection of active modules */
  162889. transencode_master_selection(cinfo, coef_arrays);
  162890. /* Wait for jpeg_finish_compress() call */
  162891. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  162892. cinfo->global_state = CSTATE_WRCOEFS;
  162893. }
  162894. /*
  162895. * Initialize the compression object with default parameters,
  162896. * then copy from the source object all parameters needed for lossless
  162897. * transcoding. Parameters that can be varied without loss (such as
  162898. * scan script and Huffman optimization) are left in their default states.
  162899. */
  162900. GLOBAL(void)
  162901. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  162902. j_compress_ptr dstinfo)
  162903. {
  162904. JQUANT_TBL ** qtblptr;
  162905. jpeg_component_info *incomp, *outcomp;
  162906. JQUANT_TBL *c_quant, *slot_quant;
  162907. int tblno, ci, coefi;
  162908. /* Safety check to ensure start_compress not called yet. */
  162909. if (dstinfo->global_state != CSTATE_START)
  162910. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  162911. /* Copy fundamental image dimensions */
  162912. dstinfo->image_width = srcinfo->image_width;
  162913. dstinfo->image_height = srcinfo->image_height;
  162914. dstinfo->input_components = srcinfo->num_components;
  162915. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  162916. /* Initialize all parameters to default values */
  162917. jpeg_set_defaults(dstinfo);
  162918. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  162919. * Fix it to get the right header markers for the image colorspace.
  162920. */
  162921. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  162922. dstinfo->data_precision = srcinfo->data_precision;
  162923. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  162924. /* Copy the source's quantization tables. */
  162925. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  162926. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  162927. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  162928. if (*qtblptr == NULL)
  162929. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  162930. MEMCOPY((*qtblptr)->quantval,
  162931. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  162932. SIZEOF((*qtblptr)->quantval));
  162933. (*qtblptr)->sent_table = FALSE;
  162934. }
  162935. }
  162936. /* Copy the source's per-component info.
  162937. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  162938. */
  162939. dstinfo->num_components = srcinfo->num_components;
  162940. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  162941. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  162942. MAX_COMPONENTS);
  162943. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  162944. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  162945. outcomp->component_id = incomp->component_id;
  162946. outcomp->h_samp_factor = incomp->h_samp_factor;
  162947. outcomp->v_samp_factor = incomp->v_samp_factor;
  162948. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  162949. /* Make sure saved quantization table for component matches the qtable
  162950. * slot. If not, the input file re-used this qtable slot.
  162951. * IJG encoder currently cannot duplicate this.
  162952. */
  162953. tblno = outcomp->quant_tbl_no;
  162954. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  162955. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  162956. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  162957. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  162958. c_quant = incomp->quant_table;
  162959. if (c_quant != NULL) {
  162960. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  162961. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  162962. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  162963. }
  162964. }
  162965. /* Note: we do not copy the source's Huffman table assignments;
  162966. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  162967. */
  162968. }
  162969. /* Also copy JFIF version and resolution information, if available.
  162970. * Strictly speaking this isn't "critical" info, but it's nearly
  162971. * always appropriate to copy it if available. In particular,
  162972. * if the application chooses to copy JFIF 1.02 extension markers from
  162973. * the source file, we need to copy the version to make sure we don't
  162974. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  162975. * We will *not*, however, copy version info from mislabeled "2.01" files.
  162976. */
  162977. if (srcinfo->saw_JFIF_marker) {
  162978. if (srcinfo->JFIF_major_version == 1) {
  162979. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  162980. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  162981. }
  162982. dstinfo->density_unit = srcinfo->density_unit;
  162983. dstinfo->X_density = srcinfo->X_density;
  162984. dstinfo->Y_density = srcinfo->Y_density;
  162985. }
  162986. }
  162987. /*
  162988. * Master selection of compression modules for transcoding.
  162989. * This substitutes for jcinit.c's initialization of the full compressor.
  162990. */
  162991. LOCAL(void)
  162992. transencode_master_selection (j_compress_ptr cinfo,
  162993. jvirt_barray_ptr * coef_arrays)
  162994. {
  162995. /* Although we don't actually use input_components for transcoding,
  162996. * jcmaster.c's initial_setup will complain if input_components is 0.
  162997. */
  162998. cinfo->input_components = 1;
  162999. /* Initialize master control (includes parameter checking/processing) */
  163000. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  163001. /* Entropy encoding: either Huffman or arithmetic coding. */
  163002. if (cinfo->arith_code) {
  163003. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163004. } else {
  163005. if (cinfo->progressive_mode) {
  163006. #ifdef C_PROGRESSIVE_SUPPORTED
  163007. jinit_phuff_encoder(cinfo);
  163008. #else
  163009. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163010. #endif
  163011. } else
  163012. jinit_huff_encoder(cinfo);
  163013. }
  163014. /* We need a special coefficient buffer controller. */
  163015. transencode_coef_controller(cinfo, coef_arrays);
  163016. jinit_marker_writer(cinfo);
  163017. /* We can now tell the memory manager to allocate virtual arrays. */
  163018. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163019. /* Write the datastream header (SOI, JFIF) immediately.
  163020. * Frame and scan headers are postponed till later.
  163021. * This lets application insert special markers after the SOI.
  163022. */
  163023. (*cinfo->marker->write_file_header) (cinfo);
  163024. }
  163025. /*
  163026. * The rest of this file is a special implementation of the coefficient
  163027. * buffer controller. This is similar to jccoefct.c, but it handles only
  163028. * output from presupplied virtual arrays. Furthermore, we generate any
  163029. * dummy padding blocks on-the-fly rather than expecting them to be present
  163030. * in the arrays.
  163031. */
  163032. /* Private buffer controller object */
  163033. typedef struct {
  163034. struct jpeg_c_coef_controller pub; /* public fields */
  163035. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  163036. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  163037. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  163038. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  163039. /* Virtual block array for each component. */
  163040. jvirt_barray_ptr * whole_image;
  163041. /* Workspace for constructing dummy blocks at right/bottom edges. */
  163042. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  163043. } my_coef_controller2;
  163044. typedef my_coef_controller2 * my_coef_ptr2;
  163045. LOCAL(void)
  163046. start_iMCU_row2 (j_compress_ptr cinfo)
  163047. /* Reset within-iMCU-row counters for a new row */
  163048. {
  163049. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163050. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  163051. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  163052. * But at the bottom of the image, process only what's left.
  163053. */
  163054. if (cinfo->comps_in_scan > 1) {
  163055. coef->MCU_rows_per_iMCU_row = 1;
  163056. } else {
  163057. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  163058. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  163059. else
  163060. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  163061. }
  163062. coef->mcu_ctr = 0;
  163063. coef->MCU_vert_offset = 0;
  163064. }
  163065. /*
  163066. * Initialize for a processing pass.
  163067. */
  163068. METHODDEF(void)
  163069. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163070. {
  163071. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163072. if (pass_mode != JBUF_CRANK_DEST)
  163073. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163074. coef->iMCU_row_num = 0;
  163075. start_iMCU_row2(cinfo);
  163076. }
  163077. /*
  163078. * Process some data.
  163079. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  163080. * per call, ie, v_samp_factor block rows for each component in the scan.
  163081. * The data is obtained from the virtual arrays and fed to the entropy coder.
  163082. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  163083. *
  163084. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  163085. */
  163086. METHODDEF(boolean)
  163087. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  163088. {
  163089. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163090. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163091. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163092. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163093. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  163094. JDIMENSION start_col;
  163095. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163096. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  163097. JBLOCKROW buffer_ptr;
  163098. jpeg_component_info *compptr;
  163099. /* Align the virtual buffers for the components used in this scan. */
  163100. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163101. compptr = cinfo->cur_comp_info[ci];
  163102. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163103. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163104. coef->iMCU_row_num * compptr->v_samp_factor,
  163105. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163106. }
  163107. /* Loop to process one whole iMCU row */
  163108. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163109. yoffset++) {
  163110. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163111. MCU_col_num++) {
  163112. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163113. blkn = 0; /* index of current DCT block within MCU */
  163114. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163115. compptr = cinfo->cur_comp_info[ci];
  163116. start_col = MCU_col_num * compptr->MCU_width;
  163117. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163118. : compptr->last_col_width;
  163119. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163120. if (coef->iMCU_row_num < last_iMCU_row ||
  163121. yindex+yoffset < compptr->last_row_height) {
  163122. /* Fill in pointers to real blocks in this row */
  163123. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163124. for (xindex = 0; xindex < blockcnt; xindex++)
  163125. MCU_buffer[blkn++] = buffer_ptr++;
  163126. } else {
  163127. /* At bottom of image, need a whole row of dummy blocks */
  163128. xindex = 0;
  163129. }
  163130. /* Fill in any dummy blocks needed in this row.
  163131. * Dummy blocks are filled in the same way as in jccoefct.c:
  163132. * all zeroes in the AC entries, DC entries equal to previous
  163133. * block's DC value. The init routine has already zeroed the
  163134. * AC entries, so we need only set the DC entries correctly.
  163135. */
  163136. for (; xindex < compptr->MCU_width; xindex++) {
  163137. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  163138. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  163139. blkn++;
  163140. }
  163141. }
  163142. }
  163143. /* Try to write the MCU. */
  163144. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  163145. /* Suspension forced; update state counters and exit */
  163146. coef->MCU_vert_offset = yoffset;
  163147. coef->mcu_ctr = MCU_col_num;
  163148. return FALSE;
  163149. }
  163150. }
  163151. /* Completed an MCU row, but perhaps not an iMCU row */
  163152. coef->mcu_ctr = 0;
  163153. }
  163154. /* Completed the iMCU row, advance counters for next one */
  163155. coef->iMCU_row_num++;
  163156. start_iMCU_row2(cinfo);
  163157. return TRUE;
  163158. }
  163159. /*
  163160. * Initialize coefficient buffer controller.
  163161. *
  163162. * Each passed coefficient array must be the right size for that
  163163. * coefficient: width_in_blocks wide and height_in_blocks high,
  163164. * with unitheight at least v_samp_factor.
  163165. */
  163166. LOCAL(void)
  163167. transencode_coef_controller (j_compress_ptr cinfo,
  163168. jvirt_barray_ptr * coef_arrays)
  163169. {
  163170. my_coef_ptr2 coef;
  163171. JBLOCKROW buffer;
  163172. int i;
  163173. coef = (my_coef_ptr2)
  163174. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163175. SIZEOF(my_coef_controller2));
  163176. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163177. coef->pub.start_pass = start_pass_coef2;
  163178. coef->pub.compress_data = compress_output2;
  163179. /* Save pointer to virtual arrays */
  163180. coef->whole_image = coef_arrays;
  163181. /* Allocate and pre-zero space for dummy DCT blocks. */
  163182. buffer = (JBLOCKROW)
  163183. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163184. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163185. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163186. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163187. coef->dummy_buffer[i] = buffer + i;
  163188. }
  163189. }
  163190. /********* End of inlined file: jctrans.c *********/
  163191. /********* Start of inlined file: jdapistd.c *********/
  163192. #define JPEG_INTERNALS
  163193. /* Forward declarations */
  163194. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  163195. /*
  163196. * Decompression initialization.
  163197. * jpeg_read_header must be completed before calling this.
  163198. *
  163199. * If a multipass operating mode was selected, this will do all but the
  163200. * last pass, and thus may take a great deal of time.
  163201. *
  163202. * Returns FALSE if suspended. The return value need be inspected only if
  163203. * a suspending data source is used.
  163204. */
  163205. GLOBAL(boolean)
  163206. jpeg_start_decompress (j_decompress_ptr cinfo)
  163207. {
  163208. if (cinfo->global_state == DSTATE_READY) {
  163209. /* First call: initialize master control, select active modules */
  163210. jinit_master_decompress(cinfo);
  163211. if (cinfo->buffered_image) {
  163212. /* No more work here; expecting jpeg_start_output next */
  163213. cinfo->global_state = DSTATE_BUFIMAGE;
  163214. return TRUE;
  163215. }
  163216. cinfo->global_state = DSTATE_PRELOAD;
  163217. }
  163218. if (cinfo->global_state == DSTATE_PRELOAD) {
  163219. /* If file has multiple scans, absorb them all into the coef buffer */
  163220. if (cinfo->inputctl->has_multiple_scans) {
  163221. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163222. for (;;) {
  163223. int retcode;
  163224. /* Call progress monitor hook if present */
  163225. if (cinfo->progress != NULL)
  163226. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163227. /* Absorb some more input */
  163228. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163229. if (retcode == JPEG_SUSPENDED)
  163230. return FALSE;
  163231. if (retcode == JPEG_REACHED_EOI)
  163232. break;
  163233. /* Advance progress counter if appropriate */
  163234. if (cinfo->progress != NULL &&
  163235. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  163236. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  163237. /* jdmaster underestimated number of scans; ratchet up one scan */
  163238. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  163239. }
  163240. }
  163241. }
  163242. #else
  163243. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163244. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163245. }
  163246. cinfo->output_scan_number = cinfo->input_scan_number;
  163247. } else if (cinfo->global_state != DSTATE_PRESCAN)
  163248. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163249. /* Perform any dummy output passes, and set up for the final pass */
  163250. return output_pass_setup(cinfo);
  163251. }
  163252. /*
  163253. * Set up for an output pass, and perform any dummy pass(es) needed.
  163254. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  163255. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  163256. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  163257. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  163258. */
  163259. LOCAL(boolean)
  163260. output_pass_setup (j_decompress_ptr cinfo)
  163261. {
  163262. if (cinfo->global_state != DSTATE_PRESCAN) {
  163263. /* First call: do pass setup */
  163264. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163265. cinfo->output_scanline = 0;
  163266. cinfo->global_state = DSTATE_PRESCAN;
  163267. }
  163268. /* Loop over any required dummy passes */
  163269. while (cinfo->master->is_dummy_pass) {
  163270. #ifdef QUANT_2PASS_SUPPORTED
  163271. /* Crank through the dummy pass */
  163272. while (cinfo->output_scanline < cinfo->output_height) {
  163273. JDIMENSION last_scanline;
  163274. /* Call progress monitor hook if present */
  163275. if (cinfo->progress != NULL) {
  163276. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163277. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163278. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163279. }
  163280. /* Process some data */
  163281. last_scanline = cinfo->output_scanline;
  163282. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  163283. &cinfo->output_scanline, (JDIMENSION) 0);
  163284. if (cinfo->output_scanline == last_scanline)
  163285. return FALSE; /* No progress made, must suspend */
  163286. }
  163287. /* Finish up dummy pass, and set up for another one */
  163288. (*cinfo->master->finish_output_pass) (cinfo);
  163289. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163290. cinfo->output_scanline = 0;
  163291. #else
  163292. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163293. #endif /* QUANT_2PASS_SUPPORTED */
  163294. }
  163295. /* Ready for application to drive output pass through
  163296. * jpeg_read_scanlines or jpeg_read_raw_data.
  163297. */
  163298. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  163299. return TRUE;
  163300. }
  163301. /*
  163302. * Read some scanlines of data from the JPEG decompressor.
  163303. *
  163304. * The return value will be the number of lines actually read.
  163305. * This may be less than the number requested in several cases,
  163306. * including bottom of image, data source suspension, and operating
  163307. * modes that emit multiple scanlines at a time.
  163308. *
  163309. * Note: we warn about excess calls to jpeg_read_scanlines() since
  163310. * this likely signals an application programmer error. However,
  163311. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  163312. */
  163313. GLOBAL(JDIMENSION)
  163314. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  163315. JDIMENSION max_lines)
  163316. {
  163317. JDIMENSION row_ctr;
  163318. if (cinfo->global_state != DSTATE_SCANNING)
  163319. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163320. if (cinfo->output_scanline >= cinfo->output_height) {
  163321. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163322. return 0;
  163323. }
  163324. /* Call progress monitor hook if present */
  163325. if (cinfo->progress != NULL) {
  163326. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163327. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163328. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163329. }
  163330. /* Process some data */
  163331. row_ctr = 0;
  163332. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  163333. cinfo->output_scanline += row_ctr;
  163334. return row_ctr;
  163335. }
  163336. /*
  163337. * Alternate entry point to read raw data.
  163338. * Processes exactly one iMCU row per call, unless suspended.
  163339. */
  163340. GLOBAL(JDIMENSION)
  163341. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  163342. JDIMENSION max_lines)
  163343. {
  163344. JDIMENSION lines_per_iMCU_row;
  163345. if (cinfo->global_state != DSTATE_RAW_OK)
  163346. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163347. if (cinfo->output_scanline >= cinfo->output_height) {
  163348. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163349. return 0;
  163350. }
  163351. /* Call progress monitor hook if present */
  163352. if (cinfo->progress != NULL) {
  163353. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163354. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163355. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163356. }
  163357. /* Verify that at least one iMCU row can be returned. */
  163358. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  163359. if (max_lines < lines_per_iMCU_row)
  163360. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  163361. /* Decompress directly into user's buffer. */
  163362. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  163363. return 0; /* suspension forced, can do nothing more */
  163364. /* OK, we processed one iMCU row. */
  163365. cinfo->output_scanline += lines_per_iMCU_row;
  163366. return lines_per_iMCU_row;
  163367. }
  163368. /* Additional entry points for buffered-image mode. */
  163369. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163370. /*
  163371. * Initialize for an output pass in buffered-image mode.
  163372. */
  163373. GLOBAL(boolean)
  163374. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  163375. {
  163376. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  163377. cinfo->global_state != DSTATE_PRESCAN)
  163378. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163379. /* Limit scan number to valid range */
  163380. if (scan_number <= 0)
  163381. scan_number = 1;
  163382. if (cinfo->inputctl->eoi_reached &&
  163383. scan_number > cinfo->input_scan_number)
  163384. scan_number = cinfo->input_scan_number;
  163385. cinfo->output_scan_number = scan_number;
  163386. /* Perform any dummy output passes, and set up for the real pass */
  163387. return output_pass_setup(cinfo);
  163388. }
  163389. /*
  163390. * Finish up after an output pass in buffered-image mode.
  163391. *
  163392. * Returns FALSE if suspended. The return value need be inspected only if
  163393. * a suspending data source is used.
  163394. */
  163395. GLOBAL(boolean)
  163396. jpeg_finish_output (j_decompress_ptr cinfo)
  163397. {
  163398. if ((cinfo->global_state == DSTATE_SCANNING ||
  163399. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  163400. /* Terminate this pass. */
  163401. /* We do not require the whole pass to have been completed. */
  163402. (*cinfo->master->finish_output_pass) (cinfo);
  163403. cinfo->global_state = DSTATE_BUFPOST;
  163404. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  163405. /* BUFPOST = repeat call after a suspension, anything else is error */
  163406. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163407. }
  163408. /* Read markers looking for SOS or EOI */
  163409. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163410. ! cinfo->inputctl->eoi_reached) {
  163411. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163412. return FALSE; /* Suspend, come back later */
  163413. }
  163414. cinfo->global_state = DSTATE_BUFIMAGE;
  163415. return TRUE;
  163416. }
  163417. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163418. /********* End of inlined file: jdapistd.c *********/
  163419. /********* Start of inlined file: jdapimin.c *********/
  163420. #define JPEG_INTERNALS
  163421. /*
  163422. * Initialization of a JPEG decompression object.
  163423. * The error manager must already be set up (in case memory manager fails).
  163424. */
  163425. GLOBAL(void)
  163426. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  163427. {
  163428. int i;
  163429. /* Guard against version mismatches between library and caller. */
  163430. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  163431. if (version != JPEG_LIB_VERSION)
  163432. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  163433. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  163434. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  163435. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  163436. /* For debugging purposes, we zero the whole master structure.
  163437. * But the application has already set the err pointer, and may have set
  163438. * client_data, so we have to save and restore those fields.
  163439. * Note: if application hasn't set client_data, tools like Purify may
  163440. * complain here.
  163441. */
  163442. {
  163443. struct jpeg_error_mgr * err = cinfo->err;
  163444. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  163445. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  163446. cinfo->err = err;
  163447. cinfo->client_data = client_data;
  163448. }
  163449. cinfo->is_decompressor = TRUE;
  163450. /* Initialize a memory manager instance for this object */
  163451. jinit_memory_mgr((j_common_ptr) cinfo);
  163452. /* Zero out pointers to permanent structures. */
  163453. cinfo->progress = NULL;
  163454. cinfo->src = NULL;
  163455. for (i = 0; i < NUM_QUANT_TBLS; i++)
  163456. cinfo->quant_tbl_ptrs[i] = NULL;
  163457. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163458. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  163459. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  163460. }
  163461. /* Initialize marker processor so application can override methods
  163462. * for COM, APPn markers before calling jpeg_read_header.
  163463. */
  163464. cinfo->marker_list = NULL;
  163465. jinit_marker_reader(cinfo);
  163466. /* And initialize the overall input controller. */
  163467. jinit_input_controller(cinfo);
  163468. /* OK, I'm ready */
  163469. cinfo->global_state = DSTATE_START;
  163470. }
  163471. /*
  163472. * Destruction of a JPEG decompression object
  163473. */
  163474. GLOBAL(void)
  163475. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  163476. {
  163477. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  163478. }
  163479. /*
  163480. * Abort processing of a JPEG decompression operation,
  163481. * but don't destroy the object itself.
  163482. */
  163483. GLOBAL(void)
  163484. jpeg_abort_decompress (j_decompress_ptr cinfo)
  163485. {
  163486. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  163487. }
  163488. /*
  163489. * Set default decompression parameters.
  163490. */
  163491. LOCAL(void)
  163492. default_decompress_parms (j_decompress_ptr cinfo)
  163493. {
  163494. /* Guess the input colorspace, and set output colorspace accordingly. */
  163495. /* (Wish JPEG committee had provided a real way to specify this...) */
  163496. /* Note application may override our guesses. */
  163497. switch (cinfo->num_components) {
  163498. case 1:
  163499. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  163500. cinfo->out_color_space = JCS_GRAYSCALE;
  163501. break;
  163502. case 3:
  163503. if (cinfo->saw_JFIF_marker) {
  163504. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  163505. } else if (cinfo->saw_Adobe_marker) {
  163506. switch (cinfo->Adobe_transform) {
  163507. case 0:
  163508. cinfo->jpeg_color_space = JCS_RGB;
  163509. break;
  163510. case 1:
  163511. cinfo->jpeg_color_space = JCS_YCbCr;
  163512. break;
  163513. default:
  163514. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163515. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163516. break;
  163517. }
  163518. } else {
  163519. /* Saw no special markers, try to guess from the component IDs */
  163520. int cid0 = cinfo->comp_info[0].component_id;
  163521. int cid1 = cinfo->comp_info[1].component_id;
  163522. int cid2 = cinfo->comp_info[2].component_id;
  163523. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  163524. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  163525. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  163526. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  163527. else {
  163528. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  163529. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163530. }
  163531. }
  163532. /* Always guess RGB is proper output colorspace. */
  163533. cinfo->out_color_space = JCS_RGB;
  163534. break;
  163535. case 4:
  163536. if (cinfo->saw_Adobe_marker) {
  163537. switch (cinfo->Adobe_transform) {
  163538. case 0:
  163539. cinfo->jpeg_color_space = JCS_CMYK;
  163540. break;
  163541. case 2:
  163542. cinfo->jpeg_color_space = JCS_YCCK;
  163543. break;
  163544. default:
  163545. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163546. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  163547. break;
  163548. }
  163549. } else {
  163550. /* No special markers, assume straight CMYK. */
  163551. cinfo->jpeg_color_space = JCS_CMYK;
  163552. }
  163553. cinfo->out_color_space = JCS_CMYK;
  163554. break;
  163555. default:
  163556. cinfo->jpeg_color_space = JCS_UNKNOWN;
  163557. cinfo->out_color_space = JCS_UNKNOWN;
  163558. break;
  163559. }
  163560. /* Set defaults for other decompression parameters. */
  163561. cinfo->scale_num = 1; /* 1:1 scaling */
  163562. cinfo->scale_denom = 1;
  163563. cinfo->output_gamma = 1.0;
  163564. cinfo->buffered_image = FALSE;
  163565. cinfo->raw_data_out = FALSE;
  163566. cinfo->dct_method = JDCT_DEFAULT;
  163567. cinfo->do_fancy_upsampling = TRUE;
  163568. cinfo->do_block_smoothing = TRUE;
  163569. cinfo->quantize_colors = FALSE;
  163570. /* We set these in case application only sets quantize_colors. */
  163571. cinfo->dither_mode = JDITHER_FS;
  163572. #ifdef QUANT_2PASS_SUPPORTED
  163573. cinfo->two_pass_quantize = TRUE;
  163574. #else
  163575. cinfo->two_pass_quantize = FALSE;
  163576. #endif
  163577. cinfo->desired_number_of_colors = 256;
  163578. cinfo->colormap = NULL;
  163579. /* Initialize for no mode change in buffered-image mode. */
  163580. cinfo->enable_1pass_quant = FALSE;
  163581. cinfo->enable_external_quant = FALSE;
  163582. cinfo->enable_2pass_quant = FALSE;
  163583. }
  163584. /*
  163585. * Decompression startup: read start of JPEG datastream to see what's there.
  163586. * Need only initialize JPEG object and supply a data source before calling.
  163587. *
  163588. * This routine will read as far as the first SOS marker (ie, actual start of
  163589. * compressed data), and will save all tables and parameters in the JPEG
  163590. * object. It will also initialize the decompression parameters to default
  163591. * values, and finally return JPEG_HEADER_OK. On return, the application may
  163592. * adjust the decompression parameters and then call jpeg_start_decompress.
  163593. * (Or, if the application only wanted to determine the image parameters,
  163594. * the data need not be decompressed. In that case, call jpeg_abort or
  163595. * jpeg_destroy to release any temporary space.)
  163596. * If an abbreviated (tables only) datastream is presented, the routine will
  163597. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  163598. * re-use the JPEG object to read the abbreviated image datastream(s).
  163599. * It is unnecessary (but OK) to call jpeg_abort in this case.
  163600. * The JPEG_SUSPENDED return code only occurs if the data source module
  163601. * requests suspension of the decompressor. In this case the application
  163602. * should load more source data and then re-call jpeg_read_header to resume
  163603. * processing.
  163604. * If a non-suspending data source is used and require_image is TRUE, then the
  163605. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  163606. *
  163607. * This routine is now just a front end to jpeg_consume_input, with some
  163608. * extra error checking.
  163609. */
  163610. GLOBAL(int)
  163611. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  163612. {
  163613. int retcode;
  163614. if (cinfo->global_state != DSTATE_START &&
  163615. cinfo->global_state != DSTATE_INHEADER)
  163616. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163617. retcode = jpeg_consume_input(cinfo);
  163618. switch (retcode) {
  163619. case JPEG_REACHED_SOS:
  163620. retcode = JPEG_HEADER_OK;
  163621. break;
  163622. case JPEG_REACHED_EOI:
  163623. if (require_image) /* Complain if application wanted an image */
  163624. ERREXIT(cinfo, JERR_NO_IMAGE);
  163625. /* Reset to start state; it would be safer to require the application to
  163626. * call jpeg_abort, but we can't change it now for compatibility reasons.
  163627. * A side effect is to free any temporary memory (there shouldn't be any).
  163628. */
  163629. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  163630. retcode = JPEG_HEADER_TABLES_ONLY;
  163631. break;
  163632. case JPEG_SUSPENDED:
  163633. /* no work */
  163634. break;
  163635. }
  163636. return retcode;
  163637. }
  163638. /*
  163639. * Consume data in advance of what the decompressor requires.
  163640. * This can be called at any time once the decompressor object has
  163641. * been created and a data source has been set up.
  163642. *
  163643. * This routine is essentially a state machine that handles a couple
  163644. * of critical state-transition actions, namely initial setup and
  163645. * transition from header scanning to ready-for-start_decompress.
  163646. * All the actual input is done via the input controller's consume_input
  163647. * method.
  163648. */
  163649. GLOBAL(int)
  163650. jpeg_consume_input (j_decompress_ptr cinfo)
  163651. {
  163652. int retcode = JPEG_SUSPENDED;
  163653. /* NB: every possible DSTATE value should be listed in this switch */
  163654. switch (cinfo->global_state) {
  163655. case DSTATE_START:
  163656. /* Start-of-datastream actions: reset appropriate modules */
  163657. (*cinfo->inputctl->reset_input_controller) (cinfo);
  163658. /* Initialize application's data source module */
  163659. (*cinfo->src->init_source) (cinfo);
  163660. cinfo->global_state = DSTATE_INHEADER;
  163661. /*FALLTHROUGH*/
  163662. case DSTATE_INHEADER:
  163663. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163664. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  163665. /* Set up default parameters based on header data */
  163666. default_decompress_parms(cinfo);
  163667. /* Set global state: ready for start_decompress */
  163668. cinfo->global_state = DSTATE_READY;
  163669. }
  163670. break;
  163671. case DSTATE_READY:
  163672. /* Can't advance past first SOS until start_decompress is called */
  163673. retcode = JPEG_REACHED_SOS;
  163674. break;
  163675. case DSTATE_PRELOAD:
  163676. case DSTATE_PRESCAN:
  163677. case DSTATE_SCANNING:
  163678. case DSTATE_RAW_OK:
  163679. case DSTATE_BUFIMAGE:
  163680. case DSTATE_BUFPOST:
  163681. case DSTATE_STOPPING:
  163682. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163683. break;
  163684. default:
  163685. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163686. }
  163687. return retcode;
  163688. }
  163689. /*
  163690. * Have we finished reading the input file?
  163691. */
  163692. GLOBAL(boolean)
  163693. jpeg_input_complete (j_decompress_ptr cinfo)
  163694. {
  163695. /* Check for valid jpeg object */
  163696. if (cinfo->global_state < DSTATE_START ||
  163697. cinfo->global_state > DSTATE_STOPPING)
  163698. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163699. return cinfo->inputctl->eoi_reached;
  163700. }
  163701. /*
  163702. * Is there more than one scan?
  163703. */
  163704. GLOBAL(boolean)
  163705. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  163706. {
  163707. /* Only valid after jpeg_read_header completes */
  163708. if (cinfo->global_state < DSTATE_READY ||
  163709. cinfo->global_state > DSTATE_STOPPING)
  163710. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163711. return cinfo->inputctl->has_multiple_scans;
  163712. }
  163713. /*
  163714. * Finish JPEG decompression.
  163715. *
  163716. * This will normally just verify the file trailer and release temp storage.
  163717. *
  163718. * Returns FALSE if suspended. The return value need be inspected only if
  163719. * a suspending data source is used.
  163720. */
  163721. GLOBAL(boolean)
  163722. jpeg_finish_decompress (j_decompress_ptr cinfo)
  163723. {
  163724. if ((cinfo->global_state == DSTATE_SCANNING ||
  163725. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  163726. /* Terminate final pass of non-buffered mode */
  163727. if (cinfo->output_scanline < cinfo->output_height)
  163728. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  163729. (*cinfo->master->finish_output_pass) (cinfo);
  163730. cinfo->global_state = DSTATE_STOPPING;
  163731. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  163732. /* Finishing after a buffered-image operation */
  163733. cinfo->global_state = DSTATE_STOPPING;
  163734. } else if (cinfo->global_state != DSTATE_STOPPING) {
  163735. /* STOPPING = repeat call after a suspension, anything else is error */
  163736. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163737. }
  163738. /* Read until EOI */
  163739. while (! cinfo->inputctl->eoi_reached) {
  163740. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163741. return FALSE; /* Suspend, come back later */
  163742. }
  163743. /* Do final cleanup */
  163744. (*cinfo->src->term_source) (cinfo);
  163745. /* We can use jpeg_abort to release memory and reset global_state */
  163746. jpeg_abort((j_common_ptr) cinfo);
  163747. return TRUE;
  163748. }
  163749. /********* End of inlined file: jdapimin.c *********/
  163750. /********* Start of inlined file: jdatasrc.c *********/
  163751. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  163752. /********* Start of inlined file: jerror.h *********/
  163753. /*
  163754. * To define the enum list of message codes, include this file without
  163755. * defining macro JMESSAGE. To create a message string table, include it
  163756. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  163757. */
  163758. #ifndef JMESSAGE
  163759. #ifndef JERROR_H
  163760. /* First time through, define the enum list */
  163761. #define JMAKE_ENUM_LIST
  163762. #else
  163763. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  163764. #define JMESSAGE(code,string)
  163765. #endif /* JERROR_H */
  163766. #endif /* JMESSAGE */
  163767. #ifdef JMAKE_ENUM_LIST
  163768. typedef enum {
  163769. #define JMESSAGE(code,string) code ,
  163770. #endif /* JMAKE_ENUM_LIST */
  163771. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  163772. /* For maintenance convenience, list is alphabetical by message code name */
  163773. JMESSAGE(JERR_ARITH_NOTIMPL,
  163774. "Sorry, there are legal restrictions on arithmetic coding")
  163775. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  163776. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  163777. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  163778. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  163779. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  163780. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  163781. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  163782. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  163783. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  163784. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  163785. JMESSAGE(JERR_BAD_LIB_VERSION,
  163786. "Wrong JPEG library version: library is %d, caller expects %d")
  163787. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  163788. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  163789. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  163790. JMESSAGE(JERR_BAD_PROGRESSION,
  163791. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  163792. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  163793. "Invalid progressive parameters at scan script entry %d")
  163794. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  163795. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  163796. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  163797. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  163798. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  163799. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  163800. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  163801. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  163802. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  163803. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  163804. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  163805. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  163806. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  163807. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  163808. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  163809. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  163810. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  163811. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  163812. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  163813. JMESSAGE(JERR_FILE_READ, "Input file read error")
  163814. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  163815. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  163816. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  163817. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  163818. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  163819. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  163820. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  163821. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  163822. "Cannot transcode due to multiple use of quantization table %d")
  163823. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  163824. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  163825. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  163826. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  163827. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  163828. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  163829. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  163830. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  163831. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  163832. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  163833. JMESSAGE(JERR_QUANT_COMPONENTS,
  163834. "Cannot quantize more than %d color components")
  163835. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  163836. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  163837. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  163838. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  163839. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  163840. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  163841. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  163842. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  163843. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  163844. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  163845. JMESSAGE(JERR_TFILE_WRITE,
  163846. "Write failed on temporary file --- out of disk space?")
  163847. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  163848. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  163849. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  163850. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  163851. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  163852. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  163853. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  163854. JMESSAGE(JMSG_VERSION, JVERSION)
  163855. JMESSAGE(JTRC_16BIT_TABLES,
  163856. "Caution: quantization tables are too coarse for baseline JPEG")
  163857. JMESSAGE(JTRC_ADOBE,
  163858. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  163859. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  163860. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  163861. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  163862. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  163863. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  163864. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  163865. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  163866. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  163867. JMESSAGE(JTRC_EOI, "End Of Image")
  163868. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  163869. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  163870. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  163871. "Warning: thumbnail image size does not match data length %u")
  163872. JMESSAGE(JTRC_JFIF_EXTENSION,
  163873. "JFIF extension marker: type 0x%02x, length %u")
  163874. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  163875. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  163876. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  163877. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  163878. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  163879. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  163880. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  163881. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  163882. JMESSAGE(JTRC_RST, "RST%d")
  163883. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  163884. "Smoothing not supported with nonstandard sampling ratios")
  163885. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  163886. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  163887. JMESSAGE(JTRC_SOI, "Start of Image")
  163888. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  163889. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  163890. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  163891. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  163892. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  163893. JMESSAGE(JTRC_THUMB_JPEG,
  163894. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  163895. JMESSAGE(JTRC_THUMB_PALETTE,
  163896. "JFIF extension marker: palette thumbnail image, length %u")
  163897. JMESSAGE(JTRC_THUMB_RGB,
  163898. "JFIF extension marker: RGB thumbnail image, length %u")
  163899. JMESSAGE(JTRC_UNKNOWN_IDS,
  163900. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  163901. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  163902. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  163903. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  163904. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  163905. "Inconsistent progression sequence for component %d coefficient %d")
  163906. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  163907. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  163908. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  163909. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  163910. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  163911. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  163912. JMESSAGE(JWRN_MUST_RESYNC,
  163913. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  163914. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  163915. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  163916. #ifdef JMAKE_ENUM_LIST
  163917. JMSG_LASTMSGCODE
  163918. } J_MESSAGE_CODE;
  163919. #undef JMAKE_ENUM_LIST
  163920. #endif /* JMAKE_ENUM_LIST */
  163921. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  163922. #undef JMESSAGE
  163923. #ifndef JERROR_H
  163924. #define JERROR_H
  163925. /* Macros to simplify using the error and trace message stuff */
  163926. /* The first parameter is either type of cinfo pointer */
  163927. /* Fatal errors (print message and exit) */
  163928. #define ERREXIT(cinfo,code) \
  163929. ((cinfo)->err->msg_code = (code), \
  163930. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163931. #define ERREXIT1(cinfo,code,p1) \
  163932. ((cinfo)->err->msg_code = (code), \
  163933. (cinfo)->err->msg_parm.i[0] = (p1), \
  163934. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163935. #define ERREXIT2(cinfo,code,p1,p2) \
  163936. ((cinfo)->err->msg_code = (code), \
  163937. (cinfo)->err->msg_parm.i[0] = (p1), \
  163938. (cinfo)->err->msg_parm.i[1] = (p2), \
  163939. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163940. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  163941. ((cinfo)->err->msg_code = (code), \
  163942. (cinfo)->err->msg_parm.i[0] = (p1), \
  163943. (cinfo)->err->msg_parm.i[1] = (p2), \
  163944. (cinfo)->err->msg_parm.i[2] = (p3), \
  163945. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163946. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  163947. ((cinfo)->err->msg_code = (code), \
  163948. (cinfo)->err->msg_parm.i[0] = (p1), \
  163949. (cinfo)->err->msg_parm.i[1] = (p2), \
  163950. (cinfo)->err->msg_parm.i[2] = (p3), \
  163951. (cinfo)->err->msg_parm.i[3] = (p4), \
  163952. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163953. #define ERREXITS(cinfo,code,str) \
  163954. ((cinfo)->err->msg_code = (code), \
  163955. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163956. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163957. #define MAKESTMT(stuff) do { stuff } while (0)
  163958. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  163959. #define WARNMS(cinfo,code) \
  163960. ((cinfo)->err->msg_code = (code), \
  163961. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163962. #define WARNMS1(cinfo,code,p1) \
  163963. ((cinfo)->err->msg_code = (code), \
  163964. (cinfo)->err->msg_parm.i[0] = (p1), \
  163965. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163966. #define WARNMS2(cinfo,code,p1,p2) \
  163967. ((cinfo)->err->msg_code = (code), \
  163968. (cinfo)->err->msg_parm.i[0] = (p1), \
  163969. (cinfo)->err->msg_parm.i[1] = (p2), \
  163970. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163971. /* Informational/debugging messages */
  163972. #define TRACEMS(cinfo,lvl,code) \
  163973. ((cinfo)->err->msg_code = (code), \
  163974. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163975. #define TRACEMS1(cinfo,lvl,code,p1) \
  163976. ((cinfo)->err->msg_code = (code), \
  163977. (cinfo)->err->msg_parm.i[0] = (p1), \
  163978. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163979. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  163980. ((cinfo)->err->msg_code = (code), \
  163981. (cinfo)->err->msg_parm.i[0] = (p1), \
  163982. (cinfo)->err->msg_parm.i[1] = (p2), \
  163983. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163984. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  163985. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163986. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  163987. (cinfo)->err->msg_code = (code); \
  163988. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163989. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  163990. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163991. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163992. (cinfo)->err->msg_code = (code); \
  163993. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163994. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  163995. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163996. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163997. _mp[4] = (p5); \
  163998. (cinfo)->err->msg_code = (code); \
  163999. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164000. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  164001. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164002. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164003. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  164004. (cinfo)->err->msg_code = (code); \
  164005. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164006. #define TRACEMSS(cinfo,lvl,code,str) \
  164007. ((cinfo)->err->msg_code = (code), \
  164008. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  164009. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164010. #endif /* JERROR_H */
  164011. /********* End of inlined file: jerror.h *********/
  164012. /* Expanded data source object for stdio input */
  164013. typedef struct {
  164014. struct jpeg_source_mgr pub; /* public fields */
  164015. FILE * infile; /* source stream */
  164016. JOCTET * buffer; /* start of buffer */
  164017. boolean start_of_file; /* have we gotten any data yet? */
  164018. } my_source_mgr;
  164019. typedef my_source_mgr * my_src_ptr;
  164020. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  164021. /*
  164022. * Initialize source --- called by jpeg_read_header
  164023. * before any data is actually read.
  164024. */
  164025. METHODDEF(void)
  164026. init_source (j_decompress_ptr cinfo)
  164027. {
  164028. my_src_ptr src = (my_src_ptr) cinfo->src;
  164029. /* We reset the empty-input-file flag for each image,
  164030. * but we don't clear the input buffer.
  164031. * This is correct behavior for reading a series of images from one source.
  164032. */
  164033. src->start_of_file = TRUE;
  164034. }
  164035. /*
  164036. * Fill the input buffer --- called whenever buffer is emptied.
  164037. *
  164038. * In typical applications, this should read fresh data into the buffer
  164039. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  164040. * reset the pointer & count to the start of the buffer, and return TRUE
  164041. * indicating that the buffer has been reloaded. It is not necessary to
  164042. * fill the buffer entirely, only to obtain at least one more byte.
  164043. *
  164044. * There is no such thing as an EOF return. If the end of the file has been
  164045. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  164046. * the buffer. In most cases, generating a warning message and inserting a
  164047. * fake EOI marker is the best course of action --- this will allow the
  164048. * decompressor to output however much of the image is there. However,
  164049. * the resulting error message is misleading if the real problem is an empty
  164050. * input file, so we handle that case specially.
  164051. *
  164052. * In applications that need to be able to suspend compression due to input
  164053. * not being available yet, a FALSE return indicates that no more data can be
  164054. * obtained right now, but more may be forthcoming later. In this situation,
  164055. * the decompressor will return to its caller (with an indication of the
  164056. * number of scanlines it has read, if any). The application should resume
  164057. * decompression after it has loaded more data into the input buffer. Note
  164058. * that there are substantial restrictions on the use of suspension --- see
  164059. * the documentation.
  164060. *
  164061. * When suspending, the decompressor will back up to a convenient restart point
  164062. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  164063. * indicate where the restart point will be if the current call returns FALSE.
  164064. * Data beyond this point must be rescanned after resumption, so move it to
  164065. * the front of the buffer rather than discarding it.
  164066. */
  164067. METHODDEF(boolean)
  164068. fill_input_buffer (j_decompress_ptr cinfo)
  164069. {
  164070. my_src_ptr src = (my_src_ptr) cinfo->src;
  164071. size_t nbytes;
  164072. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  164073. if (nbytes <= 0) {
  164074. if (src->start_of_file) /* Treat empty input file as fatal error */
  164075. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  164076. WARNMS(cinfo, JWRN_JPEG_EOF);
  164077. /* Insert a fake EOI marker */
  164078. src->buffer[0] = (JOCTET) 0xFF;
  164079. src->buffer[1] = (JOCTET) JPEG_EOI;
  164080. nbytes = 2;
  164081. }
  164082. src->pub.next_input_byte = src->buffer;
  164083. src->pub.bytes_in_buffer = nbytes;
  164084. src->start_of_file = FALSE;
  164085. return TRUE;
  164086. }
  164087. /*
  164088. * Skip data --- used to skip over a potentially large amount of
  164089. * uninteresting data (such as an APPn marker).
  164090. *
  164091. * Writers of suspendable-input applications must note that skip_input_data
  164092. * is not granted the right to give a suspension return. If the skip extends
  164093. * beyond the data currently in the buffer, the buffer can be marked empty so
  164094. * that the next read will cause a fill_input_buffer call that can suspend.
  164095. * Arranging for additional bytes to be discarded before reloading the input
  164096. * buffer is the application writer's problem.
  164097. */
  164098. METHODDEF(void)
  164099. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  164100. {
  164101. my_src_ptr src = (my_src_ptr) cinfo->src;
  164102. /* Just a dumb implementation for now. Could use fseek() except
  164103. * it doesn't work on pipes. Not clear that being smart is worth
  164104. * any trouble anyway --- large skips are infrequent.
  164105. */
  164106. if (num_bytes > 0) {
  164107. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  164108. num_bytes -= (long) src->pub.bytes_in_buffer;
  164109. (void) fill_input_buffer(cinfo);
  164110. /* note we assume that fill_input_buffer will never return FALSE,
  164111. * so suspension need not be handled.
  164112. */
  164113. }
  164114. src->pub.next_input_byte += (size_t) num_bytes;
  164115. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  164116. }
  164117. }
  164118. /*
  164119. * An additional method that can be provided by data source modules is the
  164120. * resync_to_restart method for error recovery in the presence of RST markers.
  164121. * For the moment, this source module just uses the default resync method
  164122. * provided by the JPEG library. That method assumes that no backtracking
  164123. * is possible.
  164124. */
  164125. /*
  164126. * Terminate source --- called by jpeg_finish_decompress
  164127. * after all data has been read. Often a no-op.
  164128. *
  164129. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  164130. * application must deal with any cleanup that should happen even
  164131. * for error exit.
  164132. */
  164133. METHODDEF(void)
  164134. term_source (j_decompress_ptr cinfo)
  164135. {
  164136. /* no work necessary here */
  164137. }
  164138. /*
  164139. * Prepare for input from a stdio stream.
  164140. * The caller must have already opened the stream, and is responsible
  164141. * for closing it after finishing decompression.
  164142. */
  164143. GLOBAL(void)
  164144. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  164145. {
  164146. my_src_ptr src;
  164147. /* The source object and input buffer are made permanent so that a series
  164148. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  164149. * only before the first one. (If we discarded the buffer at the end of
  164150. * one image, we'd likely lose the start of the next one.)
  164151. * This makes it unsafe to use this manager and a different source
  164152. * manager serially with the same JPEG object. Caveat programmer.
  164153. */
  164154. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  164155. cinfo->src = (struct jpeg_source_mgr *)
  164156. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164157. SIZEOF(my_source_mgr));
  164158. src = (my_src_ptr) cinfo->src;
  164159. src->buffer = (JOCTET *)
  164160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164161. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  164162. }
  164163. src = (my_src_ptr) cinfo->src;
  164164. src->pub.init_source = init_source;
  164165. src->pub.fill_input_buffer = fill_input_buffer;
  164166. src->pub.skip_input_data = skip_input_data;
  164167. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  164168. src->pub.term_source = term_source;
  164169. src->infile = infile;
  164170. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  164171. src->pub.next_input_byte = NULL; /* until buffer loaded */
  164172. }
  164173. /********* End of inlined file: jdatasrc.c *********/
  164174. /********* Start of inlined file: jdcoefct.c *********/
  164175. #define JPEG_INTERNALS
  164176. /* Block smoothing is only applicable for progressive JPEG, so: */
  164177. #ifndef D_PROGRESSIVE_SUPPORTED
  164178. #undef BLOCK_SMOOTHING_SUPPORTED
  164179. #endif
  164180. /* Private buffer controller object */
  164181. typedef struct {
  164182. struct jpeg_d_coef_controller pub; /* public fields */
  164183. /* These variables keep track of the current location of the input side. */
  164184. /* cinfo->input_iMCU_row is also used for this. */
  164185. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  164186. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164187. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164188. /* The output side's location is represented by cinfo->output_iMCU_row. */
  164189. /* In single-pass modes, it's sufficient to buffer just one MCU.
  164190. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  164191. * and let the entropy decoder write into that workspace each time.
  164192. * (On 80x86, the workspace is FAR even though it's not really very big;
  164193. * this is to keep the module interfaces unchanged when a large coefficient
  164194. * buffer is necessary.)
  164195. * In multi-pass modes, this array points to the current MCU's blocks
  164196. * within the virtual arrays; it is used only by the input side.
  164197. */
  164198. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  164199. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164200. /* In multi-pass modes, we need a virtual block array for each component. */
  164201. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  164202. #endif
  164203. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164204. /* When doing block smoothing, we latch coefficient Al values here */
  164205. int * coef_bits_latch;
  164206. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  164207. #endif
  164208. } my_coef_controller3;
  164209. typedef my_coef_controller3 * my_coef_ptr3;
  164210. /* Forward declarations */
  164211. METHODDEF(int) decompress_onepass
  164212. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164213. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164214. METHODDEF(int) decompress_data
  164215. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164216. #endif
  164217. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164218. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  164219. METHODDEF(int) decompress_smooth_data
  164220. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164221. #endif
  164222. LOCAL(void)
  164223. start_iMCU_row3 (j_decompress_ptr cinfo)
  164224. /* Reset within-iMCU-row counters for a new row (input side) */
  164225. {
  164226. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164227. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164228. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164229. * But at the bottom of the image, process only what's left.
  164230. */
  164231. if (cinfo->comps_in_scan > 1) {
  164232. coef->MCU_rows_per_iMCU_row = 1;
  164233. } else {
  164234. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  164235. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164236. else
  164237. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164238. }
  164239. coef->MCU_ctr = 0;
  164240. coef->MCU_vert_offset = 0;
  164241. }
  164242. /*
  164243. * Initialize for an input processing pass.
  164244. */
  164245. METHODDEF(void)
  164246. start_input_pass (j_decompress_ptr cinfo)
  164247. {
  164248. cinfo->input_iMCU_row = 0;
  164249. start_iMCU_row3(cinfo);
  164250. }
  164251. /*
  164252. * Initialize for an output processing pass.
  164253. */
  164254. METHODDEF(void)
  164255. start_output_pass (j_decompress_ptr cinfo)
  164256. {
  164257. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164258. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164259. /* If multipass, check to see whether to use block smoothing on this pass */
  164260. if (coef->pub.coef_arrays != NULL) {
  164261. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  164262. coef->pub.decompress_data = decompress_smooth_data;
  164263. else
  164264. coef->pub.decompress_data = decompress_data;
  164265. }
  164266. #endif
  164267. cinfo->output_iMCU_row = 0;
  164268. }
  164269. /*
  164270. * Decompress and return some data in the single-pass case.
  164271. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164272. * Input and output must run in lockstep since we have only a one-MCU buffer.
  164273. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164274. *
  164275. * NB: output_buf contains a plane for each component in image,
  164276. * which we index according to the component's SOF position.
  164277. */
  164278. METHODDEF(int)
  164279. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164280. {
  164281. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164282. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164283. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  164284. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164285. int blkn, ci, xindex, yindex, yoffset, useful_width;
  164286. JSAMPARRAY output_ptr;
  164287. JDIMENSION start_col, output_col;
  164288. jpeg_component_info *compptr;
  164289. inverse_DCT_method_ptr inverse_DCT;
  164290. /* Loop to process as much as one whole iMCU row */
  164291. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164292. yoffset++) {
  164293. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  164294. MCU_col_num++) {
  164295. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  164296. jzero_far((void FAR *) coef->MCU_buffer[0],
  164297. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  164298. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164299. /* Suspension forced; update state counters and exit */
  164300. coef->MCU_vert_offset = yoffset;
  164301. coef->MCU_ctr = MCU_col_num;
  164302. return JPEG_SUSPENDED;
  164303. }
  164304. /* Determine where data should go in output_buf and do the IDCT thing.
  164305. * We skip dummy blocks at the right and bottom edges (but blkn gets
  164306. * incremented past them!). Note the inner loop relies on having
  164307. * allocated the MCU_buffer[] blocks sequentially.
  164308. */
  164309. blkn = 0; /* index of current DCT block within MCU */
  164310. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164311. compptr = cinfo->cur_comp_info[ci];
  164312. /* Don't bother to IDCT an uninteresting component. */
  164313. if (! compptr->component_needed) {
  164314. blkn += compptr->MCU_blocks;
  164315. continue;
  164316. }
  164317. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  164318. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  164319. : compptr->last_col_width;
  164320. output_ptr = output_buf[compptr->component_index] +
  164321. yoffset * compptr->DCT_scaled_size;
  164322. start_col = MCU_col_num * compptr->MCU_sample_width;
  164323. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164324. if (cinfo->input_iMCU_row < last_iMCU_row ||
  164325. yoffset+yindex < compptr->last_row_height) {
  164326. output_col = start_col;
  164327. for (xindex = 0; xindex < useful_width; xindex++) {
  164328. (*inverse_DCT) (cinfo, compptr,
  164329. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  164330. output_ptr, output_col);
  164331. output_col += compptr->DCT_scaled_size;
  164332. }
  164333. }
  164334. blkn += compptr->MCU_width;
  164335. output_ptr += compptr->DCT_scaled_size;
  164336. }
  164337. }
  164338. }
  164339. /* Completed an MCU row, but perhaps not an iMCU row */
  164340. coef->MCU_ctr = 0;
  164341. }
  164342. /* Completed the iMCU row, advance counters for next one */
  164343. cinfo->output_iMCU_row++;
  164344. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164345. start_iMCU_row3(cinfo);
  164346. return JPEG_ROW_COMPLETED;
  164347. }
  164348. /* Completed the scan */
  164349. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164350. return JPEG_SCAN_COMPLETED;
  164351. }
  164352. /*
  164353. * Dummy consume-input routine for single-pass operation.
  164354. */
  164355. METHODDEF(int)
  164356. dummy_consume_data (j_decompress_ptr cinfo)
  164357. {
  164358. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  164359. }
  164360. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164361. /*
  164362. * Consume input data and store it in the full-image coefficient buffer.
  164363. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  164364. * ie, v_samp_factor block rows for each component in the scan.
  164365. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164366. */
  164367. METHODDEF(int)
  164368. consume_data (j_decompress_ptr cinfo)
  164369. {
  164370. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164371. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164372. int blkn, ci, xindex, yindex, yoffset;
  164373. JDIMENSION start_col;
  164374. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  164375. JBLOCKROW buffer_ptr;
  164376. jpeg_component_info *compptr;
  164377. /* Align the virtual buffers for the components used in this scan. */
  164378. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164379. compptr = cinfo->cur_comp_info[ci];
  164380. buffer[ci] = (*cinfo->mem->access_virt_barray)
  164381. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  164382. cinfo->input_iMCU_row * compptr->v_samp_factor,
  164383. (JDIMENSION) compptr->v_samp_factor, TRUE);
  164384. /* Note: entropy decoder expects buffer to be zeroed,
  164385. * but this is handled automatically by the memory manager
  164386. * because we requested a pre-zeroed array.
  164387. */
  164388. }
  164389. /* Loop to process one whole iMCU row */
  164390. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164391. yoffset++) {
  164392. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  164393. MCU_col_num++) {
  164394. /* Construct list of pointers to DCT blocks belonging to this MCU */
  164395. blkn = 0; /* index of current DCT block within MCU */
  164396. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164397. compptr = cinfo->cur_comp_info[ci];
  164398. start_col = MCU_col_num * compptr->MCU_width;
  164399. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164400. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  164401. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  164402. coef->MCU_buffer[blkn++] = buffer_ptr++;
  164403. }
  164404. }
  164405. }
  164406. /* Try to fetch the MCU. */
  164407. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164408. /* Suspension forced; update state counters and exit */
  164409. coef->MCU_vert_offset = yoffset;
  164410. coef->MCU_ctr = MCU_col_num;
  164411. return JPEG_SUSPENDED;
  164412. }
  164413. }
  164414. /* Completed an MCU row, but perhaps not an iMCU row */
  164415. coef->MCU_ctr = 0;
  164416. }
  164417. /* Completed the iMCU row, advance counters for next one */
  164418. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164419. start_iMCU_row3(cinfo);
  164420. return JPEG_ROW_COMPLETED;
  164421. }
  164422. /* Completed the scan */
  164423. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164424. return JPEG_SCAN_COMPLETED;
  164425. }
  164426. /*
  164427. * Decompress and return some data in the multi-pass case.
  164428. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164429. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164430. *
  164431. * NB: output_buf contains a plane for each component in image.
  164432. */
  164433. METHODDEF(int)
  164434. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164435. {
  164436. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164437. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164438. JDIMENSION block_num;
  164439. int ci, block_row, block_rows;
  164440. JBLOCKARRAY buffer;
  164441. JBLOCKROW buffer_ptr;
  164442. JSAMPARRAY output_ptr;
  164443. JDIMENSION output_col;
  164444. jpeg_component_info *compptr;
  164445. inverse_DCT_method_ptr inverse_DCT;
  164446. /* Force some input to be done if we are getting ahead of the input. */
  164447. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  164448. (cinfo->input_scan_number == cinfo->output_scan_number &&
  164449. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  164450. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164451. return JPEG_SUSPENDED;
  164452. }
  164453. /* OK, output from the virtual arrays. */
  164454. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164455. ci++, compptr++) {
  164456. /* Don't bother to IDCT an uninteresting component. */
  164457. if (! compptr->component_needed)
  164458. continue;
  164459. /* Align the virtual buffer for this component. */
  164460. buffer = (*cinfo->mem->access_virt_barray)
  164461. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164462. cinfo->output_iMCU_row * compptr->v_samp_factor,
  164463. (JDIMENSION) compptr->v_samp_factor, FALSE);
  164464. /* Count non-dummy DCT block rows in this iMCU row. */
  164465. if (cinfo->output_iMCU_row < last_iMCU_row)
  164466. block_rows = compptr->v_samp_factor;
  164467. else {
  164468. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164469. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164470. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164471. }
  164472. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164473. output_ptr = output_buf[ci];
  164474. /* Loop over all DCT blocks to be processed. */
  164475. for (block_row = 0; block_row < block_rows; block_row++) {
  164476. buffer_ptr = buffer[block_row];
  164477. output_col = 0;
  164478. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  164479. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  164480. output_ptr, output_col);
  164481. buffer_ptr++;
  164482. output_col += compptr->DCT_scaled_size;
  164483. }
  164484. output_ptr += compptr->DCT_scaled_size;
  164485. }
  164486. }
  164487. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164488. return JPEG_ROW_COMPLETED;
  164489. return JPEG_SCAN_COMPLETED;
  164490. }
  164491. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164492. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164493. /*
  164494. * This code applies interblock smoothing as described by section K.8
  164495. * of the JPEG standard: the first 5 AC coefficients are estimated from
  164496. * the DC values of a DCT block and its 8 neighboring blocks.
  164497. * We apply smoothing only for progressive JPEG decoding, and only if
  164498. * the coefficients it can estimate are not yet known to full precision.
  164499. */
  164500. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  164501. #define Q01_POS 1
  164502. #define Q10_POS 8
  164503. #define Q20_POS 16
  164504. #define Q11_POS 9
  164505. #define Q02_POS 2
  164506. /*
  164507. * Determine whether block smoothing is applicable and safe.
  164508. * We also latch the current states of the coef_bits[] entries for the
  164509. * AC coefficients; otherwise, if the input side of the decompressor
  164510. * advances into a new scan, we might think the coefficients are known
  164511. * more accurately than they really are.
  164512. */
  164513. LOCAL(boolean)
  164514. smoothing_ok (j_decompress_ptr cinfo)
  164515. {
  164516. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164517. boolean smoothing_useful = FALSE;
  164518. int ci, coefi;
  164519. jpeg_component_info *compptr;
  164520. JQUANT_TBL * qtable;
  164521. int * coef_bits;
  164522. int * coef_bits_latch;
  164523. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  164524. return FALSE;
  164525. /* Allocate latch area if not already done */
  164526. if (coef->coef_bits_latch == NULL)
  164527. coef->coef_bits_latch = (int *)
  164528. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164529. cinfo->num_components *
  164530. (SAVED_COEFS * SIZEOF(int)));
  164531. coef_bits_latch = coef->coef_bits_latch;
  164532. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164533. ci++, compptr++) {
  164534. /* All components' quantization values must already be latched. */
  164535. if ((qtable = compptr->quant_table) == NULL)
  164536. return FALSE;
  164537. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  164538. if (qtable->quantval[0] == 0 ||
  164539. qtable->quantval[Q01_POS] == 0 ||
  164540. qtable->quantval[Q10_POS] == 0 ||
  164541. qtable->quantval[Q20_POS] == 0 ||
  164542. qtable->quantval[Q11_POS] == 0 ||
  164543. qtable->quantval[Q02_POS] == 0)
  164544. return FALSE;
  164545. /* DC values must be at least partly known for all components. */
  164546. coef_bits = cinfo->coef_bits[ci];
  164547. if (coef_bits[0] < 0)
  164548. return FALSE;
  164549. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  164550. for (coefi = 1; coefi <= 5; coefi++) {
  164551. coef_bits_latch[coefi] = coef_bits[coefi];
  164552. if (coef_bits[coefi] != 0)
  164553. smoothing_useful = TRUE;
  164554. }
  164555. coef_bits_latch += SAVED_COEFS;
  164556. }
  164557. return smoothing_useful;
  164558. }
  164559. /*
  164560. * Variant of decompress_data for use when doing block smoothing.
  164561. */
  164562. METHODDEF(int)
  164563. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164564. {
  164565. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164566. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164567. JDIMENSION block_num, last_block_column;
  164568. int ci, block_row, block_rows, access_rows;
  164569. JBLOCKARRAY buffer;
  164570. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  164571. JSAMPARRAY output_ptr;
  164572. JDIMENSION output_col;
  164573. jpeg_component_info *compptr;
  164574. inverse_DCT_method_ptr inverse_DCT;
  164575. boolean first_row, last_row;
  164576. JBLOCK workspace;
  164577. int *coef_bits;
  164578. JQUANT_TBL *quanttbl;
  164579. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  164580. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  164581. int Al, pred;
  164582. /* Force some input to be done if we are getting ahead of the input. */
  164583. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164584. ! cinfo->inputctl->eoi_reached) {
  164585. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  164586. /* If input is working on current scan, we ordinarily want it to
  164587. * have completed the current row. But if input scan is DC,
  164588. * we want it to keep one row ahead so that next block row's DC
  164589. * values are up to date.
  164590. */
  164591. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  164592. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  164593. break;
  164594. }
  164595. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164596. return JPEG_SUSPENDED;
  164597. }
  164598. /* OK, output from the virtual arrays. */
  164599. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164600. ci++, compptr++) {
  164601. /* Don't bother to IDCT an uninteresting component. */
  164602. if (! compptr->component_needed)
  164603. continue;
  164604. /* Count non-dummy DCT block rows in this iMCU row. */
  164605. if (cinfo->output_iMCU_row < last_iMCU_row) {
  164606. block_rows = compptr->v_samp_factor;
  164607. access_rows = block_rows * 2; /* this and next iMCU row */
  164608. last_row = FALSE;
  164609. } else {
  164610. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164611. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164612. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164613. access_rows = block_rows; /* this iMCU row only */
  164614. last_row = TRUE;
  164615. }
  164616. /* Align the virtual buffer for this component. */
  164617. if (cinfo->output_iMCU_row > 0) {
  164618. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  164619. buffer = (*cinfo->mem->access_virt_barray)
  164620. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164621. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  164622. (JDIMENSION) access_rows, FALSE);
  164623. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  164624. first_row = FALSE;
  164625. } else {
  164626. buffer = (*cinfo->mem->access_virt_barray)
  164627. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164628. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  164629. first_row = TRUE;
  164630. }
  164631. /* Fetch component-dependent info */
  164632. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  164633. quanttbl = compptr->quant_table;
  164634. Q00 = quanttbl->quantval[0];
  164635. Q01 = quanttbl->quantval[Q01_POS];
  164636. Q10 = quanttbl->quantval[Q10_POS];
  164637. Q20 = quanttbl->quantval[Q20_POS];
  164638. Q11 = quanttbl->quantval[Q11_POS];
  164639. Q02 = quanttbl->quantval[Q02_POS];
  164640. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164641. output_ptr = output_buf[ci];
  164642. /* Loop over all DCT blocks to be processed. */
  164643. for (block_row = 0; block_row < block_rows; block_row++) {
  164644. buffer_ptr = buffer[block_row];
  164645. if (first_row && block_row == 0)
  164646. prev_block_row = buffer_ptr;
  164647. else
  164648. prev_block_row = buffer[block_row-1];
  164649. if (last_row && block_row == block_rows-1)
  164650. next_block_row = buffer_ptr;
  164651. else
  164652. next_block_row = buffer[block_row+1];
  164653. /* We fetch the surrounding DC values using a sliding-register approach.
  164654. * Initialize all nine here so as to do the right thing on narrow pics.
  164655. */
  164656. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  164657. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  164658. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  164659. output_col = 0;
  164660. last_block_column = compptr->width_in_blocks - 1;
  164661. for (block_num = 0; block_num <= last_block_column; block_num++) {
  164662. /* Fetch current DCT block into workspace so we can modify it. */
  164663. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  164664. /* Update DC values */
  164665. if (block_num < last_block_column) {
  164666. DC3 = (int) prev_block_row[1][0];
  164667. DC6 = (int) buffer_ptr[1][0];
  164668. DC9 = (int) next_block_row[1][0];
  164669. }
  164670. /* Compute coefficient estimates per K.8.
  164671. * An estimate is applied only if coefficient is still zero,
  164672. * and is not known to be fully accurate.
  164673. */
  164674. /* AC01 */
  164675. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  164676. num = 36 * Q00 * (DC4 - DC6);
  164677. if (num >= 0) {
  164678. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  164679. if (Al > 0 && pred >= (1<<Al))
  164680. pred = (1<<Al)-1;
  164681. } else {
  164682. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  164683. if (Al > 0 && pred >= (1<<Al))
  164684. pred = (1<<Al)-1;
  164685. pred = -pred;
  164686. }
  164687. workspace[1] = (JCOEF) pred;
  164688. }
  164689. /* AC10 */
  164690. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  164691. num = 36 * Q00 * (DC2 - DC8);
  164692. if (num >= 0) {
  164693. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  164694. if (Al > 0 && pred >= (1<<Al))
  164695. pred = (1<<Al)-1;
  164696. } else {
  164697. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  164698. if (Al > 0 && pred >= (1<<Al))
  164699. pred = (1<<Al)-1;
  164700. pred = -pred;
  164701. }
  164702. workspace[8] = (JCOEF) pred;
  164703. }
  164704. /* AC20 */
  164705. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  164706. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  164707. if (num >= 0) {
  164708. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  164709. if (Al > 0 && pred >= (1<<Al))
  164710. pred = (1<<Al)-1;
  164711. } else {
  164712. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  164713. if (Al > 0 && pred >= (1<<Al))
  164714. pred = (1<<Al)-1;
  164715. pred = -pred;
  164716. }
  164717. workspace[16] = (JCOEF) pred;
  164718. }
  164719. /* AC11 */
  164720. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  164721. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  164722. if (num >= 0) {
  164723. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  164724. if (Al > 0 && pred >= (1<<Al))
  164725. pred = (1<<Al)-1;
  164726. } else {
  164727. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  164728. if (Al > 0 && pred >= (1<<Al))
  164729. pred = (1<<Al)-1;
  164730. pred = -pred;
  164731. }
  164732. workspace[9] = (JCOEF) pred;
  164733. }
  164734. /* AC02 */
  164735. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  164736. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  164737. if (num >= 0) {
  164738. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  164739. if (Al > 0 && pred >= (1<<Al))
  164740. pred = (1<<Al)-1;
  164741. } else {
  164742. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  164743. if (Al > 0 && pred >= (1<<Al))
  164744. pred = (1<<Al)-1;
  164745. pred = -pred;
  164746. }
  164747. workspace[2] = (JCOEF) pred;
  164748. }
  164749. /* OK, do the IDCT */
  164750. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  164751. output_ptr, output_col);
  164752. /* Advance for next column */
  164753. DC1 = DC2; DC2 = DC3;
  164754. DC4 = DC5; DC5 = DC6;
  164755. DC7 = DC8; DC8 = DC9;
  164756. buffer_ptr++, prev_block_row++, next_block_row++;
  164757. output_col += compptr->DCT_scaled_size;
  164758. }
  164759. output_ptr += compptr->DCT_scaled_size;
  164760. }
  164761. }
  164762. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164763. return JPEG_ROW_COMPLETED;
  164764. return JPEG_SCAN_COMPLETED;
  164765. }
  164766. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  164767. /*
  164768. * Initialize coefficient buffer controller.
  164769. */
  164770. GLOBAL(void)
  164771. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164772. {
  164773. my_coef_ptr3 coef;
  164774. coef = (my_coef_ptr3)
  164775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164776. SIZEOF(my_coef_controller3));
  164777. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  164778. coef->pub.start_input_pass = start_input_pass;
  164779. coef->pub.start_output_pass = start_output_pass;
  164780. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164781. coef->coef_bits_latch = NULL;
  164782. #endif
  164783. /* Create the coefficient buffer. */
  164784. if (need_full_buffer) {
  164785. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164786. /* Allocate a full-image virtual array for each component, */
  164787. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  164788. /* Note we ask for a pre-zeroed array. */
  164789. int ci, access_rows;
  164790. jpeg_component_info *compptr;
  164791. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164792. ci++, compptr++) {
  164793. access_rows = compptr->v_samp_factor;
  164794. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164795. /* If block smoothing could be used, need a bigger window */
  164796. if (cinfo->progressive_mode)
  164797. access_rows *= 3;
  164798. #endif
  164799. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  164800. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  164801. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  164802. (long) compptr->h_samp_factor),
  164803. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164804. (long) compptr->v_samp_factor),
  164805. (JDIMENSION) access_rows);
  164806. }
  164807. coef->pub.consume_data = consume_data;
  164808. coef->pub.decompress_data = decompress_data;
  164809. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  164810. #else
  164811. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164812. #endif
  164813. } else {
  164814. /* We only need a single-MCU buffer. */
  164815. JBLOCKROW buffer;
  164816. int i;
  164817. buffer = (JBLOCKROW)
  164818. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164819. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164820. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  164821. coef->MCU_buffer[i] = buffer + i;
  164822. }
  164823. coef->pub.consume_data = dummy_consume_data;
  164824. coef->pub.decompress_data = decompress_onepass;
  164825. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  164826. }
  164827. }
  164828. /********* End of inlined file: jdcoefct.c *********/
  164829. #undef FIX
  164830. /********* Start of inlined file: jdcolor.c *********/
  164831. #define JPEG_INTERNALS
  164832. /* Private subobject */
  164833. typedef struct {
  164834. struct jpeg_color_deconverter pub; /* public fields */
  164835. /* Private state for YCC->RGB conversion */
  164836. int * Cr_r_tab; /* => table for Cr to R conversion */
  164837. int * Cb_b_tab; /* => table for Cb to B conversion */
  164838. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  164839. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  164840. } my_color_deconverter2;
  164841. typedef my_color_deconverter2 * my_cconvert_ptr2;
  164842. /**************** YCbCr -> RGB conversion: most common case **************/
  164843. /*
  164844. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  164845. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  164846. * The conversion equations to be implemented are therefore
  164847. * R = Y + 1.40200 * Cr
  164848. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  164849. * B = Y + 1.77200 * Cb
  164850. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  164851. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  164852. *
  164853. * To avoid floating-point arithmetic, we represent the fractional constants
  164854. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  164855. * the products by 2^16, with appropriate rounding, to get the correct answer.
  164856. * Notice that Y, being an integral input, does not contribute any fraction
  164857. * so it need not participate in the rounding.
  164858. *
  164859. * For even more speed, we avoid doing any multiplications in the inner loop
  164860. * by precalculating the constants times Cb and Cr for all possible values.
  164861. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  164862. * for 12-bit samples it is still acceptable. It's not very reasonable for
  164863. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  164864. * colorspace anyway.
  164865. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  164866. * values for the G calculation are left scaled up, since we must add them
  164867. * together before rounding.
  164868. */
  164869. #define SCALEBITS 16 /* speediest right-shift on some machines */
  164870. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  164871. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  164872. /*
  164873. * Initialize tables for YCC->RGB colorspace conversion.
  164874. */
  164875. LOCAL(void)
  164876. build_ycc_rgb_table (j_decompress_ptr cinfo)
  164877. {
  164878. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164879. int i;
  164880. INT32 x;
  164881. SHIFT_TEMPS
  164882. cconvert->Cr_r_tab = (int *)
  164883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164884. (MAXJSAMPLE+1) * SIZEOF(int));
  164885. cconvert->Cb_b_tab = (int *)
  164886. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164887. (MAXJSAMPLE+1) * SIZEOF(int));
  164888. cconvert->Cr_g_tab = (INT32 *)
  164889. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164890. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164891. cconvert->Cb_g_tab = (INT32 *)
  164892. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164893. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164894. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  164895. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  164896. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  164897. /* Cr=>R value is nearest int to 1.40200 * x */
  164898. cconvert->Cr_r_tab[i] = (int)
  164899. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  164900. /* Cb=>B value is nearest int to 1.77200 * x */
  164901. cconvert->Cb_b_tab[i] = (int)
  164902. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  164903. /* Cr=>G value is scaled-up -0.71414 * x */
  164904. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  164905. /* Cb=>G value is scaled-up -0.34414 * x */
  164906. /* We also add in ONE_HALF so that need not do it in inner loop */
  164907. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  164908. }
  164909. }
  164910. /*
  164911. * Convert some rows of samples to the output colorspace.
  164912. *
  164913. * Note that we change from noninterleaved, one-plane-per-component format
  164914. * to interleaved-pixel format. The output buffer is therefore three times
  164915. * as wide as the input buffer.
  164916. * A starting row offset is provided only for the input buffer. The caller
  164917. * can easily adjust the passed output_buf value to accommodate any row
  164918. * offset required on that side.
  164919. */
  164920. METHODDEF(void)
  164921. ycc_rgb_convert (j_decompress_ptr cinfo,
  164922. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164923. JSAMPARRAY output_buf, int num_rows)
  164924. {
  164925. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164926. register int y, cb, cr;
  164927. register JSAMPROW outptr;
  164928. register JSAMPROW inptr0, inptr1, inptr2;
  164929. register JDIMENSION col;
  164930. JDIMENSION num_cols = cinfo->output_width;
  164931. /* copy these pointers into registers if possible */
  164932. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164933. register int * Crrtab = cconvert->Cr_r_tab;
  164934. register int * Cbbtab = cconvert->Cb_b_tab;
  164935. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164936. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164937. SHIFT_TEMPS
  164938. while (--num_rows >= 0) {
  164939. inptr0 = input_buf[0][input_row];
  164940. inptr1 = input_buf[1][input_row];
  164941. inptr2 = input_buf[2][input_row];
  164942. input_row++;
  164943. outptr = *output_buf++;
  164944. for (col = 0; col < num_cols; col++) {
  164945. y = GETJSAMPLE(inptr0[col]);
  164946. cb = GETJSAMPLE(inptr1[col]);
  164947. cr = GETJSAMPLE(inptr2[col]);
  164948. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164949. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  164950. outptr[RGB_GREEN] = range_limit[y +
  164951. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164952. SCALEBITS))];
  164953. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  164954. outptr += RGB_PIXELSIZE;
  164955. }
  164956. }
  164957. }
  164958. /**************** Cases other than YCbCr -> RGB **************/
  164959. /*
  164960. * Color conversion for no colorspace change: just copy the data,
  164961. * converting from separate-planes to interleaved representation.
  164962. */
  164963. METHODDEF(void)
  164964. null_convert2 (j_decompress_ptr cinfo,
  164965. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164966. JSAMPARRAY output_buf, int num_rows)
  164967. {
  164968. register JSAMPROW inptr, outptr;
  164969. register JDIMENSION count;
  164970. register int num_components = cinfo->num_components;
  164971. JDIMENSION num_cols = cinfo->output_width;
  164972. int ci;
  164973. while (--num_rows >= 0) {
  164974. for (ci = 0; ci < num_components; ci++) {
  164975. inptr = input_buf[ci][input_row];
  164976. outptr = output_buf[0] + ci;
  164977. for (count = num_cols; count > 0; count--) {
  164978. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  164979. outptr += num_components;
  164980. }
  164981. }
  164982. input_row++;
  164983. output_buf++;
  164984. }
  164985. }
  164986. /*
  164987. * Color conversion for grayscale: just copy the data.
  164988. * This also works for YCbCr -> grayscale conversion, in which
  164989. * we just copy the Y (luminance) component and ignore chrominance.
  164990. */
  164991. METHODDEF(void)
  164992. grayscale_convert2 (j_decompress_ptr cinfo,
  164993. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164994. JSAMPARRAY output_buf, int num_rows)
  164995. {
  164996. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  164997. num_rows, cinfo->output_width);
  164998. }
  164999. /*
  165000. * Convert grayscale to RGB: just duplicate the graylevel three times.
  165001. * This is provided to support applications that don't want to cope
  165002. * with grayscale as a separate case.
  165003. */
  165004. METHODDEF(void)
  165005. gray_rgb_convert (j_decompress_ptr cinfo,
  165006. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165007. JSAMPARRAY output_buf, int num_rows)
  165008. {
  165009. register JSAMPROW inptr, outptr;
  165010. register JDIMENSION col;
  165011. JDIMENSION num_cols = cinfo->output_width;
  165012. while (--num_rows >= 0) {
  165013. inptr = input_buf[0][input_row++];
  165014. outptr = *output_buf++;
  165015. for (col = 0; col < num_cols; col++) {
  165016. /* We can dispense with GETJSAMPLE() here */
  165017. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  165018. outptr += RGB_PIXELSIZE;
  165019. }
  165020. }
  165021. }
  165022. /*
  165023. * Adobe-style YCCK->CMYK conversion.
  165024. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  165025. * conversion as above, while passing K (black) unchanged.
  165026. * We assume build_ycc_rgb_table has been called.
  165027. */
  165028. METHODDEF(void)
  165029. ycck_cmyk_convert (j_decompress_ptr cinfo,
  165030. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165031. JSAMPARRAY output_buf, int num_rows)
  165032. {
  165033. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165034. register int y, cb, cr;
  165035. register JSAMPROW outptr;
  165036. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  165037. register JDIMENSION col;
  165038. JDIMENSION num_cols = cinfo->output_width;
  165039. /* copy these pointers into registers if possible */
  165040. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  165041. register int * Crrtab = cconvert->Cr_r_tab;
  165042. register int * Cbbtab = cconvert->Cb_b_tab;
  165043. register INT32 * Crgtab = cconvert->Cr_g_tab;
  165044. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  165045. SHIFT_TEMPS
  165046. while (--num_rows >= 0) {
  165047. inptr0 = input_buf[0][input_row];
  165048. inptr1 = input_buf[1][input_row];
  165049. inptr2 = input_buf[2][input_row];
  165050. inptr3 = input_buf[3][input_row];
  165051. input_row++;
  165052. outptr = *output_buf++;
  165053. for (col = 0; col < num_cols; col++) {
  165054. y = GETJSAMPLE(inptr0[col]);
  165055. cb = GETJSAMPLE(inptr1[col]);
  165056. cr = GETJSAMPLE(inptr2[col]);
  165057. /* Range-limiting is essential due to noise introduced by DCT losses. */
  165058. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  165059. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  165060. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  165061. SCALEBITS)))];
  165062. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  165063. /* K passes through unchanged */
  165064. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  165065. outptr += 4;
  165066. }
  165067. }
  165068. }
  165069. /*
  165070. * Empty method for start_pass.
  165071. */
  165072. METHODDEF(void)
  165073. start_pass_dcolor (j_decompress_ptr cinfo)
  165074. {
  165075. /* no work needed */
  165076. }
  165077. /*
  165078. * Module initialization routine for output colorspace conversion.
  165079. */
  165080. GLOBAL(void)
  165081. jinit_color_deconverter (j_decompress_ptr cinfo)
  165082. {
  165083. my_cconvert_ptr2 cconvert;
  165084. int ci;
  165085. cconvert = (my_cconvert_ptr2)
  165086. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165087. SIZEOF(my_color_deconverter2));
  165088. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  165089. cconvert->pub.start_pass = start_pass_dcolor;
  165090. /* Make sure num_components agrees with jpeg_color_space */
  165091. switch (cinfo->jpeg_color_space) {
  165092. case JCS_GRAYSCALE:
  165093. if (cinfo->num_components != 1)
  165094. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165095. break;
  165096. case JCS_RGB:
  165097. case JCS_YCbCr:
  165098. if (cinfo->num_components != 3)
  165099. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165100. break;
  165101. case JCS_CMYK:
  165102. case JCS_YCCK:
  165103. if (cinfo->num_components != 4)
  165104. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165105. break;
  165106. default: /* JCS_UNKNOWN can be anything */
  165107. if (cinfo->num_components < 1)
  165108. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165109. break;
  165110. }
  165111. /* Set out_color_components and conversion method based on requested space.
  165112. * Also clear the component_needed flags for any unused components,
  165113. * so that earlier pipeline stages can avoid useless computation.
  165114. */
  165115. switch (cinfo->out_color_space) {
  165116. case JCS_GRAYSCALE:
  165117. cinfo->out_color_components = 1;
  165118. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  165119. cinfo->jpeg_color_space == JCS_YCbCr) {
  165120. cconvert->pub.color_convert = grayscale_convert2;
  165121. /* For color->grayscale conversion, only the Y (0) component is needed */
  165122. for (ci = 1; ci < cinfo->num_components; ci++)
  165123. cinfo->comp_info[ci].component_needed = FALSE;
  165124. } else
  165125. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165126. break;
  165127. case JCS_RGB:
  165128. cinfo->out_color_components = RGB_PIXELSIZE;
  165129. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  165130. cconvert->pub.color_convert = ycc_rgb_convert;
  165131. build_ycc_rgb_table(cinfo);
  165132. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  165133. cconvert->pub.color_convert = gray_rgb_convert;
  165134. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  165135. cconvert->pub.color_convert = null_convert2;
  165136. } else
  165137. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165138. break;
  165139. case JCS_CMYK:
  165140. cinfo->out_color_components = 4;
  165141. if (cinfo->jpeg_color_space == JCS_YCCK) {
  165142. cconvert->pub.color_convert = ycck_cmyk_convert;
  165143. build_ycc_rgb_table(cinfo);
  165144. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  165145. cconvert->pub.color_convert = null_convert2;
  165146. } else
  165147. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165148. break;
  165149. default:
  165150. /* Permit null conversion to same output space */
  165151. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  165152. cinfo->out_color_components = cinfo->num_components;
  165153. cconvert->pub.color_convert = null_convert2;
  165154. } else /* unsupported non-null conversion */
  165155. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165156. break;
  165157. }
  165158. if (cinfo->quantize_colors)
  165159. cinfo->output_components = 1; /* single colormapped output component */
  165160. else
  165161. cinfo->output_components = cinfo->out_color_components;
  165162. }
  165163. /********* End of inlined file: jdcolor.c *********/
  165164. #undef FIX
  165165. /********* Start of inlined file: jddctmgr.c *********/
  165166. #define JPEG_INTERNALS
  165167. /*
  165168. * The decompressor input side (jdinput.c) saves away the appropriate
  165169. * quantization table for each component at the start of the first scan
  165170. * involving that component. (This is necessary in order to correctly
  165171. * decode files that reuse Q-table slots.)
  165172. * When we are ready to make an output pass, the saved Q-table is converted
  165173. * to a multiplier table that will actually be used by the IDCT routine.
  165174. * The multiplier table contents are IDCT-method-dependent. To support
  165175. * application changes in IDCT method between scans, we can remake the
  165176. * multiplier tables if necessary.
  165177. * In buffered-image mode, the first output pass may occur before any data
  165178. * has been seen for some components, and thus before their Q-tables have
  165179. * been saved away. To handle this case, multiplier tables are preset
  165180. * to zeroes; the result of the IDCT will be a neutral gray level.
  165181. */
  165182. /* Private subobject for this module */
  165183. typedef struct {
  165184. struct jpeg_inverse_dct pub; /* public fields */
  165185. /* This array contains the IDCT method code that each multiplier table
  165186. * is currently set up for, or -1 if it's not yet set up.
  165187. * The actual multiplier tables are pointed to by dct_table in the
  165188. * per-component comp_info structures.
  165189. */
  165190. int cur_method[MAX_COMPONENTS];
  165191. } my_idct_controller;
  165192. typedef my_idct_controller * my_idct_ptr;
  165193. /* Allocated multiplier tables: big enough for any supported variant */
  165194. typedef union {
  165195. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  165196. #ifdef DCT_IFAST_SUPPORTED
  165197. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  165198. #endif
  165199. #ifdef DCT_FLOAT_SUPPORTED
  165200. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  165201. #endif
  165202. } multiplier_table;
  165203. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  165204. * so be sure to compile that code if either ISLOW or SCALING is requested.
  165205. */
  165206. #ifdef DCT_ISLOW_SUPPORTED
  165207. #define PROVIDE_ISLOW_TABLES
  165208. #else
  165209. #ifdef IDCT_SCALING_SUPPORTED
  165210. #define PROVIDE_ISLOW_TABLES
  165211. #endif
  165212. #endif
  165213. /*
  165214. * Prepare for an output pass.
  165215. * Here we select the proper IDCT routine for each component and build
  165216. * a matching multiplier table.
  165217. */
  165218. METHODDEF(void)
  165219. start_pass (j_decompress_ptr cinfo)
  165220. {
  165221. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  165222. int ci, i;
  165223. jpeg_component_info *compptr;
  165224. int method = 0;
  165225. inverse_DCT_method_ptr method_ptr = NULL;
  165226. JQUANT_TBL * qtbl;
  165227. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165228. ci++, compptr++) {
  165229. /* Select the proper IDCT routine for this component's scaling */
  165230. switch (compptr->DCT_scaled_size) {
  165231. #ifdef IDCT_SCALING_SUPPORTED
  165232. case 1:
  165233. method_ptr = jpeg_idct_1x1;
  165234. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165235. break;
  165236. case 2:
  165237. method_ptr = jpeg_idct_2x2;
  165238. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165239. break;
  165240. case 4:
  165241. method_ptr = jpeg_idct_4x4;
  165242. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165243. break;
  165244. #endif
  165245. case DCTSIZE:
  165246. switch (cinfo->dct_method) {
  165247. #ifdef DCT_ISLOW_SUPPORTED
  165248. case JDCT_ISLOW:
  165249. method_ptr = jpeg_idct_islow;
  165250. method = JDCT_ISLOW;
  165251. break;
  165252. #endif
  165253. #ifdef DCT_IFAST_SUPPORTED
  165254. case JDCT_IFAST:
  165255. method_ptr = jpeg_idct_ifast;
  165256. method = JDCT_IFAST;
  165257. break;
  165258. #endif
  165259. #ifdef DCT_FLOAT_SUPPORTED
  165260. case JDCT_FLOAT:
  165261. method_ptr = jpeg_idct_float;
  165262. method = JDCT_FLOAT;
  165263. break;
  165264. #endif
  165265. default:
  165266. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165267. break;
  165268. }
  165269. break;
  165270. default:
  165271. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  165272. break;
  165273. }
  165274. idct->pub.inverse_DCT[ci] = method_ptr;
  165275. /* Create multiplier table from quant table.
  165276. * However, we can skip this if the component is uninteresting
  165277. * or if we already built the table. Also, if no quant table
  165278. * has yet been saved for the component, we leave the
  165279. * multiplier table all-zero; we'll be reading zeroes from the
  165280. * coefficient controller's buffer anyway.
  165281. */
  165282. if (! compptr->component_needed || idct->cur_method[ci] == method)
  165283. continue;
  165284. qtbl = compptr->quant_table;
  165285. if (qtbl == NULL) /* happens if no data yet for component */
  165286. continue;
  165287. idct->cur_method[ci] = method;
  165288. switch (method) {
  165289. #ifdef PROVIDE_ISLOW_TABLES
  165290. case JDCT_ISLOW:
  165291. {
  165292. /* For LL&M IDCT method, multipliers are equal to raw quantization
  165293. * coefficients, but are stored as ints to ensure access efficiency.
  165294. */
  165295. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  165296. for (i = 0; i < DCTSIZE2; i++) {
  165297. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  165298. }
  165299. }
  165300. break;
  165301. #endif
  165302. #ifdef DCT_IFAST_SUPPORTED
  165303. case JDCT_IFAST:
  165304. {
  165305. /* For AA&N IDCT method, multipliers are equal to quantization
  165306. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165307. * scalefactor[0] = 1
  165308. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165309. * For integer operation, the multiplier table is to be scaled by
  165310. * IFAST_SCALE_BITS.
  165311. */
  165312. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  165313. #define CONST_BITS 14
  165314. static const INT16 aanscales[DCTSIZE2] = {
  165315. /* precomputed values scaled up by 14 bits */
  165316. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165317. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  165318. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  165319. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  165320. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165321. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  165322. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  165323. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  165324. };
  165325. SHIFT_TEMPS
  165326. for (i = 0; i < DCTSIZE2; i++) {
  165327. ifmtbl[i] = (IFAST_MULT_TYPE)
  165328. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  165329. (INT32) aanscales[i]),
  165330. CONST_BITS-IFAST_SCALE_BITS);
  165331. }
  165332. }
  165333. break;
  165334. #endif
  165335. #ifdef DCT_FLOAT_SUPPORTED
  165336. case JDCT_FLOAT:
  165337. {
  165338. /* For float AA&N IDCT method, multipliers are equal to quantization
  165339. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165340. * scalefactor[0] = 1
  165341. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165342. */
  165343. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  165344. int row, col;
  165345. static const double aanscalefactor[DCTSIZE] = {
  165346. 1.0, 1.387039845, 1.306562965, 1.175875602,
  165347. 1.0, 0.785694958, 0.541196100, 0.275899379
  165348. };
  165349. i = 0;
  165350. for (row = 0; row < DCTSIZE; row++) {
  165351. for (col = 0; col < DCTSIZE; col++) {
  165352. fmtbl[i] = (FLOAT_MULT_TYPE)
  165353. ((double) qtbl->quantval[i] *
  165354. aanscalefactor[row] * aanscalefactor[col]);
  165355. i++;
  165356. }
  165357. }
  165358. }
  165359. break;
  165360. #endif
  165361. default:
  165362. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165363. break;
  165364. }
  165365. }
  165366. }
  165367. /*
  165368. * Initialize IDCT manager.
  165369. */
  165370. GLOBAL(void)
  165371. jinit_inverse_dct (j_decompress_ptr cinfo)
  165372. {
  165373. my_idct_ptr idct;
  165374. int ci;
  165375. jpeg_component_info *compptr;
  165376. idct = (my_idct_ptr)
  165377. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165378. SIZEOF(my_idct_controller));
  165379. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  165380. idct->pub.start_pass = start_pass;
  165381. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165382. ci++, compptr++) {
  165383. /* Allocate and pre-zero a multiplier table for each component */
  165384. compptr->dct_table =
  165385. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165386. SIZEOF(multiplier_table));
  165387. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  165388. /* Mark multiplier table not yet set up for any method */
  165389. idct->cur_method[ci] = -1;
  165390. }
  165391. }
  165392. /********* End of inlined file: jddctmgr.c *********/
  165393. #undef CONST_BITS
  165394. #undef ASSIGN_STATE
  165395. /********* Start of inlined file: jdhuff.c *********/
  165396. #define JPEG_INTERNALS
  165397. /********* Start of inlined file: jdhuff.h *********/
  165398. /* Short forms of external names for systems with brain-damaged linkers. */
  165399. #ifndef __jdhuff_h__
  165400. #define __jdhuff_h__
  165401. #ifdef NEED_SHORT_EXTERNAL_NAMES
  165402. #define jpeg_make_d_derived_tbl jMkDDerived
  165403. #define jpeg_fill_bit_buffer jFilBitBuf
  165404. #define jpeg_huff_decode jHufDecode
  165405. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  165406. /* Derived data constructed for each Huffman table */
  165407. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  165408. typedef struct {
  165409. /* Basic tables: (element [0] of each array is unused) */
  165410. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  165411. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  165412. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  165413. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  165414. * the smallest code of length k; so given a code of length k, the
  165415. * corresponding symbol is huffval[code + valoffset[k]]
  165416. */
  165417. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  165418. JHUFF_TBL *pub;
  165419. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  165420. * the input data stream. If the next Huffman code is no more
  165421. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  165422. * the corresponding symbol directly from these tables.
  165423. */
  165424. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  165425. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  165426. } d_derived_tbl;
  165427. /* Expand a Huffman table definition into the derived format */
  165428. EXTERN(void) jpeg_make_d_derived_tbl
  165429. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  165430. d_derived_tbl ** pdtbl));
  165431. /*
  165432. * Fetching the next N bits from the input stream is a time-critical operation
  165433. * for the Huffman decoders. We implement it with a combination of inline
  165434. * macros and out-of-line subroutines. Note that N (the number of bits
  165435. * demanded at one time) never exceeds 15 for JPEG use.
  165436. *
  165437. * We read source bytes into get_buffer and dole out bits as needed.
  165438. * If get_buffer already contains enough bits, they are fetched in-line
  165439. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  165440. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  165441. * as full as possible (not just to the number of bits needed; this
  165442. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  165443. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  165444. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  165445. * at least the requested number of bits --- dummy zeroes are inserted if
  165446. * necessary.
  165447. */
  165448. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  165449. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  165450. /* If long is > 32 bits on your machine, and shifting/masking longs is
  165451. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  165452. * appropriately should be a win. Unfortunately we can't define the size
  165453. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  165454. * because not all machines measure sizeof in 8-bit bytes.
  165455. */
  165456. typedef struct { /* Bitreading state saved across MCUs */
  165457. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165458. int bits_left; /* # of unused bits in it */
  165459. } bitread_perm_state;
  165460. typedef struct { /* Bitreading working state within an MCU */
  165461. /* Current data source location */
  165462. /* We need a copy, rather than munging the original, in case of suspension */
  165463. const JOCTET * next_input_byte; /* => next byte to read from source */
  165464. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  165465. /* Bit input buffer --- note these values are kept in register variables,
  165466. * not in this struct, inside the inner loops.
  165467. */
  165468. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165469. int bits_left; /* # of unused bits in it */
  165470. /* Pointer needed by jpeg_fill_bit_buffer. */
  165471. j_decompress_ptr cinfo; /* back link to decompress master record */
  165472. } bitread_working_state;
  165473. /* Macros to declare and load/save bitread local variables. */
  165474. #define BITREAD_STATE_VARS \
  165475. register bit_buf_type get_buffer; \
  165476. register int bits_left; \
  165477. bitread_working_state br_state
  165478. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  165479. br_state.cinfo = cinfop; \
  165480. br_state.next_input_byte = cinfop->src->next_input_byte; \
  165481. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  165482. get_buffer = permstate.get_buffer; \
  165483. bits_left = permstate.bits_left;
  165484. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  165485. cinfop->src->next_input_byte = br_state.next_input_byte; \
  165486. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  165487. permstate.get_buffer = get_buffer; \
  165488. permstate.bits_left = bits_left
  165489. /*
  165490. * These macros provide the in-line portion of bit fetching.
  165491. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  165492. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  165493. * The variables get_buffer and bits_left are assumed to be locals,
  165494. * but the state struct might not be (jpeg_huff_decode needs this).
  165495. * CHECK_BIT_BUFFER(state,n,action);
  165496. * Ensure there are N bits in get_buffer; if suspend, take action.
  165497. * val = GET_BITS(n);
  165498. * Fetch next N bits.
  165499. * val = PEEK_BITS(n);
  165500. * Fetch next N bits without removing them from the buffer.
  165501. * DROP_BITS(n);
  165502. * Discard next N bits.
  165503. * The value N should be a simple variable, not an expression, because it
  165504. * is evaluated multiple times.
  165505. */
  165506. #define CHECK_BIT_BUFFER(state,nbits,action) \
  165507. { if (bits_left < (nbits)) { \
  165508. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  165509. { action; } \
  165510. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  165511. #define GET_BITS(nbits) \
  165512. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  165513. #define PEEK_BITS(nbits) \
  165514. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  165515. #define DROP_BITS(nbits) \
  165516. (bits_left -= (nbits))
  165517. /* Load up the bit buffer to a depth of at least nbits */
  165518. EXTERN(boolean) jpeg_fill_bit_buffer
  165519. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165520. register int bits_left, int nbits));
  165521. /*
  165522. * Code for extracting next Huffman-coded symbol from input bit stream.
  165523. * Again, this is time-critical and we make the main paths be macros.
  165524. *
  165525. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  165526. * without looping. Usually, more than 95% of the Huffman codes will be 8
  165527. * or fewer bits long. The few overlength codes are handled with a loop,
  165528. * which need not be inline code.
  165529. *
  165530. * Notes about the HUFF_DECODE macro:
  165531. * 1. Near the end of the data segment, we may fail to get enough bits
  165532. * for a lookahead. In that case, we do it the hard way.
  165533. * 2. If the lookahead table contains no entry, the next code must be
  165534. * more than HUFF_LOOKAHEAD bits long.
  165535. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  165536. */
  165537. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  165538. { register int nb, look; \
  165539. if (bits_left < HUFF_LOOKAHEAD) { \
  165540. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  165541. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165542. if (bits_left < HUFF_LOOKAHEAD) { \
  165543. nb = 1; goto slowlabel; \
  165544. } \
  165545. } \
  165546. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  165547. if ((nb = htbl->look_nbits[look]) != 0) { \
  165548. DROP_BITS(nb); \
  165549. result = htbl->look_sym[look]; \
  165550. } else { \
  165551. nb = HUFF_LOOKAHEAD+1; \
  165552. slowlabel: \
  165553. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  165554. { failaction; } \
  165555. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165556. } \
  165557. }
  165558. /* Out-of-line case for Huffman code fetching */
  165559. EXTERN(int) jpeg_huff_decode
  165560. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165561. register int bits_left, d_derived_tbl * htbl, int min_bits));
  165562. #endif
  165563. /********* End of inlined file: jdhuff.h *********/
  165564. /* Declarations shared with jdphuff.c */
  165565. /*
  165566. * Expanded entropy decoder object for Huffman decoding.
  165567. *
  165568. * The savable_state subrecord contains fields that change within an MCU,
  165569. * but must not be updated permanently until we complete the MCU.
  165570. */
  165571. typedef struct {
  165572. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165573. } savable_state2;
  165574. /* This macro is to work around compilers with missing or broken
  165575. * structure assignment. You'll need to fix this code if you have
  165576. * such a compiler and you change MAX_COMPS_IN_SCAN.
  165577. */
  165578. #ifndef NO_STRUCT_ASSIGN
  165579. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  165580. #else
  165581. #if MAX_COMPS_IN_SCAN == 4
  165582. #define ASSIGN_STATE(dest,src) \
  165583. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  165584. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  165585. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  165586. (dest).last_dc_val[3] = (src).last_dc_val[3])
  165587. #endif
  165588. #endif
  165589. typedef struct {
  165590. struct jpeg_entropy_decoder pub; /* public fields */
  165591. /* These fields are loaded into local variables at start of each MCU.
  165592. * In case of suspension, we exit WITHOUT updating them.
  165593. */
  165594. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  165595. savable_state2 saved; /* Other state at start of MCU */
  165596. /* These fields are NOT loaded into local working state. */
  165597. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165598. /* Pointers to derived tables (these workspaces have image lifespan) */
  165599. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  165600. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  165601. /* Precalculated info set up by start_pass for use in decode_mcu: */
  165602. /* Pointers to derived tables to be used for each block within an MCU */
  165603. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165604. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165605. /* Whether we care about the DC and AC coefficient values for each block */
  165606. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  165607. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  165608. } huff_entropy_decoder2;
  165609. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  165610. /*
  165611. * Initialize for a Huffman-compressed scan.
  165612. */
  165613. METHODDEF(void)
  165614. start_pass_huff_decoder (j_decompress_ptr cinfo)
  165615. {
  165616. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165617. int ci, blkn, dctbl, actbl;
  165618. jpeg_component_info * compptr;
  165619. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  165620. * This ought to be an error condition, but we make it a warning because
  165621. * there are some baseline files out there with all zeroes in these bytes.
  165622. */
  165623. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  165624. cinfo->Ah != 0 || cinfo->Al != 0)
  165625. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  165626. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165627. compptr = cinfo->cur_comp_info[ci];
  165628. dctbl = compptr->dc_tbl_no;
  165629. actbl = compptr->ac_tbl_no;
  165630. /* Compute derived values for Huffman tables */
  165631. /* We may do this more than once for a table, but it's not expensive */
  165632. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  165633. & entropy->dc_derived_tbls[dctbl]);
  165634. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  165635. & entropy->ac_derived_tbls[actbl]);
  165636. /* Initialize DC predictions to 0 */
  165637. entropy->saved.last_dc_val[ci] = 0;
  165638. }
  165639. /* Precalculate decoding info for each block in an MCU of this scan */
  165640. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165641. ci = cinfo->MCU_membership[blkn];
  165642. compptr = cinfo->cur_comp_info[ci];
  165643. /* Precalculate which table to use for each block */
  165644. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  165645. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  165646. /* Decide whether we really care about the coefficient values */
  165647. if (compptr->component_needed) {
  165648. entropy->dc_needed[blkn] = TRUE;
  165649. /* we don't need the ACs if producing a 1/8th-size image */
  165650. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  165651. } else {
  165652. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  165653. }
  165654. }
  165655. /* Initialize bitread state variables */
  165656. entropy->bitstate.bits_left = 0;
  165657. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  165658. entropy->pub.insufficient_data = FALSE;
  165659. /* Initialize restart counter */
  165660. entropy->restarts_to_go = cinfo->restart_interval;
  165661. }
  165662. /*
  165663. * Compute the derived values for a Huffman table.
  165664. * This routine also performs some validation checks on the table.
  165665. *
  165666. * Note this is also used by jdphuff.c.
  165667. */
  165668. GLOBAL(void)
  165669. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  165670. d_derived_tbl ** pdtbl)
  165671. {
  165672. JHUFF_TBL *htbl;
  165673. d_derived_tbl *dtbl;
  165674. int p, i, l, si, numsymbols;
  165675. int lookbits, ctr;
  165676. char huffsize[257];
  165677. unsigned int huffcode[257];
  165678. unsigned int code;
  165679. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  165680. * paralleling the order of the symbols themselves in htbl->huffval[].
  165681. */
  165682. /* Find the input Huffman table */
  165683. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  165684. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165685. htbl =
  165686. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  165687. if (htbl == NULL)
  165688. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165689. /* Allocate a workspace if we haven't already done so. */
  165690. if (*pdtbl == NULL)
  165691. *pdtbl = (d_derived_tbl *)
  165692. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165693. SIZEOF(d_derived_tbl));
  165694. dtbl = *pdtbl;
  165695. dtbl->pub = htbl; /* fill in back link */
  165696. /* Figure C.1: make table of Huffman code length for each symbol */
  165697. p = 0;
  165698. for (l = 1; l <= 16; l++) {
  165699. i = (int) htbl->bits[l];
  165700. if (i < 0 || p + i > 256) /* protect against table overrun */
  165701. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165702. while (i--)
  165703. huffsize[p++] = (char) l;
  165704. }
  165705. huffsize[p] = 0;
  165706. numsymbols = p;
  165707. /* Figure C.2: generate the codes themselves */
  165708. /* We also validate that the counts represent a legal Huffman code tree. */
  165709. code = 0;
  165710. si = huffsize[0];
  165711. p = 0;
  165712. while (huffsize[p]) {
  165713. while (((int) huffsize[p]) == si) {
  165714. huffcode[p++] = code;
  165715. code++;
  165716. }
  165717. /* code is now 1 more than the last code used for codelength si; but
  165718. * it must still fit in si bits, since no code is allowed to be all ones.
  165719. */
  165720. if (((INT32) code) >= (((INT32) 1) << si))
  165721. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165722. code <<= 1;
  165723. si++;
  165724. }
  165725. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  165726. p = 0;
  165727. for (l = 1; l <= 16; l++) {
  165728. if (htbl->bits[l]) {
  165729. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  165730. * minus the minimum code of length l
  165731. */
  165732. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  165733. p += htbl->bits[l];
  165734. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  165735. } else {
  165736. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  165737. }
  165738. }
  165739. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  165740. /* Compute lookahead tables to speed up decoding.
  165741. * First we set all the table entries to 0, indicating "too long";
  165742. * then we iterate through the Huffman codes that are short enough and
  165743. * fill in all the entries that correspond to bit sequences starting
  165744. * with that code.
  165745. */
  165746. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  165747. p = 0;
  165748. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  165749. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  165750. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  165751. /* Generate left-justified code followed by all possible bit sequences */
  165752. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  165753. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  165754. dtbl->look_nbits[lookbits] = l;
  165755. dtbl->look_sym[lookbits] = htbl->huffval[p];
  165756. lookbits++;
  165757. }
  165758. }
  165759. }
  165760. /* Validate symbols as being reasonable.
  165761. * For AC tables, we make no check, but accept all byte values 0..255.
  165762. * For DC tables, we require the symbols to be in range 0..15.
  165763. * (Tighter bounds could be applied depending on the data depth and mode,
  165764. * but this is sufficient to ensure safe decoding.)
  165765. */
  165766. if (isDC) {
  165767. for (i = 0; i < numsymbols; i++) {
  165768. int sym = htbl->huffval[i];
  165769. if (sym < 0 || sym > 15)
  165770. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165771. }
  165772. }
  165773. }
  165774. /*
  165775. * Out-of-line code for bit fetching (shared with jdphuff.c).
  165776. * See jdhuff.h for info about usage.
  165777. * Note: current values of get_buffer and bits_left are passed as parameters,
  165778. * but are returned in the corresponding fields of the state struct.
  165779. *
  165780. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  165781. * of get_buffer to be used. (On machines with wider words, an even larger
  165782. * buffer could be used.) However, on some machines 32-bit shifts are
  165783. * quite slow and take time proportional to the number of places shifted.
  165784. * (This is true with most PC compilers, for instance.) In this case it may
  165785. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  165786. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  165787. */
  165788. #ifdef SLOW_SHIFT_32
  165789. #define MIN_GET_BITS 15 /* minimum allowable value */
  165790. #else
  165791. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  165792. #endif
  165793. GLOBAL(boolean)
  165794. jpeg_fill_bit_buffer (bitread_working_state * state,
  165795. register bit_buf_type get_buffer, register int bits_left,
  165796. int nbits)
  165797. /* Load up the bit buffer to a depth of at least nbits */
  165798. {
  165799. /* Copy heavily used state fields into locals (hopefully registers) */
  165800. register const JOCTET * next_input_byte = state->next_input_byte;
  165801. register size_t bytes_in_buffer = state->bytes_in_buffer;
  165802. j_decompress_ptr cinfo = state->cinfo;
  165803. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  165804. /* (It is assumed that no request will be for more than that many bits.) */
  165805. /* We fail to do so only if we hit a marker or are forced to suspend. */
  165806. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  165807. while (bits_left < MIN_GET_BITS) {
  165808. register int c;
  165809. /* Attempt to read a byte */
  165810. if (bytes_in_buffer == 0) {
  165811. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165812. return FALSE;
  165813. next_input_byte = cinfo->src->next_input_byte;
  165814. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165815. }
  165816. bytes_in_buffer--;
  165817. c = GETJOCTET(*next_input_byte++);
  165818. /* If it's 0xFF, check and discard stuffed zero byte */
  165819. if (c == 0xFF) {
  165820. /* Loop here to discard any padding FF's on terminating marker,
  165821. * so that we can save a valid unread_marker value. NOTE: we will
  165822. * accept multiple FF's followed by a 0 as meaning a single FF data
  165823. * byte. This data pattern is not valid according to the standard.
  165824. */
  165825. do {
  165826. if (bytes_in_buffer == 0) {
  165827. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165828. return FALSE;
  165829. next_input_byte = cinfo->src->next_input_byte;
  165830. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165831. }
  165832. bytes_in_buffer--;
  165833. c = GETJOCTET(*next_input_byte++);
  165834. } while (c == 0xFF);
  165835. if (c == 0) {
  165836. /* Found FF/00, which represents an FF data byte */
  165837. c = 0xFF;
  165838. } else {
  165839. /* Oops, it's actually a marker indicating end of compressed data.
  165840. * Save the marker code for later use.
  165841. * Fine point: it might appear that we should save the marker into
  165842. * bitread working state, not straight into permanent state. But
  165843. * once we have hit a marker, we cannot need to suspend within the
  165844. * current MCU, because we will read no more bytes from the data
  165845. * source. So it is OK to update permanent state right away.
  165846. */
  165847. cinfo->unread_marker = c;
  165848. /* See if we need to insert some fake zero bits. */
  165849. goto no_more_bytes;
  165850. }
  165851. }
  165852. /* OK, load c into get_buffer */
  165853. get_buffer = (get_buffer << 8) | c;
  165854. bits_left += 8;
  165855. } /* end while */
  165856. } else {
  165857. no_more_bytes:
  165858. /* We get here if we've read the marker that terminates the compressed
  165859. * data segment. There should be enough bits in the buffer register
  165860. * to satisfy the request; if so, no problem.
  165861. */
  165862. if (nbits > bits_left) {
  165863. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  165864. * the data stream, so that we can produce some kind of image.
  165865. * We use a nonvolatile flag to ensure that only one warning message
  165866. * appears per data segment.
  165867. */
  165868. if (! cinfo->entropy->insufficient_data) {
  165869. WARNMS(cinfo, JWRN_HIT_MARKER);
  165870. cinfo->entropy->insufficient_data = TRUE;
  165871. }
  165872. /* Fill the buffer with zero bits */
  165873. get_buffer <<= MIN_GET_BITS - bits_left;
  165874. bits_left = MIN_GET_BITS;
  165875. }
  165876. }
  165877. /* Unload the local registers */
  165878. state->next_input_byte = next_input_byte;
  165879. state->bytes_in_buffer = bytes_in_buffer;
  165880. state->get_buffer = get_buffer;
  165881. state->bits_left = bits_left;
  165882. return TRUE;
  165883. }
  165884. /*
  165885. * Out-of-line code for Huffman code decoding.
  165886. * See jdhuff.h for info about usage.
  165887. */
  165888. GLOBAL(int)
  165889. jpeg_huff_decode (bitread_working_state * state,
  165890. register bit_buf_type get_buffer, register int bits_left,
  165891. d_derived_tbl * htbl, int min_bits)
  165892. {
  165893. register int l = min_bits;
  165894. register INT32 code;
  165895. /* HUFF_DECODE has determined that the code is at least min_bits */
  165896. /* bits long, so fetch that many bits in one swoop. */
  165897. CHECK_BIT_BUFFER(*state, l, return -1);
  165898. code = GET_BITS(l);
  165899. /* Collect the rest of the Huffman code one bit at a time. */
  165900. /* This is per Figure F.16 in the JPEG spec. */
  165901. while (code > htbl->maxcode[l]) {
  165902. code <<= 1;
  165903. CHECK_BIT_BUFFER(*state, 1, return -1);
  165904. code |= GET_BITS(1);
  165905. l++;
  165906. }
  165907. /* Unload the local registers */
  165908. state->get_buffer = get_buffer;
  165909. state->bits_left = bits_left;
  165910. /* With garbage input we may reach the sentinel value l = 17. */
  165911. if (l > 16) {
  165912. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  165913. return 0; /* fake a zero as the safest result */
  165914. }
  165915. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  165916. }
  165917. /*
  165918. * Check for a restart marker & resynchronize decoder.
  165919. * Returns FALSE if must suspend.
  165920. */
  165921. LOCAL(boolean)
  165922. process_restart (j_decompress_ptr cinfo)
  165923. {
  165924. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165925. int ci;
  165926. /* Throw away any unused bits remaining in bit buffer; */
  165927. /* include any full bytes in next_marker's count of discarded bytes */
  165928. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  165929. entropy->bitstate.bits_left = 0;
  165930. /* Advance past the RSTn marker */
  165931. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  165932. return FALSE;
  165933. /* Re-initialize DC predictions to 0 */
  165934. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  165935. entropy->saved.last_dc_val[ci] = 0;
  165936. /* Reset restart counter */
  165937. entropy->restarts_to_go = cinfo->restart_interval;
  165938. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  165939. * against a marker. In that case we will end up treating the next data
  165940. * segment as empty, and we can avoid producing bogus output pixels by
  165941. * leaving the flag set.
  165942. */
  165943. if (cinfo->unread_marker == 0)
  165944. entropy->pub.insufficient_data = FALSE;
  165945. return TRUE;
  165946. }
  165947. /*
  165948. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  165949. * The coefficients are reordered from zigzag order into natural array order,
  165950. * but are not dequantized.
  165951. *
  165952. * The i'th block of the MCU is stored into the block pointed to by
  165953. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  165954. * (Wholesale zeroing is usually a little faster than retail...)
  165955. *
  165956. * Returns FALSE if data source requested suspension. In that case no
  165957. * changes have been made to permanent state. (Exception: some output
  165958. * coefficients may already have been assigned. This is harmless for
  165959. * this module, since we'll just re-assign them on the next call.)
  165960. */
  165961. METHODDEF(boolean)
  165962. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  165963. {
  165964. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165965. int blkn;
  165966. BITREAD_STATE_VARS;
  165967. savable_state2 state;
  165968. /* Process restart marker if needed; may have to suspend */
  165969. if (cinfo->restart_interval) {
  165970. if (entropy->restarts_to_go == 0)
  165971. if (! process_restart(cinfo))
  165972. return FALSE;
  165973. }
  165974. /* If we've run out of data, just leave the MCU set to zeroes.
  165975. * This way, we return uniform gray for the remainder of the segment.
  165976. */
  165977. if (! entropy->pub.insufficient_data) {
  165978. /* Load up working state */
  165979. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  165980. ASSIGN_STATE(state, entropy->saved);
  165981. /* Outer loop handles each block in the MCU */
  165982. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165983. JBLOCKROW block = MCU_data[blkn];
  165984. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  165985. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  165986. register int s, k, r;
  165987. /* Decode a single block's worth of coefficients */
  165988. /* Section F.2.2.1: decode the DC coefficient difference */
  165989. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  165990. if (s) {
  165991. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165992. r = GET_BITS(s);
  165993. s = HUFF_EXTEND(r, s);
  165994. }
  165995. if (entropy->dc_needed[blkn]) {
  165996. /* Convert DC difference to actual value, update last_dc_val */
  165997. int ci = cinfo->MCU_membership[blkn];
  165998. s += state.last_dc_val[ci];
  165999. state.last_dc_val[ci] = s;
  166000. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  166001. (*block)[0] = (JCOEF) s;
  166002. }
  166003. if (entropy->ac_needed[blkn]) {
  166004. /* Section F.2.2.2: decode the AC coefficients */
  166005. /* Since zeroes are skipped, output area must be cleared beforehand */
  166006. for (k = 1; k < DCTSIZE2; k++) {
  166007. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  166008. r = s >> 4;
  166009. s &= 15;
  166010. if (s) {
  166011. k += r;
  166012. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166013. r = GET_BITS(s);
  166014. s = HUFF_EXTEND(r, s);
  166015. /* Output coefficient in natural (dezigzagged) order.
  166016. * Note: the extra entries in jpeg_natural_order[] will save us
  166017. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  166018. */
  166019. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  166020. } else {
  166021. if (r != 15)
  166022. break;
  166023. k += 15;
  166024. }
  166025. }
  166026. } else {
  166027. /* Section F.2.2.2: decode the AC coefficients */
  166028. /* In this path we just discard the values */
  166029. for (k = 1; k < DCTSIZE2; k++) {
  166030. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  166031. r = s >> 4;
  166032. s &= 15;
  166033. if (s) {
  166034. k += r;
  166035. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166036. DROP_BITS(s);
  166037. } else {
  166038. if (r != 15)
  166039. break;
  166040. k += 15;
  166041. }
  166042. }
  166043. }
  166044. }
  166045. /* Completed MCU, so update state */
  166046. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166047. ASSIGN_STATE(entropy->saved, state);
  166048. }
  166049. /* Account for restart interval (no-op if not using restarts) */
  166050. entropy->restarts_to_go--;
  166051. return TRUE;
  166052. }
  166053. /*
  166054. * Module initialization routine for Huffman entropy decoding.
  166055. */
  166056. GLOBAL(void)
  166057. jinit_huff_decoder (j_decompress_ptr cinfo)
  166058. {
  166059. huff_entropy_ptr2 entropy;
  166060. int i;
  166061. entropy = (huff_entropy_ptr2)
  166062. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166063. SIZEOF(huff_entropy_decoder2));
  166064. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  166065. entropy->pub.start_pass = start_pass_huff_decoder;
  166066. entropy->pub.decode_mcu = decode_mcu;
  166067. /* Mark tables unallocated */
  166068. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166069. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  166070. }
  166071. }
  166072. /********* End of inlined file: jdhuff.c *********/
  166073. /********* Start of inlined file: jdinput.c *********/
  166074. #define JPEG_INTERNALS
  166075. /* Private state */
  166076. typedef struct {
  166077. struct jpeg_input_controller pub; /* public fields */
  166078. boolean inheaders; /* TRUE until first SOS is reached */
  166079. } my_input_controller;
  166080. typedef my_input_controller * my_inputctl_ptr;
  166081. /* Forward declarations */
  166082. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  166083. /*
  166084. * Routines to calculate various quantities related to the size of the image.
  166085. */
  166086. LOCAL(void)
  166087. initial_setup2 (j_decompress_ptr cinfo)
  166088. /* Called once, when first SOS marker is reached */
  166089. {
  166090. int ci;
  166091. jpeg_component_info *compptr;
  166092. /* Make sure image isn't bigger than I can handle */
  166093. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  166094. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  166095. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  166096. /* For now, precision must match compiled-in value... */
  166097. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  166098. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  166099. /* Check that number of components won't exceed internal array sizes */
  166100. if (cinfo->num_components > MAX_COMPONENTS)
  166101. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  166102. MAX_COMPONENTS);
  166103. /* Compute maximum sampling factors; check factor validity */
  166104. cinfo->max_h_samp_factor = 1;
  166105. cinfo->max_v_samp_factor = 1;
  166106. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166107. ci++, compptr++) {
  166108. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  166109. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  166110. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  166111. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  166112. compptr->h_samp_factor);
  166113. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  166114. compptr->v_samp_factor);
  166115. }
  166116. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  166117. * In the full decompressor, this will be overridden by jdmaster.c;
  166118. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  166119. */
  166120. cinfo->min_DCT_scaled_size = DCTSIZE;
  166121. /* Compute dimensions of components */
  166122. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166123. ci++, compptr++) {
  166124. compptr->DCT_scaled_size = DCTSIZE;
  166125. /* Size in DCT blocks */
  166126. compptr->width_in_blocks = (JDIMENSION)
  166127. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166128. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166129. compptr->height_in_blocks = (JDIMENSION)
  166130. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166131. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166132. /* downsampled_width and downsampled_height will also be overridden by
  166133. * jdmaster.c if we are doing full decompression. The transcoder library
  166134. * doesn't use these values, but the calling application might.
  166135. */
  166136. /* Size in samples */
  166137. compptr->downsampled_width = (JDIMENSION)
  166138. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166139. (long) cinfo->max_h_samp_factor);
  166140. compptr->downsampled_height = (JDIMENSION)
  166141. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166142. (long) cinfo->max_v_samp_factor);
  166143. /* Mark component needed, until color conversion says otherwise */
  166144. compptr->component_needed = TRUE;
  166145. /* Mark no quantization table yet saved for component */
  166146. compptr->quant_table = NULL;
  166147. }
  166148. /* Compute number of fully interleaved MCU rows. */
  166149. cinfo->total_iMCU_rows = (JDIMENSION)
  166150. jdiv_round_up((long) cinfo->image_height,
  166151. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166152. /* Decide whether file contains multiple scans */
  166153. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  166154. cinfo->inputctl->has_multiple_scans = TRUE;
  166155. else
  166156. cinfo->inputctl->has_multiple_scans = FALSE;
  166157. }
  166158. LOCAL(void)
  166159. per_scan_setup2 (j_decompress_ptr cinfo)
  166160. /* Do computations that are needed before processing a JPEG scan */
  166161. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  166162. {
  166163. int ci, mcublks, tmp;
  166164. jpeg_component_info *compptr;
  166165. if (cinfo->comps_in_scan == 1) {
  166166. /* Noninterleaved (single-component) scan */
  166167. compptr = cinfo->cur_comp_info[0];
  166168. /* Overall image size in MCUs */
  166169. cinfo->MCUs_per_row = compptr->width_in_blocks;
  166170. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  166171. /* For noninterleaved scan, always one block per MCU */
  166172. compptr->MCU_width = 1;
  166173. compptr->MCU_height = 1;
  166174. compptr->MCU_blocks = 1;
  166175. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  166176. compptr->last_col_width = 1;
  166177. /* For noninterleaved scans, it is convenient to define last_row_height
  166178. * as the number of block rows present in the last iMCU row.
  166179. */
  166180. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166181. if (tmp == 0) tmp = compptr->v_samp_factor;
  166182. compptr->last_row_height = tmp;
  166183. /* Prepare array describing MCU composition */
  166184. cinfo->blocks_in_MCU = 1;
  166185. cinfo->MCU_membership[0] = 0;
  166186. } else {
  166187. /* Interleaved (multi-component) scan */
  166188. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  166189. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  166190. MAX_COMPS_IN_SCAN);
  166191. /* Overall image size in MCUs */
  166192. cinfo->MCUs_per_row = (JDIMENSION)
  166193. jdiv_round_up((long) cinfo->image_width,
  166194. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  166195. cinfo->MCU_rows_in_scan = (JDIMENSION)
  166196. jdiv_round_up((long) cinfo->image_height,
  166197. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166198. cinfo->blocks_in_MCU = 0;
  166199. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166200. compptr = cinfo->cur_comp_info[ci];
  166201. /* Sampling factors give # of blocks of component in each MCU */
  166202. compptr->MCU_width = compptr->h_samp_factor;
  166203. compptr->MCU_height = compptr->v_samp_factor;
  166204. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  166205. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  166206. /* Figure number of non-dummy blocks in last MCU column & row */
  166207. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  166208. if (tmp == 0) tmp = compptr->MCU_width;
  166209. compptr->last_col_width = tmp;
  166210. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  166211. if (tmp == 0) tmp = compptr->MCU_height;
  166212. compptr->last_row_height = tmp;
  166213. /* Prepare array describing MCU composition */
  166214. mcublks = compptr->MCU_blocks;
  166215. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  166216. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166217. while (mcublks-- > 0) {
  166218. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166219. }
  166220. }
  166221. }
  166222. }
  166223. /*
  166224. * Save away a copy of the Q-table referenced by each component present
  166225. * in the current scan, unless already saved during a prior scan.
  166226. *
  166227. * In a multiple-scan JPEG file, the encoder could assign different components
  166228. * the same Q-table slot number, but change table definitions between scans
  166229. * so that each component uses a different Q-table. (The IJG encoder is not
  166230. * currently capable of doing this, but other encoders might.) Since we want
  166231. * to be able to dequantize all the components at the end of the file, this
  166232. * means that we have to save away the table actually used for each component.
  166233. * We do this by copying the table at the start of the first scan containing
  166234. * the component.
  166235. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  166236. * slot between scans of a component using that slot. If the encoder does so
  166237. * anyway, this decoder will simply use the Q-table values that were current
  166238. * at the start of the first scan for the component.
  166239. *
  166240. * The decompressor output side looks only at the saved quant tables,
  166241. * not at the current Q-table slots.
  166242. */
  166243. LOCAL(void)
  166244. latch_quant_tables (j_decompress_ptr cinfo)
  166245. {
  166246. int ci, qtblno;
  166247. jpeg_component_info *compptr;
  166248. JQUANT_TBL * qtbl;
  166249. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166250. compptr = cinfo->cur_comp_info[ci];
  166251. /* No work if we already saved Q-table for this component */
  166252. if (compptr->quant_table != NULL)
  166253. continue;
  166254. /* Make sure specified quantization table is present */
  166255. qtblno = compptr->quant_tbl_no;
  166256. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  166257. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  166258. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  166259. /* OK, save away the quantization table */
  166260. qtbl = (JQUANT_TBL *)
  166261. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166262. SIZEOF(JQUANT_TBL));
  166263. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  166264. compptr->quant_table = qtbl;
  166265. }
  166266. }
  166267. /*
  166268. * Initialize the input modules to read a scan of compressed data.
  166269. * The first call to this is done by jdmaster.c after initializing
  166270. * the entire decompressor (during jpeg_start_decompress).
  166271. * Subsequent calls come from consume_markers, below.
  166272. */
  166273. METHODDEF(void)
  166274. start_input_pass2 (j_decompress_ptr cinfo)
  166275. {
  166276. per_scan_setup2(cinfo);
  166277. latch_quant_tables(cinfo);
  166278. (*cinfo->entropy->start_pass) (cinfo);
  166279. (*cinfo->coef->start_input_pass) (cinfo);
  166280. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  166281. }
  166282. /*
  166283. * Finish up after inputting a compressed-data scan.
  166284. * This is called by the coefficient controller after it's read all
  166285. * the expected data of the scan.
  166286. */
  166287. METHODDEF(void)
  166288. finish_input_pass (j_decompress_ptr cinfo)
  166289. {
  166290. cinfo->inputctl->consume_input = consume_markers;
  166291. }
  166292. /*
  166293. * Read JPEG markers before, between, or after compressed-data scans.
  166294. * Change state as necessary when a new scan is reached.
  166295. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  166296. *
  166297. * The consume_input method pointer points either here or to the
  166298. * coefficient controller's consume_data routine, depending on whether
  166299. * we are reading a compressed data segment or inter-segment markers.
  166300. */
  166301. METHODDEF(int)
  166302. consume_markers (j_decompress_ptr cinfo)
  166303. {
  166304. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166305. int val;
  166306. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  166307. return JPEG_REACHED_EOI;
  166308. val = (*cinfo->marker->read_markers) (cinfo);
  166309. switch (val) {
  166310. case JPEG_REACHED_SOS: /* Found SOS */
  166311. if (inputctl->inheaders) { /* 1st SOS */
  166312. initial_setup2(cinfo);
  166313. inputctl->inheaders = FALSE;
  166314. /* Note: start_input_pass must be called by jdmaster.c
  166315. * before any more input can be consumed. jdapimin.c is
  166316. * responsible for enforcing this sequencing.
  166317. */
  166318. } else { /* 2nd or later SOS marker */
  166319. if (! inputctl->pub.has_multiple_scans)
  166320. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  166321. start_input_pass2(cinfo);
  166322. }
  166323. break;
  166324. case JPEG_REACHED_EOI: /* Found EOI */
  166325. inputctl->pub.eoi_reached = TRUE;
  166326. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  166327. if (cinfo->marker->saw_SOF)
  166328. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  166329. } else {
  166330. /* Prevent infinite loop in coef ctlr's decompress_data routine
  166331. * if user set output_scan_number larger than number of scans.
  166332. */
  166333. if (cinfo->output_scan_number > cinfo->input_scan_number)
  166334. cinfo->output_scan_number = cinfo->input_scan_number;
  166335. }
  166336. break;
  166337. case JPEG_SUSPENDED:
  166338. break;
  166339. }
  166340. return val;
  166341. }
  166342. /*
  166343. * Reset state to begin a fresh datastream.
  166344. */
  166345. METHODDEF(void)
  166346. reset_input_controller (j_decompress_ptr cinfo)
  166347. {
  166348. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166349. inputctl->pub.consume_input = consume_markers;
  166350. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166351. inputctl->pub.eoi_reached = FALSE;
  166352. inputctl->inheaders = TRUE;
  166353. /* Reset other modules */
  166354. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166355. (*cinfo->marker->reset_marker_reader) (cinfo);
  166356. /* Reset progression state -- would be cleaner if entropy decoder did this */
  166357. cinfo->coef_bits = NULL;
  166358. }
  166359. /*
  166360. * Initialize the input controller module.
  166361. * This is called only once, when the decompression object is created.
  166362. */
  166363. GLOBAL(void)
  166364. jinit_input_controller (j_decompress_ptr cinfo)
  166365. {
  166366. my_inputctl_ptr inputctl;
  166367. /* Create subobject in permanent pool */
  166368. inputctl = (my_inputctl_ptr)
  166369. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166370. SIZEOF(my_input_controller));
  166371. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  166372. /* Initialize method pointers */
  166373. inputctl->pub.consume_input = consume_markers;
  166374. inputctl->pub.reset_input_controller = reset_input_controller;
  166375. inputctl->pub.start_input_pass = start_input_pass2;
  166376. inputctl->pub.finish_input_pass = finish_input_pass;
  166377. /* Initialize state: can't use reset_input_controller since we don't
  166378. * want to try to reset other modules yet.
  166379. */
  166380. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166381. inputctl->pub.eoi_reached = FALSE;
  166382. inputctl->inheaders = TRUE;
  166383. }
  166384. /********* End of inlined file: jdinput.c *********/
  166385. /********* Start of inlined file: jdmainct.c *********/
  166386. #define JPEG_INTERNALS
  166387. /*
  166388. * In the current system design, the main buffer need never be a full-image
  166389. * buffer; any full-height buffers will be found inside the coefficient or
  166390. * postprocessing controllers. Nonetheless, the main controller is not
  166391. * trivial. Its responsibility is to provide context rows for upsampling/
  166392. * rescaling, and doing this in an efficient fashion is a bit tricky.
  166393. *
  166394. * Postprocessor input data is counted in "row groups". A row group
  166395. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  166396. * sample rows of each component. (We require DCT_scaled_size values to be
  166397. * chosen such that these numbers are integers. In practice DCT_scaled_size
  166398. * values will likely be powers of two, so we actually have the stronger
  166399. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  166400. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  166401. * row group (times any additional scale factor that the upsampler is
  166402. * applying).
  166403. *
  166404. * The coefficient controller will deliver data to us one iMCU row at a time;
  166405. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  166406. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  166407. * to one row of MCUs when the image is fully interleaved.) Note that the
  166408. * number of sample rows varies across components, but the number of row
  166409. * groups does not. Some garbage sample rows may be included in the last iMCU
  166410. * row at the bottom of the image.
  166411. *
  166412. * Depending on the vertical scaling algorithm used, the upsampler may need
  166413. * access to the sample row(s) above and below its current input row group.
  166414. * The upsampler is required to set need_context_rows TRUE at global selection
  166415. * time if so. When need_context_rows is FALSE, this controller can simply
  166416. * obtain one iMCU row at a time from the coefficient controller and dole it
  166417. * out as row groups to the postprocessor.
  166418. *
  166419. * When need_context_rows is TRUE, this controller guarantees that the buffer
  166420. * passed to postprocessing contains at least one row group's worth of samples
  166421. * above and below the row group(s) being processed. Note that the context
  166422. * rows "above" the first passed row group appear at negative row offsets in
  166423. * the passed buffer. At the top and bottom of the image, the required
  166424. * context rows are manufactured by duplicating the first or last real sample
  166425. * row; this avoids having special cases in the upsampling inner loops.
  166426. *
  166427. * The amount of context is fixed at one row group just because that's a
  166428. * convenient number for this controller to work with. The existing
  166429. * upsamplers really only need one sample row of context. An upsampler
  166430. * supporting arbitrary output rescaling might wish for more than one row
  166431. * group of context when shrinking the image; tough, we don't handle that.
  166432. * (This is justified by the assumption that downsizing will be handled mostly
  166433. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  166434. * the upsample step needn't be much less than one.)
  166435. *
  166436. * To provide the desired context, we have to retain the last two row groups
  166437. * of one iMCU row while reading in the next iMCU row. (The last row group
  166438. * can't be processed until we have another row group for its below-context,
  166439. * and so we have to save the next-to-last group too for its above-context.)
  166440. * We could do this most simply by copying data around in our buffer, but
  166441. * that'd be very slow. We can avoid copying any data by creating a rather
  166442. * strange pointer structure. Here's how it works. We allocate a workspace
  166443. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  166444. * of row groups per iMCU row). We create two sets of redundant pointers to
  166445. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  166446. * pointer lists look like this:
  166447. * M+1 M-1
  166448. * master pointer --> 0 master pointer --> 0
  166449. * 1 1
  166450. * ... ...
  166451. * M-3 M-3
  166452. * M-2 M
  166453. * M-1 M+1
  166454. * M M-2
  166455. * M+1 M-1
  166456. * 0 0
  166457. * We read alternate iMCU rows using each master pointer; thus the last two
  166458. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  166459. * The pointer lists are set up so that the required context rows appear to
  166460. * be adjacent to the proper places when we pass the pointer lists to the
  166461. * upsampler.
  166462. *
  166463. * The above pictures describe the normal state of the pointer lists.
  166464. * At top and bottom of the image, we diddle the pointer lists to duplicate
  166465. * the first or last sample row as necessary (this is cheaper than copying
  166466. * sample rows around).
  166467. *
  166468. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  166469. * situation each iMCU row provides only one row group so the buffering logic
  166470. * must be different (eg, we must read two iMCU rows before we can emit the
  166471. * first row group). For now, we simply do not support providing context
  166472. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  166473. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  166474. * want it quick and dirty, so a context-free upsampler is sufficient.
  166475. */
  166476. /* Private buffer controller object */
  166477. typedef struct {
  166478. struct jpeg_d_main_controller pub; /* public fields */
  166479. /* Pointer to allocated workspace (M or M+2 row groups). */
  166480. JSAMPARRAY buffer[MAX_COMPONENTS];
  166481. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  166482. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  166483. /* Remaining fields are only used in the context case. */
  166484. /* These are the master pointers to the funny-order pointer lists. */
  166485. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  166486. int whichptr; /* indicates which pointer set is now in use */
  166487. int context_state; /* process_data state machine status */
  166488. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  166489. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  166490. } my_main_controller4;
  166491. typedef my_main_controller4 * my_main_ptr4;
  166492. /* context_state values: */
  166493. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  166494. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  166495. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  166496. /* Forward declarations */
  166497. METHODDEF(void) process_data_simple_main2
  166498. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166499. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166500. METHODDEF(void) process_data_context_main
  166501. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166502. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166503. #ifdef QUANT_2PASS_SUPPORTED
  166504. METHODDEF(void) process_data_crank_post
  166505. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166506. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166507. #endif
  166508. LOCAL(void)
  166509. alloc_funny_pointers (j_decompress_ptr cinfo)
  166510. /* Allocate space for the funny pointer lists.
  166511. * This is done only once, not once per pass.
  166512. */
  166513. {
  166514. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166515. int ci, rgroup;
  166516. int M = cinfo->min_DCT_scaled_size;
  166517. jpeg_component_info *compptr;
  166518. JSAMPARRAY xbuf;
  166519. /* Get top-level space for component array pointers.
  166520. * We alloc both arrays with one call to save a few cycles.
  166521. */
  166522. main_->xbuffer[0] = (JSAMPIMAGE)
  166523. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166524. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  166525. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  166526. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166527. ci++, compptr++) {
  166528. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166529. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166530. /* Get space for pointer lists --- M+4 row groups in each list.
  166531. * We alloc both pointer lists with one call to save a few cycles.
  166532. */
  166533. xbuf = (JSAMPARRAY)
  166534. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166535. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  166536. xbuf += rgroup; /* want one row group at negative offsets */
  166537. main_->xbuffer[0][ci] = xbuf;
  166538. xbuf += rgroup * (M + 4);
  166539. main_->xbuffer[1][ci] = xbuf;
  166540. }
  166541. }
  166542. LOCAL(void)
  166543. make_funny_pointers (j_decompress_ptr cinfo)
  166544. /* Create the funny pointer lists discussed in the comments above.
  166545. * The actual workspace is already allocated (in main->buffer),
  166546. * and the space for the pointer lists is allocated too.
  166547. * This routine just fills in the curiously ordered lists.
  166548. * This will be repeated at the beginning of each pass.
  166549. */
  166550. {
  166551. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166552. int ci, i, rgroup;
  166553. int M = cinfo->min_DCT_scaled_size;
  166554. jpeg_component_info *compptr;
  166555. JSAMPARRAY buf, xbuf0, xbuf1;
  166556. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166557. ci++, compptr++) {
  166558. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166559. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166560. xbuf0 = main_->xbuffer[0][ci];
  166561. xbuf1 = main_->xbuffer[1][ci];
  166562. /* First copy the workspace pointers as-is */
  166563. buf = main_->buffer[ci];
  166564. for (i = 0; i < rgroup * (M + 2); i++) {
  166565. xbuf0[i] = xbuf1[i] = buf[i];
  166566. }
  166567. /* In the second list, put the last four row groups in swapped order */
  166568. for (i = 0; i < rgroup * 2; i++) {
  166569. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  166570. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  166571. }
  166572. /* The wraparound pointers at top and bottom will be filled later
  166573. * (see set_wraparound_pointers, below). Initially we want the "above"
  166574. * pointers to duplicate the first actual data line. This only needs
  166575. * to happen in xbuffer[0].
  166576. */
  166577. for (i = 0; i < rgroup; i++) {
  166578. xbuf0[i - rgroup] = xbuf0[0];
  166579. }
  166580. }
  166581. }
  166582. LOCAL(void)
  166583. set_wraparound_pointers (j_decompress_ptr cinfo)
  166584. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  166585. * This changes the pointer list state from top-of-image to the normal state.
  166586. */
  166587. {
  166588. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166589. int ci, i, rgroup;
  166590. int M = cinfo->min_DCT_scaled_size;
  166591. jpeg_component_info *compptr;
  166592. JSAMPARRAY xbuf0, xbuf1;
  166593. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166594. ci++, compptr++) {
  166595. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166596. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166597. xbuf0 = main_->xbuffer[0][ci];
  166598. xbuf1 = main_->xbuffer[1][ci];
  166599. for (i = 0; i < rgroup; i++) {
  166600. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  166601. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  166602. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  166603. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  166604. }
  166605. }
  166606. }
  166607. LOCAL(void)
  166608. set_bottom_pointers (j_decompress_ptr cinfo)
  166609. /* Change the pointer lists to duplicate the last sample row at the bottom
  166610. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  166611. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  166612. */
  166613. {
  166614. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166615. int ci, i, rgroup, iMCUheight, rows_left;
  166616. jpeg_component_info *compptr;
  166617. JSAMPARRAY xbuf;
  166618. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166619. ci++, compptr++) {
  166620. /* Count sample rows in one iMCU row and in one row group */
  166621. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  166622. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  166623. /* Count nondummy sample rows remaining for this component */
  166624. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  166625. if (rows_left == 0) rows_left = iMCUheight;
  166626. /* Count nondummy row groups. Should get same answer for each component,
  166627. * so we need only do it once.
  166628. */
  166629. if (ci == 0) {
  166630. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  166631. }
  166632. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  166633. * last partial rowgroup and ensures at least one full rowgroup of context.
  166634. */
  166635. xbuf = main_->xbuffer[main_->whichptr][ci];
  166636. for (i = 0; i < rgroup * 2; i++) {
  166637. xbuf[rows_left + i] = xbuf[rows_left-1];
  166638. }
  166639. }
  166640. }
  166641. /*
  166642. * Initialize for a processing pass.
  166643. */
  166644. METHODDEF(void)
  166645. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  166646. {
  166647. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166648. switch (pass_mode) {
  166649. case JBUF_PASS_THRU:
  166650. if (cinfo->upsample->need_context_rows) {
  166651. main_->pub.process_data = process_data_context_main;
  166652. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  166653. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  166654. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166655. main_->iMCU_row_ctr = 0;
  166656. } else {
  166657. /* Simple case with no context needed */
  166658. main_->pub.process_data = process_data_simple_main2;
  166659. }
  166660. main_->buffer_full = FALSE; /* Mark buffer empty */
  166661. main_->rowgroup_ctr = 0;
  166662. break;
  166663. #ifdef QUANT_2PASS_SUPPORTED
  166664. case JBUF_CRANK_DEST:
  166665. /* For last pass of 2-pass quantization, just crank the postprocessor */
  166666. main_->pub.process_data = process_data_crank_post;
  166667. break;
  166668. #endif
  166669. default:
  166670. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166671. break;
  166672. }
  166673. }
  166674. /*
  166675. * Process some data.
  166676. * This handles the simple case where no context is required.
  166677. */
  166678. METHODDEF(void)
  166679. process_data_simple_main2 (j_decompress_ptr cinfo,
  166680. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166681. JDIMENSION out_rows_avail)
  166682. {
  166683. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166684. JDIMENSION rowgroups_avail;
  166685. /* Read input data if we haven't filled the main buffer yet */
  166686. if (! main_->buffer_full) {
  166687. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  166688. return; /* suspension forced, can do nothing more */
  166689. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166690. }
  166691. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  166692. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  166693. /* Note: at the bottom of the image, we may pass extra garbage row groups
  166694. * to the postprocessor. The postprocessor has to check for bottom
  166695. * of image anyway (at row resolution), so no point in us doing it too.
  166696. */
  166697. /* Feed the postprocessor */
  166698. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  166699. &main_->rowgroup_ctr, rowgroups_avail,
  166700. output_buf, out_row_ctr, out_rows_avail);
  166701. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  166702. if (main_->rowgroup_ctr >= rowgroups_avail) {
  166703. main_->buffer_full = FALSE;
  166704. main_->rowgroup_ctr = 0;
  166705. }
  166706. }
  166707. /*
  166708. * Process some data.
  166709. * This handles the case where context rows must be provided.
  166710. */
  166711. METHODDEF(void)
  166712. process_data_context_main (j_decompress_ptr cinfo,
  166713. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166714. JDIMENSION out_rows_avail)
  166715. {
  166716. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166717. /* Read input data if we haven't filled the main buffer yet */
  166718. if (! main_->buffer_full) {
  166719. if (! (*cinfo->coef->decompress_data) (cinfo,
  166720. main_->xbuffer[main_->whichptr]))
  166721. return; /* suspension forced, can do nothing more */
  166722. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166723. main_->iMCU_row_ctr++; /* count rows received */
  166724. }
  166725. /* Postprocessor typically will not swallow all the input data it is handed
  166726. * in one call (due to filling the output buffer first). Must be prepared
  166727. * to exit and restart. This switch lets us keep track of how far we got.
  166728. * Note that each case falls through to the next on successful completion.
  166729. */
  166730. switch (main_->context_state) {
  166731. case CTX_POSTPONED_ROW:
  166732. /* Call postprocessor using previously set pointers for postponed row */
  166733. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166734. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166735. output_buf, out_row_ctr, out_rows_avail);
  166736. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166737. return; /* Need to suspend */
  166738. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166739. if (*out_row_ctr >= out_rows_avail)
  166740. return; /* Postprocessor exactly filled output buf */
  166741. /*FALLTHROUGH*/
  166742. case CTX_PREPARE_FOR_IMCU:
  166743. /* Prepare to process first M-1 row groups of this iMCU row */
  166744. main_->rowgroup_ctr = 0;
  166745. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  166746. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  166747. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  166748. */
  166749. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  166750. set_bottom_pointers(cinfo);
  166751. main_->context_state = CTX_PROCESS_IMCU;
  166752. /*FALLTHROUGH*/
  166753. case CTX_PROCESS_IMCU:
  166754. /* Call postprocessor using previously set pointers */
  166755. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166756. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166757. output_buf, out_row_ctr, out_rows_avail);
  166758. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166759. return; /* Need to suspend */
  166760. /* After the first iMCU, change wraparound pointers to normal state */
  166761. if (main_->iMCU_row_ctr == 1)
  166762. set_wraparound_pointers(cinfo);
  166763. /* Prepare to load new iMCU row using other xbuffer list */
  166764. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  166765. main_->buffer_full = FALSE;
  166766. /* Still need to process last row group of this iMCU row, */
  166767. /* which is saved at index M+1 of the other xbuffer */
  166768. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  166769. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  166770. main_->context_state = CTX_POSTPONED_ROW;
  166771. }
  166772. }
  166773. /*
  166774. * Process some data.
  166775. * Final pass of two-pass quantization: just call the postprocessor.
  166776. * Source data will be the postprocessor controller's internal buffer.
  166777. */
  166778. #ifdef QUANT_2PASS_SUPPORTED
  166779. METHODDEF(void)
  166780. process_data_crank_post (j_decompress_ptr cinfo,
  166781. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166782. JDIMENSION out_rows_avail)
  166783. {
  166784. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  166785. (JDIMENSION *) NULL, (JDIMENSION) 0,
  166786. output_buf, out_row_ctr, out_rows_avail);
  166787. }
  166788. #endif /* QUANT_2PASS_SUPPORTED */
  166789. /*
  166790. * Initialize main buffer controller.
  166791. */
  166792. GLOBAL(void)
  166793. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166794. {
  166795. my_main_ptr4 main_;
  166796. int ci, rgroup, ngroups;
  166797. jpeg_component_info *compptr;
  166798. main_ = (my_main_ptr4)
  166799. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166800. SIZEOF(my_main_controller4));
  166801. cinfo->main = (struct jpeg_d_main_controller *) main_;
  166802. main_->pub.start_pass = start_pass_main2;
  166803. if (need_full_buffer) /* shouldn't happen */
  166804. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166805. /* Allocate the workspace.
  166806. * ngroups is the number of row groups we need.
  166807. */
  166808. if (cinfo->upsample->need_context_rows) {
  166809. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  166810. ERREXIT(cinfo, JERR_NOTIMPL);
  166811. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  166812. ngroups = cinfo->min_DCT_scaled_size + 2;
  166813. } else {
  166814. ngroups = cinfo->min_DCT_scaled_size;
  166815. }
  166816. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166817. ci++, compptr++) {
  166818. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166819. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166820. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  166821. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166822. compptr->width_in_blocks * compptr->DCT_scaled_size,
  166823. (JDIMENSION) (rgroup * ngroups));
  166824. }
  166825. }
  166826. /********* End of inlined file: jdmainct.c *********/
  166827. /********* Start of inlined file: jdmarker.c *********/
  166828. #define JPEG_INTERNALS
  166829. /* Private state */
  166830. typedef struct {
  166831. struct jpeg_marker_reader pub; /* public fields */
  166832. /* Application-overridable marker processing methods */
  166833. jpeg_marker_parser_method process_COM;
  166834. jpeg_marker_parser_method process_APPn[16];
  166835. /* Limit on marker data length to save for each marker type */
  166836. unsigned int length_limit_COM;
  166837. unsigned int length_limit_APPn[16];
  166838. /* Status of COM/APPn marker saving */
  166839. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  166840. unsigned int bytes_read; /* data bytes read so far in marker */
  166841. /* Note: cur_marker is not linked into marker_list until it's all read. */
  166842. } my_marker_reader;
  166843. typedef my_marker_reader * my_marker_ptr2;
  166844. /*
  166845. * Macros for fetching data from the data source module.
  166846. *
  166847. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  166848. * the current restart point; we update them only when we have reached a
  166849. * suitable place to restart if a suspension occurs.
  166850. */
  166851. /* Declare and initialize local copies of input pointer/count */
  166852. #define INPUT_VARS(cinfo) \
  166853. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  166854. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  166855. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  166856. /* Unload the local copies --- do this only at a restart boundary */
  166857. #define INPUT_SYNC(cinfo) \
  166858. ( datasrc->next_input_byte = next_input_byte, \
  166859. datasrc->bytes_in_buffer = bytes_in_buffer )
  166860. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  166861. #define INPUT_RELOAD(cinfo) \
  166862. ( next_input_byte = datasrc->next_input_byte, \
  166863. bytes_in_buffer = datasrc->bytes_in_buffer )
  166864. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  166865. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  166866. * but we must reload the local copies after a successful fill.
  166867. */
  166868. #define MAKE_BYTE_AVAIL(cinfo,action) \
  166869. if (bytes_in_buffer == 0) { \
  166870. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  166871. { action; } \
  166872. INPUT_RELOAD(cinfo); \
  166873. }
  166874. /* Read a byte into variable V.
  166875. * If must suspend, take the specified action (typically "return FALSE").
  166876. */
  166877. #define INPUT_BYTE(cinfo,V,action) \
  166878. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166879. bytes_in_buffer--; \
  166880. V = GETJOCTET(*next_input_byte++); )
  166881. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  166882. * V should be declared unsigned int or perhaps INT32.
  166883. */
  166884. #define INPUT_2BYTES(cinfo,V,action) \
  166885. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166886. bytes_in_buffer--; \
  166887. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  166888. MAKE_BYTE_AVAIL(cinfo,action); \
  166889. bytes_in_buffer--; \
  166890. V += GETJOCTET(*next_input_byte++); )
  166891. /*
  166892. * Routines to process JPEG markers.
  166893. *
  166894. * Entry condition: JPEG marker itself has been read and its code saved
  166895. * in cinfo->unread_marker; input restart point is just after the marker.
  166896. *
  166897. * Exit: if return TRUE, have read and processed any parameters, and have
  166898. * updated the restart point to point after the parameters.
  166899. * If return FALSE, was forced to suspend before reaching end of
  166900. * marker parameters; restart point has not been moved. Same routine
  166901. * will be called again after application supplies more input data.
  166902. *
  166903. * This approach to suspension assumes that all of a marker's parameters
  166904. * can fit into a single input bufferload. This should hold for "normal"
  166905. * markers. Some COM/APPn markers might have large parameter segments
  166906. * that might not fit. If we are simply dropping such a marker, we use
  166907. * skip_input_data to get past it, and thereby put the problem on the
  166908. * source manager's shoulders. If we are saving the marker's contents
  166909. * into memory, we use a slightly different convention: when forced to
  166910. * suspend, the marker processor updates the restart point to the end of
  166911. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  166912. * On resumption, cinfo->unread_marker still contains the marker code,
  166913. * but the data source will point to the next chunk of marker data.
  166914. * The marker processor must retain internal state to deal with this.
  166915. *
  166916. * Note that we don't bother to avoid duplicate trace messages if a
  166917. * suspension occurs within marker parameters. Other side effects
  166918. * require more care.
  166919. */
  166920. LOCAL(boolean)
  166921. get_soi (j_decompress_ptr cinfo)
  166922. /* Process an SOI marker */
  166923. {
  166924. int i;
  166925. TRACEMS(cinfo, 1, JTRC_SOI);
  166926. if (cinfo->marker->saw_SOI)
  166927. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  166928. /* Reset all parameters that are defined to be reset by SOI */
  166929. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166930. cinfo->arith_dc_L[i] = 0;
  166931. cinfo->arith_dc_U[i] = 1;
  166932. cinfo->arith_ac_K[i] = 5;
  166933. }
  166934. cinfo->restart_interval = 0;
  166935. /* Set initial assumptions for colorspace etc */
  166936. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166937. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  166938. cinfo->saw_JFIF_marker = FALSE;
  166939. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  166940. cinfo->JFIF_minor_version = 1;
  166941. cinfo->density_unit = 0;
  166942. cinfo->X_density = 1;
  166943. cinfo->Y_density = 1;
  166944. cinfo->saw_Adobe_marker = FALSE;
  166945. cinfo->Adobe_transform = 0;
  166946. cinfo->marker->saw_SOI = TRUE;
  166947. return TRUE;
  166948. }
  166949. LOCAL(boolean)
  166950. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  166951. /* Process a SOFn marker */
  166952. {
  166953. INT32 length;
  166954. int c, ci;
  166955. jpeg_component_info * compptr;
  166956. INPUT_VARS(cinfo);
  166957. cinfo->progressive_mode = is_prog;
  166958. cinfo->arith_code = is_arith;
  166959. INPUT_2BYTES(cinfo, length, return FALSE);
  166960. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  166961. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  166962. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  166963. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  166964. length -= 8;
  166965. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  166966. (int) cinfo->image_width, (int) cinfo->image_height,
  166967. cinfo->num_components);
  166968. if (cinfo->marker->saw_SOF)
  166969. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  166970. /* We don't support files in which the image height is initially specified */
  166971. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  166972. /* might as well have a general sanity check. */
  166973. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  166974. || cinfo->num_components <= 0)
  166975. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  166976. if (length != (cinfo->num_components * 3))
  166977. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166978. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  166979. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  166980. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166981. cinfo->num_components * SIZEOF(jpeg_component_info));
  166982. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166983. ci++, compptr++) {
  166984. compptr->component_index = ci;
  166985. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  166986. INPUT_BYTE(cinfo, c, return FALSE);
  166987. compptr->h_samp_factor = (c >> 4) & 15;
  166988. compptr->v_samp_factor = (c ) & 15;
  166989. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  166990. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  166991. compptr->component_id, compptr->h_samp_factor,
  166992. compptr->v_samp_factor, compptr->quant_tbl_no);
  166993. }
  166994. cinfo->marker->saw_SOF = TRUE;
  166995. INPUT_SYNC(cinfo);
  166996. return TRUE;
  166997. }
  166998. LOCAL(boolean)
  166999. get_sos (j_decompress_ptr cinfo)
  167000. /* Process a SOS marker */
  167001. {
  167002. INT32 length;
  167003. int i, ci, n, c, cc;
  167004. jpeg_component_info * compptr;
  167005. INPUT_VARS(cinfo);
  167006. if (! cinfo->marker->saw_SOF)
  167007. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  167008. INPUT_2BYTES(cinfo, length, return FALSE);
  167009. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  167010. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  167011. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  167012. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167013. cinfo->comps_in_scan = n;
  167014. /* Collect the component-spec parameters */
  167015. for (i = 0; i < n; i++) {
  167016. INPUT_BYTE(cinfo, cc, return FALSE);
  167017. INPUT_BYTE(cinfo, c, return FALSE);
  167018. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167019. ci++, compptr++) {
  167020. if (cc == compptr->component_id)
  167021. goto id_found;
  167022. }
  167023. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  167024. id_found:
  167025. cinfo->cur_comp_info[i] = compptr;
  167026. compptr->dc_tbl_no = (c >> 4) & 15;
  167027. compptr->ac_tbl_no = (c ) & 15;
  167028. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  167029. compptr->dc_tbl_no, compptr->ac_tbl_no);
  167030. }
  167031. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  167032. INPUT_BYTE(cinfo, c, return FALSE);
  167033. cinfo->Ss = c;
  167034. INPUT_BYTE(cinfo, c, return FALSE);
  167035. cinfo->Se = c;
  167036. INPUT_BYTE(cinfo, c, return FALSE);
  167037. cinfo->Ah = (c >> 4) & 15;
  167038. cinfo->Al = (c ) & 15;
  167039. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  167040. cinfo->Ah, cinfo->Al);
  167041. /* Prepare to scan data & restart markers */
  167042. cinfo->marker->next_restart_num = 0;
  167043. /* Count another SOS marker */
  167044. cinfo->input_scan_number++;
  167045. INPUT_SYNC(cinfo);
  167046. return TRUE;
  167047. }
  167048. #ifdef D_ARITH_CODING_SUPPORTED
  167049. LOCAL(boolean)
  167050. get_dac (j_decompress_ptr cinfo)
  167051. /* Process a DAC marker */
  167052. {
  167053. INT32 length;
  167054. int index, val;
  167055. INPUT_VARS(cinfo);
  167056. INPUT_2BYTES(cinfo, length, return FALSE);
  167057. length -= 2;
  167058. while (length > 0) {
  167059. INPUT_BYTE(cinfo, index, return FALSE);
  167060. INPUT_BYTE(cinfo, val, return FALSE);
  167061. length -= 2;
  167062. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  167063. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  167064. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  167065. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  167066. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  167067. } else { /* define DC table */
  167068. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  167069. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  167070. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  167071. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  167072. }
  167073. }
  167074. if (length != 0)
  167075. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167076. INPUT_SYNC(cinfo);
  167077. return TRUE;
  167078. }
  167079. #else /* ! D_ARITH_CODING_SUPPORTED */
  167080. #define get_dac(cinfo) skip_variable(cinfo)
  167081. #endif /* D_ARITH_CODING_SUPPORTED */
  167082. LOCAL(boolean)
  167083. get_dht (j_decompress_ptr cinfo)
  167084. /* Process a DHT marker */
  167085. {
  167086. INT32 length;
  167087. UINT8 bits[17];
  167088. UINT8 huffval[256];
  167089. int i, index, count;
  167090. JHUFF_TBL **htblptr;
  167091. INPUT_VARS(cinfo);
  167092. INPUT_2BYTES(cinfo, length, return FALSE);
  167093. length -= 2;
  167094. while (length > 16) {
  167095. INPUT_BYTE(cinfo, index, return FALSE);
  167096. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  167097. bits[0] = 0;
  167098. count = 0;
  167099. for (i = 1; i <= 16; i++) {
  167100. INPUT_BYTE(cinfo, bits[i], return FALSE);
  167101. count += bits[i];
  167102. }
  167103. length -= 1 + 16;
  167104. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167105. bits[1], bits[2], bits[3], bits[4],
  167106. bits[5], bits[6], bits[7], bits[8]);
  167107. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167108. bits[9], bits[10], bits[11], bits[12],
  167109. bits[13], bits[14], bits[15], bits[16]);
  167110. /* Here we just do minimal validation of the counts to avoid walking
  167111. * off the end of our table space. jdhuff.c will check more carefully.
  167112. */
  167113. if (count > 256 || ((INT32) count) > length)
  167114. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167115. for (i = 0; i < count; i++)
  167116. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  167117. length -= count;
  167118. if (index & 0x10) { /* AC table definition */
  167119. index -= 0x10;
  167120. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  167121. } else { /* DC table definition */
  167122. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  167123. }
  167124. if (index < 0 || index >= NUM_HUFF_TBLS)
  167125. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  167126. if (*htblptr == NULL)
  167127. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  167128. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  167129. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  167130. }
  167131. if (length != 0)
  167132. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167133. INPUT_SYNC(cinfo);
  167134. return TRUE;
  167135. }
  167136. LOCAL(boolean)
  167137. get_dqt (j_decompress_ptr cinfo)
  167138. /* Process a DQT marker */
  167139. {
  167140. INT32 length;
  167141. int n, i, prec;
  167142. unsigned int tmp;
  167143. JQUANT_TBL *quant_ptr;
  167144. INPUT_VARS(cinfo);
  167145. INPUT_2BYTES(cinfo, length, return FALSE);
  167146. length -= 2;
  167147. while (length > 0) {
  167148. INPUT_BYTE(cinfo, n, return FALSE);
  167149. prec = n >> 4;
  167150. n &= 0x0F;
  167151. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  167152. if (n >= NUM_QUANT_TBLS)
  167153. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  167154. if (cinfo->quant_tbl_ptrs[n] == NULL)
  167155. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  167156. quant_ptr = cinfo->quant_tbl_ptrs[n];
  167157. for (i = 0; i < DCTSIZE2; i++) {
  167158. if (prec)
  167159. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167160. else
  167161. INPUT_BYTE(cinfo, tmp, return FALSE);
  167162. /* We convert the zigzag-order table to natural array order. */
  167163. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  167164. }
  167165. if (cinfo->err->trace_level >= 2) {
  167166. for (i = 0; i < DCTSIZE2; i += 8) {
  167167. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  167168. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  167169. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  167170. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  167171. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  167172. }
  167173. }
  167174. length -= DCTSIZE2+1;
  167175. if (prec) length -= DCTSIZE2;
  167176. }
  167177. if (length != 0)
  167178. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167179. INPUT_SYNC(cinfo);
  167180. return TRUE;
  167181. }
  167182. LOCAL(boolean)
  167183. get_dri (j_decompress_ptr cinfo)
  167184. /* Process a DRI marker */
  167185. {
  167186. INT32 length;
  167187. unsigned int tmp;
  167188. INPUT_VARS(cinfo);
  167189. INPUT_2BYTES(cinfo, length, return FALSE);
  167190. if (length != 4)
  167191. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167192. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167193. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  167194. cinfo->restart_interval = tmp;
  167195. INPUT_SYNC(cinfo);
  167196. return TRUE;
  167197. }
  167198. /*
  167199. * Routines for processing APPn and COM markers.
  167200. * These are either saved in memory or discarded, per application request.
  167201. * APP0 and APP14 are specially checked to see if they are
  167202. * JFIF and Adobe markers, respectively.
  167203. */
  167204. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  167205. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  167206. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  167207. LOCAL(void)
  167208. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167209. unsigned int datalen, INT32 remaining)
  167210. /* Examine first few bytes from an APP0.
  167211. * Take appropriate action if it is a JFIF marker.
  167212. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167213. */
  167214. {
  167215. INT32 totallen = (INT32) datalen + remaining;
  167216. if (datalen >= APP0_DATA_LEN &&
  167217. GETJOCTET(data[0]) == 0x4A &&
  167218. GETJOCTET(data[1]) == 0x46 &&
  167219. GETJOCTET(data[2]) == 0x49 &&
  167220. GETJOCTET(data[3]) == 0x46 &&
  167221. GETJOCTET(data[4]) == 0) {
  167222. /* Found JFIF APP0 marker: save info */
  167223. cinfo->saw_JFIF_marker = TRUE;
  167224. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  167225. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  167226. cinfo->density_unit = GETJOCTET(data[7]);
  167227. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  167228. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  167229. /* Check version.
  167230. * Major version must be 1, anything else signals an incompatible change.
  167231. * (We used to treat this as an error, but now it's a nonfatal warning,
  167232. * because some bozo at Hijaak couldn't read the spec.)
  167233. * Minor version should be 0..2, but process anyway if newer.
  167234. */
  167235. if (cinfo->JFIF_major_version != 1)
  167236. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  167237. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  167238. /* Generate trace messages */
  167239. TRACEMS5(cinfo, 1, JTRC_JFIF,
  167240. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  167241. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  167242. /* Validate thumbnail dimensions and issue appropriate messages */
  167243. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  167244. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  167245. GETJOCTET(data[12]), GETJOCTET(data[13]));
  167246. totallen -= APP0_DATA_LEN;
  167247. if (totallen !=
  167248. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  167249. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  167250. } else if (datalen >= 6 &&
  167251. GETJOCTET(data[0]) == 0x4A &&
  167252. GETJOCTET(data[1]) == 0x46 &&
  167253. GETJOCTET(data[2]) == 0x58 &&
  167254. GETJOCTET(data[3]) == 0x58 &&
  167255. GETJOCTET(data[4]) == 0) {
  167256. /* Found JFIF "JFXX" extension APP0 marker */
  167257. /* The library doesn't actually do anything with these,
  167258. * but we try to produce a helpful trace message.
  167259. */
  167260. switch (GETJOCTET(data[5])) {
  167261. case 0x10:
  167262. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  167263. break;
  167264. case 0x11:
  167265. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  167266. break;
  167267. case 0x13:
  167268. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  167269. break;
  167270. default:
  167271. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  167272. GETJOCTET(data[5]), (int) totallen);
  167273. break;
  167274. }
  167275. } else {
  167276. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  167277. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  167278. }
  167279. }
  167280. LOCAL(void)
  167281. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167282. unsigned int datalen, INT32 remaining)
  167283. /* Examine first few bytes from an APP14.
  167284. * Take appropriate action if it is an Adobe marker.
  167285. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167286. */
  167287. {
  167288. unsigned int version, flags0, flags1, transform;
  167289. if (datalen >= APP14_DATA_LEN &&
  167290. GETJOCTET(data[0]) == 0x41 &&
  167291. GETJOCTET(data[1]) == 0x64 &&
  167292. GETJOCTET(data[2]) == 0x6F &&
  167293. GETJOCTET(data[3]) == 0x62 &&
  167294. GETJOCTET(data[4]) == 0x65) {
  167295. /* Found Adobe APP14 marker */
  167296. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  167297. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  167298. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  167299. transform = GETJOCTET(data[11]);
  167300. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  167301. cinfo->saw_Adobe_marker = TRUE;
  167302. cinfo->Adobe_transform = (UINT8) transform;
  167303. } else {
  167304. /* Start of APP14 does not match "Adobe", or too short */
  167305. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  167306. }
  167307. }
  167308. METHODDEF(boolean)
  167309. get_interesting_appn (j_decompress_ptr cinfo)
  167310. /* Process an APP0 or APP14 marker without saving it */
  167311. {
  167312. INT32 length;
  167313. JOCTET b[APPN_DATA_LEN];
  167314. unsigned int i, numtoread;
  167315. INPUT_VARS(cinfo);
  167316. INPUT_2BYTES(cinfo, length, return FALSE);
  167317. length -= 2;
  167318. /* get the interesting part of the marker data */
  167319. if (length >= APPN_DATA_LEN)
  167320. numtoread = APPN_DATA_LEN;
  167321. else if (length > 0)
  167322. numtoread = (unsigned int) length;
  167323. else
  167324. numtoread = 0;
  167325. for (i = 0; i < numtoread; i++)
  167326. INPUT_BYTE(cinfo, b[i], return FALSE);
  167327. length -= numtoread;
  167328. /* process it */
  167329. switch (cinfo->unread_marker) {
  167330. case M_APP0:
  167331. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  167332. break;
  167333. case M_APP14:
  167334. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  167335. break;
  167336. default:
  167337. /* can't get here unless jpeg_save_markers chooses wrong processor */
  167338. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167339. break;
  167340. }
  167341. /* skip any remaining data -- could be lots */
  167342. INPUT_SYNC(cinfo);
  167343. if (length > 0)
  167344. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167345. return TRUE;
  167346. }
  167347. #ifdef SAVE_MARKERS_SUPPORTED
  167348. METHODDEF(boolean)
  167349. save_marker (j_decompress_ptr cinfo)
  167350. /* Save an APPn or COM marker into the marker list */
  167351. {
  167352. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167353. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  167354. unsigned int bytes_read, data_length;
  167355. JOCTET FAR * data;
  167356. INT32 length = 0;
  167357. INPUT_VARS(cinfo);
  167358. if (cur_marker == NULL) {
  167359. /* begin reading a marker */
  167360. INPUT_2BYTES(cinfo, length, return FALSE);
  167361. length -= 2;
  167362. if (length >= 0) { /* watch out for bogus length word */
  167363. /* figure out how much we want to save */
  167364. unsigned int limit;
  167365. if (cinfo->unread_marker == (int) M_COM)
  167366. limit = marker->length_limit_COM;
  167367. else
  167368. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  167369. if ((unsigned int) length < limit)
  167370. limit = (unsigned int) length;
  167371. /* allocate and initialize the marker item */
  167372. cur_marker = (jpeg_saved_marker_ptr)
  167373. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167374. SIZEOF(struct jpeg_marker_struct) + limit);
  167375. cur_marker->next = NULL;
  167376. cur_marker->marker = (UINT8) cinfo->unread_marker;
  167377. cur_marker->original_length = (unsigned int) length;
  167378. cur_marker->data_length = limit;
  167379. /* data area is just beyond the jpeg_marker_struct */
  167380. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  167381. marker->cur_marker = cur_marker;
  167382. marker->bytes_read = 0;
  167383. bytes_read = 0;
  167384. data_length = limit;
  167385. } else {
  167386. /* deal with bogus length word */
  167387. bytes_read = data_length = 0;
  167388. data = NULL;
  167389. }
  167390. } else {
  167391. /* resume reading a marker */
  167392. bytes_read = marker->bytes_read;
  167393. data_length = cur_marker->data_length;
  167394. data = cur_marker->data + bytes_read;
  167395. }
  167396. while (bytes_read < data_length) {
  167397. INPUT_SYNC(cinfo); /* move the restart point to here */
  167398. marker->bytes_read = bytes_read;
  167399. /* If there's not at least one byte in buffer, suspend */
  167400. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  167401. /* Copy bytes with reasonable rapidity */
  167402. while (bytes_read < data_length && bytes_in_buffer > 0) {
  167403. *data++ = *next_input_byte++;
  167404. bytes_in_buffer--;
  167405. bytes_read++;
  167406. }
  167407. }
  167408. /* Done reading what we want to read */
  167409. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  167410. /* Add new marker to end of list */
  167411. if (cinfo->marker_list == NULL) {
  167412. cinfo->marker_list = cur_marker;
  167413. } else {
  167414. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  167415. while (prev->next != NULL)
  167416. prev = prev->next;
  167417. prev->next = cur_marker;
  167418. }
  167419. /* Reset pointer & calc remaining data length */
  167420. data = cur_marker->data;
  167421. length = cur_marker->original_length - data_length;
  167422. }
  167423. /* Reset to initial state for next marker */
  167424. marker->cur_marker = NULL;
  167425. /* Process the marker if interesting; else just make a generic trace msg */
  167426. switch (cinfo->unread_marker) {
  167427. case M_APP0:
  167428. examine_app0(cinfo, data, data_length, length);
  167429. break;
  167430. case M_APP14:
  167431. examine_app14(cinfo, data, data_length, length);
  167432. break;
  167433. default:
  167434. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  167435. (int) (data_length + length));
  167436. break;
  167437. }
  167438. /* skip any remaining data -- could be lots */
  167439. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167440. if (length > 0)
  167441. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167442. return TRUE;
  167443. }
  167444. #endif /* SAVE_MARKERS_SUPPORTED */
  167445. METHODDEF(boolean)
  167446. skip_variable (j_decompress_ptr cinfo)
  167447. /* Skip over an unknown or uninteresting variable-length marker */
  167448. {
  167449. INT32 length;
  167450. INPUT_VARS(cinfo);
  167451. INPUT_2BYTES(cinfo, length, return FALSE);
  167452. length -= 2;
  167453. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  167454. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167455. if (length > 0)
  167456. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167457. return TRUE;
  167458. }
  167459. /*
  167460. * Find the next JPEG marker, save it in cinfo->unread_marker.
  167461. * Returns FALSE if had to suspend before reaching a marker;
  167462. * in that case cinfo->unread_marker is unchanged.
  167463. *
  167464. * Note that the result might not be a valid marker code,
  167465. * but it will never be 0 or FF.
  167466. */
  167467. LOCAL(boolean)
  167468. next_marker (j_decompress_ptr cinfo)
  167469. {
  167470. int c;
  167471. INPUT_VARS(cinfo);
  167472. for (;;) {
  167473. INPUT_BYTE(cinfo, c, return FALSE);
  167474. /* Skip any non-FF bytes.
  167475. * This may look a bit inefficient, but it will not occur in a valid file.
  167476. * We sync after each discarded byte so that a suspending data source
  167477. * can discard the byte from its buffer.
  167478. */
  167479. while (c != 0xFF) {
  167480. cinfo->marker->discarded_bytes++;
  167481. INPUT_SYNC(cinfo);
  167482. INPUT_BYTE(cinfo, c, return FALSE);
  167483. }
  167484. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  167485. * pad bytes, so don't count them in discarded_bytes. We assume there
  167486. * will not be so many consecutive FF bytes as to overflow a suspending
  167487. * data source's input buffer.
  167488. */
  167489. do {
  167490. INPUT_BYTE(cinfo, c, return FALSE);
  167491. } while (c == 0xFF);
  167492. if (c != 0)
  167493. break; /* found a valid marker, exit loop */
  167494. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  167495. * Discard it and loop back to try again.
  167496. */
  167497. cinfo->marker->discarded_bytes += 2;
  167498. INPUT_SYNC(cinfo);
  167499. }
  167500. if (cinfo->marker->discarded_bytes != 0) {
  167501. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  167502. cinfo->marker->discarded_bytes = 0;
  167503. }
  167504. cinfo->unread_marker = c;
  167505. INPUT_SYNC(cinfo);
  167506. return TRUE;
  167507. }
  167508. LOCAL(boolean)
  167509. first_marker (j_decompress_ptr cinfo)
  167510. /* Like next_marker, but used to obtain the initial SOI marker. */
  167511. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  167512. * we might well scan an entire input file before realizing it ain't JPEG.
  167513. * If an application wants to process non-JFIF files, it must seek to the
  167514. * SOI before calling the JPEG library.
  167515. */
  167516. {
  167517. int c, c2;
  167518. INPUT_VARS(cinfo);
  167519. INPUT_BYTE(cinfo, c, return FALSE);
  167520. INPUT_BYTE(cinfo, c2, return FALSE);
  167521. if (c != 0xFF || c2 != (int) M_SOI)
  167522. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  167523. cinfo->unread_marker = c2;
  167524. INPUT_SYNC(cinfo);
  167525. return TRUE;
  167526. }
  167527. /*
  167528. * Read markers until SOS or EOI.
  167529. *
  167530. * Returns same codes as are defined for jpeg_consume_input:
  167531. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167532. */
  167533. METHODDEF(int)
  167534. read_markers (j_decompress_ptr cinfo)
  167535. {
  167536. /* Outer loop repeats once for each marker. */
  167537. for (;;) {
  167538. /* Collect the marker proper, unless we already did. */
  167539. /* NB: first_marker() enforces the requirement that SOI appear first. */
  167540. if (cinfo->unread_marker == 0) {
  167541. if (! cinfo->marker->saw_SOI) {
  167542. if (! first_marker(cinfo))
  167543. return JPEG_SUSPENDED;
  167544. } else {
  167545. if (! next_marker(cinfo))
  167546. return JPEG_SUSPENDED;
  167547. }
  167548. }
  167549. /* At this point cinfo->unread_marker contains the marker code and the
  167550. * input point is just past the marker proper, but before any parameters.
  167551. * A suspension will cause us to return with this state still true.
  167552. */
  167553. switch (cinfo->unread_marker) {
  167554. case M_SOI:
  167555. if (! get_soi(cinfo))
  167556. return JPEG_SUSPENDED;
  167557. break;
  167558. case M_SOF0: /* Baseline */
  167559. case M_SOF1: /* Extended sequential, Huffman */
  167560. if (! get_sof(cinfo, FALSE, FALSE))
  167561. return JPEG_SUSPENDED;
  167562. break;
  167563. case M_SOF2: /* Progressive, Huffman */
  167564. if (! get_sof(cinfo, TRUE, FALSE))
  167565. return JPEG_SUSPENDED;
  167566. break;
  167567. case M_SOF9: /* Extended sequential, arithmetic */
  167568. if (! get_sof(cinfo, FALSE, TRUE))
  167569. return JPEG_SUSPENDED;
  167570. break;
  167571. case M_SOF10: /* Progressive, arithmetic */
  167572. if (! get_sof(cinfo, TRUE, TRUE))
  167573. return JPEG_SUSPENDED;
  167574. break;
  167575. /* Currently unsupported SOFn types */
  167576. case M_SOF3: /* Lossless, Huffman */
  167577. case M_SOF5: /* Differential sequential, Huffman */
  167578. case M_SOF6: /* Differential progressive, Huffman */
  167579. case M_SOF7: /* Differential lossless, Huffman */
  167580. case M_JPG: /* Reserved for JPEG extensions */
  167581. case M_SOF11: /* Lossless, arithmetic */
  167582. case M_SOF13: /* Differential sequential, arithmetic */
  167583. case M_SOF14: /* Differential progressive, arithmetic */
  167584. case M_SOF15: /* Differential lossless, arithmetic */
  167585. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  167586. break;
  167587. case M_SOS:
  167588. if (! get_sos(cinfo))
  167589. return JPEG_SUSPENDED;
  167590. cinfo->unread_marker = 0; /* processed the marker */
  167591. return JPEG_REACHED_SOS;
  167592. case M_EOI:
  167593. TRACEMS(cinfo, 1, JTRC_EOI);
  167594. cinfo->unread_marker = 0; /* processed the marker */
  167595. return JPEG_REACHED_EOI;
  167596. case M_DAC:
  167597. if (! get_dac(cinfo))
  167598. return JPEG_SUSPENDED;
  167599. break;
  167600. case M_DHT:
  167601. if (! get_dht(cinfo))
  167602. return JPEG_SUSPENDED;
  167603. break;
  167604. case M_DQT:
  167605. if (! get_dqt(cinfo))
  167606. return JPEG_SUSPENDED;
  167607. break;
  167608. case M_DRI:
  167609. if (! get_dri(cinfo))
  167610. return JPEG_SUSPENDED;
  167611. break;
  167612. case M_APP0:
  167613. case M_APP1:
  167614. case M_APP2:
  167615. case M_APP3:
  167616. case M_APP4:
  167617. case M_APP5:
  167618. case M_APP6:
  167619. case M_APP7:
  167620. case M_APP8:
  167621. case M_APP9:
  167622. case M_APP10:
  167623. case M_APP11:
  167624. case M_APP12:
  167625. case M_APP13:
  167626. case M_APP14:
  167627. case M_APP15:
  167628. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  167629. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  167630. return JPEG_SUSPENDED;
  167631. break;
  167632. case M_COM:
  167633. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  167634. return JPEG_SUSPENDED;
  167635. break;
  167636. case M_RST0: /* these are all parameterless */
  167637. case M_RST1:
  167638. case M_RST2:
  167639. case M_RST3:
  167640. case M_RST4:
  167641. case M_RST5:
  167642. case M_RST6:
  167643. case M_RST7:
  167644. case M_TEM:
  167645. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  167646. break;
  167647. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  167648. if (! skip_variable(cinfo))
  167649. return JPEG_SUSPENDED;
  167650. break;
  167651. default: /* must be DHP, EXP, JPGn, or RESn */
  167652. /* For now, we treat the reserved markers as fatal errors since they are
  167653. * likely to be used to signal incompatible JPEG Part 3 extensions.
  167654. * Once the JPEG 3 version-number marker is well defined, this code
  167655. * ought to change!
  167656. */
  167657. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167658. break;
  167659. }
  167660. /* Successfully processed marker, so reset state variable */
  167661. cinfo->unread_marker = 0;
  167662. } /* end loop */
  167663. }
  167664. /*
  167665. * Read a restart marker, which is expected to appear next in the datastream;
  167666. * if the marker is not there, take appropriate recovery action.
  167667. * Returns FALSE if suspension is required.
  167668. *
  167669. * This is called by the entropy decoder after it has read an appropriate
  167670. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  167671. * has already read a marker from the data source. Under normal conditions
  167672. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  167673. * it holds a marker which the decoder will be unable to read past.
  167674. */
  167675. METHODDEF(boolean)
  167676. read_restart_marker (j_decompress_ptr cinfo)
  167677. {
  167678. /* Obtain a marker unless we already did. */
  167679. /* Note that next_marker will complain if it skips any data. */
  167680. if (cinfo->unread_marker == 0) {
  167681. if (! next_marker(cinfo))
  167682. return FALSE;
  167683. }
  167684. if (cinfo->unread_marker ==
  167685. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  167686. /* Normal case --- swallow the marker and let entropy decoder continue */
  167687. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  167688. cinfo->unread_marker = 0;
  167689. } else {
  167690. /* Uh-oh, the restart markers have been messed up. */
  167691. /* Let the data source manager determine how to resync. */
  167692. if (! (*cinfo->src->resync_to_restart) (cinfo,
  167693. cinfo->marker->next_restart_num))
  167694. return FALSE;
  167695. }
  167696. /* Update next-restart state */
  167697. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  167698. return TRUE;
  167699. }
  167700. /*
  167701. * This is the default resync_to_restart method for data source managers
  167702. * to use if they don't have any better approach. Some data source managers
  167703. * may be able to back up, or may have additional knowledge about the data
  167704. * which permits a more intelligent recovery strategy; such managers would
  167705. * presumably supply their own resync method.
  167706. *
  167707. * read_restart_marker calls resync_to_restart if it finds a marker other than
  167708. * the restart marker it was expecting. (This code is *not* used unless
  167709. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  167710. * the marker code actually found (might be anything, except 0 or FF).
  167711. * The desired restart marker number (0..7) is passed as a parameter.
  167712. * This routine is supposed to apply whatever error recovery strategy seems
  167713. * appropriate in order to position the input stream to the next data segment.
  167714. * Note that cinfo->unread_marker is treated as a marker appearing before
  167715. * the current data-source input point; usually it should be reset to zero
  167716. * before returning.
  167717. * Returns FALSE if suspension is required.
  167718. *
  167719. * This implementation is substantially constrained by wanting to treat the
  167720. * input as a data stream; this means we can't back up. Therefore, we have
  167721. * only the following actions to work with:
  167722. * 1. Simply discard the marker and let the entropy decoder resume at next
  167723. * byte of file.
  167724. * 2. Read forward until we find another marker, discarding intervening
  167725. * data. (In theory we could look ahead within the current bufferload,
  167726. * without having to discard data if we don't find the desired marker.
  167727. * This idea is not implemented here, in part because it makes behavior
  167728. * dependent on buffer size and chance buffer-boundary positions.)
  167729. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  167730. * This will cause the entropy decoder to process an empty data segment,
  167731. * inserting dummy zeroes, and then we will reprocess the marker.
  167732. *
  167733. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  167734. * appropriate if the found marker is a future restart marker (indicating
  167735. * that we have missed the desired restart marker, probably because it got
  167736. * corrupted).
  167737. * We apply #2 or #3 if the found marker is a restart marker no more than
  167738. * two counts behind or ahead of the expected one. We also apply #2 if the
  167739. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  167740. * If the found marker is a restart marker more than 2 counts away, we do #1
  167741. * (too much risk that the marker is erroneous; with luck we will be able to
  167742. * resync at some future point).
  167743. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  167744. * overrunning the end of a scan. An implementation limited to single-scan
  167745. * files might find it better to apply #2 for markers other than EOI, since
  167746. * any other marker would have to be bogus data in that case.
  167747. */
  167748. GLOBAL(boolean)
  167749. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  167750. {
  167751. int marker = cinfo->unread_marker;
  167752. int action = 1;
  167753. /* Always put up a warning. */
  167754. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  167755. /* Outer loop handles repeated decision after scanning forward. */
  167756. for (;;) {
  167757. if (marker < (int) M_SOF0)
  167758. action = 2; /* invalid marker */
  167759. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  167760. action = 3; /* valid non-restart marker */
  167761. else {
  167762. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  167763. marker == ((int) M_RST0 + ((desired+2) & 7)))
  167764. action = 3; /* one of the next two expected restarts */
  167765. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  167766. marker == ((int) M_RST0 + ((desired-2) & 7)))
  167767. action = 2; /* a prior restart, so advance */
  167768. else
  167769. action = 1; /* desired restart or too far away */
  167770. }
  167771. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  167772. switch (action) {
  167773. case 1:
  167774. /* Discard marker and let entropy decoder resume processing. */
  167775. cinfo->unread_marker = 0;
  167776. return TRUE;
  167777. case 2:
  167778. /* Scan to the next marker, and repeat the decision loop. */
  167779. if (! next_marker(cinfo))
  167780. return FALSE;
  167781. marker = cinfo->unread_marker;
  167782. break;
  167783. case 3:
  167784. /* Return without advancing past this marker. */
  167785. /* Entropy decoder will be forced to process an empty segment. */
  167786. return TRUE;
  167787. }
  167788. } /* end loop */
  167789. }
  167790. /*
  167791. * Reset marker processing state to begin a fresh datastream.
  167792. */
  167793. METHODDEF(void)
  167794. reset_marker_reader (j_decompress_ptr cinfo)
  167795. {
  167796. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167797. cinfo->comp_info = NULL; /* until allocated by get_sof */
  167798. cinfo->input_scan_number = 0; /* no SOS seen yet */
  167799. cinfo->unread_marker = 0; /* no pending marker */
  167800. marker->pub.saw_SOI = FALSE; /* set internal state too */
  167801. marker->pub.saw_SOF = FALSE;
  167802. marker->pub.discarded_bytes = 0;
  167803. marker->cur_marker = NULL;
  167804. }
  167805. /*
  167806. * Initialize the marker reader module.
  167807. * This is called only once, when the decompression object is created.
  167808. */
  167809. GLOBAL(void)
  167810. jinit_marker_reader (j_decompress_ptr cinfo)
  167811. {
  167812. my_marker_ptr2 marker;
  167813. int i;
  167814. /* Create subobject in permanent pool */
  167815. marker = (my_marker_ptr2)
  167816. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167817. SIZEOF(my_marker_reader));
  167818. cinfo->marker = (struct jpeg_marker_reader *) marker;
  167819. /* Initialize public method pointers */
  167820. marker->pub.reset_marker_reader = reset_marker_reader;
  167821. marker->pub.read_markers = read_markers;
  167822. marker->pub.read_restart_marker = read_restart_marker;
  167823. /* Initialize COM/APPn processing.
  167824. * By default, we examine and then discard APP0 and APP14,
  167825. * but simply discard COM and all other APPn.
  167826. */
  167827. marker->process_COM = skip_variable;
  167828. marker->length_limit_COM = 0;
  167829. for (i = 0; i < 16; i++) {
  167830. marker->process_APPn[i] = skip_variable;
  167831. marker->length_limit_APPn[i] = 0;
  167832. }
  167833. marker->process_APPn[0] = get_interesting_appn;
  167834. marker->process_APPn[14] = get_interesting_appn;
  167835. /* Reset marker processing state */
  167836. reset_marker_reader(cinfo);
  167837. }
  167838. /*
  167839. * Control saving of COM and APPn markers into marker_list.
  167840. */
  167841. #ifdef SAVE_MARKERS_SUPPORTED
  167842. GLOBAL(void)
  167843. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  167844. unsigned int length_limit)
  167845. {
  167846. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167847. long maxlength;
  167848. jpeg_marker_parser_method processor;
  167849. /* Length limit mustn't be larger than what we can allocate
  167850. * (should only be a concern in a 16-bit environment).
  167851. */
  167852. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  167853. if (((long) length_limit) > maxlength)
  167854. length_limit = (unsigned int) maxlength;
  167855. /* Choose processor routine to use.
  167856. * APP0/APP14 have special requirements.
  167857. */
  167858. if (length_limit) {
  167859. processor = save_marker;
  167860. /* If saving APP0/APP14, save at least enough for our internal use. */
  167861. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  167862. length_limit = APP0_DATA_LEN;
  167863. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  167864. length_limit = APP14_DATA_LEN;
  167865. } else {
  167866. processor = skip_variable;
  167867. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  167868. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  167869. processor = get_interesting_appn;
  167870. }
  167871. if (marker_code == (int) M_COM) {
  167872. marker->process_COM = processor;
  167873. marker->length_limit_COM = length_limit;
  167874. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  167875. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  167876. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  167877. } else
  167878. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167879. }
  167880. #endif /* SAVE_MARKERS_SUPPORTED */
  167881. /*
  167882. * Install a special processing method for COM or APPn markers.
  167883. */
  167884. GLOBAL(void)
  167885. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  167886. jpeg_marker_parser_method routine)
  167887. {
  167888. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167889. if (marker_code == (int) M_COM)
  167890. marker->process_COM = routine;
  167891. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  167892. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  167893. else
  167894. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167895. }
  167896. /********* End of inlined file: jdmarker.c *********/
  167897. /********* Start of inlined file: jdmaster.c *********/
  167898. #define JPEG_INTERNALS
  167899. /* Private state */
  167900. typedef struct {
  167901. struct jpeg_decomp_master pub; /* public fields */
  167902. int pass_number; /* # of passes completed */
  167903. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  167904. /* Saved references to initialized quantizer modules,
  167905. * in case we need to switch modes.
  167906. */
  167907. struct jpeg_color_quantizer * quantizer_1pass;
  167908. struct jpeg_color_quantizer * quantizer_2pass;
  167909. } my_decomp_master;
  167910. typedef my_decomp_master * my_master_ptr6;
  167911. /*
  167912. * Determine whether merged upsample/color conversion should be used.
  167913. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  167914. */
  167915. LOCAL(boolean)
  167916. use_merged_upsample (j_decompress_ptr cinfo)
  167917. {
  167918. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167919. /* Merging is the equivalent of plain box-filter upsampling */
  167920. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  167921. return FALSE;
  167922. /* jdmerge.c only supports YCC=>RGB color conversion */
  167923. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  167924. cinfo->out_color_space != JCS_RGB ||
  167925. cinfo->out_color_components != RGB_PIXELSIZE)
  167926. return FALSE;
  167927. /* and it only handles 2h1v or 2h2v sampling ratios */
  167928. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  167929. cinfo->comp_info[1].h_samp_factor != 1 ||
  167930. cinfo->comp_info[2].h_samp_factor != 1 ||
  167931. cinfo->comp_info[0].v_samp_factor > 2 ||
  167932. cinfo->comp_info[1].v_samp_factor != 1 ||
  167933. cinfo->comp_info[2].v_samp_factor != 1)
  167934. return FALSE;
  167935. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  167936. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167937. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167938. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  167939. return FALSE;
  167940. /* ??? also need to test for upsample-time rescaling, when & if supported */
  167941. return TRUE; /* by golly, it'll work... */
  167942. #else
  167943. return FALSE;
  167944. #endif
  167945. }
  167946. /*
  167947. * Compute output image dimensions and related values.
  167948. * NOTE: this is exported for possible use by application.
  167949. * Hence it mustn't do anything that can't be done twice.
  167950. * Also note that it may be called before the master module is initialized!
  167951. */
  167952. GLOBAL(void)
  167953. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  167954. /* Do computations that are needed before master selection phase */
  167955. {
  167956. #ifdef IDCT_SCALING_SUPPORTED
  167957. int ci;
  167958. jpeg_component_info *compptr;
  167959. #endif
  167960. /* Prevent application from calling me at wrong times */
  167961. if (cinfo->global_state != DSTATE_READY)
  167962. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167963. #ifdef IDCT_SCALING_SUPPORTED
  167964. /* Compute actual output image dimensions and DCT scaling choices. */
  167965. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  167966. /* Provide 1/8 scaling */
  167967. cinfo->output_width = (JDIMENSION)
  167968. jdiv_round_up((long) cinfo->image_width, 8L);
  167969. cinfo->output_height = (JDIMENSION)
  167970. jdiv_round_up((long) cinfo->image_height, 8L);
  167971. cinfo->min_DCT_scaled_size = 1;
  167972. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  167973. /* Provide 1/4 scaling */
  167974. cinfo->output_width = (JDIMENSION)
  167975. jdiv_round_up((long) cinfo->image_width, 4L);
  167976. cinfo->output_height = (JDIMENSION)
  167977. jdiv_round_up((long) cinfo->image_height, 4L);
  167978. cinfo->min_DCT_scaled_size = 2;
  167979. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  167980. /* Provide 1/2 scaling */
  167981. cinfo->output_width = (JDIMENSION)
  167982. jdiv_round_up((long) cinfo->image_width, 2L);
  167983. cinfo->output_height = (JDIMENSION)
  167984. jdiv_round_up((long) cinfo->image_height, 2L);
  167985. cinfo->min_DCT_scaled_size = 4;
  167986. } else {
  167987. /* Provide 1/1 scaling */
  167988. cinfo->output_width = cinfo->image_width;
  167989. cinfo->output_height = cinfo->image_height;
  167990. cinfo->min_DCT_scaled_size = DCTSIZE;
  167991. }
  167992. /* In selecting the actual DCT scaling for each component, we try to
  167993. * scale up the chroma components via IDCT scaling rather than upsampling.
  167994. * This saves time if the upsampler gets to use 1:1 scaling.
  167995. * Note this code assumes that the supported DCT scalings are powers of 2.
  167996. */
  167997. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167998. ci++, compptr++) {
  167999. int ssize = cinfo->min_DCT_scaled_size;
  168000. while (ssize < DCTSIZE &&
  168001. (compptr->h_samp_factor * ssize * 2 <=
  168002. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  168003. (compptr->v_samp_factor * ssize * 2 <=
  168004. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  168005. ssize = ssize * 2;
  168006. }
  168007. compptr->DCT_scaled_size = ssize;
  168008. }
  168009. /* Recompute downsampled dimensions of components;
  168010. * application needs to know these if using raw downsampled data.
  168011. */
  168012. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168013. ci++, compptr++) {
  168014. /* Size in samples, after IDCT scaling */
  168015. compptr->downsampled_width = (JDIMENSION)
  168016. jdiv_round_up((long) cinfo->image_width *
  168017. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  168018. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  168019. compptr->downsampled_height = (JDIMENSION)
  168020. jdiv_round_up((long) cinfo->image_height *
  168021. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  168022. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  168023. }
  168024. #else /* !IDCT_SCALING_SUPPORTED */
  168025. /* Hardwire it to "no scaling" */
  168026. cinfo->output_width = cinfo->image_width;
  168027. cinfo->output_height = cinfo->image_height;
  168028. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  168029. * and has computed unscaled downsampled_width and downsampled_height.
  168030. */
  168031. #endif /* IDCT_SCALING_SUPPORTED */
  168032. /* Report number of components in selected colorspace. */
  168033. /* Probably this should be in the color conversion module... */
  168034. switch (cinfo->out_color_space) {
  168035. case JCS_GRAYSCALE:
  168036. cinfo->out_color_components = 1;
  168037. break;
  168038. case JCS_RGB:
  168039. #if RGB_PIXELSIZE != 3
  168040. cinfo->out_color_components = RGB_PIXELSIZE;
  168041. break;
  168042. #endif /* else share code with YCbCr */
  168043. case JCS_YCbCr:
  168044. cinfo->out_color_components = 3;
  168045. break;
  168046. case JCS_CMYK:
  168047. case JCS_YCCK:
  168048. cinfo->out_color_components = 4;
  168049. break;
  168050. default: /* else must be same colorspace as in file */
  168051. cinfo->out_color_components = cinfo->num_components;
  168052. break;
  168053. }
  168054. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  168055. cinfo->out_color_components);
  168056. /* See if upsampler will want to emit more than one row at a time */
  168057. if (use_merged_upsample(cinfo))
  168058. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  168059. else
  168060. cinfo->rec_outbuf_height = 1;
  168061. }
  168062. /*
  168063. * Several decompression processes need to range-limit values to the range
  168064. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  168065. * due to noise introduced by quantization, roundoff error, etc. These
  168066. * processes are inner loops and need to be as fast as possible. On most
  168067. * machines, particularly CPUs with pipelines or instruction prefetch,
  168068. * a (subscript-check-less) C table lookup
  168069. * x = sample_range_limit[x];
  168070. * is faster than explicit tests
  168071. * if (x < 0) x = 0;
  168072. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  168073. * These processes all use a common table prepared by the routine below.
  168074. *
  168075. * For most steps we can mathematically guarantee that the initial value
  168076. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  168077. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  168078. * limiting step (just after the IDCT), a wildly out-of-range value is
  168079. * possible if the input data is corrupt. To avoid any chance of indexing
  168080. * off the end of memory and getting a bad-pointer trap, we perform the
  168081. * post-IDCT limiting thus:
  168082. * x = range_limit[x & MASK];
  168083. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  168084. * samples. Under normal circumstances this is more than enough range and
  168085. * a correct output will be generated; with bogus input data the mask will
  168086. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  168087. * For the post-IDCT step, we want to convert the data from signed to unsigned
  168088. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  168089. * So the post-IDCT limiting table ends up looking like this:
  168090. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  168091. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168092. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168093. * 0,1,...,CENTERJSAMPLE-1
  168094. * Negative inputs select values from the upper half of the table after
  168095. * masking.
  168096. *
  168097. * We can save some space by overlapping the start of the post-IDCT table
  168098. * with the simpler range limiting table. The post-IDCT table begins at
  168099. * sample_range_limit + CENTERJSAMPLE.
  168100. *
  168101. * Note that the table is allocated in near data space on PCs; it's small
  168102. * enough and used often enough to justify this.
  168103. */
  168104. LOCAL(void)
  168105. prepare_range_limit_table (j_decompress_ptr cinfo)
  168106. /* Allocate and fill in the sample_range_limit table */
  168107. {
  168108. JSAMPLE * table;
  168109. int i;
  168110. table = (JSAMPLE *)
  168111. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168112. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168113. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  168114. cinfo->sample_range_limit = table;
  168115. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  168116. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  168117. /* Main part of "simple" table: limit[x] = x */
  168118. for (i = 0; i <= MAXJSAMPLE; i++)
  168119. table[i] = (JSAMPLE) i;
  168120. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  168121. /* End of simple table, rest of first half of post-IDCT table */
  168122. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  168123. table[i] = MAXJSAMPLE;
  168124. /* Second half of post-IDCT table */
  168125. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  168126. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168127. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  168128. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  168129. }
  168130. /*
  168131. * Master selection of decompression modules.
  168132. * This is done once at jpeg_start_decompress time. We determine
  168133. * which modules will be used and give them appropriate initialization calls.
  168134. * We also initialize the decompressor input side to begin consuming data.
  168135. *
  168136. * Since jpeg_read_header has finished, we know what is in the SOF
  168137. * and (first) SOS markers. We also have all the application parameter
  168138. * settings.
  168139. */
  168140. LOCAL(void)
  168141. master_selection (j_decompress_ptr cinfo)
  168142. {
  168143. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168144. boolean use_c_buffer;
  168145. long samplesperrow;
  168146. JDIMENSION jd_samplesperrow;
  168147. /* Initialize dimensions and other stuff */
  168148. jpeg_calc_output_dimensions(cinfo);
  168149. prepare_range_limit_table(cinfo);
  168150. /* Width of an output scanline must be representable as JDIMENSION. */
  168151. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  168152. jd_samplesperrow = (JDIMENSION) samplesperrow;
  168153. if ((long) jd_samplesperrow != samplesperrow)
  168154. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  168155. /* Initialize my private state */
  168156. master->pass_number = 0;
  168157. master->using_merged_upsample = use_merged_upsample(cinfo);
  168158. /* Color quantizer selection */
  168159. master->quantizer_1pass = NULL;
  168160. master->quantizer_2pass = NULL;
  168161. /* No mode changes if not using buffered-image mode. */
  168162. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  168163. cinfo->enable_1pass_quant = FALSE;
  168164. cinfo->enable_external_quant = FALSE;
  168165. cinfo->enable_2pass_quant = FALSE;
  168166. }
  168167. if (cinfo->quantize_colors) {
  168168. if (cinfo->raw_data_out)
  168169. ERREXIT(cinfo, JERR_NOTIMPL);
  168170. /* 2-pass quantizer only works in 3-component color space. */
  168171. if (cinfo->out_color_components != 3) {
  168172. cinfo->enable_1pass_quant = TRUE;
  168173. cinfo->enable_external_quant = FALSE;
  168174. cinfo->enable_2pass_quant = FALSE;
  168175. cinfo->colormap = NULL;
  168176. } else if (cinfo->colormap != NULL) {
  168177. cinfo->enable_external_quant = TRUE;
  168178. } else if (cinfo->two_pass_quantize) {
  168179. cinfo->enable_2pass_quant = TRUE;
  168180. } else {
  168181. cinfo->enable_1pass_quant = TRUE;
  168182. }
  168183. if (cinfo->enable_1pass_quant) {
  168184. #ifdef QUANT_1PASS_SUPPORTED
  168185. jinit_1pass_quantizer(cinfo);
  168186. master->quantizer_1pass = cinfo->cquantize;
  168187. #else
  168188. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168189. #endif
  168190. }
  168191. /* We use the 2-pass code to map to external colormaps. */
  168192. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  168193. #ifdef QUANT_2PASS_SUPPORTED
  168194. jinit_2pass_quantizer(cinfo);
  168195. master->quantizer_2pass = cinfo->cquantize;
  168196. #else
  168197. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168198. #endif
  168199. }
  168200. /* If both quantizers are initialized, the 2-pass one is left active;
  168201. * this is necessary for starting with quantization to an external map.
  168202. */
  168203. }
  168204. /* Post-processing: in particular, color conversion first */
  168205. if (! cinfo->raw_data_out) {
  168206. if (master->using_merged_upsample) {
  168207. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168208. jinit_merged_upsampler(cinfo); /* does color conversion too */
  168209. #else
  168210. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168211. #endif
  168212. } else {
  168213. jinit_color_deconverter(cinfo);
  168214. jinit_upsampler(cinfo);
  168215. }
  168216. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  168217. }
  168218. /* Inverse DCT */
  168219. jinit_inverse_dct(cinfo);
  168220. /* Entropy decoding: either Huffman or arithmetic coding. */
  168221. if (cinfo->arith_code) {
  168222. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168223. } else {
  168224. if (cinfo->progressive_mode) {
  168225. #ifdef D_PROGRESSIVE_SUPPORTED
  168226. jinit_phuff_decoder(cinfo);
  168227. #else
  168228. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168229. #endif
  168230. } else
  168231. jinit_huff_decoder(cinfo);
  168232. }
  168233. /* Initialize principal buffer controllers. */
  168234. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  168235. jinit_d_coef_controller(cinfo, use_c_buffer);
  168236. if (! cinfo->raw_data_out)
  168237. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  168238. /* We can now tell the memory manager to allocate virtual arrays. */
  168239. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168240. /* Initialize input side of decompressor to consume first scan. */
  168241. (*cinfo->inputctl->start_input_pass) (cinfo);
  168242. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168243. /* If jpeg_start_decompress will read the whole file, initialize
  168244. * progress monitoring appropriately. The input step is counted
  168245. * as one pass.
  168246. */
  168247. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  168248. cinfo->inputctl->has_multiple_scans) {
  168249. int nscans;
  168250. /* Estimate number of scans to set pass_limit. */
  168251. if (cinfo->progressive_mode) {
  168252. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168253. nscans = 2 + 3 * cinfo->num_components;
  168254. } else {
  168255. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168256. nscans = cinfo->num_components;
  168257. }
  168258. cinfo->progress->pass_counter = 0L;
  168259. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168260. cinfo->progress->completed_passes = 0;
  168261. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  168262. /* Count the input pass as done */
  168263. master->pass_number++;
  168264. }
  168265. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168266. }
  168267. /*
  168268. * Per-pass setup.
  168269. * This is called at the beginning of each output pass. We determine which
  168270. * modules will be active during this pass and give them appropriate
  168271. * start_pass calls. We also set is_dummy_pass to indicate whether this
  168272. * is a "real" output pass or a dummy pass for color quantization.
  168273. * (In the latter case, jdapistd.c will crank the pass to completion.)
  168274. */
  168275. METHODDEF(void)
  168276. prepare_for_output_pass (j_decompress_ptr cinfo)
  168277. {
  168278. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168279. if (master->pub.is_dummy_pass) {
  168280. #ifdef QUANT_2PASS_SUPPORTED
  168281. /* Final pass of 2-pass quantization */
  168282. master->pub.is_dummy_pass = FALSE;
  168283. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  168284. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  168285. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  168286. #else
  168287. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168288. #endif /* QUANT_2PASS_SUPPORTED */
  168289. } else {
  168290. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  168291. /* Select new quantization method */
  168292. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  168293. cinfo->cquantize = master->quantizer_2pass;
  168294. master->pub.is_dummy_pass = TRUE;
  168295. } else if (cinfo->enable_1pass_quant) {
  168296. cinfo->cquantize = master->quantizer_1pass;
  168297. } else {
  168298. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168299. }
  168300. }
  168301. (*cinfo->idct->start_pass) (cinfo);
  168302. (*cinfo->coef->start_output_pass) (cinfo);
  168303. if (! cinfo->raw_data_out) {
  168304. if (! master->using_merged_upsample)
  168305. (*cinfo->cconvert->start_pass) (cinfo);
  168306. (*cinfo->upsample->start_pass) (cinfo);
  168307. if (cinfo->quantize_colors)
  168308. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  168309. (*cinfo->post->start_pass) (cinfo,
  168310. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  168311. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  168312. }
  168313. }
  168314. /* Set up progress monitor's pass info if present */
  168315. if (cinfo->progress != NULL) {
  168316. cinfo->progress->completed_passes = master->pass_number;
  168317. cinfo->progress->total_passes = master->pass_number +
  168318. (master->pub.is_dummy_pass ? 2 : 1);
  168319. /* In buffered-image mode, we assume one more output pass if EOI not
  168320. * yet reached, but no more passes if EOI has been reached.
  168321. */
  168322. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  168323. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  168324. }
  168325. }
  168326. }
  168327. /*
  168328. * Finish up at end of an output pass.
  168329. */
  168330. METHODDEF(void)
  168331. finish_output_pass (j_decompress_ptr cinfo)
  168332. {
  168333. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168334. if (cinfo->quantize_colors)
  168335. (*cinfo->cquantize->finish_pass) (cinfo);
  168336. master->pass_number++;
  168337. }
  168338. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168339. /*
  168340. * Switch to a new external colormap between output passes.
  168341. */
  168342. GLOBAL(void)
  168343. jpeg_new_colormap (j_decompress_ptr cinfo)
  168344. {
  168345. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168346. /* Prevent application from calling me at wrong times */
  168347. if (cinfo->global_state != DSTATE_BUFIMAGE)
  168348. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168349. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  168350. cinfo->colormap != NULL) {
  168351. /* Select 2-pass quantizer for external colormap use */
  168352. cinfo->cquantize = master->quantizer_2pass;
  168353. /* Notify quantizer of colormap change */
  168354. (*cinfo->cquantize->new_color_map) (cinfo);
  168355. master->pub.is_dummy_pass = FALSE; /* just in case */
  168356. } else
  168357. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168358. }
  168359. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168360. /*
  168361. * Initialize master decompression control and select active modules.
  168362. * This is performed at the start of jpeg_start_decompress.
  168363. */
  168364. GLOBAL(void)
  168365. jinit_master_decompress (j_decompress_ptr cinfo)
  168366. {
  168367. my_master_ptr6 master;
  168368. master = (my_master_ptr6)
  168369. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168370. SIZEOF(my_decomp_master));
  168371. cinfo->master = (struct jpeg_decomp_master *) master;
  168372. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  168373. master->pub.finish_output_pass = finish_output_pass;
  168374. master->pub.is_dummy_pass = FALSE;
  168375. master_selection(cinfo);
  168376. }
  168377. /********* End of inlined file: jdmaster.c *********/
  168378. #undef FIX
  168379. /********* Start of inlined file: jdmerge.c *********/
  168380. #define JPEG_INTERNALS
  168381. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168382. /* Private subobject */
  168383. typedef struct {
  168384. struct jpeg_upsampler pub; /* public fields */
  168385. /* Pointer to routine to do actual upsampling/conversion of one row group */
  168386. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  168387. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168388. JSAMPARRAY output_buf));
  168389. /* Private state for YCC->RGB conversion */
  168390. int * Cr_r_tab; /* => table for Cr to R conversion */
  168391. int * Cb_b_tab; /* => table for Cb to B conversion */
  168392. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168393. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168394. /* For 2:1 vertical sampling, we produce two output rows at a time.
  168395. * We need a "spare" row buffer to hold the second output row if the
  168396. * application provides just a one-row buffer; we also use the spare
  168397. * to discard the dummy last row if the image height is odd.
  168398. */
  168399. JSAMPROW spare_row;
  168400. boolean spare_full; /* T if spare buffer is occupied */
  168401. JDIMENSION out_row_width; /* samples per output row */
  168402. JDIMENSION rows_to_go; /* counts rows remaining in image */
  168403. } my_upsampler;
  168404. typedef my_upsampler * my_upsample_ptr;
  168405. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168406. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168407. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168408. /*
  168409. * Initialize tables for YCC->RGB colorspace conversion.
  168410. * This is taken directly from jdcolor.c; see that file for more info.
  168411. */
  168412. LOCAL(void)
  168413. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  168414. {
  168415. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168416. int i;
  168417. INT32 x;
  168418. SHIFT_TEMPS
  168419. upsample->Cr_r_tab = (int *)
  168420. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168421. (MAXJSAMPLE+1) * SIZEOF(int));
  168422. upsample->Cb_b_tab = (int *)
  168423. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168424. (MAXJSAMPLE+1) * SIZEOF(int));
  168425. upsample->Cr_g_tab = (INT32 *)
  168426. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168427. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168428. upsample->Cb_g_tab = (INT32 *)
  168429. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168430. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168431. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168432. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168433. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168434. /* Cr=>R value is nearest int to 1.40200 * x */
  168435. upsample->Cr_r_tab[i] = (int)
  168436. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168437. /* Cb=>B value is nearest int to 1.77200 * x */
  168438. upsample->Cb_b_tab[i] = (int)
  168439. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168440. /* Cr=>G value is scaled-up -0.71414 * x */
  168441. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168442. /* Cb=>G value is scaled-up -0.34414 * x */
  168443. /* We also add in ONE_HALF so that need not do it in inner loop */
  168444. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168445. }
  168446. }
  168447. /*
  168448. * Initialize for an upsampling pass.
  168449. */
  168450. METHODDEF(void)
  168451. start_pass_merged_upsample (j_decompress_ptr cinfo)
  168452. {
  168453. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168454. /* Mark the spare buffer empty */
  168455. upsample->spare_full = FALSE;
  168456. /* Initialize total-height counter for detecting bottom of image */
  168457. upsample->rows_to_go = cinfo->output_height;
  168458. }
  168459. /*
  168460. * Control routine to do upsampling (and color conversion).
  168461. *
  168462. * The control routine just handles the row buffering considerations.
  168463. */
  168464. METHODDEF(void)
  168465. merged_2v_upsample (j_decompress_ptr cinfo,
  168466. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168467. JDIMENSION in_row_groups_avail,
  168468. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168469. JDIMENSION out_rows_avail)
  168470. /* 2:1 vertical sampling case: may need a spare row. */
  168471. {
  168472. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168473. JSAMPROW work_ptrs[2];
  168474. JDIMENSION num_rows; /* number of rows returned to caller */
  168475. if (upsample->spare_full) {
  168476. /* If we have a spare row saved from a previous cycle, just return it. */
  168477. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  168478. 1, upsample->out_row_width);
  168479. num_rows = 1;
  168480. upsample->spare_full = FALSE;
  168481. } else {
  168482. /* Figure number of rows to return to caller. */
  168483. num_rows = 2;
  168484. /* Not more than the distance to the end of the image. */
  168485. if (num_rows > upsample->rows_to_go)
  168486. num_rows = upsample->rows_to_go;
  168487. /* And not more than what the client can accept: */
  168488. out_rows_avail -= *out_row_ctr;
  168489. if (num_rows > out_rows_avail)
  168490. num_rows = out_rows_avail;
  168491. /* Create output pointer array for upsampler. */
  168492. work_ptrs[0] = output_buf[*out_row_ctr];
  168493. if (num_rows > 1) {
  168494. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  168495. } else {
  168496. work_ptrs[1] = upsample->spare_row;
  168497. upsample->spare_full = TRUE;
  168498. }
  168499. /* Now do the upsampling. */
  168500. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  168501. }
  168502. /* Adjust counts */
  168503. *out_row_ctr += num_rows;
  168504. upsample->rows_to_go -= num_rows;
  168505. /* When the buffer is emptied, declare this input row group consumed */
  168506. if (! upsample->spare_full)
  168507. (*in_row_group_ctr)++;
  168508. }
  168509. METHODDEF(void)
  168510. merged_1v_upsample (j_decompress_ptr cinfo,
  168511. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168512. JDIMENSION in_row_groups_avail,
  168513. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168514. JDIMENSION out_rows_avail)
  168515. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  168516. {
  168517. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168518. /* Just do the upsampling. */
  168519. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  168520. output_buf + *out_row_ctr);
  168521. /* Adjust counts */
  168522. (*out_row_ctr)++;
  168523. (*in_row_group_ctr)++;
  168524. }
  168525. /*
  168526. * These are the routines invoked by the control routines to do
  168527. * the actual upsampling/conversion. One row group is processed per call.
  168528. *
  168529. * Note: since we may be writing directly into application-supplied buffers,
  168530. * we have to be honest about the output width; we can't assume the buffer
  168531. * has been rounded up to an even width.
  168532. */
  168533. /*
  168534. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  168535. */
  168536. METHODDEF(void)
  168537. h2v1_merged_upsample (j_decompress_ptr cinfo,
  168538. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168539. JSAMPARRAY output_buf)
  168540. {
  168541. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168542. register int y, cred, cgreen, cblue;
  168543. int cb, cr;
  168544. register JSAMPROW outptr;
  168545. JSAMPROW inptr0, inptr1, inptr2;
  168546. JDIMENSION col;
  168547. /* copy these pointers into registers if possible */
  168548. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168549. int * Crrtab = upsample->Cr_r_tab;
  168550. int * Cbbtab = upsample->Cb_b_tab;
  168551. INT32 * Crgtab = upsample->Cr_g_tab;
  168552. INT32 * Cbgtab = upsample->Cb_g_tab;
  168553. SHIFT_TEMPS
  168554. inptr0 = input_buf[0][in_row_group_ctr];
  168555. inptr1 = input_buf[1][in_row_group_ctr];
  168556. inptr2 = input_buf[2][in_row_group_ctr];
  168557. outptr = output_buf[0];
  168558. /* Loop for each pair of output pixels */
  168559. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168560. /* Do the chroma part of the calculation */
  168561. cb = GETJSAMPLE(*inptr1++);
  168562. cr = GETJSAMPLE(*inptr2++);
  168563. cred = Crrtab[cr];
  168564. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168565. cblue = Cbbtab[cb];
  168566. /* Fetch 2 Y values and emit 2 pixels */
  168567. y = GETJSAMPLE(*inptr0++);
  168568. outptr[RGB_RED] = range_limit[y + cred];
  168569. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168570. outptr[RGB_BLUE] = range_limit[y + cblue];
  168571. outptr += RGB_PIXELSIZE;
  168572. y = GETJSAMPLE(*inptr0++);
  168573. outptr[RGB_RED] = range_limit[y + cred];
  168574. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168575. outptr[RGB_BLUE] = range_limit[y + cblue];
  168576. outptr += RGB_PIXELSIZE;
  168577. }
  168578. /* If image width is odd, do the last output column separately */
  168579. if (cinfo->output_width & 1) {
  168580. cb = GETJSAMPLE(*inptr1);
  168581. cr = GETJSAMPLE(*inptr2);
  168582. cred = Crrtab[cr];
  168583. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168584. cblue = Cbbtab[cb];
  168585. y = GETJSAMPLE(*inptr0);
  168586. outptr[RGB_RED] = range_limit[y + cred];
  168587. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168588. outptr[RGB_BLUE] = range_limit[y + cblue];
  168589. }
  168590. }
  168591. /*
  168592. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  168593. */
  168594. METHODDEF(void)
  168595. h2v2_merged_upsample (j_decompress_ptr cinfo,
  168596. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168597. JSAMPARRAY output_buf)
  168598. {
  168599. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168600. register int y, cred, cgreen, cblue;
  168601. int cb, cr;
  168602. register JSAMPROW outptr0, outptr1;
  168603. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  168604. JDIMENSION col;
  168605. /* copy these pointers into registers if possible */
  168606. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168607. int * Crrtab = upsample->Cr_r_tab;
  168608. int * Cbbtab = upsample->Cb_b_tab;
  168609. INT32 * Crgtab = upsample->Cr_g_tab;
  168610. INT32 * Cbgtab = upsample->Cb_g_tab;
  168611. SHIFT_TEMPS
  168612. inptr00 = input_buf[0][in_row_group_ctr*2];
  168613. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  168614. inptr1 = input_buf[1][in_row_group_ctr];
  168615. inptr2 = input_buf[2][in_row_group_ctr];
  168616. outptr0 = output_buf[0];
  168617. outptr1 = output_buf[1];
  168618. /* Loop for each group of output pixels */
  168619. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168620. /* Do the chroma part of the calculation */
  168621. cb = GETJSAMPLE(*inptr1++);
  168622. cr = GETJSAMPLE(*inptr2++);
  168623. cred = Crrtab[cr];
  168624. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168625. cblue = Cbbtab[cb];
  168626. /* Fetch 4 Y values and emit 4 pixels */
  168627. y = GETJSAMPLE(*inptr00++);
  168628. outptr0[RGB_RED] = range_limit[y + cred];
  168629. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168630. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168631. outptr0 += RGB_PIXELSIZE;
  168632. y = GETJSAMPLE(*inptr00++);
  168633. outptr0[RGB_RED] = range_limit[y + cred];
  168634. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168635. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168636. outptr0 += RGB_PIXELSIZE;
  168637. y = GETJSAMPLE(*inptr01++);
  168638. outptr1[RGB_RED] = range_limit[y + cred];
  168639. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168640. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168641. outptr1 += RGB_PIXELSIZE;
  168642. y = GETJSAMPLE(*inptr01++);
  168643. outptr1[RGB_RED] = range_limit[y + cred];
  168644. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168645. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168646. outptr1 += RGB_PIXELSIZE;
  168647. }
  168648. /* If image width is odd, do the last output column separately */
  168649. if (cinfo->output_width & 1) {
  168650. cb = GETJSAMPLE(*inptr1);
  168651. cr = GETJSAMPLE(*inptr2);
  168652. cred = Crrtab[cr];
  168653. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168654. cblue = Cbbtab[cb];
  168655. y = GETJSAMPLE(*inptr00);
  168656. outptr0[RGB_RED] = range_limit[y + cred];
  168657. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168658. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168659. y = GETJSAMPLE(*inptr01);
  168660. outptr1[RGB_RED] = range_limit[y + cred];
  168661. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168662. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168663. }
  168664. }
  168665. /*
  168666. * Module initialization routine for merged upsampling/color conversion.
  168667. *
  168668. * NB: this is called under the conditions determined by use_merged_upsample()
  168669. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  168670. * of this module; no safety checks are made here.
  168671. */
  168672. GLOBAL(void)
  168673. jinit_merged_upsampler (j_decompress_ptr cinfo)
  168674. {
  168675. my_upsample_ptr upsample;
  168676. upsample = (my_upsample_ptr)
  168677. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168678. SIZEOF(my_upsampler));
  168679. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168680. upsample->pub.start_pass = start_pass_merged_upsample;
  168681. upsample->pub.need_context_rows = FALSE;
  168682. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  168683. if (cinfo->max_v_samp_factor == 2) {
  168684. upsample->pub.upsample = merged_2v_upsample;
  168685. upsample->upmethod = h2v2_merged_upsample;
  168686. /* Allocate a spare row buffer */
  168687. upsample->spare_row = (JSAMPROW)
  168688. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168689. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  168690. } else {
  168691. upsample->pub.upsample = merged_1v_upsample;
  168692. upsample->upmethod = h2v1_merged_upsample;
  168693. /* No spare row needed */
  168694. upsample->spare_row = NULL;
  168695. }
  168696. build_ycc_rgb_table2(cinfo);
  168697. }
  168698. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  168699. /********* End of inlined file: jdmerge.c *********/
  168700. #undef ASSIGN_STATE
  168701. /********* Start of inlined file: jdphuff.c *********/
  168702. #define JPEG_INTERNALS
  168703. #ifdef D_PROGRESSIVE_SUPPORTED
  168704. /*
  168705. * Expanded entropy decoder object for progressive Huffman decoding.
  168706. *
  168707. * The savable_state subrecord contains fields that change within an MCU,
  168708. * but must not be updated permanently until we complete the MCU.
  168709. */
  168710. typedef struct {
  168711. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  168712. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168713. } savable_state3;
  168714. /* This macro is to work around compilers with missing or broken
  168715. * structure assignment. You'll need to fix this code if you have
  168716. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168717. */
  168718. #ifndef NO_STRUCT_ASSIGN
  168719. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168720. #else
  168721. #if MAX_COMPS_IN_SCAN == 4
  168722. #define ASSIGN_STATE(dest,src) \
  168723. ((dest).EOBRUN = (src).EOBRUN, \
  168724. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  168725. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168726. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168727. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168728. #endif
  168729. #endif
  168730. typedef struct {
  168731. struct jpeg_entropy_decoder pub; /* public fields */
  168732. /* These fields are loaded into local variables at start of each MCU.
  168733. * In case of suspension, we exit WITHOUT updating them.
  168734. */
  168735. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168736. savable_state3 saved; /* Other state at start of MCU */
  168737. /* These fields are NOT loaded into local working state. */
  168738. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168739. /* Pointers to derived tables (these workspaces have image lifespan) */
  168740. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  168741. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  168742. } phuff_entropy_decoder;
  168743. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  168744. /* Forward declarations */
  168745. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  168746. JBLOCKROW *MCU_data));
  168747. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  168748. JBLOCKROW *MCU_data));
  168749. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  168750. JBLOCKROW *MCU_data));
  168751. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  168752. JBLOCKROW *MCU_data));
  168753. /*
  168754. * Initialize for a Huffman-compressed scan.
  168755. */
  168756. METHODDEF(void)
  168757. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  168758. {
  168759. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168760. boolean is_DC_band, bad;
  168761. int ci, coefi, tbl;
  168762. int *coef_bit_ptr;
  168763. jpeg_component_info * compptr;
  168764. is_DC_band = (cinfo->Ss == 0);
  168765. /* Validate scan parameters */
  168766. bad = FALSE;
  168767. if (is_DC_band) {
  168768. if (cinfo->Se != 0)
  168769. bad = TRUE;
  168770. } else {
  168771. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  168772. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  168773. bad = TRUE;
  168774. /* AC scans may have only one component */
  168775. if (cinfo->comps_in_scan != 1)
  168776. bad = TRUE;
  168777. }
  168778. if (cinfo->Ah != 0) {
  168779. /* Successive approximation refinement scan: must have Al = Ah-1. */
  168780. if (cinfo->Al != cinfo->Ah-1)
  168781. bad = TRUE;
  168782. }
  168783. if (cinfo->Al > 13) /* need not check for < 0 */
  168784. bad = TRUE;
  168785. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  168786. * but the spec doesn't say so, and we try to be liberal about what we
  168787. * accept. Note: large Al values could result in out-of-range DC
  168788. * coefficients during early scans, leading to bizarre displays due to
  168789. * overflows in the IDCT math. But we won't crash.
  168790. */
  168791. if (bad)
  168792. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  168793. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  168794. /* Update progression status, and verify that scan order is legal.
  168795. * Note that inter-scan inconsistencies are treated as warnings
  168796. * not fatal errors ... not clear if this is right way to behave.
  168797. */
  168798. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168799. int cindex = cinfo->cur_comp_info[ci]->component_index;
  168800. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  168801. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  168802. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  168803. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  168804. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  168805. if (cinfo->Ah != expected)
  168806. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  168807. coef_bit_ptr[coefi] = cinfo->Al;
  168808. }
  168809. }
  168810. /* Select MCU decoding routine */
  168811. if (cinfo->Ah == 0) {
  168812. if (is_DC_band)
  168813. entropy->pub.decode_mcu = decode_mcu_DC_first;
  168814. else
  168815. entropy->pub.decode_mcu = decode_mcu_AC_first;
  168816. } else {
  168817. if (is_DC_band)
  168818. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  168819. else
  168820. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  168821. }
  168822. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168823. compptr = cinfo->cur_comp_info[ci];
  168824. /* Make sure requested tables are present, and compute derived tables.
  168825. * We may build same derived table more than once, but it's not expensive.
  168826. */
  168827. if (is_DC_band) {
  168828. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  168829. tbl = compptr->dc_tbl_no;
  168830. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  168831. & entropy->derived_tbls[tbl]);
  168832. }
  168833. } else {
  168834. tbl = compptr->ac_tbl_no;
  168835. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  168836. & entropy->derived_tbls[tbl]);
  168837. /* remember the single active table */
  168838. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  168839. }
  168840. /* Initialize DC predictions to 0 */
  168841. entropy->saved.last_dc_val[ci] = 0;
  168842. }
  168843. /* Initialize bitread state variables */
  168844. entropy->bitstate.bits_left = 0;
  168845. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168846. entropy->pub.insufficient_data = FALSE;
  168847. /* Initialize private state variables */
  168848. entropy->saved.EOBRUN = 0;
  168849. /* Initialize restart counter */
  168850. entropy->restarts_to_go = cinfo->restart_interval;
  168851. }
  168852. /*
  168853. * Check for a restart marker & resynchronize decoder.
  168854. * Returns FALSE if must suspend.
  168855. */
  168856. LOCAL(boolean)
  168857. process_restartp (j_decompress_ptr cinfo)
  168858. {
  168859. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168860. int ci;
  168861. /* Throw away any unused bits remaining in bit buffer; */
  168862. /* include any full bytes in next_marker's count of discarded bytes */
  168863. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  168864. entropy->bitstate.bits_left = 0;
  168865. /* Advance past the RSTn marker */
  168866. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  168867. return FALSE;
  168868. /* Re-initialize DC predictions to 0 */
  168869. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  168870. entropy->saved.last_dc_val[ci] = 0;
  168871. /* Re-init EOB run count, too */
  168872. entropy->saved.EOBRUN = 0;
  168873. /* Reset restart counter */
  168874. entropy->restarts_to_go = cinfo->restart_interval;
  168875. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  168876. * against a marker. In that case we will end up treating the next data
  168877. * segment as empty, and we can avoid producing bogus output pixels by
  168878. * leaving the flag set.
  168879. */
  168880. if (cinfo->unread_marker == 0)
  168881. entropy->pub.insufficient_data = FALSE;
  168882. return TRUE;
  168883. }
  168884. /*
  168885. * Huffman MCU decoding.
  168886. * Each of these routines decodes and returns one MCU's worth of
  168887. * Huffman-compressed coefficients.
  168888. * The coefficients are reordered from zigzag order into natural array order,
  168889. * but are not dequantized.
  168890. *
  168891. * The i'th block of the MCU is stored into the block pointed to by
  168892. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  168893. *
  168894. * We return FALSE if data source requested suspension. In that case no
  168895. * changes have been made to permanent state. (Exception: some output
  168896. * coefficients may already have been assigned. This is harmless for
  168897. * spectral selection, since we'll just re-assign them on the next call.
  168898. * Successive approximation AC refinement has to be more careful, however.)
  168899. */
  168900. /*
  168901. * MCU decoding for DC initial scan (either spectral selection,
  168902. * or first pass of successive approximation).
  168903. */
  168904. METHODDEF(boolean)
  168905. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168906. {
  168907. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168908. int Al = cinfo->Al;
  168909. register int s, r;
  168910. int blkn, ci;
  168911. JBLOCKROW block;
  168912. BITREAD_STATE_VARS;
  168913. savable_state3 state;
  168914. d_derived_tbl * tbl;
  168915. jpeg_component_info * compptr;
  168916. /* Process restart marker if needed; may have to suspend */
  168917. if (cinfo->restart_interval) {
  168918. if (entropy->restarts_to_go == 0)
  168919. if (! process_restartp(cinfo))
  168920. return FALSE;
  168921. }
  168922. /* If we've run out of data, just leave the MCU set to zeroes.
  168923. * This way, we return uniform gray for the remainder of the segment.
  168924. */
  168925. if (! entropy->pub.insufficient_data) {
  168926. /* Load up working state */
  168927. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168928. ASSIGN_STATE(state, entropy->saved);
  168929. /* Outer loop handles each block in the MCU */
  168930. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168931. block = MCU_data[blkn];
  168932. ci = cinfo->MCU_membership[blkn];
  168933. compptr = cinfo->cur_comp_info[ci];
  168934. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  168935. /* Decode a single block's worth of coefficients */
  168936. /* Section F.2.2.1: decode the DC coefficient difference */
  168937. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  168938. if (s) {
  168939. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168940. r = GET_BITS(s);
  168941. s = HUFF_EXTEND(r, s);
  168942. }
  168943. /* Convert DC difference to actual value, update last_dc_val */
  168944. s += state.last_dc_val[ci];
  168945. state.last_dc_val[ci] = s;
  168946. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  168947. (*block)[0] = (JCOEF) (s << Al);
  168948. }
  168949. /* Completed MCU, so update state */
  168950. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168951. ASSIGN_STATE(entropy->saved, state);
  168952. }
  168953. /* Account for restart interval (no-op if not using restarts) */
  168954. entropy->restarts_to_go--;
  168955. return TRUE;
  168956. }
  168957. /*
  168958. * MCU decoding for AC initial scan (either spectral selection,
  168959. * or first pass of successive approximation).
  168960. */
  168961. METHODDEF(boolean)
  168962. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168963. {
  168964. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168965. int Se = cinfo->Se;
  168966. int Al = cinfo->Al;
  168967. register int s, k, r;
  168968. unsigned int EOBRUN;
  168969. JBLOCKROW block;
  168970. BITREAD_STATE_VARS;
  168971. d_derived_tbl * tbl;
  168972. /* Process restart marker if needed; may have to suspend */
  168973. if (cinfo->restart_interval) {
  168974. if (entropy->restarts_to_go == 0)
  168975. if (! process_restartp(cinfo))
  168976. return FALSE;
  168977. }
  168978. /* If we've run out of data, just leave the MCU set to zeroes.
  168979. * This way, we return uniform gray for the remainder of the segment.
  168980. */
  168981. if (! entropy->pub.insufficient_data) {
  168982. /* Load up working state.
  168983. * We can avoid loading/saving bitread state if in an EOB run.
  168984. */
  168985. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168986. /* There is always only one block per MCU */
  168987. if (EOBRUN > 0) /* if it's a band of zeroes... */
  168988. EOBRUN--; /* ...process it now (we do nothing) */
  168989. else {
  168990. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168991. block = MCU_data[0];
  168992. tbl = entropy->ac_derived_tbl;
  168993. for (k = cinfo->Ss; k <= Se; k++) {
  168994. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  168995. r = s >> 4;
  168996. s &= 15;
  168997. if (s) {
  168998. k += r;
  168999. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169000. r = GET_BITS(s);
  169001. s = HUFF_EXTEND(r, s);
  169002. /* Scale and output coefficient in natural (dezigzagged) order */
  169003. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  169004. } else {
  169005. if (r == 15) { /* ZRL */
  169006. k += 15; /* skip 15 zeroes in band */
  169007. } else { /* EOBr, run length is 2^r + appended bits */
  169008. EOBRUN = 1 << r;
  169009. if (r) { /* EOBr, r > 0 */
  169010. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  169011. r = GET_BITS(r);
  169012. EOBRUN += r;
  169013. }
  169014. EOBRUN--; /* this band is processed at this moment */
  169015. break; /* force end-of-band */
  169016. }
  169017. }
  169018. }
  169019. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169020. }
  169021. /* Completed MCU, so update state */
  169022. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169023. }
  169024. /* Account for restart interval (no-op if not using restarts) */
  169025. entropy->restarts_to_go--;
  169026. return TRUE;
  169027. }
  169028. /*
  169029. * MCU decoding for DC successive approximation refinement scan.
  169030. * Note: we assume such scans can be multi-component, although the spec
  169031. * is not very clear on the point.
  169032. */
  169033. METHODDEF(boolean)
  169034. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169035. {
  169036. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169037. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169038. int blkn;
  169039. JBLOCKROW block;
  169040. BITREAD_STATE_VARS;
  169041. /* Process restart marker if needed; may have to suspend */
  169042. if (cinfo->restart_interval) {
  169043. if (entropy->restarts_to_go == 0)
  169044. if (! process_restartp(cinfo))
  169045. return FALSE;
  169046. }
  169047. /* Not worth the cycles to check insufficient_data here,
  169048. * since we will not change the data anyway if we read zeroes.
  169049. */
  169050. /* Load up working state */
  169051. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169052. /* Outer loop handles each block in the MCU */
  169053. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169054. block = MCU_data[blkn];
  169055. /* Encoded data is simply the next bit of the two's-complement DC value */
  169056. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  169057. if (GET_BITS(1))
  169058. (*block)[0] |= p1;
  169059. /* Note: since we use |=, repeating the assignment later is safe */
  169060. }
  169061. /* Completed MCU, so update state */
  169062. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169063. /* Account for restart interval (no-op if not using restarts) */
  169064. entropy->restarts_to_go--;
  169065. return TRUE;
  169066. }
  169067. /*
  169068. * MCU decoding for AC successive approximation refinement scan.
  169069. */
  169070. METHODDEF(boolean)
  169071. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169072. {
  169073. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169074. int Se = cinfo->Se;
  169075. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169076. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  169077. register int s, k, r;
  169078. unsigned int EOBRUN;
  169079. JBLOCKROW block;
  169080. JCOEFPTR thiscoef;
  169081. BITREAD_STATE_VARS;
  169082. d_derived_tbl * tbl;
  169083. int num_newnz;
  169084. int newnz_pos[DCTSIZE2];
  169085. /* Process restart marker if needed; may have to suspend */
  169086. if (cinfo->restart_interval) {
  169087. if (entropy->restarts_to_go == 0)
  169088. if (! process_restartp(cinfo))
  169089. return FALSE;
  169090. }
  169091. /* If we've run out of data, don't modify the MCU.
  169092. */
  169093. if (! entropy->pub.insufficient_data) {
  169094. /* Load up working state */
  169095. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169096. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169097. /* There is always only one block per MCU */
  169098. block = MCU_data[0];
  169099. tbl = entropy->ac_derived_tbl;
  169100. /* If we are forced to suspend, we must undo the assignments to any newly
  169101. * nonzero coefficients in the block, because otherwise we'd get confused
  169102. * next time about which coefficients were already nonzero.
  169103. * But we need not undo addition of bits to already-nonzero coefficients;
  169104. * instead, we can test the current bit to see if we already did it.
  169105. */
  169106. num_newnz = 0;
  169107. /* initialize coefficient loop counter to start of band */
  169108. k = cinfo->Ss;
  169109. if (EOBRUN == 0) {
  169110. for (; k <= Se; k++) {
  169111. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  169112. r = s >> 4;
  169113. s &= 15;
  169114. if (s) {
  169115. if (s != 1) /* size of new coef should always be 1 */
  169116. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  169117. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169118. if (GET_BITS(1))
  169119. s = p1; /* newly nonzero coef is positive */
  169120. else
  169121. s = m1; /* newly nonzero coef is negative */
  169122. } else {
  169123. if (r != 15) {
  169124. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  169125. if (r) {
  169126. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  169127. r = GET_BITS(r);
  169128. EOBRUN += r;
  169129. }
  169130. break; /* rest of block is handled by EOB logic */
  169131. }
  169132. /* note s = 0 for processing ZRL */
  169133. }
  169134. /* Advance over already-nonzero coefs and r still-zero coefs,
  169135. * appending correction bits to the nonzeroes. A correction bit is 1
  169136. * if the absolute value of the coefficient must be increased.
  169137. */
  169138. do {
  169139. thiscoef = *block + jpeg_natural_order[k];
  169140. if (*thiscoef != 0) {
  169141. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169142. if (GET_BITS(1)) {
  169143. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  169144. if (*thiscoef >= 0)
  169145. *thiscoef += p1;
  169146. else
  169147. *thiscoef += m1;
  169148. }
  169149. }
  169150. } else {
  169151. if (--r < 0)
  169152. break; /* reached target zero coefficient */
  169153. }
  169154. k++;
  169155. } while (k <= Se);
  169156. if (s) {
  169157. int pos = jpeg_natural_order[k];
  169158. /* Output newly nonzero coefficient */
  169159. (*block)[pos] = (JCOEF) s;
  169160. /* Remember its position in case we have to suspend */
  169161. newnz_pos[num_newnz++] = pos;
  169162. }
  169163. }
  169164. }
  169165. if (EOBRUN > 0) {
  169166. /* Scan any remaining coefficient positions after the end-of-band
  169167. * (the last newly nonzero coefficient, if any). Append a correction
  169168. * bit to each already-nonzero coefficient. A correction bit is 1
  169169. * if the absolute value of the coefficient must be increased.
  169170. */
  169171. for (; k <= Se; k++) {
  169172. thiscoef = *block + jpeg_natural_order[k];
  169173. if (*thiscoef != 0) {
  169174. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169175. if (GET_BITS(1)) {
  169176. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  169177. if (*thiscoef >= 0)
  169178. *thiscoef += p1;
  169179. else
  169180. *thiscoef += m1;
  169181. }
  169182. }
  169183. }
  169184. }
  169185. /* Count one block completed in EOB run */
  169186. EOBRUN--;
  169187. }
  169188. /* Completed MCU, so update state */
  169189. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169190. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169191. }
  169192. /* Account for restart interval (no-op if not using restarts) */
  169193. entropy->restarts_to_go--;
  169194. return TRUE;
  169195. undoit:
  169196. /* Re-zero any output coefficients that we made newly nonzero */
  169197. while (num_newnz > 0)
  169198. (*block)[newnz_pos[--num_newnz]] = 0;
  169199. return FALSE;
  169200. }
  169201. /*
  169202. * Module initialization routine for progressive Huffman entropy decoding.
  169203. */
  169204. GLOBAL(void)
  169205. jinit_phuff_decoder (j_decompress_ptr cinfo)
  169206. {
  169207. phuff_entropy_ptr2 entropy;
  169208. int *coef_bit_ptr;
  169209. int ci, i;
  169210. entropy = (phuff_entropy_ptr2)
  169211. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169212. SIZEOF(phuff_entropy_decoder));
  169213. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169214. entropy->pub.start_pass = start_pass_phuff_decoder;
  169215. /* Mark derived tables unallocated */
  169216. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169217. entropy->derived_tbls[i] = NULL;
  169218. }
  169219. /* Create progression status table */
  169220. cinfo->coef_bits = (int (*)[DCTSIZE2])
  169221. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169222. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  169223. coef_bit_ptr = & cinfo->coef_bits[0][0];
  169224. for (ci = 0; ci < cinfo->num_components; ci++)
  169225. for (i = 0; i < DCTSIZE2; i++)
  169226. *coef_bit_ptr++ = -1;
  169227. }
  169228. #endif /* D_PROGRESSIVE_SUPPORTED */
  169229. /********* End of inlined file: jdphuff.c *********/
  169230. /********* Start of inlined file: jdpostct.c *********/
  169231. #define JPEG_INTERNALS
  169232. /* Private buffer controller object */
  169233. typedef struct {
  169234. struct jpeg_d_post_controller pub; /* public fields */
  169235. /* Color quantization source buffer: this holds output data from
  169236. * the upsample/color conversion step to be passed to the quantizer.
  169237. * For two-pass color quantization, we need a full-image buffer;
  169238. * for one-pass operation, a strip buffer is sufficient.
  169239. */
  169240. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  169241. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  169242. JDIMENSION strip_height; /* buffer size in rows */
  169243. /* for two-pass mode only: */
  169244. JDIMENSION starting_row; /* row # of first row in current strip */
  169245. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  169246. } my_post_controller;
  169247. typedef my_post_controller * my_post_ptr;
  169248. /* Forward declarations */
  169249. METHODDEF(void) post_process_1pass
  169250. JPP((j_decompress_ptr cinfo,
  169251. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169252. JDIMENSION in_row_groups_avail,
  169253. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169254. JDIMENSION out_rows_avail));
  169255. #ifdef QUANT_2PASS_SUPPORTED
  169256. METHODDEF(void) post_process_prepass
  169257. JPP((j_decompress_ptr cinfo,
  169258. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169259. JDIMENSION in_row_groups_avail,
  169260. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169261. JDIMENSION out_rows_avail));
  169262. METHODDEF(void) post_process_2pass
  169263. JPP((j_decompress_ptr cinfo,
  169264. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169265. JDIMENSION in_row_groups_avail,
  169266. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169267. JDIMENSION out_rows_avail));
  169268. #endif
  169269. /*
  169270. * Initialize for a processing pass.
  169271. */
  169272. METHODDEF(void)
  169273. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  169274. {
  169275. my_post_ptr post = (my_post_ptr) cinfo->post;
  169276. switch (pass_mode) {
  169277. case JBUF_PASS_THRU:
  169278. if (cinfo->quantize_colors) {
  169279. /* Single-pass processing with color quantization. */
  169280. post->pub.post_process_data = post_process_1pass;
  169281. /* We could be doing buffered-image output before starting a 2-pass
  169282. * color quantization; in that case, jinit_d_post_controller did not
  169283. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  169284. */
  169285. if (post->buffer == NULL) {
  169286. post->buffer = (*cinfo->mem->access_virt_sarray)
  169287. ((j_common_ptr) cinfo, post->whole_image,
  169288. (JDIMENSION) 0, post->strip_height, TRUE);
  169289. }
  169290. } else {
  169291. /* For single-pass processing without color quantization,
  169292. * I have no work to do; just call the upsampler directly.
  169293. */
  169294. post->pub.post_process_data = cinfo->upsample->upsample;
  169295. }
  169296. break;
  169297. #ifdef QUANT_2PASS_SUPPORTED
  169298. case JBUF_SAVE_AND_PASS:
  169299. /* First pass of 2-pass quantization */
  169300. if (post->whole_image == NULL)
  169301. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169302. post->pub.post_process_data = post_process_prepass;
  169303. break;
  169304. case JBUF_CRANK_DEST:
  169305. /* Second pass of 2-pass quantization */
  169306. if (post->whole_image == NULL)
  169307. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169308. post->pub.post_process_data = post_process_2pass;
  169309. break;
  169310. #endif /* QUANT_2PASS_SUPPORTED */
  169311. default:
  169312. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169313. break;
  169314. }
  169315. post->starting_row = post->next_row = 0;
  169316. }
  169317. /*
  169318. * Process some data in the one-pass (strip buffer) case.
  169319. * This is used for color precision reduction as well as one-pass quantization.
  169320. */
  169321. METHODDEF(void)
  169322. post_process_1pass (j_decompress_ptr cinfo,
  169323. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169324. JDIMENSION in_row_groups_avail,
  169325. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169326. JDIMENSION out_rows_avail)
  169327. {
  169328. my_post_ptr post = (my_post_ptr) cinfo->post;
  169329. JDIMENSION num_rows, max_rows;
  169330. /* Fill the buffer, but not more than what we can dump out in one go. */
  169331. /* Note we rely on the upsampler to detect bottom of image. */
  169332. max_rows = out_rows_avail - *out_row_ctr;
  169333. if (max_rows > post->strip_height)
  169334. max_rows = post->strip_height;
  169335. num_rows = 0;
  169336. (*cinfo->upsample->upsample) (cinfo,
  169337. input_buf, in_row_group_ctr, in_row_groups_avail,
  169338. post->buffer, &num_rows, max_rows);
  169339. /* Quantize and emit data. */
  169340. (*cinfo->cquantize->color_quantize) (cinfo,
  169341. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  169342. *out_row_ctr += num_rows;
  169343. }
  169344. #ifdef QUANT_2PASS_SUPPORTED
  169345. /*
  169346. * Process some data in the first pass of 2-pass quantization.
  169347. */
  169348. METHODDEF(void)
  169349. post_process_prepass (j_decompress_ptr cinfo,
  169350. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169351. JDIMENSION in_row_groups_avail,
  169352. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169353. JDIMENSION out_rows_avail)
  169354. {
  169355. my_post_ptr post = (my_post_ptr) cinfo->post;
  169356. JDIMENSION old_next_row, num_rows;
  169357. /* Reposition virtual buffer if at start of strip. */
  169358. if (post->next_row == 0) {
  169359. post->buffer = (*cinfo->mem->access_virt_sarray)
  169360. ((j_common_ptr) cinfo, post->whole_image,
  169361. post->starting_row, post->strip_height, TRUE);
  169362. }
  169363. /* Upsample some data (up to a strip height's worth). */
  169364. old_next_row = post->next_row;
  169365. (*cinfo->upsample->upsample) (cinfo,
  169366. input_buf, in_row_group_ctr, in_row_groups_avail,
  169367. post->buffer, &post->next_row, post->strip_height);
  169368. /* Allow quantizer to scan new data. No data is emitted, */
  169369. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  169370. if (post->next_row > old_next_row) {
  169371. num_rows = post->next_row - old_next_row;
  169372. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  169373. (JSAMPARRAY) NULL, (int) num_rows);
  169374. *out_row_ctr += num_rows;
  169375. }
  169376. /* Advance if we filled the strip. */
  169377. if (post->next_row >= post->strip_height) {
  169378. post->starting_row += post->strip_height;
  169379. post->next_row = 0;
  169380. }
  169381. }
  169382. /*
  169383. * Process some data in the second pass of 2-pass quantization.
  169384. */
  169385. METHODDEF(void)
  169386. post_process_2pass (j_decompress_ptr cinfo,
  169387. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169388. JDIMENSION in_row_groups_avail,
  169389. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169390. JDIMENSION out_rows_avail)
  169391. {
  169392. my_post_ptr post = (my_post_ptr) cinfo->post;
  169393. JDIMENSION num_rows, max_rows;
  169394. /* Reposition virtual buffer if at start of strip. */
  169395. if (post->next_row == 0) {
  169396. post->buffer = (*cinfo->mem->access_virt_sarray)
  169397. ((j_common_ptr) cinfo, post->whole_image,
  169398. post->starting_row, post->strip_height, FALSE);
  169399. }
  169400. /* Determine number of rows to emit. */
  169401. num_rows = post->strip_height - post->next_row; /* available in strip */
  169402. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  169403. if (num_rows > max_rows)
  169404. num_rows = max_rows;
  169405. /* We have to check bottom of image here, can't depend on upsampler. */
  169406. max_rows = cinfo->output_height - post->starting_row;
  169407. if (num_rows > max_rows)
  169408. num_rows = max_rows;
  169409. /* Quantize and emit data. */
  169410. (*cinfo->cquantize->color_quantize) (cinfo,
  169411. post->buffer + post->next_row, output_buf + *out_row_ctr,
  169412. (int) num_rows);
  169413. *out_row_ctr += num_rows;
  169414. /* Advance if we filled the strip. */
  169415. post->next_row += num_rows;
  169416. if (post->next_row >= post->strip_height) {
  169417. post->starting_row += post->strip_height;
  169418. post->next_row = 0;
  169419. }
  169420. }
  169421. #endif /* QUANT_2PASS_SUPPORTED */
  169422. /*
  169423. * Initialize postprocessing controller.
  169424. */
  169425. GLOBAL(void)
  169426. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169427. {
  169428. my_post_ptr post;
  169429. post = (my_post_ptr)
  169430. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169431. SIZEOF(my_post_controller));
  169432. cinfo->post = (struct jpeg_d_post_controller *) post;
  169433. post->pub.start_pass = start_pass_dpost;
  169434. post->whole_image = NULL; /* flag for no virtual arrays */
  169435. post->buffer = NULL; /* flag for no strip buffer */
  169436. /* Create the quantization buffer, if needed */
  169437. if (cinfo->quantize_colors) {
  169438. /* The buffer strip height is max_v_samp_factor, which is typically
  169439. * an efficient number of rows for upsampling to return.
  169440. * (In the presence of output rescaling, we might want to be smarter?)
  169441. */
  169442. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  169443. if (need_full_buffer) {
  169444. /* Two-pass color quantization: need full-image storage. */
  169445. /* We round up the number of rows to a multiple of the strip height. */
  169446. #ifdef QUANT_2PASS_SUPPORTED
  169447. post->whole_image = (*cinfo->mem->request_virt_sarray)
  169448. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  169449. cinfo->output_width * cinfo->out_color_components,
  169450. (JDIMENSION) jround_up((long) cinfo->output_height,
  169451. (long) post->strip_height),
  169452. post->strip_height);
  169453. #else
  169454. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169455. #endif /* QUANT_2PASS_SUPPORTED */
  169456. } else {
  169457. /* One-pass color quantization: just make a strip buffer. */
  169458. post->buffer = (*cinfo->mem->alloc_sarray)
  169459. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169460. cinfo->output_width * cinfo->out_color_components,
  169461. post->strip_height);
  169462. }
  169463. }
  169464. }
  169465. /********* End of inlined file: jdpostct.c *********/
  169466. #undef FIX
  169467. /********* Start of inlined file: jdsample.c *********/
  169468. #define JPEG_INTERNALS
  169469. /* Pointer to routine to upsample a single component */
  169470. typedef JMETHOD(void, upsample1_ptr,
  169471. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169472. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  169473. /* Private subobject */
  169474. typedef struct {
  169475. struct jpeg_upsampler pub; /* public fields */
  169476. /* Color conversion buffer. When using separate upsampling and color
  169477. * conversion steps, this buffer holds one upsampled row group until it
  169478. * has been color converted and output.
  169479. * Note: we do not allocate any storage for component(s) which are full-size,
  169480. * ie do not need rescaling. The corresponding entry of color_buf[] is
  169481. * simply set to point to the input data array, thereby avoiding copying.
  169482. */
  169483. JSAMPARRAY color_buf[MAX_COMPONENTS];
  169484. /* Per-component upsampling method pointers */
  169485. upsample1_ptr methods[MAX_COMPONENTS];
  169486. int next_row_out; /* counts rows emitted from color_buf */
  169487. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169488. /* Height of an input row group for each component. */
  169489. int rowgroup_height[MAX_COMPONENTS];
  169490. /* These arrays save pixel expansion factors so that int_expand need not
  169491. * recompute them each time. They are unused for other upsampling methods.
  169492. */
  169493. UINT8 h_expand[MAX_COMPONENTS];
  169494. UINT8 v_expand[MAX_COMPONENTS];
  169495. } my_upsampler2;
  169496. typedef my_upsampler2 * my_upsample_ptr2;
  169497. /*
  169498. * Initialize for an upsampling pass.
  169499. */
  169500. METHODDEF(void)
  169501. start_pass_upsample (j_decompress_ptr cinfo)
  169502. {
  169503. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169504. /* Mark the conversion buffer empty */
  169505. upsample->next_row_out = cinfo->max_v_samp_factor;
  169506. /* Initialize total-height counter for detecting bottom of image */
  169507. upsample->rows_to_go = cinfo->output_height;
  169508. }
  169509. /*
  169510. * Control routine to do upsampling (and color conversion).
  169511. *
  169512. * In this version we upsample each component independently.
  169513. * We upsample one row group into the conversion buffer, then apply
  169514. * color conversion a row at a time.
  169515. */
  169516. METHODDEF(void)
  169517. sep_upsample (j_decompress_ptr cinfo,
  169518. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169519. JDIMENSION in_row_groups_avail,
  169520. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169521. JDIMENSION out_rows_avail)
  169522. {
  169523. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169524. int ci;
  169525. jpeg_component_info * compptr;
  169526. JDIMENSION num_rows;
  169527. /* Fill the conversion buffer, if it's empty */
  169528. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  169529. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169530. ci++, compptr++) {
  169531. /* Invoke per-component upsample method. Notice we pass a POINTER
  169532. * to color_buf[ci], so that fullsize_upsample can change it.
  169533. */
  169534. (*upsample->methods[ci]) (cinfo, compptr,
  169535. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  169536. upsample->color_buf + ci);
  169537. }
  169538. upsample->next_row_out = 0;
  169539. }
  169540. /* Color-convert and emit rows */
  169541. /* How many we have in the buffer: */
  169542. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  169543. /* Not more than the distance to the end of the image. Need this test
  169544. * in case the image height is not a multiple of max_v_samp_factor:
  169545. */
  169546. if (num_rows > upsample->rows_to_go)
  169547. num_rows = upsample->rows_to_go;
  169548. /* And not more than what the client can accept: */
  169549. out_rows_avail -= *out_row_ctr;
  169550. if (num_rows > out_rows_avail)
  169551. num_rows = out_rows_avail;
  169552. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  169553. (JDIMENSION) upsample->next_row_out,
  169554. output_buf + *out_row_ctr,
  169555. (int) num_rows);
  169556. /* Adjust counts */
  169557. *out_row_ctr += num_rows;
  169558. upsample->rows_to_go -= num_rows;
  169559. upsample->next_row_out += num_rows;
  169560. /* When the buffer is emptied, declare this input row group consumed */
  169561. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  169562. (*in_row_group_ctr)++;
  169563. }
  169564. /*
  169565. * These are the routines invoked by sep_upsample to upsample pixel values
  169566. * of a single component. One row group is processed per call.
  169567. */
  169568. /*
  169569. * For full-size components, we just make color_buf[ci] point at the
  169570. * input buffer, and thus avoid copying any data. Note that this is
  169571. * safe only because sep_upsample doesn't declare the input row group
  169572. * "consumed" until we are done color converting and emitting it.
  169573. */
  169574. METHODDEF(void)
  169575. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169576. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169577. {
  169578. *output_data_ptr = input_data;
  169579. }
  169580. /*
  169581. * This is a no-op version used for "uninteresting" components.
  169582. * These components will not be referenced by color conversion.
  169583. */
  169584. METHODDEF(void)
  169585. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169586. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169587. {
  169588. *output_data_ptr = NULL; /* safety check */
  169589. }
  169590. /*
  169591. * This version handles any integral sampling ratios.
  169592. * This is not used for typical JPEG files, so it need not be fast.
  169593. * Nor, for that matter, is it particularly accurate: the algorithm is
  169594. * simple replication of the input pixel onto the corresponding output
  169595. * pixels. The hi-falutin sampling literature refers to this as a
  169596. * "box filter". A box filter tends to introduce visible artifacts,
  169597. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  169598. * you would be well advised to improve this code.
  169599. */
  169600. METHODDEF(void)
  169601. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169602. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169603. {
  169604. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169605. JSAMPARRAY output_data = *output_data_ptr;
  169606. register JSAMPROW inptr, outptr;
  169607. register JSAMPLE invalue;
  169608. register int h;
  169609. JSAMPROW outend;
  169610. int h_expand, v_expand;
  169611. int inrow, outrow;
  169612. h_expand = upsample->h_expand[compptr->component_index];
  169613. v_expand = upsample->v_expand[compptr->component_index];
  169614. inrow = outrow = 0;
  169615. while (outrow < cinfo->max_v_samp_factor) {
  169616. /* Generate one output row with proper horizontal expansion */
  169617. inptr = input_data[inrow];
  169618. outptr = output_data[outrow];
  169619. outend = outptr + cinfo->output_width;
  169620. while (outptr < outend) {
  169621. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169622. for (h = h_expand; h > 0; h--) {
  169623. *outptr++ = invalue;
  169624. }
  169625. }
  169626. /* Generate any additional output rows by duplicating the first one */
  169627. if (v_expand > 1) {
  169628. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169629. v_expand-1, cinfo->output_width);
  169630. }
  169631. inrow++;
  169632. outrow += v_expand;
  169633. }
  169634. }
  169635. /*
  169636. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  169637. * It's still a box filter.
  169638. */
  169639. METHODDEF(void)
  169640. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169641. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169642. {
  169643. JSAMPARRAY output_data = *output_data_ptr;
  169644. register JSAMPROW inptr, outptr;
  169645. register JSAMPLE invalue;
  169646. JSAMPROW outend;
  169647. int inrow;
  169648. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169649. inptr = input_data[inrow];
  169650. outptr = output_data[inrow];
  169651. outend = outptr + cinfo->output_width;
  169652. while (outptr < outend) {
  169653. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169654. *outptr++ = invalue;
  169655. *outptr++ = invalue;
  169656. }
  169657. }
  169658. }
  169659. /*
  169660. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  169661. * It's still a box filter.
  169662. */
  169663. METHODDEF(void)
  169664. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169665. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169666. {
  169667. JSAMPARRAY output_data = *output_data_ptr;
  169668. register JSAMPROW inptr, outptr;
  169669. register JSAMPLE invalue;
  169670. JSAMPROW outend;
  169671. int inrow, outrow;
  169672. inrow = outrow = 0;
  169673. while (outrow < cinfo->max_v_samp_factor) {
  169674. inptr = input_data[inrow];
  169675. outptr = output_data[outrow];
  169676. outend = outptr + cinfo->output_width;
  169677. while (outptr < outend) {
  169678. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169679. *outptr++ = invalue;
  169680. *outptr++ = invalue;
  169681. }
  169682. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169683. 1, cinfo->output_width);
  169684. inrow++;
  169685. outrow += 2;
  169686. }
  169687. }
  169688. /*
  169689. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  169690. *
  169691. * The upsampling algorithm is linear interpolation between pixel centers,
  169692. * also known as a "triangle filter". This is a good compromise between
  169693. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  169694. * of the way between input pixel centers.
  169695. *
  169696. * A note about the "bias" calculations: when rounding fractional values to
  169697. * integer, we do not want to always round 0.5 up to the next integer.
  169698. * If we did that, we'd introduce a noticeable bias towards larger values.
  169699. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  169700. * alternate pixel locations (a simple ordered dither pattern).
  169701. */
  169702. METHODDEF(void)
  169703. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169704. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169705. {
  169706. JSAMPARRAY output_data = *output_data_ptr;
  169707. register JSAMPROW inptr, outptr;
  169708. register int invalue;
  169709. register JDIMENSION colctr;
  169710. int inrow;
  169711. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169712. inptr = input_data[inrow];
  169713. outptr = output_data[inrow];
  169714. /* Special case for first column */
  169715. invalue = GETJSAMPLE(*inptr++);
  169716. *outptr++ = (JSAMPLE) invalue;
  169717. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  169718. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169719. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  169720. invalue = GETJSAMPLE(*inptr++) * 3;
  169721. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  169722. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  169723. }
  169724. /* Special case for last column */
  169725. invalue = GETJSAMPLE(*inptr);
  169726. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  169727. *outptr++ = (JSAMPLE) invalue;
  169728. }
  169729. }
  169730. /*
  169731. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  169732. * Again a triangle filter; see comments for h2v1 case, above.
  169733. *
  169734. * It is OK for us to reference the adjacent input rows because we demanded
  169735. * context from the main buffer controller (see initialization code).
  169736. */
  169737. METHODDEF(void)
  169738. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169739. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169740. {
  169741. JSAMPARRAY output_data = *output_data_ptr;
  169742. register JSAMPROW inptr0, inptr1, outptr;
  169743. #if BITS_IN_JSAMPLE == 8
  169744. register int thiscolsum, lastcolsum, nextcolsum;
  169745. #else
  169746. register INT32 thiscolsum, lastcolsum, nextcolsum;
  169747. #endif
  169748. register JDIMENSION colctr;
  169749. int inrow, outrow, v;
  169750. inrow = outrow = 0;
  169751. while (outrow < cinfo->max_v_samp_factor) {
  169752. for (v = 0; v < 2; v++) {
  169753. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  169754. inptr0 = input_data[inrow];
  169755. if (v == 0) /* next nearest is row above */
  169756. inptr1 = input_data[inrow-1];
  169757. else /* next nearest is row below */
  169758. inptr1 = input_data[inrow+1];
  169759. outptr = output_data[outrow++];
  169760. /* Special case for first column */
  169761. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169762. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169763. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  169764. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169765. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169766. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169767. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  169768. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  169769. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169770. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169771. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169772. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169773. }
  169774. /* Special case for last column */
  169775. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169776. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  169777. }
  169778. inrow++;
  169779. }
  169780. }
  169781. /*
  169782. * Module initialization routine for upsampling.
  169783. */
  169784. GLOBAL(void)
  169785. jinit_upsampler (j_decompress_ptr cinfo)
  169786. {
  169787. my_upsample_ptr2 upsample;
  169788. int ci;
  169789. jpeg_component_info * compptr;
  169790. boolean need_buffer, do_fancy;
  169791. int h_in_group, v_in_group, h_out_group, v_out_group;
  169792. upsample = (my_upsample_ptr2)
  169793. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169794. SIZEOF(my_upsampler2));
  169795. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169796. upsample->pub.start_pass = start_pass_upsample;
  169797. upsample->pub.upsample = sep_upsample;
  169798. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  169799. if (cinfo->CCIR601_sampling) /* this isn't supported */
  169800. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  169801. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  169802. * so don't ask for it.
  169803. */
  169804. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  169805. /* Verify we can handle the sampling factors, select per-component methods,
  169806. * and create storage as needed.
  169807. */
  169808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169809. ci++, compptr++) {
  169810. /* Compute size of an "input group" after IDCT scaling. This many samples
  169811. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  169812. */
  169813. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  169814. cinfo->min_DCT_scaled_size;
  169815. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169816. cinfo->min_DCT_scaled_size;
  169817. h_out_group = cinfo->max_h_samp_factor;
  169818. v_out_group = cinfo->max_v_samp_factor;
  169819. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  169820. need_buffer = TRUE;
  169821. if (! compptr->component_needed) {
  169822. /* Don't bother to upsample an uninteresting component. */
  169823. upsample->methods[ci] = noop_upsample;
  169824. need_buffer = FALSE;
  169825. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  169826. /* Fullsize components can be processed without any work. */
  169827. upsample->methods[ci] = fullsize_upsample;
  169828. need_buffer = FALSE;
  169829. } else if (h_in_group * 2 == h_out_group &&
  169830. v_in_group == v_out_group) {
  169831. /* Special cases for 2h1v upsampling */
  169832. if (do_fancy && compptr->downsampled_width > 2)
  169833. upsample->methods[ci] = h2v1_fancy_upsample;
  169834. else
  169835. upsample->methods[ci] = h2v1_upsample;
  169836. } else if (h_in_group * 2 == h_out_group &&
  169837. v_in_group * 2 == v_out_group) {
  169838. /* Special cases for 2h2v upsampling */
  169839. if (do_fancy && compptr->downsampled_width > 2) {
  169840. upsample->methods[ci] = h2v2_fancy_upsample;
  169841. upsample->pub.need_context_rows = TRUE;
  169842. } else
  169843. upsample->methods[ci] = h2v2_upsample;
  169844. } else if ((h_out_group % h_in_group) == 0 &&
  169845. (v_out_group % v_in_group) == 0) {
  169846. /* Generic integral-factors upsampling method */
  169847. upsample->methods[ci] = int_upsample;
  169848. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  169849. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  169850. } else
  169851. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  169852. if (need_buffer) {
  169853. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  169854. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169855. (JDIMENSION) jround_up((long) cinfo->output_width,
  169856. (long) cinfo->max_h_samp_factor),
  169857. (JDIMENSION) cinfo->max_v_samp_factor);
  169858. }
  169859. }
  169860. }
  169861. /********* End of inlined file: jdsample.c *********/
  169862. /********* Start of inlined file: jdtrans.c *********/
  169863. #define JPEG_INTERNALS
  169864. /* Forward declarations */
  169865. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  169866. /*
  169867. * Read the coefficient arrays from a JPEG file.
  169868. * jpeg_read_header must be completed before calling this.
  169869. *
  169870. * The entire image is read into a set of virtual coefficient-block arrays,
  169871. * one per component. The return value is a pointer to the array of
  169872. * virtual-array descriptors. These can be manipulated directly via the
  169873. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  169874. * To release the memory occupied by the virtual arrays, call
  169875. * jpeg_finish_decompress() when done with the data.
  169876. *
  169877. * An alternative usage is to simply obtain access to the coefficient arrays
  169878. * during a buffered-image-mode decompression operation. This is allowed
  169879. * after any jpeg_finish_output() call. The arrays can be accessed until
  169880. * jpeg_finish_decompress() is called. (Note that any call to the library
  169881. * may reposition the arrays, so don't rely on access_virt_barray() results
  169882. * to stay valid across library calls.)
  169883. *
  169884. * Returns NULL if suspended. This case need be checked only if
  169885. * a suspending data source is used.
  169886. */
  169887. GLOBAL(jvirt_barray_ptr *)
  169888. jpeg_read_coefficients (j_decompress_ptr cinfo)
  169889. {
  169890. if (cinfo->global_state == DSTATE_READY) {
  169891. /* First call: initialize active modules */
  169892. transdecode_master_selection(cinfo);
  169893. cinfo->global_state = DSTATE_RDCOEFS;
  169894. }
  169895. if (cinfo->global_state == DSTATE_RDCOEFS) {
  169896. /* Absorb whole file into the coef buffer */
  169897. for (;;) {
  169898. int retcode;
  169899. /* Call progress monitor hook if present */
  169900. if (cinfo->progress != NULL)
  169901. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  169902. /* Absorb some more input */
  169903. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  169904. if (retcode == JPEG_SUSPENDED)
  169905. return NULL;
  169906. if (retcode == JPEG_REACHED_EOI)
  169907. break;
  169908. /* Advance progress counter if appropriate */
  169909. if (cinfo->progress != NULL &&
  169910. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  169911. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  169912. /* startup underestimated number of scans; ratchet up one scan */
  169913. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  169914. }
  169915. }
  169916. }
  169917. /* Set state so that jpeg_finish_decompress does the right thing */
  169918. cinfo->global_state = DSTATE_STOPPING;
  169919. }
  169920. /* At this point we should be in state DSTATE_STOPPING if being used
  169921. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  169922. * to the coefficients during a full buffered-image-mode decompression.
  169923. */
  169924. if ((cinfo->global_state == DSTATE_STOPPING ||
  169925. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  169926. return cinfo->coef->coef_arrays;
  169927. }
  169928. /* Oops, improper usage */
  169929. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169930. return NULL; /* keep compiler happy */
  169931. }
  169932. /*
  169933. * Master selection of decompression modules for transcoding.
  169934. * This substitutes for jdmaster.c's initialization of the full decompressor.
  169935. */
  169936. LOCAL(void)
  169937. transdecode_master_selection (j_decompress_ptr cinfo)
  169938. {
  169939. /* This is effectively a buffered-image operation. */
  169940. cinfo->buffered_image = TRUE;
  169941. /* Entropy decoding: either Huffman or arithmetic coding. */
  169942. if (cinfo->arith_code) {
  169943. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169944. } else {
  169945. if (cinfo->progressive_mode) {
  169946. #ifdef D_PROGRESSIVE_SUPPORTED
  169947. jinit_phuff_decoder(cinfo);
  169948. #else
  169949. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169950. #endif
  169951. } else
  169952. jinit_huff_decoder(cinfo);
  169953. }
  169954. /* Always get a full-image coefficient buffer. */
  169955. jinit_d_coef_controller(cinfo, TRUE);
  169956. /* We can now tell the memory manager to allocate virtual arrays. */
  169957. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169958. /* Initialize input side of decompressor to consume first scan. */
  169959. (*cinfo->inputctl->start_input_pass) (cinfo);
  169960. /* Initialize progress monitoring. */
  169961. if (cinfo->progress != NULL) {
  169962. int nscans;
  169963. /* Estimate number of scans to set pass_limit. */
  169964. if (cinfo->progressive_mode) {
  169965. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169966. nscans = 2 + 3 * cinfo->num_components;
  169967. } else if (cinfo->inputctl->has_multiple_scans) {
  169968. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169969. nscans = cinfo->num_components;
  169970. } else {
  169971. nscans = 1;
  169972. }
  169973. cinfo->progress->pass_counter = 0L;
  169974. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169975. cinfo->progress->completed_passes = 0;
  169976. cinfo->progress->total_passes = 1;
  169977. }
  169978. }
  169979. /********* End of inlined file: jdtrans.c *********/
  169980. /********* Start of inlined file: jfdctflt.c *********/
  169981. #define JPEG_INTERNALS
  169982. #ifdef DCT_FLOAT_SUPPORTED
  169983. /*
  169984. * This module is specialized to the case DCTSIZE = 8.
  169985. */
  169986. #if DCTSIZE != 8
  169987. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169988. #endif
  169989. /*
  169990. * Perform the forward DCT on one block of samples.
  169991. */
  169992. GLOBAL(void)
  169993. jpeg_fdct_float (FAST_FLOAT * data)
  169994. {
  169995. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169996. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169997. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  169998. FAST_FLOAT *dataptr;
  169999. int ctr;
  170000. /* Pass 1: process rows. */
  170001. dataptr = data;
  170002. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170003. tmp0 = dataptr[0] + dataptr[7];
  170004. tmp7 = dataptr[0] - dataptr[7];
  170005. tmp1 = dataptr[1] + dataptr[6];
  170006. tmp6 = dataptr[1] - dataptr[6];
  170007. tmp2 = dataptr[2] + dataptr[5];
  170008. tmp5 = dataptr[2] - dataptr[5];
  170009. tmp3 = dataptr[3] + dataptr[4];
  170010. tmp4 = dataptr[3] - dataptr[4];
  170011. /* Even part */
  170012. tmp10 = tmp0 + tmp3; /* phase 2 */
  170013. tmp13 = tmp0 - tmp3;
  170014. tmp11 = tmp1 + tmp2;
  170015. tmp12 = tmp1 - tmp2;
  170016. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170017. dataptr[4] = tmp10 - tmp11;
  170018. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170019. dataptr[2] = tmp13 + z1; /* phase 5 */
  170020. dataptr[6] = tmp13 - z1;
  170021. /* Odd part */
  170022. tmp10 = tmp4 + tmp5; /* phase 2 */
  170023. tmp11 = tmp5 + tmp6;
  170024. tmp12 = tmp6 + tmp7;
  170025. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170026. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170027. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170028. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170029. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170030. z11 = tmp7 + z3; /* phase 5 */
  170031. z13 = tmp7 - z3;
  170032. dataptr[5] = z13 + z2; /* phase 6 */
  170033. dataptr[3] = z13 - z2;
  170034. dataptr[1] = z11 + z4;
  170035. dataptr[7] = z11 - z4;
  170036. dataptr += DCTSIZE; /* advance pointer to next row */
  170037. }
  170038. /* Pass 2: process columns. */
  170039. dataptr = data;
  170040. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170041. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170042. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170043. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170044. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170045. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170046. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170047. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170048. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170049. /* Even part */
  170050. tmp10 = tmp0 + tmp3; /* phase 2 */
  170051. tmp13 = tmp0 - tmp3;
  170052. tmp11 = tmp1 + tmp2;
  170053. tmp12 = tmp1 - tmp2;
  170054. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170055. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170056. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170057. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170058. dataptr[DCTSIZE*6] = tmp13 - z1;
  170059. /* Odd part */
  170060. tmp10 = tmp4 + tmp5; /* phase 2 */
  170061. tmp11 = tmp5 + tmp6;
  170062. tmp12 = tmp6 + tmp7;
  170063. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170064. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170065. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170066. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170067. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170068. z11 = tmp7 + z3; /* phase 5 */
  170069. z13 = tmp7 - z3;
  170070. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170071. dataptr[DCTSIZE*3] = z13 - z2;
  170072. dataptr[DCTSIZE*1] = z11 + z4;
  170073. dataptr[DCTSIZE*7] = z11 - z4;
  170074. dataptr++; /* advance pointer to next column */
  170075. }
  170076. }
  170077. #endif /* DCT_FLOAT_SUPPORTED */
  170078. /********* End of inlined file: jfdctflt.c *********/
  170079. /********* Start of inlined file: jfdctint.c *********/
  170080. #define JPEG_INTERNALS
  170081. #ifdef DCT_ISLOW_SUPPORTED
  170082. /*
  170083. * This module is specialized to the case DCTSIZE = 8.
  170084. */
  170085. #if DCTSIZE != 8
  170086. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170087. #endif
  170088. /*
  170089. * The poop on this scaling stuff is as follows:
  170090. *
  170091. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  170092. * larger than the true DCT outputs. The final outputs are therefore
  170093. * a factor of N larger than desired; since N=8 this can be cured by
  170094. * a simple right shift at the end of the algorithm. The advantage of
  170095. * this arrangement is that we save two multiplications per 1-D DCT,
  170096. * because the y0 and y4 outputs need not be divided by sqrt(N).
  170097. * In the IJG code, this factor of 8 is removed by the quantization step
  170098. * (in jcdctmgr.c), NOT in this module.
  170099. *
  170100. * We have to do addition and subtraction of the integer inputs, which
  170101. * is no problem, and multiplication by fractional constants, which is
  170102. * a problem to do in integer arithmetic. We multiply all the constants
  170103. * by CONST_SCALE and convert them to integer constants (thus retaining
  170104. * CONST_BITS bits of precision in the constants). After doing a
  170105. * multiplication we have to divide the product by CONST_SCALE, with proper
  170106. * rounding, to produce the correct output. This division can be done
  170107. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170108. * as long as possible so that partial sums can be added together with
  170109. * full fractional precision.
  170110. *
  170111. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170112. * they are represented to better-than-integral precision. These outputs
  170113. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170114. * with the recommended scaling. (For 12-bit sample data, the intermediate
  170115. * array is INT32 anyway.)
  170116. *
  170117. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170118. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170119. * shows that the values given below are the most effective.
  170120. */
  170121. #if BITS_IN_JSAMPLE == 8
  170122. #define CONST_BITS 13
  170123. #define PASS1_BITS 2
  170124. #else
  170125. #define CONST_BITS 13
  170126. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170127. #endif
  170128. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170129. * causing a lot of useless floating-point operations at run time.
  170130. * To get around this we use the following pre-calculated constants.
  170131. * If you change CONST_BITS you may want to add appropriate values.
  170132. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170133. */
  170134. #if CONST_BITS == 13
  170135. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170136. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170137. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170138. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170139. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170140. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170141. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170142. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170143. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170144. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170145. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170146. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170147. #else
  170148. #define FIX_0_298631336 FIX(0.298631336)
  170149. #define FIX_0_390180644 FIX(0.390180644)
  170150. #define FIX_0_541196100 FIX(0.541196100)
  170151. #define FIX_0_765366865 FIX(0.765366865)
  170152. #define FIX_0_899976223 FIX(0.899976223)
  170153. #define FIX_1_175875602 FIX(1.175875602)
  170154. #define FIX_1_501321110 FIX(1.501321110)
  170155. #define FIX_1_847759065 FIX(1.847759065)
  170156. #define FIX_1_961570560 FIX(1.961570560)
  170157. #define FIX_2_053119869 FIX(2.053119869)
  170158. #define FIX_2_562915447 FIX(2.562915447)
  170159. #define FIX_3_072711026 FIX(3.072711026)
  170160. #endif
  170161. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170162. * For 8-bit samples with the recommended scaling, all the variable
  170163. * and constant values involved are no more than 16 bits wide, so a
  170164. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170165. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170166. */
  170167. #if BITS_IN_JSAMPLE == 8
  170168. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170169. #else
  170170. #define MULTIPLY(var,const) ((var) * (const))
  170171. #endif
  170172. /*
  170173. * Perform the forward DCT on one block of samples.
  170174. */
  170175. GLOBAL(void)
  170176. jpeg_fdct_islow (DCTELEM * data)
  170177. {
  170178. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170179. INT32 tmp10, tmp11, tmp12, tmp13;
  170180. INT32 z1, z2, z3, z4, z5;
  170181. DCTELEM *dataptr;
  170182. int ctr;
  170183. SHIFT_TEMPS
  170184. /* Pass 1: process rows. */
  170185. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  170186. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170187. dataptr = data;
  170188. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170189. tmp0 = dataptr[0] + dataptr[7];
  170190. tmp7 = dataptr[0] - dataptr[7];
  170191. tmp1 = dataptr[1] + dataptr[6];
  170192. tmp6 = dataptr[1] - dataptr[6];
  170193. tmp2 = dataptr[2] + dataptr[5];
  170194. tmp5 = dataptr[2] - dataptr[5];
  170195. tmp3 = dataptr[3] + dataptr[4];
  170196. tmp4 = dataptr[3] - dataptr[4];
  170197. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170198. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170199. */
  170200. tmp10 = tmp0 + tmp3;
  170201. tmp13 = tmp0 - tmp3;
  170202. tmp11 = tmp1 + tmp2;
  170203. tmp12 = tmp1 - tmp2;
  170204. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  170205. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  170206. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170207. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170208. CONST_BITS-PASS1_BITS);
  170209. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170210. CONST_BITS-PASS1_BITS);
  170211. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170212. * cK represents cos(K*pi/16).
  170213. * i0..i3 in the paper are tmp4..tmp7 here.
  170214. */
  170215. z1 = tmp4 + tmp7;
  170216. z2 = tmp5 + tmp6;
  170217. z3 = tmp4 + tmp6;
  170218. z4 = tmp5 + tmp7;
  170219. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170220. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170221. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170222. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170223. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170224. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170225. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170226. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170227. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170228. z3 += z5;
  170229. z4 += z5;
  170230. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  170231. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  170232. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  170233. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  170234. dataptr += DCTSIZE; /* advance pointer to next row */
  170235. }
  170236. /* Pass 2: process columns.
  170237. * We remove the PASS1_BITS scaling, but leave the results scaled up
  170238. * by an overall factor of 8.
  170239. */
  170240. dataptr = data;
  170241. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170242. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170243. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170244. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170245. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170246. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170247. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170248. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170249. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170250. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170251. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170252. */
  170253. tmp10 = tmp0 + tmp3;
  170254. tmp13 = tmp0 - tmp3;
  170255. tmp11 = tmp1 + tmp2;
  170256. tmp12 = tmp1 - tmp2;
  170257. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  170258. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  170259. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170260. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170261. CONST_BITS+PASS1_BITS);
  170262. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170263. CONST_BITS+PASS1_BITS);
  170264. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170265. * cK represents cos(K*pi/16).
  170266. * i0..i3 in the paper are tmp4..tmp7 here.
  170267. */
  170268. z1 = tmp4 + tmp7;
  170269. z2 = tmp5 + tmp6;
  170270. z3 = tmp4 + tmp6;
  170271. z4 = tmp5 + tmp7;
  170272. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170273. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170274. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170275. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170276. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170277. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170278. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170279. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170280. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170281. z3 += z5;
  170282. z4 += z5;
  170283. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  170284. CONST_BITS+PASS1_BITS);
  170285. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  170286. CONST_BITS+PASS1_BITS);
  170287. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  170288. CONST_BITS+PASS1_BITS);
  170289. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  170290. CONST_BITS+PASS1_BITS);
  170291. dataptr++; /* advance pointer to next column */
  170292. }
  170293. }
  170294. #endif /* DCT_ISLOW_SUPPORTED */
  170295. /********* End of inlined file: jfdctint.c *********/
  170296. #undef CONST_BITS
  170297. #undef MULTIPLY
  170298. #undef FIX_0_541196100
  170299. /********* Start of inlined file: jfdctfst.c *********/
  170300. #define JPEG_INTERNALS
  170301. #ifdef DCT_IFAST_SUPPORTED
  170302. /*
  170303. * This module is specialized to the case DCTSIZE = 8.
  170304. */
  170305. #if DCTSIZE != 8
  170306. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170307. #endif
  170308. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170309. * see jfdctint.c for more details. However, we choose to descale
  170310. * (right shift) multiplication products as soon as they are formed,
  170311. * rather than carrying additional fractional bits into subsequent additions.
  170312. * This compromises accuracy slightly, but it lets us save a few shifts.
  170313. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170314. * everywhere except in the multiplications proper; this saves a good deal
  170315. * of work on 16-bit-int machines.
  170316. *
  170317. * Again to save a few shifts, the intermediate results between pass 1 and
  170318. * pass 2 are not upscaled, but are represented only to integral precision.
  170319. *
  170320. * A final compromise is to represent the multiplicative constants to only
  170321. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170322. * machines, and may also reduce the cost of multiplication (since there
  170323. * are fewer one-bits in the constants).
  170324. */
  170325. #define CONST_BITS 8
  170326. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170327. * causing a lot of useless floating-point operations at run time.
  170328. * To get around this we use the following pre-calculated constants.
  170329. * If you change CONST_BITS you may want to add appropriate values.
  170330. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170331. */
  170332. #if CONST_BITS == 8
  170333. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  170334. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  170335. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  170336. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  170337. #else
  170338. #define FIX_0_382683433 FIX(0.382683433)
  170339. #define FIX_0_541196100 FIX(0.541196100)
  170340. #define FIX_0_707106781 FIX(0.707106781)
  170341. #define FIX_1_306562965 FIX(1.306562965)
  170342. #endif
  170343. /* We can gain a little more speed, with a further compromise in accuracy,
  170344. * by omitting the addition in a descaling shift. This yields an incorrectly
  170345. * rounded result half the time...
  170346. */
  170347. #ifndef USE_ACCURATE_ROUNDING
  170348. #undef DESCALE
  170349. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170350. #endif
  170351. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170352. * descale to yield a DCTELEM result.
  170353. */
  170354. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170355. /*
  170356. * Perform the forward DCT on one block of samples.
  170357. */
  170358. GLOBAL(void)
  170359. jpeg_fdct_ifast (DCTELEM * data)
  170360. {
  170361. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170362. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170363. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  170364. DCTELEM *dataptr;
  170365. int ctr;
  170366. SHIFT_TEMPS
  170367. /* Pass 1: process rows. */
  170368. dataptr = data;
  170369. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170370. tmp0 = dataptr[0] + dataptr[7];
  170371. tmp7 = dataptr[0] - dataptr[7];
  170372. tmp1 = dataptr[1] + dataptr[6];
  170373. tmp6 = dataptr[1] - dataptr[6];
  170374. tmp2 = dataptr[2] + dataptr[5];
  170375. tmp5 = dataptr[2] - dataptr[5];
  170376. tmp3 = dataptr[3] + dataptr[4];
  170377. tmp4 = dataptr[3] - dataptr[4];
  170378. /* Even part */
  170379. tmp10 = tmp0 + tmp3; /* phase 2 */
  170380. tmp13 = tmp0 - tmp3;
  170381. tmp11 = tmp1 + tmp2;
  170382. tmp12 = tmp1 - tmp2;
  170383. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170384. dataptr[4] = tmp10 - tmp11;
  170385. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170386. dataptr[2] = tmp13 + z1; /* phase 5 */
  170387. dataptr[6] = tmp13 - z1;
  170388. /* Odd part */
  170389. tmp10 = tmp4 + tmp5; /* phase 2 */
  170390. tmp11 = tmp5 + tmp6;
  170391. tmp12 = tmp6 + tmp7;
  170392. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170393. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170394. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170395. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170396. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170397. z11 = tmp7 + z3; /* phase 5 */
  170398. z13 = tmp7 - z3;
  170399. dataptr[5] = z13 + z2; /* phase 6 */
  170400. dataptr[3] = z13 - z2;
  170401. dataptr[1] = z11 + z4;
  170402. dataptr[7] = z11 - z4;
  170403. dataptr += DCTSIZE; /* advance pointer to next row */
  170404. }
  170405. /* Pass 2: process columns. */
  170406. dataptr = data;
  170407. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170408. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170409. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170410. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170411. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170412. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170413. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170414. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170415. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170416. /* Even part */
  170417. tmp10 = tmp0 + tmp3; /* phase 2 */
  170418. tmp13 = tmp0 - tmp3;
  170419. tmp11 = tmp1 + tmp2;
  170420. tmp12 = tmp1 - tmp2;
  170421. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170422. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170423. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170424. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170425. dataptr[DCTSIZE*6] = tmp13 - z1;
  170426. /* Odd part */
  170427. tmp10 = tmp4 + tmp5; /* phase 2 */
  170428. tmp11 = tmp5 + tmp6;
  170429. tmp12 = tmp6 + tmp7;
  170430. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170431. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170432. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170433. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170434. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170435. z11 = tmp7 + z3; /* phase 5 */
  170436. z13 = tmp7 - z3;
  170437. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170438. dataptr[DCTSIZE*3] = z13 - z2;
  170439. dataptr[DCTSIZE*1] = z11 + z4;
  170440. dataptr[DCTSIZE*7] = z11 - z4;
  170441. dataptr++; /* advance pointer to next column */
  170442. }
  170443. }
  170444. #endif /* DCT_IFAST_SUPPORTED */
  170445. /********* End of inlined file: jfdctfst.c *********/
  170446. #undef FIX_0_541196100
  170447. /********* Start of inlined file: jidctflt.c *********/
  170448. #define JPEG_INTERNALS
  170449. #ifdef DCT_FLOAT_SUPPORTED
  170450. /*
  170451. * This module is specialized to the case DCTSIZE = 8.
  170452. */
  170453. #if DCTSIZE != 8
  170454. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170455. #endif
  170456. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170457. * entry; produce a float result.
  170458. */
  170459. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  170460. /*
  170461. * Perform dequantization and inverse DCT on one block of coefficients.
  170462. */
  170463. GLOBAL(void)
  170464. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170465. JCOEFPTR coef_block,
  170466. JSAMPARRAY output_buf, JDIMENSION output_col)
  170467. {
  170468. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170469. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170470. FAST_FLOAT z5, z10, z11, z12, z13;
  170471. JCOEFPTR inptr;
  170472. FLOAT_MULT_TYPE * quantptr;
  170473. FAST_FLOAT * wsptr;
  170474. JSAMPROW outptr;
  170475. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170476. int ctr;
  170477. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  170478. SHIFT_TEMPS
  170479. /* Pass 1: process columns from input, store into work array. */
  170480. inptr = coef_block;
  170481. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  170482. wsptr = workspace;
  170483. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170484. /* Due to quantization, we will usually find that many of the input
  170485. * coefficients are zero, especially the AC terms. We can exploit this
  170486. * by short-circuiting the IDCT calculation for any column in which all
  170487. * the AC terms are zero. In that case each output is equal to the
  170488. * DC coefficient (with scale factor as needed).
  170489. * With typical images and quantization tables, half or more of the
  170490. * column DCT calculations can be simplified this way.
  170491. */
  170492. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170493. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170494. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170495. inptr[DCTSIZE*7] == 0) {
  170496. /* AC terms all zero */
  170497. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170498. wsptr[DCTSIZE*0] = dcval;
  170499. wsptr[DCTSIZE*1] = dcval;
  170500. wsptr[DCTSIZE*2] = dcval;
  170501. wsptr[DCTSIZE*3] = dcval;
  170502. wsptr[DCTSIZE*4] = dcval;
  170503. wsptr[DCTSIZE*5] = dcval;
  170504. wsptr[DCTSIZE*6] = dcval;
  170505. wsptr[DCTSIZE*7] = dcval;
  170506. inptr++; /* advance pointers to next column */
  170507. quantptr++;
  170508. wsptr++;
  170509. continue;
  170510. }
  170511. /* Even part */
  170512. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170513. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170514. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170515. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170516. tmp10 = tmp0 + tmp2; /* phase 3 */
  170517. tmp11 = tmp0 - tmp2;
  170518. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170519. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  170520. tmp0 = tmp10 + tmp13; /* phase 2 */
  170521. tmp3 = tmp10 - tmp13;
  170522. tmp1 = tmp11 + tmp12;
  170523. tmp2 = tmp11 - tmp12;
  170524. /* Odd part */
  170525. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170526. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170527. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170528. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170529. z13 = tmp6 + tmp5; /* phase 6 */
  170530. z10 = tmp6 - tmp5;
  170531. z11 = tmp4 + tmp7;
  170532. z12 = tmp4 - tmp7;
  170533. tmp7 = z11 + z13; /* phase 5 */
  170534. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  170535. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170536. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170537. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170538. tmp6 = tmp12 - tmp7; /* phase 2 */
  170539. tmp5 = tmp11 - tmp6;
  170540. tmp4 = tmp10 + tmp5;
  170541. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  170542. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  170543. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  170544. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  170545. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  170546. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  170547. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  170548. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  170549. inptr++; /* advance pointers to next column */
  170550. quantptr++;
  170551. wsptr++;
  170552. }
  170553. /* Pass 2: process rows from work array, store into output array. */
  170554. /* Note that we must descale the results by a factor of 8 == 2**3. */
  170555. wsptr = workspace;
  170556. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170557. outptr = output_buf[ctr] + output_col;
  170558. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170559. * However, the column calculation has created many nonzero AC terms, so
  170560. * the simplification applies less often (typically 5% to 10% of the time).
  170561. * And testing floats for zero is relatively expensive, so we don't bother.
  170562. */
  170563. /* Even part */
  170564. tmp10 = wsptr[0] + wsptr[4];
  170565. tmp11 = wsptr[0] - wsptr[4];
  170566. tmp13 = wsptr[2] + wsptr[6];
  170567. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  170568. tmp0 = tmp10 + tmp13;
  170569. tmp3 = tmp10 - tmp13;
  170570. tmp1 = tmp11 + tmp12;
  170571. tmp2 = tmp11 - tmp12;
  170572. /* Odd part */
  170573. z13 = wsptr[5] + wsptr[3];
  170574. z10 = wsptr[5] - wsptr[3];
  170575. z11 = wsptr[1] + wsptr[7];
  170576. z12 = wsptr[1] - wsptr[7];
  170577. tmp7 = z11 + z13;
  170578. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  170579. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170580. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170581. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170582. tmp6 = tmp12 - tmp7;
  170583. tmp5 = tmp11 - tmp6;
  170584. tmp4 = tmp10 + tmp5;
  170585. /* Final output stage: scale down by a factor of 8 and range-limit */
  170586. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  170587. & RANGE_MASK];
  170588. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  170589. & RANGE_MASK];
  170590. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  170591. & RANGE_MASK];
  170592. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  170593. & RANGE_MASK];
  170594. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  170595. & RANGE_MASK];
  170596. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  170597. & RANGE_MASK];
  170598. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  170599. & RANGE_MASK];
  170600. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  170601. & RANGE_MASK];
  170602. wsptr += DCTSIZE; /* advance pointer to next row */
  170603. }
  170604. }
  170605. #endif /* DCT_FLOAT_SUPPORTED */
  170606. /********* End of inlined file: jidctflt.c *********/
  170607. #undef CONST_BITS
  170608. #undef FIX_1_847759065
  170609. #undef MULTIPLY
  170610. #undef DEQUANTIZE
  170611. #undef DESCALE
  170612. /********* Start of inlined file: jidctfst.c *********/
  170613. #define JPEG_INTERNALS
  170614. #ifdef DCT_IFAST_SUPPORTED
  170615. /*
  170616. * This module is specialized to the case DCTSIZE = 8.
  170617. */
  170618. #if DCTSIZE != 8
  170619. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170620. #endif
  170621. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170622. * see jidctint.c for more details. However, we choose to descale
  170623. * (right shift) multiplication products as soon as they are formed,
  170624. * rather than carrying additional fractional bits into subsequent additions.
  170625. * This compromises accuracy slightly, but it lets us save a few shifts.
  170626. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170627. * everywhere except in the multiplications proper; this saves a good deal
  170628. * of work on 16-bit-int machines.
  170629. *
  170630. * The dequantized coefficients are not integers because the AA&N scaling
  170631. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  170632. * so that the first and second IDCT rounds have the same input scaling.
  170633. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  170634. * avoid a descaling shift; this compromises accuracy rather drastically
  170635. * for small quantization table entries, but it saves a lot of shifts.
  170636. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  170637. * so we use a much larger scaling factor to preserve accuracy.
  170638. *
  170639. * A final compromise is to represent the multiplicative constants to only
  170640. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170641. * machines, and may also reduce the cost of multiplication (since there
  170642. * are fewer one-bits in the constants).
  170643. */
  170644. #if BITS_IN_JSAMPLE == 8
  170645. #define CONST_BITS 8
  170646. #define PASS1_BITS 2
  170647. #else
  170648. #define CONST_BITS 8
  170649. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170650. #endif
  170651. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170652. * causing a lot of useless floating-point operations at run time.
  170653. * To get around this we use the following pre-calculated constants.
  170654. * If you change CONST_BITS you may want to add appropriate values.
  170655. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170656. */
  170657. #if CONST_BITS == 8
  170658. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  170659. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  170660. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  170661. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  170662. #else
  170663. #define FIX_1_082392200 FIX(1.082392200)
  170664. #define FIX_1_414213562 FIX(1.414213562)
  170665. #define FIX_1_847759065 FIX(1.847759065)
  170666. #define FIX_2_613125930 FIX(2.613125930)
  170667. #endif
  170668. /* We can gain a little more speed, with a further compromise in accuracy,
  170669. * by omitting the addition in a descaling shift. This yields an incorrectly
  170670. * rounded result half the time...
  170671. */
  170672. #ifndef USE_ACCURATE_ROUNDING
  170673. #undef DESCALE
  170674. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170675. #endif
  170676. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170677. * descale to yield a DCTELEM result.
  170678. */
  170679. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170680. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170681. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  170682. * multiplication will do. For 12-bit data, the multiplier table is
  170683. * declared INT32, so a 32-bit multiply will be used.
  170684. */
  170685. #if BITS_IN_JSAMPLE == 8
  170686. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  170687. #else
  170688. #define DEQUANTIZE(coef,quantval) \
  170689. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  170690. #endif
  170691. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  170692. * We assume that int right shift is unsigned if INT32 right shift is.
  170693. */
  170694. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  170695. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  170696. #if BITS_IN_JSAMPLE == 8
  170697. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  170698. #else
  170699. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  170700. #endif
  170701. #define IRIGHT_SHIFT(x,shft) \
  170702. ((ishift_temp = (x)) < 0 ? \
  170703. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  170704. (ishift_temp >> (shft)))
  170705. #else
  170706. #define ISHIFT_TEMPS
  170707. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  170708. #endif
  170709. #ifdef USE_ACCURATE_ROUNDING
  170710. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  170711. #else
  170712. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  170713. #endif
  170714. /*
  170715. * Perform dequantization and inverse DCT on one block of coefficients.
  170716. */
  170717. GLOBAL(void)
  170718. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170719. JCOEFPTR coef_block,
  170720. JSAMPARRAY output_buf, JDIMENSION output_col)
  170721. {
  170722. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170723. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170724. DCTELEM z5, z10, z11, z12, z13;
  170725. JCOEFPTR inptr;
  170726. IFAST_MULT_TYPE * quantptr;
  170727. int * wsptr;
  170728. JSAMPROW outptr;
  170729. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170730. int ctr;
  170731. int workspace[DCTSIZE2]; /* buffers data between passes */
  170732. SHIFT_TEMPS /* for DESCALE */
  170733. ISHIFT_TEMPS /* for IDESCALE */
  170734. /* Pass 1: process columns from input, store into work array. */
  170735. inptr = coef_block;
  170736. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  170737. wsptr = workspace;
  170738. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170739. /* Due to quantization, we will usually find that many of the input
  170740. * coefficients are zero, especially the AC terms. We can exploit this
  170741. * by short-circuiting the IDCT calculation for any column in which all
  170742. * the AC terms are zero. In that case each output is equal to the
  170743. * DC coefficient (with scale factor as needed).
  170744. * With typical images and quantization tables, half or more of the
  170745. * column DCT calculations can be simplified this way.
  170746. */
  170747. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170748. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170749. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170750. inptr[DCTSIZE*7] == 0) {
  170751. /* AC terms all zero */
  170752. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170753. wsptr[DCTSIZE*0] = dcval;
  170754. wsptr[DCTSIZE*1] = dcval;
  170755. wsptr[DCTSIZE*2] = dcval;
  170756. wsptr[DCTSIZE*3] = dcval;
  170757. wsptr[DCTSIZE*4] = dcval;
  170758. wsptr[DCTSIZE*5] = dcval;
  170759. wsptr[DCTSIZE*6] = dcval;
  170760. wsptr[DCTSIZE*7] = dcval;
  170761. inptr++; /* advance pointers to next column */
  170762. quantptr++;
  170763. wsptr++;
  170764. continue;
  170765. }
  170766. /* Even part */
  170767. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170768. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170769. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170770. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170771. tmp10 = tmp0 + tmp2; /* phase 3 */
  170772. tmp11 = tmp0 - tmp2;
  170773. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170774. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  170775. tmp0 = tmp10 + tmp13; /* phase 2 */
  170776. tmp3 = tmp10 - tmp13;
  170777. tmp1 = tmp11 + tmp12;
  170778. tmp2 = tmp11 - tmp12;
  170779. /* Odd part */
  170780. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170781. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170782. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170783. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170784. z13 = tmp6 + tmp5; /* phase 6 */
  170785. z10 = tmp6 - tmp5;
  170786. z11 = tmp4 + tmp7;
  170787. z12 = tmp4 - tmp7;
  170788. tmp7 = z11 + z13; /* phase 5 */
  170789. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170790. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170791. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170792. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170793. tmp6 = tmp12 - tmp7; /* phase 2 */
  170794. tmp5 = tmp11 - tmp6;
  170795. tmp4 = tmp10 + tmp5;
  170796. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  170797. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  170798. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  170799. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  170800. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  170801. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  170802. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  170803. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  170804. inptr++; /* advance pointers to next column */
  170805. quantptr++;
  170806. wsptr++;
  170807. }
  170808. /* Pass 2: process rows from work array, store into output array. */
  170809. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170810. /* and also undo the PASS1_BITS scaling. */
  170811. wsptr = workspace;
  170812. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170813. outptr = output_buf[ctr] + output_col;
  170814. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170815. * However, the column calculation has created many nonzero AC terms, so
  170816. * the simplification applies less often (typically 5% to 10% of the time).
  170817. * On machines with very fast multiplication, it's possible that the
  170818. * test takes more time than it's worth. In that case this section
  170819. * may be commented out.
  170820. */
  170821. #ifndef NO_ZERO_ROW_TEST
  170822. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170823. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170824. /* AC terms all zero */
  170825. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  170826. & RANGE_MASK];
  170827. outptr[0] = dcval;
  170828. outptr[1] = dcval;
  170829. outptr[2] = dcval;
  170830. outptr[3] = dcval;
  170831. outptr[4] = dcval;
  170832. outptr[5] = dcval;
  170833. outptr[6] = dcval;
  170834. outptr[7] = dcval;
  170835. wsptr += DCTSIZE; /* advance pointer to next row */
  170836. continue;
  170837. }
  170838. #endif
  170839. /* Even part */
  170840. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  170841. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  170842. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  170843. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  170844. - tmp13;
  170845. tmp0 = tmp10 + tmp13;
  170846. tmp3 = tmp10 - tmp13;
  170847. tmp1 = tmp11 + tmp12;
  170848. tmp2 = tmp11 - tmp12;
  170849. /* Odd part */
  170850. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  170851. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  170852. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  170853. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  170854. tmp7 = z11 + z13; /* phase 5 */
  170855. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170856. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170857. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170858. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170859. tmp6 = tmp12 - tmp7; /* phase 2 */
  170860. tmp5 = tmp11 - tmp6;
  170861. tmp4 = tmp10 + tmp5;
  170862. /* Final output stage: scale down by a factor of 8 and range-limit */
  170863. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  170864. & RANGE_MASK];
  170865. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  170866. & RANGE_MASK];
  170867. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  170868. & RANGE_MASK];
  170869. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  170870. & RANGE_MASK];
  170871. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  170872. & RANGE_MASK];
  170873. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  170874. & RANGE_MASK];
  170875. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  170876. & RANGE_MASK];
  170877. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  170878. & RANGE_MASK];
  170879. wsptr += DCTSIZE; /* advance pointer to next row */
  170880. }
  170881. }
  170882. #endif /* DCT_IFAST_SUPPORTED */
  170883. /********* End of inlined file: jidctfst.c *********/
  170884. #undef CONST_BITS
  170885. #undef FIX_1_847759065
  170886. #undef MULTIPLY
  170887. #undef DEQUANTIZE
  170888. /********* Start of inlined file: jidctint.c *********/
  170889. #define JPEG_INTERNALS
  170890. #ifdef DCT_ISLOW_SUPPORTED
  170891. /*
  170892. * This module is specialized to the case DCTSIZE = 8.
  170893. */
  170894. #if DCTSIZE != 8
  170895. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170896. #endif
  170897. /*
  170898. * The poop on this scaling stuff is as follows:
  170899. *
  170900. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  170901. * larger than the true IDCT outputs. The final outputs are therefore
  170902. * a factor of N larger than desired; since N=8 this can be cured by
  170903. * a simple right shift at the end of the algorithm. The advantage of
  170904. * this arrangement is that we save two multiplications per 1-D IDCT,
  170905. * because the y0 and y4 inputs need not be divided by sqrt(N).
  170906. *
  170907. * We have to do addition and subtraction of the integer inputs, which
  170908. * is no problem, and multiplication by fractional constants, which is
  170909. * a problem to do in integer arithmetic. We multiply all the constants
  170910. * by CONST_SCALE and convert them to integer constants (thus retaining
  170911. * CONST_BITS bits of precision in the constants). After doing a
  170912. * multiplication we have to divide the product by CONST_SCALE, with proper
  170913. * rounding, to produce the correct output. This division can be done
  170914. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170915. * as long as possible so that partial sums can be added together with
  170916. * full fractional precision.
  170917. *
  170918. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170919. * they are represented to better-than-integral precision. These outputs
  170920. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170921. * with the recommended scaling. (To scale up 12-bit sample data further, an
  170922. * intermediate INT32 array would be needed.)
  170923. *
  170924. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170925. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170926. * shows that the values given below are the most effective.
  170927. */
  170928. #if BITS_IN_JSAMPLE == 8
  170929. #define CONST_BITS 13
  170930. #define PASS1_BITS 2
  170931. #else
  170932. #define CONST_BITS 13
  170933. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170934. #endif
  170935. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170936. * causing a lot of useless floating-point operations at run time.
  170937. * To get around this we use the following pre-calculated constants.
  170938. * If you change CONST_BITS you may want to add appropriate values.
  170939. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170940. */
  170941. #if CONST_BITS == 13
  170942. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170943. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170944. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170945. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170946. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170947. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170948. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170949. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170950. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170951. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170952. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170953. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170954. #else
  170955. #define FIX_0_298631336 FIX(0.298631336)
  170956. #define FIX_0_390180644 FIX(0.390180644)
  170957. #define FIX_0_541196100 FIX(0.541196100)
  170958. #define FIX_0_765366865 FIX(0.765366865)
  170959. #define FIX_0_899976223 FIX(0.899976223)
  170960. #define FIX_1_175875602 FIX(1.175875602)
  170961. #define FIX_1_501321110 FIX(1.501321110)
  170962. #define FIX_1_847759065 FIX(1.847759065)
  170963. #define FIX_1_961570560 FIX(1.961570560)
  170964. #define FIX_2_053119869 FIX(2.053119869)
  170965. #define FIX_2_562915447 FIX(2.562915447)
  170966. #define FIX_3_072711026 FIX(3.072711026)
  170967. #endif
  170968. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170969. * For 8-bit samples with the recommended scaling, all the variable
  170970. * and constant values involved are no more than 16 bits wide, so a
  170971. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170972. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170973. */
  170974. #if BITS_IN_JSAMPLE == 8
  170975. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170976. #else
  170977. #define MULTIPLY(var,const) ((var) * (const))
  170978. #endif
  170979. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170980. * entry; produce an int result. In this module, both inputs and result
  170981. * are 16 bits or less, so either int or short multiply will work.
  170982. */
  170983. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170984. /*
  170985. * Perform dequantization and inverse DCT on one block of coefficients.
  170986. */
  170987. GLOBAL(void)
  170988. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170989. JCOEFPTR coef_block,
  170990. JSAMPARRAY output_buf, JDIMENSION output_col)
  170991. {
  170992. INT32 tmp0, tmp1, tmp2, tmp3;
  170993. INT32 tmp10, tmp11, tmp12, tmp13;
  170994. INT32 z1, z2, z3, z4, z5;
  170995. JCOEFPTR inptr;
  170996. ISLOW_MULT_TYPE * quantptr;
  170997. int * wsptr;
  170998. JSAMPROW outptr;
  170999. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171000. int ctr;
  171001. int workspace[DCTSIZE2]; /* buffers data between passes */
  171002. SHIFT_TEMPS
  171003. /* Pass 1: process columns from input, store into work array. */
  171004. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  171005. /* furthermore, we scale the results by 2**PASS1_BITS. */
  171006. inptr = coef_block;
  171007. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171008. wsptr = workspace;
  171009. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171010. /* Due to quantization, we will usually find that many of the input
  171011. * coefficients are zero, especially the AC terms. We can exploit this
  171012. * by short-circuiting the IDCT calculation for any column in which all
  171013. * the AC terms are zero. In that case each output is equal to the
  171014. * DC coefficient (with scale factor as needed).
  171015. * With typical images and quantization tables, half or more of the
  171016. * column DCT calculations can be simplified this way.
  171017. */
  171018. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171019. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171020. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171021. inptr[DCTSIZE*7] == 0) {
  171022. /* AC terms all zero */
  171023. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171024. wsptr[DCTSIZE*0] = dcval;
  171025. wsptr[DCTSIZE*1] = dcval;
  171026. wsptr[DCTSIZE*2] = dcval;
  171027. wsptr[DCTSIZE*3] = dcval;
  171028. wsptr[DCTSIZE*4] = dcval;
  171029. wsptr[DCTSIZE*5] = dcval;
  171030. wsptr[DCTSIZE*6] = dcval;
  171031. wsptr[DCTSIZE*7] = dcval;
  171032. inptr++; /* advance pointers to next column */
  171033. quantptr++;
  171034. wsptr++;
  171035. continue;
  171036. }
  171037. /* Even part: reverse the even part of the forward DCT. */
  171038. /* The rotator is sqrt(2)*c(-6). */
  171039. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171040. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171041. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171042. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171043. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171044. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171045. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171046. tmp0 = (z2 + z3) << CONST_BITS;
  171047. tmp1 = (z2 - z3) << CONST_BITS;
  171048. tmp10 = tmp0 + tmp3;
  171049. tmp13 = tmp0 - tmp3;
  171050. tmp11 = tmp1 + tmp2;
  171051. tmp12 = tmp1 - tmp2;
  171052. /* Odd part per figure 8; the matrix is unitary and hence its
  171053. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171054. */
  171055. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171056. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171057. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171058. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171059. z1 = tmp0 + tmp3;
  171060. z2 = tmp1 + tmp2;
  171061. z3 = tmp0 + tmp2;
  171062. z4 = tmp1 + tmp3;
  171063. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171064. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171065. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171066. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171067. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171068. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171069. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171070. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171071. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171072. z3 += z5;
  171073. z4 += z5;
  171074. tmp0 += z1 + z3;
  171075. tmp1 += z2 + z4;
  171076. tmp2 += z2 + z3;
  171077. tmp3 += z1 + z4;
  171078. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171079. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  171080. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  171081. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  171082. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  171083. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  171084. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  171085. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  171086. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  171087. inptr++; /* advance pointers to next column */
  171088. quantptr++;
  171089. wsptr++;
  171090. }
  171091. /* Pass 2: process rows from work array, store into output array. */
  171092. /* Note that we must descale the results by a factor of 8 == 2**3, */
  171093. /* and also undo the PASS1_BITS scaling. */
  171094. wsptr = workspace;
  171095. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171096. outptr = output_buf[ctr] + output_col;
  171097. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171098. * However, the column calculation has created many nonzero AC terms, so
  171099. * the simplification applies less often (typically 5% to 10% of the time).
  171100. * On machines with very fast multiplication, it's possible that the
  171101. * test takes more time than it's worth. In that case this section
  171102. * may be commented out.
  171103. */
  171104. #ifndef NO_ZERO_ROW_TEST
  171105. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  171106. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171107. /* AC terms all zero */
  171108. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171109. & RANGE_MASK];
  171110. outptr[0] = dcval;
  171111. outptr[1] = dcval;
  171112. outptr[2] = dcval;
  171113. outptr[3] = dcval;
  171114. outptr[4] = dcval;
  171115. outptr[5] = dcval;
  171116. outptr[6] = dcval;
  171117. outptr[7] = dcval;
  171118. wsptr += DCTSIZE; /* advance pointer to next row */
  171119. continue;
  171120. }
  171121. #endif
  171122. /* Even part: reverse the even part of the forward DCT. */
  171123. /* The rotator is sqrt(2)*c(-6). */
  171124. z2 = (INT32) wsptr[2];
  171125. z3 = (INT32) wsptr[6];
  171126. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171127. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171128. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171129. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  171130. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  171131. tmp10 = tmp0 + tmp3;
  171132. tmp13 = tmp0 - tmp3;
  171133. tmp11 = tmp1 + tmp2;
  171134. tmp12 = tmp1 - tmp2;
  171135. /* Odd part per figure 8; the matrix is unitary and hence its
  171136. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171137. */
  171138. tmp0 = (INT32) wsptr[7];
  171139. tmp1 = (INT32) wsptr[5];
  171140. tmp2 = (INT32) wsptr[3];
  171141. tmp3 = (INT32) wsptr[1];
  171142. z1 = tmp0 + tmp3;
  171143. z2 = tmp1 + tmp2;
  171144. z3 = tmp0 + tmp2;
  171145. z4 = tmp1 + tmp3;
  171146. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171147. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171148. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171149. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171150. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171151. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171152. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171153. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171154. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171155. z3 += z5;
  171156. z4 += z5;
  171157. tmp0 += z1 + z3;
  171158. tmp1 += z2 + z4;
  171159. tmp2 += z2 + z3;
  171160. tmp3 += z1 + z4;
  171161. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171162. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  171163. CONST_BITS+PASS1_BITS+3)
  171164. & RANGE_MASK];
  171165. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  171166. CONST_BITS+PASS1_BITS+3)
  171167. & RANGE_MASK];
  171168. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  171169. CONST_BITS+PASS1_BITS+3)
  171170. & RANGE_MASK];
  171171. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  171172. CONST_BITS+PASS1_BITS+3)
  171173. & RANGE_MASK];
  171174. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  171175. CONST_BITS+PASS1_BITS+3)
  171176. & RANGE_MASK];
  171177. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  171178. CONST_BITS+PASS1_BITS+3)
  171179. & RANGE_MASK];
  171180. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  171181. CONST_BITS+PASS1_BITS+3)
  171182. & RANGE_MASK];
  171183. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  171184. CONST_BITS+PASS1_BITS+3)
  171185. & RANGE_MASK];
  171186. wsptr += DCTSIZE; /* advance pointer to next row */
  171187. }
  171188. }
  171189. #endif /* DCT_ISLOW_SUPPORTED */
  171190. /********* End of inlined file: jidctint.c *********/
  171191. /********* Start of inlined file: jidctred.c *********/
  171192. #define JPEG_INTERNALS
  171193. #ifdef IDCT_SCALING_SUPPORTED
  171194. /*
  171195. * This module is specialized to the case DCTSIZE = 8.
  171196. */
  171197. #if DCTSIZE != 8
  171198. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171199. #endif
  171200. /* Scaling is the same as in jidctint.c. */
  171201. #if BITS_IN_JSAMPLE == 8
  171202. #define CONST_BITS 13
  171203. #define PASS1_BITS 2
  171204. #else
  171205. #define CONST_BITS 13
  171206. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171207. #endif
  171208. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171209. * causing a lot of useless floating-point operations at run time.
  171210. * To get around this we use the following pre-calculated constants.
  171211. * If you change CONST_BITS you may want to add appropriate values.
  171212. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171213. */
  171214. #if CONST_BITS == 13
  171215. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  171216. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  171217. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  171218. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  171219. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171220. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  171221. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171222. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  171223. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  171224. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  171225. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171226. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  171227. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171228. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  171229. #else
  171230. #define FIX_0_211164243 FIX(0.211164243)
  171231. #define FIX_0_509795579 FIX(0.509795579)
  171232. #define FIX_0_601344887 FIX(0.601344887)
  171233. #define FIX_0_720959822 FIX(0.720959822)
  171234. #define FIX_0_765366865 FIX(0.765366865)
  171235. #define FIX_0_850430095 FIX(0.850430095)
  171236. #define FIX_0_899976223 FIX(0.899976223)
  171237. #define FIX_1_061594337 FIX(1.061594337)
  171238. #define FIX_1_272758580 FIX(1.272758580)
  171239. #define FIX_1_451774981 FIX(1.451774981)
  171240. #define FIX_1_847759065 FIX(1.847759065)
  171241. #define FIX_2_172734803 FIX(2.172734803)
  171242. #define FIX_2_562915447 FIX(2.562915447)
  171243. #define FIX_3_624509785 FIX(3.624509785)
  171244. #endif
  171245. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171246. * For 8-bit samples with the recommended scaling, all the variable
  171247. * and constant values involved are no more than 16 bits wide, so a
  171248. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171249. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171250. */
  171251. #if BITS_IN_JSAMPLE == 8
  171252. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171253. #else
  171254. #define MULTIPLY(var,const) ((var) * (const))
  171255. #endif
  171256. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171257. * entry; produce an int result. In this module, both inputs and result
  171258. * are 16 bits or less, so either int or short multiply will work.
  171259. */
  171260. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171261. /*
  171262. * Perform dequantization and inverse DCT on one block of coefficients,
  171263. * producing a reduced-size 4x4 output block.
  171264. */
  171265. GLOBAL(void)
  171266. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171267. JCOEFPTR coef_block,
  171268. JSAMPARRAY output_buf, JDIMENSION output_col)
  171269. {
  171270. INT32 tmp0, tmp2, tmp10, tmp12;
  171271. INT32 z1, z2, z3, z4;
  171272. JCOEFPTR inptr;
  171273. ISLOW_MULT_TYPE * quantptr;
  171274. int * wsptr;
  171275. JSAMPROW outptr;
  171276. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171277. int ctr;
  171278. int workspace[DCTSIZE*4]; /* buffers data between passes */
  171279. SHIFT_TEMPS
  171280. /* Pass 1: process columns from input, store into work array. */
  171281. inptr = coef_block;
  171282. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171283. wsptr = workspace;
  171284. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171285. /* Don't bother to process column 4, because second pass won't use it */
  171286. if (ctr == DCTSIZE-4)
  171287. continue;
  171288. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171289. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  171290. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  171291. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  171292. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171293. wsptr[DCTSIZE*0] = dcval;
  171294. wsptr[DCTSIZE*1] = dcval;
  171295. wsptr[DCTSIZE*2] = dcval;
  171296. wsptr[DCTSIZE*3] = dcval;
  171297. continue;
  171298. }
  171299. /* Even part */
  171300. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171301. tmp0 <<= (CONST_BITS+1);
  171302. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171303. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171304. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  171305. tmp10 = tmp0 + tmp2;
  171306. tmp12 = tmp0 - tmp2;
  171307. /* Odd part */
  171308. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171309. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171310. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171311. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171312. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171313. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171314. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171315. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171316. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171317. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171318. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171319. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171320. /* Final output stage */
  171321. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  171322. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  171323. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  171324. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  171325. }
  171326. /* Pass 2: process 4 rows from work array, store into output array. */
  171327. wsptr = workspace;
  171328. for (ctr = 0; ctr < 4; ctr++) {
  171329. outptr = output_buf[ctr] + output_col;
  171330. /* It's not clear whether a zero row test is worthwhile here ... */
  171331. #ifndef NO_ZERO_ROW_TEST
  171332. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  171333. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171334. /* AC terms all zero */
  171335. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171336. & RANGE_MASK];
  171337. outptr[0] = dcval;
  171338. outptr[1] = dcval;
  171339. outptr[2] = dcval;
  171340. outptr[3] = dcval;
  171341. wsptr += DCTSIZE; /* advance pointer to next row */
  171342. continue;
  171343. }
  171344. #endif
  171345. /* Even part */
  171346. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  171347. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  171348. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  171349. tmp10 = tmp0 + tmp2;
  171350. tmp12 = tmp0 - tmp2;
  171351. /* Odd part */
  171352. z1 = (INT32) wsptr[7];
  171353. z2 = (INT32) wsptr[5];
  171354. z3 = (INT32) wsptr[3];
  171355. z4 = (INT32) wsptr[1];
  171356. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171357. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171358. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171359. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171360. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171361. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171362. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171363. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171364. /* Final output stage */
  171365. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  171366. CONST_BITS+PASS1_BITS+3+1)
  171367. & RANGE_MASK];
  171368. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  171369. CONST_BITS+PASS1_BITS+3+1)
  171370. & RANGE_MASK];
  171371. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  171372. CONST_BITS+PASS1_BITS+3+1)
  171373. & RANGE_MASK];
  171374. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  171375. CONST_BITS+PASS1_BITS+3+1)
  171376. & RANGE_MASK];
  171377. wsptr += DCTSIZE; /* advance pointer to next row */
  171378. }
  171379. }
  171380. /*
  171381. * Perform dequantization and inverse DCT on one block of coefficients,
  171382. * producing a reduced-size 2x2 output block.
  171383. */
  171384. GLOBAL(void)
  171385. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171386. JCOEFPTR coef_block,
  171387. JSAMPARRAY output_buf, JDIMENSION output_col)
  171388. {
  171389. INT32 tmp0, tmp10, z1;
  171390. JCOEFPTR inptr;
  171391. ISLOW_MULT_TYPE * quantptr;
  171392. int * wsptr;
  171393. JSAMPROW outptr;
  171394. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171395. int ctr;
  171396. int workspace[DCTSIZE*2]; /* buffers data between passes */
  171397. SHIFT_TEMPS
  171398. /* Pass 1: process columns from input, store into work array. */
  171399. inptr = coef_block;
  171400. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171401. wsptr = workspace;
  171402. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171403. /* Don't bother to process columns 2,4,6 */
  171404. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  171405. continue;
  171406. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  171407. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  171408. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  171409. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171410. wsptr[DCTSIZE*0] = dcval;
  171411. wsptr[DCTSIZE*1] = dcval;
  171412. continue;
  171413. }
  171414. /* Even part */
  171415. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171416. tmp10 = z1 << (CONST_BITS+2);
  171417. /* Odd part */
  171418. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171419. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  171420. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171421. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  171422. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171423. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  171424. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171425. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171426. /* Final output stage */
  171427. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  171428. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  171429. }
  171430. /* Pass 2: process 2 rows from work array, store into output array. */
  171431. wsptr = workspace;
  171432. for (ctr = 0; ctr < 2; ctr++) {
  171433. outptr = output_buf[ctr] + output_col;
  171434. /* It's not clear whether a zero row test is worthwhile here ... */
  171435. #ifndef NO_ZERO_ROW_TEST
  171436. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  171437. /* AC terms all zero */
  171438. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171439. & RANGE_MASK];
  171440. outptr[0] = dcval;
  171441. outptr[1] = dcval;
  171442. wsptr += DCTSIZE; /* advance pointer to next row */
  171443. continue;
  171444. }
  171445. #endif
  171446. /* Even part */
  171447. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  171448. /* Odd part */
  171449. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  171450. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  171451. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  171452. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171453. /* Final output stage */
  171454. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  171455. CONST_BITS+PASS1_BITS+3+2)
  171456. & RANGE_MASK];
  171457. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  171458. CONST_BITS+PASS1_BITS+3+2)
  171459. & RANGE_MASK];
  171460. wsptr += DCTSIZE; /* advance pointer to next row */
  171461. }
  171462. }
  171463. /*
  171464. * Perform dequantization and inverse DCT on one block of coefficients,
  171465. * producing a reduced-size 1x1 output block.
  171466. */
  171467. GLOBAL(void)
  171468. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171469. JCOEFPTR coef_block,
  171470. JSAMPARRAY output_buf, JDIMENSION output_col)
  171471. {
  171472. int dcval;
  171473. ISLOW_MULT_TYPE * quantptr;
  171474. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171475. SHIFT_TEMPS
  171476. /* We hardly need an inverse DCT routine for this: just take the
  171477. * average pixel value, which is one-eighth of the DC coefficient.
  171478. */
  171479. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171480. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  171481. dcval = (int) DESCALE((INT32) dcval, 3);
  171482. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  171483. }
  171484. #endif /* IDCT_SCALING_SUPPORTED */
  171485. /********* End of inlined file: jidctred.c *********/
  171486. /********* Start of inlined file: jmemmgr.c *********/
  171487. #define JPEG_INTERNALS
  171488. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  171489. /********* Start of inlined file: jmemsys.h *********/
  171490. #ifndef __jmemsys_h__
  171491. #define __jmemsys_h__
  171492. /* Short forms of external names for systems with brain-damaged linkers. */
  171493. #ifdef NEED_SHORT_EXTERNAL_NAMES
  171494. #define jpeg_get_small jGetSmall
  171495. #define jpeg_free_small jFreeSmall
  171496. #define jpeg_get_large jGetLarge
  171497. #define jpeg_free_large jFreeLarge
  171498. #define jpeg_mem_available jMemAvail
  171499. #define jpeg_open_backing_store jOpenBackStore
  171500. #define jpeg_mem_init jMemInit
  171501. #define jpeg_mem_term jMemTerm
  171502. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  171503. /*
  171504. * These two functions are used to allocate and release small chunks of
  171505. * memory. (Typically the total amount requested through jpeg_get_small is
  171506. * no more than 20K or so; this will be requested in chunks of a few K each.)
  171507. * Behavior should be the same as for the standard library functions malloc
  171508. * and free; in particular, jpeg_get_small must return NULL on failure.
  171509. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  171510. * size of the object being freed, just in case it's needed.
  171511. * On an 80x86 machine using small-data memory model, these manage near heap.
  171512. */
  171513. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  171514. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  171515. size_t sizeofobject));
  171516. /*
  171517. * These two functions are used to allocate and release large chunks of
  171518. * memory (up to the total free space designated by jpeg_mem_available).
  171519. * The interface is the same as above, except that on an 80x86 machine,
  171520. * far pointers are used. On most other machines these are identical to
  171521. * the jpeg_get/free_small routines; but we keep them separate anyway,
  171522. * in case a different allocation strategy is desirable for large chunks.
  171523. */
  171524. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  171525. size_t sizeofobject));
  171526. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  171527. size_t sizeofobject));
  171528. /*
  171529. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  171530. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  171531. * matter, but that case should never come into play). This macro is needed
  171532. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  171533. * On those machines, we expect that jconfig.h will provide a proper value.
  171534. * On machines with 32-bit flat address spaces, any large constant may be used.
  171535. *
  171536. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  171537. * size_t and will be a multiple of sizeof(align_type).
  171538. */
  171539. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  171540. #define MAX_ALLOC_CHUNK 1000000000L
  171541. #endif
  171542. /*
  171543. * This routine computes the total space still available for allocation by
  171544. * jpeg_get_large. If more space than this is needed, backing store will be
  171545. * used. NOTE: any memory already allocated must not be counted.
  171546. *
  171547. * There is a minimum space requirement, corresponding to the minimum
  171548. * feasible buffer sizes; jmemmgr.c will request that much space even if
  171549. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  171550. * all working storage in memory, is also passed in case it is useful.
  171551. * Finally, the total space already allocated is passed. If no better
  171552. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  171553. * is often a suitable calculation.
  171554. *
  171555. * It is OK for jpeg_mem_available to underestimate the space available
  171556. * (that'll just lead to more backing-store access than is really necessary).
  171557. * However, an overestimate will lead to failure. Hence it's wise to subtract
  171558. * a slop factor from the true available space. 5% should be enough.
  171559. *
  171560. * On machines with lots of virtual memory, any large constant may be returned.
  171561. * Conversely, zero may be returned to always use the minimum amount of memory.
  171562. */
  171563. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  171564. long min_bytes_needed,
  171565. long max_bytes_needed,
  171566. long already_allocated));
  171567. /*
  171568. * This structure holds whatever state is needed to access a single
  171569. * backing-store object. The read/write/close method pointers are called
  171570. * by jmemmgr.c to manipulate the backing-store object; all other fields
  171571. * are private to the system-dependent backing store routines.
  171572. */
  171573. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  171574. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  171575. typedef unsigned short XMSH; /* type of extended-memory handles */
  171576. typedef unsigned short EMSH; /* type of expanded-memory handles */
  171577. typedef union {
  171578. short file_handle; /* DOS file handle if it's a temp file */
  171579. XMSH xms_handle; /* handle if it's a chunk of XMS */
  171580. EMSH ems_handle; /* handle if it's a chunk of EMS */
  171581. } handle_union;
  171582. #endif /* USE_MSDOS_MEMMGR */
  171583. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  171584. #include <Files.h>
  171585. #endif /* USE_MAC_MEMMGR */
  171586. //typedef struct backing_store_struct * backing_store_ptr;
  171587. typedef struct backing_store_struct {
  171588. /* Methods for reading/writing/closing this backing-store object */
  171589. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  171590. struct backing_store_struct *info,
  171591. void FAR * buffer_address,
  171592. long file_offset, long byte_count));
  171593. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  171594. struct backing_store_struct *info,
  171595. void FAR * buffer_address,
  171596. long file_offset, long byte_count));
  171597. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  171598. struct backing_store_struct *info));
  171599. /* Private fields for system-dependent backing-store management */
  171600. #ifdef USE_MSDOS_MEMMGR
  171601. /* For the MS-DOS manager (jmemdos.c), we need: */
  171602. handle_union handle; /* reference to backing-store storage object */
  171603. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171604. #else
  171605. #ifdef USE_MAC_MEMMGR
  171606. /* For the Mac manager (jmemmac.c), we need: */
  171607. short temp_file; /* file reference number to temp file */
  171608. FSSpec tempSpec; /* the FSSpec for the temp file */
  171609. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171610. #else
  171611. /* For a typical implementation with temp files, we need: */
  171612. FILE * temp_file; /* stdio reference to temp file */
  171613. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  171614. #endif
  171615. #endif
  171616. } backing_store_info;
  171617. /*
  171618. * Initial opening of a backing-store object. This must fill in the
  171619. * read/write/close pointers in the object. The read/write routines
  171620. * may take an error exit if the specified maximum file size is exceeded.
  171621. * (If jpeg_mem_available always returns a large value, this routine can
  171622. * just take an error exit.)
  171623. */
  171624. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  171625. struct backing_store_struct *info,
  171626. long total_bytes_needed));
  171627. /*
  171628. * These routines take care of any system-dependent initialization and
  171629. * cleanup required. jpeg_mem_init will be called before anything is
  171630. * allocated (and, therefore, nothing in cinfo is of use except the error
  171631. * manager pointer). It should return a suitable default value for
  171632. * max_memory_to_use; this may subsequently be overridden by the surrounding
  171633. * application. (Note that max_memory_to_use is only important if
  171634. * jpeg_mem_available chooses to consult it ... no one else will.)
  171635. * jpeg_mem_term may assume that all requested memory has been freed and that
  171636. * all opened backing-store objects have been closed.
  171637. */
  171638. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  171639. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  171640. #endif
  171641. /********* End of inlined file: jmemsys.h *********/
  171642. /* import the system-dependent declarations */
  171643. #ifndef NO_GETENV
  171644. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  171645. extern char * getenv JPP((const char * name));
  171646. #endif
  171647. #endif
  171648. /*
  171649. * Some important notes:
  171650. * The allocation routines provided here must never return NULL.
  171651. * They should exit to error_exit if unsuccessful.
  171652. *
  171653. * It's not a good idea to try to merge the sarray and barray routines,
  171654. * even though they are textually almost the same, because samples are
  171655. * usually stored as bytes while coefficients are shorts or ints. Thus,
  171656. * in machines where byte pointers have a different representation from
  171657. * word pointers, the resulting machine code could not be the same.
  171658. */
  171659. /*
  171660. * Many machines require storage alignment: longs must start on 4-byte
  171661. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  171662. * always returns pointers that are multiples of the worst-case alignment
  171663. * requirement, and we had better do so too.
  171664. * There isn't any really portable way to determine the worst-case alignment
  171665. * requirement. This module assumes that the alignment requirement is
  171666. * multiples of sizeof(ALIGN_TYPE).
  171667. * By default, we define ALIGN_TYPE as double. This is necessary on some
  171668. * workstations (where doubles really do need 8-byte alignment) and will work
  171669. * fine on nearly everything. If your machine has lesser alignment needs,
  171670. * you can save a few bytes by making ALIGN_TYPE smaller.
  171671. * The only place I know of where this will NOT work is certain Macintosh
  171672. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  171673. * Doing 10-byte alignment is counterproductive because longwords won't be
  171674. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  171675. * such a compiler.
  171676. */
  171677. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  171678. #define ALIGN_TYPE double
  171679. #endif
  171680. /*
  171681. * We allocate objects from "pools", where each pool is gotten with a single
  171682. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  171683. * overhead within a pool, except for alignment padding. Each pool has a
  171684. * header with a link to the next pool of the same class.
  171685. * Small and large pool headers are identical except that the latter's
  171686. * link pointer must be FAR on 80x86 machines.
  171687. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  171688. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  171689. * of the alignment requirement of ALIGN_TYPE.
  171690. */
  171691. typedef union small_pool_struct * small_pool_ptr;
  171692. typedef union small_pool_struct {
  171693. struct {
  171694. small_pool_ptr next; /* next in list of pools */
  171695. size_t bytes_used; /* how many bytes already used within pool */
  171696. size_t bytes_left; /* bytes still available in this pool */
  171697. } hdr;
  171698. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171699. } small_pool_hdr;
  171700. typedef union large_pool_struct FAR * large_pool_ptr;
  171701. typedef union large_pool_struct {
  171702. struct {
  171703. large_pool_ptr next; /* next in list of pools */
  171704. size_t bytes_used; /* how many bytes already used within pool */
  171705. size_t bytes_left; /* bytes still available in this pool */
  171706. } hdr;
  171707. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171708. } large_pool_hdr;
  171709. /*
  171710. * Here is the full definition of a memory manager object.
  171711. */
  171712. typedef struct {
  171713. struct jpeg_memory_mgr pub; /* public fields */
  171714. /* Each pool identifier (lifetime class) names a linked list of pools. */
  171715. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  171716. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  171717. /* Since we only have one lifetime class of virtual arrays, only one
  171718. * linked list is necessary (for each datatype). Note that the virtual
  171719. * array control blocks being linked together are actually stored somewhere
  171720. * in the small-pool list.
  171721. */
  171722. jvirt_sarray_ptr virt_sarray_list;
  171723. jvirt_barray_ptr virt_barray_list;
  171724. /* This counts total space obtained from jpeg_get_small/large */
  171725. long total_space_allocated;
  171726. /* alloc_sarray and alloc_barray set this value for use by virtual
  171727. * array routines.
  171728. */
  171729. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  171730. } my_memory_mgr;
  171731. typedef my_memory_mgr * my_mem_ptr;
  171732. /*
  171733. * The control blocks for virtual arrays.
  171734. * Note that these blocks are allocated in the "small" pool area.
  171735. * System-dependent info for the associated backing store (if any) is hidden
  171736. * inside the backing_store_info struct.
  171737. */
  171738. struct jvirt_sarray_control {
  171739. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  171740. JDIMENSION rows_in_array; /* total virtual array height */
  171741. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  171742. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  171743. JDIMENSION rows_in_mem; /* height of memory buffer */
  171744. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171745. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171746. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171747. boolean pre_zero; /* pre-zero mode requested? */
  171748. boolean dirty; /* do current buffer contents need written? */
  171749. boolean b_s_open; /* is backing-store data valid? */
  171750. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  171751. backing_store_info b_s_info; /* System-dependent control info */
  171752. };
  171753. struct jvirt_barray_control {
  171754. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  171755. JDIMENSION rows_in_array; /* total virtual array height */
  171756. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  171757. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  171758. JDIMENSION rows_in_mem; /* height of memory buffer */
  171759. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171760. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171761. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171762. boolean pre_zero; /* pre-zero mode requested? */
  171763. boolean dirty; /* do current buffer contents need written? */
  171764. boolean b_s_open; /* is backing-store data valid? */
  171765. jvirt_barray_ptr next; /* link to next virtual barray control block */
  171766. backing_store_info b_s_info; /* System-dependent control info */
  171767. };
  171768. #ifdef MEM_STATS /* optional extra stuff for statistics */
  171769. LOCAL(void)
  171770. print_mem_stats (j_common_ptr cinfo, int pool_id)
  171771. {
  171772. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171773. small_pool_ptr shdr_ptr;
  171774. large_pool_ptr lhdr_ptr;
  171775. /* Since this is only a debugging stub, we can cheat a little by using
  171776. * fprintf directly rather than going through the trace message code.
  171777. * This is helpful because message parm array can't handle longs.
  171778. */
  171779. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  171780. pool_id, mem->total_space_allocated);
  171781. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  171782. lhdr_ptr = lhdr_ptr->hdr.next) {
  171783. fprintf(stderr, " Large chunk used %ld\n",
  171784. (long) lhdr_ptr->hdr.bytes_used);
  171785. }
  171786. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  171787. shdr_ptr = shdr_ptr->hdr.next) {
  171788. fprintf(stderr, " Small chunk used %ld free %ld\n",
  171789. (long) shdr_ptr->hdr.bytes_used,
  171790. (long) shdr_ptr->hdr.bytes_left);
  171791. }
  171792. }
  171793. #endif /* MEM_STATS */
  171794. LOCAL(void)
  171795. out_of_memory (j_common_ptr cinfo, int which)
  171796. /* Report an out-of-memory error and stop execution */
  171797. /* If we compiled MEM_STATS support, report alloc requests before dying */
  171798. {
  171799. #ifdef MEM_STATS
  171800. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  171801. #endif
  171802. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  171803. }
  171804. /*
  171805. * Allocation of "small" objects.
  171806. *
  171807. * For these, we use pooled storage. When a new pool must be created,
  171808. * we try to get enough space for the current request plus a "slop" factor,
  171809. * where the slop will be the amount of leftover space in the new pool.
  171810. * The speed vs. space tradeoff is largely determined by the slop values.
  171811. * A different slop value is provided for each pool class (lifetime),
  171812. * and we also distinguish the first pool of a class from later ones.
  171813. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  171814. * machines, but may be too small if longs are 64 bits or more.
  171815. */
  171816. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  171817. {
  171818. 1600, /* first PERMANENT pool */
  171819. 16000 /* first IMAGE pool */
  171820. };
  171821. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  171822. {
  171823. 0, /* additional PERMANENT pools */
  171824. 5000 /* additional IMAGE pools */
  171825. };
  171826. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  171827. METHODDEF(void *)
  171828. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171829. /* Allocate a "small" object */
  171830. {
  171831. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171832. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  171833. char * data_ptr;
  171834. size_t odd_bytes, min_request, slop;
  171835. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171836. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  171837. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  171838. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171839. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171840. if (odd_bytes > 0)
  171841. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171842. /* See if space is available in any existing pool */
  171843. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171844. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171845. prev_hdr_ptr = NULL;
  171846. hdr_ptr = mem->small_list[pool_id];
  171847. while (hdr_ptr != NULL) {
  171848. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  171849. break; /* found pool with enough space */
  171850. prev_hdr_ptr = hdr_ptr;
  171851. hdr_ptr = hdr_ptr->hdr.next;
  171852. }
  171853. /* Time to make a new pool? */
  171854. if (hdr_ptr == NULL) {
  171855. /* min_request is what we need now, slop is what will be leftover */
  171856. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  171857. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171858. slop = first_pool_slop[pool_id];
  171859. else
  171860. slop = extra_pool_slop[pool_id];
  171861. /* Don't ask for more than MAX_ALLOC_CHUNK */
  171862. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  171863. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  171864. /* Try to get space, if fail reduce slop and try again */
  171865. for (;;) {
  171866. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  171867. if (hdr_ptr != NULL)
  171868. break;
  171869. slop /= 2;
  171870. if (slop < MIN_SLOP) /* give up when it gets real small */
  171871. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  171872. }
  171873. mem->total_space_allocated += min_request + slop;
  171874. /* Success, initialize the new pool header and add to end of list */
  171875. hdr_ptr->hdr.next = NULL;
  171876. hdr_ptr->hdr.bytes_used = 0;
  171877. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  171878. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171879. mem->small_list[pool_id] = hdr_ptr;
  171880. else
  171881. prev_hdr_ptr->hdr.next = hdr_ptr;
  171882. }
  171883. /* OK, allocate the object from the current pool */
  171884. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  171885. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  171886. hdr_ptr->hdr.bytes_used += sizeofobject;
  171887. hdr_ptr->hdr.bytes_left -= sizeofobject;
  171888. return (void *) data_ptr;
  171889. }
  171890. /*
  171891. * Allocation of "large" objects.
  171892. *
  171893. * The external semantics of these are the same as "small" objects,
  171894. * except that FAR pointers are used on 80x86. However the pool
  171895. * management heuristics are quite different. We assume that each
  171896. * request is large enough that it may as well be passed directly to
  171897. * jpeg_get_large; the pool management just links everything together
  171898. * so that we can free it all on demand.
  171899. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  171900. * structures. The routines that create these structures (see below)
  171901. * deliberately bunch rows together to ensure a large request size.
  171902. */
  171903. METHODDEF(void FAR *)
  171904. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171905. /* Allocate a "large" object */
  171906. {
  171907. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171908. large_pool_ptr hdr_ptr;
  171909. size_t odd_bytes;
  171910. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171911. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  171912. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  171913. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171914. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171915. if (odd_bytes > 0)
  171916. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171917. /* Always make a new pool */
  171918. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171919. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171920. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  171921. SIZEOF(large_pool_hdr));
  171922. if (hdr_ptr == NULL)
  171923. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  171924. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  171925. /* Success, initialize the new pool header and add to list */
  171926. hdr_ptr->hdr.next = mem->large_list[pool_id];
  171927. /* We maintain space counts in each pool header for statistical purposes,
  171928. * even though they are not needed for allocation.
  171929. */
  171930. hdr_ptr->hdr.bytes_used = sizeofobject;
  171931. hdr_ptr->hdr.bytes_left = 0;
  171932. mem->large_list[pool_id] = hdr_ptr;
  171933. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  171934. }
  171935. /*
  171936. * Creation of 2-D sample arrays.
  171937. * The pointers are in near heap, the samples themselves in FAR heap.
  171938. *
  171939. * To minimize allocation overhead and to allow I/O of large contiguous
  171940. * blocks, we allocate the sample rows in groups of as many rows as possible
  171941. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  171942. * NB: the virtual array control routines, later in this file, know about
  171943. * this chunking of rows. The rowsperchunk value is left in the mem manager
  171944. * object so that it can be saved away if this sarray is the workspace for
  171945. * a virtual array.
  171946. */
  171947. METHODDEF(JSAMPARRAY)
  171948. alloc_sarray (j_common_ptr cinfo, int pool_id,
  171949. JDIMENSION samplesperrow, JDIMENSION numrows)
  171950. /* Allocate a 2-D sample array */
  171951. {
  171952. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171953. JSAMPARRAY result;
  171954. JSAMPROW workspace;
  171955. JDIMENSION rowsperchunk, currow, i;
  171956. long ltemp;
  171957. /* Calculate max # of rows allowed in one allocation chunk */
  171958. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171959. ((long) samplesperrow * SIZEOF(JSAMPLE));
  171960. if (ltemp <= 0)
  171961. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171962. if (ltemp < (long) numrows)
  171963. rowsperchunk = (JDIMENSION) ltemp;
  171964. else
  171965. rowsperchunk = numrows;
  171966. mem->last_rowsperchunk = rowsperchunk;
  171967. /* Get space for row pointers (small object) */
  171968. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  171969. (size_t) (numrows * SIZEOF(JSAMPROW)));
  171970. /* Get the rows themselves (large objects) */
  171971. currow = 0;
  171972. while (currow < numrows) {
  171973. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171974. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  171975. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  171976. * SIZEOF(JSAMPLE)));
  171977. for (i = rowsperchunk; i > 0; i--) {
  171978. result[currow++] = workspace;
  171979. workspace += samplesperrow;
  171980. }
  171981. }
  171982. return result;
  171983. }
  171984. /*
  171985. * Creation of 2-D coefficient-block arrays.
  171986. * This is essentially the same as the code for sample arrays, above.
  171987. */
  171988. METHODDEF(JBLOCKARRAY)
  171989. alloc_barray (j_common_ptr cinfo, int pool_id,
  171990. JDIMENSION blocksperrow, JDIMENSION numrows)
  171991. /* Allocate a 2-D coefficient-block array */
  171992. {
  171993. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171994. JBLOCKARRAY result;
  171995. JBLOCKROW workspace;
  171996. JDIMENSION rowsperchunk, currow, i;
  171997. long ltemp;
  171998. /* Calculate max # of rows allowed in one allocation chunk */
  171999. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172000. ((long) blocksperrow * SIZEOF(JBLOCK));
  172001. if (ltemp <= 0)
  172002. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172003. if (ltemp < (long) numrows)
  172004. rowsperchunk = (JDIMENSION) ltemp;
  172005. else
  172006. rowsperchunk = numrows;
  172007. mem->last_rowsperchunk = rowsperchunk;
  172008. /* Get space for row pointers (small object) */
  172009. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  172010. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  172011. /* Get the rows themselves (large objects) */
  172012. currow = 0;
  172013. while (currow < numrows) {
  172014. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172015. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  172016. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  172017. * SIZEOF(JBLOCK)));
  172018. for (i = rowsperchunk; i > 0; i--) {
  172019. result[currow++] = workspace;
  172020. workspace += blocksperrow;
  172021. }
  172022. }
  172023. return result;
  172024. }
  172025. /*
  172026. * About virtual array management:
  172027. *
  172028. * The above "normal" array routines are only used to allocate strip buffers
  172029. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  172030. * are handled as "virtual" arrays. The array is still accessed a strip at a
  172031. * time, but the memory manager must save the whole array for repeated
  172032. * accesses. The intended implementation is that there is a strip buffer in
  172033. * memory (as high as is possible given the desired memory limit), plus a
  172034. * backing file that holds the rest of the array.
  172035. *
  172036. * The request_virt_array routines are told the total size of the image and
  172037. * the maximum number of rows that will be accessed at once. The in-memory
  172038. * buffer must be at least as large as the maxaccess value.
  172039. *
  172040. * The request routines create control blocks but not the in-memory buffers.
  172041. * That is postponed until realize_virt_arrays is called. At that time the
  172042. * total amount of space needed is known (approximately, anyway), so free
  172043. * memory can be divided up fairly.
  172044. *
  172045. * The access_virt_array routines are responsible for making a specific strip
  172046. * area accessible (after reading or writing the backing file, if necessary).
  172047. * Note that the access routines are told whether the caller intends to modify
  172048. * the accessed strip; during a read-only pass this saves having to rewrite
  172049. * data to disk. The access routines are also responsible for pre-zeroing
  172050. * any newly accessed rows, if pre-zeroing was requested.
  172051. *
  172052. * In current usage, the access requests are usually for nonoverlapping
  172053. * strips; that is, successive access start_row numbers differ by exactly
  172054. * num_rows = maxaccess. This means we can get good performance with simple
  172055. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  172056. * of the access height; then there will never be accesses across bufferload
  172057. * boundaries. The code will still work with overlapping access requests,
  172058. * but it doesn't handle bufferload overlaps very efficiently.
  172059. */
  172060. METHODDEF(jvirt_sarray_ptr)
  172061. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172062. JDIMENSION samplesperrow, JDIMENSION numrows,
  172063. JDIMENSION maxaccess)
  172064. /* Request a virtual 2-D sample array */
  172065. {
  172066. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172067. jvirt_sarray_ptr result;
  172068. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172069. if (pool_id != JPOOL_IMAGE)
  172070. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172071. /* get control block */
  172072. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  172073. SIZEOF(struct jvirt_sarray_control));
  172074. result->mem_buffer = NULL; /* marks array not yet realized */
  172075. result->rows_in_array = numrows;
  172076. result->samplesperrow = samplesperrow;
  172077. result->maxaccess = maxaccess;
  172078. result->pre_zero = pre_zero;
  172079. result->b_s_open = FALSE; /* no associated backing-store object */
  172080. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  172081. mem->virt_sarray_list = result;
  172082. return result;
  172083. }
  172084. METHODDEF(jvirt_barray_ptr)
  172085. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172086. JDIMENSION blocksperrow, JDIMENSION numrows,
  172087. JDIMENSION maxaccess)
  172088. /* Request a virtual 2-D coefficient-block array */
  172089. {
  172090. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172091. jvirt_barray_ptr result;
  172092. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172093. if (pool_id != JPOOL_IMAGE)
  172094. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172095. /* get control block */
  172096. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  172097. SIZEOF(struct jvirt_barray_control));
  172098. result->mem_buffer = NULL; /* marks array not yet realized */
  172099. result->rows_in_array = numrows;
  172100. result->blocksperrow = blocksperrow;
  172101. result->maxaccess = maxaccess;
  172102. result->pre_zero = pre_zero;
  172103. result->b_s_open = FALSE; /* no associated backing-store object */
  172104. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  172105. mem->virt_barray_list = result;
  172106. return result;
  172107. }
  172108. METHODDEF(void)
  172109. realize_virt_arrays (j_common_ptr cinfo)
  172110. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  172111. {
  172112. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172113. long space_per_minheight, maximum_space, avail_mem;
  172114. long minheights, max_minheights;
  172115. jvirt_sarray_ptr sptr;
  172116. jvirt_barray_ptr bptr;
  172117. /* Compute the minimum space needed (maxaccess rows in each buffer)
  172118. * and the maximum space needed (full image height in each buffer).
  172119. * These may be of use to the system-dependent jpeg_mem_available routine.
  172120. */
  172121. space_per_minheight = 0;
  172122. maximum_space = 0;
  172123. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172124. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172125. space_per_minheight += (long) sptr->maxaccess *
  172126. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172127. maximum_space += (long) sptr->rows_in_array *
  172128. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172129. }
  172130. }
  172131. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172132. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172133. space_per_minheight += (long) bptr->maxaccess *
  172134. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172135. maximum_space += (long) bptr->rows_in_array *
  172136. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172137. }
  172138. }
  172139. if (space_per_minheight <= 0)
  172140. return; /* no unrealized arrays, no work */
  172141. /* Determine amount of memory to actually use; this is system-dependent. */
  172142. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  172143. mem->total_space_allocated);
  172144. /* If the maximum space needed is available, make all the buffers full
  172145. * height; otherwise parcel it out with the same number of minheights
  172146. * in each buffer.
  172147. */
  172148. if (avail_mem >= maximum_space)
  172149. max_minheights = 1000000000L;
  172150. else {
  172151. max_minheights = avail_mem / space_per_minheight;
  172152. /* If there doesn't seem to be enough space, try to get the minimum
  172153. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  172154. */
  172155. if (max_minheights <= 0)
  172156. max_minheights = 1;
  172157. }
  172158. /* Allocate the in-memory buffers and initialize backing store as needed. */
  172159. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172160. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172161. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  172162. if (minheights <= max_minheights) {
  172163. /* This buffer fits in memory */
  172164. sptr->rows_in_mem = sptr->rows_in_array;
  172165. } else {
  172166. /* It doesn't fit in memory, create backing store. */
  172167. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  172168. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  172169. (long) sptr->rows_in_array *
  172170. (long) sptr->samplesperrow *
  172171. (long) SIZEOF(JSAMPLE));
  172172. sptr->b_s_open = TRUE;
  172173. }
  172174. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  172175. sptr->samplesperrow, sptr->rows_in_mem);
  172176. sptr->rowsperchunk = mem->last_rowsperchunk;
  172177. sptr->cur_start_row = 0;
  172178. sptr->first_undef_row = 0;
  172179. sptr->dirty = FALSE;
  172180. }
  172181. }
  172182. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172183. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172184. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  172185. if (minheights <= max_minheights) {
  172186. /* This buffer fits in memory */
  172187. bptr->rows_in_mem = bptr->rows_in_array;
  172188. } else {
  172189. /* It doesn't fit in memory, create backing store. */
  172190. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  172191. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  172192. (long) bptr->rows_in_array *
  172193. (long) bptr->blocksperrow *
  172194. (long) SIZEOF(JBLOCK));
  172195. bptr->b_s_open = TRUE;
  172196. }
  172197. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  172198. bptr->blocksperrow, bptr->rows_in_mem);
  172199. bptr->rowsperchunk = mem->last_rowsperchunk;
  172200. bptr->cur_start_row = 0;
  172201. bptr->first_undef_row = 0;
  172202. bptr->dirty = FALSE;
  172203. }
  172204. }
  172205. }
  172206. LOCAL(void)
  172207. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  172208. /* Do backing store read or write of a virtual sample array */
  172209. {
  172210. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172211. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172212. file_offset = ptr->cur_start_row * bytesperrow;
  172213. /* Loop to read or write each allocation chunk in mem_buffer */
  172214. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172215. /* One chunk, but check for short chunk at end of buffer */
  172216. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172217. /* Transfer no more than is currently defined */
  172218. thisrow = (long) ptr->cur_start_row + i;
  172219. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172220. /* Transfer no more than fits in file */
  172221. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172222. if (rows <= 0) /* this chunk might be past end of file! */
  172223. break;
  172224. byte_count = rows * bytesperrow;
  172225. if (writing)
  172226. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172227. (void FAR *) ptr->mem_buffer[i],
  172228. file_offset, byte_count);
  172229. else
  172230. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172231. (void FAR *) ptr->mem_buffer[i],
  172232. file_offset, byte_count);
  172233. file_offset += byte_count;
  172234. }
  172235. }
  172236. LOCAL(void)
  172237. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  172238. /* Do backing store read or write of a virtual coefficient-block array */
  172239. {
  172240. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172241. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  172242. file_offset = ptr->cur_start_row * bytesperrow;
  172243. /* Loop to read or write each allocation chunk in mem_buffer */
  172244. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172245. /* One chunk, but check for short chunk at end of buffer */
  172246. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172247. /* Transfer no more than is currently defined */
  172248. thisrow = (long) ptr->cur_start_row + i;
  172249. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172250. /* Transfer no more than fits in file */
  172251. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172252. if (rows <= 0) /* this chunk might be past end of file! */
  172253. break;
  172254. byte_count = rows * bytesperrow;
  172255. if (writing)
  172256. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172257. (void FAR *) ptr->mem_buffer[i],
  172258. file_offset, byte_count);
  172259. else
  172260. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172261. (void FAR *) ptr->mem_buffer[i],
  172262. file_offset, byte_count);
  172263. file_offset += byte_count;
  172264. }
  172265. }
  172266. METHODDEF(JSAMPARRAY)
  172267. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  172268. JDIMENSION start_row, JDIMENSION num_rows,
  172269. boolean writable)
  172270. /* Access the part of a virtual sample array starting at start_row */
  172271. /* and extending for num_rows rows. writable is true if */
  172272. /* caller intends to modify the accessed area. */
  172273. {
  172274. JDIMENSION end_row = start_row + num_rows;
  172275. JDIMENSION undef_row;
  172276. /* debugging check */
  172277. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172278. ptr->mem_buffer == NULL)
  172279. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172280. /* Make the desired part of the virtual array accessible */
  172281. if (start_row < ptr->cur_start_row ||
  172282. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172283. if (! ptr->b_s_open)
  172284. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172285. /* Flush old buffer contents if necessary */
  172286. if (ptr->dirty) {
  172287. do_sarray_io(cinfo, ptr, TRUE);
  172288. ptr->dirty = FALSE;
  172289. }
  172290. /* Decide what part of virtual array to access.
  172291. * Algorithm: if target address > current window, assume forward scan,
  172292. * load starting at target address. If target address < current window,
  172293. * assume backward scan, load so that target area is top of window.
  172294. * Note that when switching from forward write to forward read, will have
  172295. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172296. */
  172297. if (start_row > ptr->cur_start_row) {
  172298. ptr->cur_start_row = start_row;
  172299. } else {
  172300. /* use long arithmetic here to avoid overflow & unsigned problems */
  172301. long ltemp;
  172302. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172303. if (ltemp < 0)
  172304. ltemp = 0; /* don't fall off front end of file */
  172305. ptr->cur_start_row = (JDIMENSION) ltemp;
  172306. }
  172307. /* Read in the selected part of the array.
  172308. * During the initial write pass, we will do no actual read
  172309. * because the selected part is all undefined.
  172310. */
  172311. do_sarray_io(cinfo, ptr, FALSE);
  172312. }
  172313. /* Ensure the accessed part of the array is defined; prezero if needed.
  172314. * To improve locality of access, we only prezero the part of the array
  172315. * that the caller is about to access, not the entire in-memory array.
  172316. */
  172317. if (ptr->first_undef_row < end_row) {
  172318. if (ptr->first_undef_row < start_row) {
  172319. if (writable) /* writer skipped over a section of array */
  172320. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172321. undef_row = start_row; /* but reader is allowed to read ahead */
  172322. } else {
  172323. undef_row = ptr->first_undef_row;
  172324. }
  172325. if (writable)
  172326. ptr->first_undef_row = end_row;
  172327. if (ptr->pre_zero) {
  172328. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172329. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172330. end_row -= ptr->cur_start_row;
  172331. while (undef_row < end_row) {
  172332. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172333. undef_row++;
  172334. }
  172335. } else {
  172336. if (! writable) /* reader looking at undefined data */
  172337. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172338. }
  172339. }
  172340. /* Flag the buffer dirty if caller will write in it */
  172341. if (writable)
  172342. ptr->dirty = TRUE;
  172343. /* Return address of proper part of the buffer */
  172344. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172345. }
  172346. METHODDEF(JBLOCKARRAY)
  172347. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  172348. JDIMENSION start_row, JDIMENSION num_rows,
  172349. boolean writable)
  172350. /* Access the part of a virtual block array starting at start_row */
  172351. /* and extending for num_rows rows. writable is true if */
  172352. /* caller intends to modify the accessed area. */
  172353. {
  172354. JDIMENSION end_row = start_row + num_rows;
  172355. JDIMENSION undef_row;
  172356. /* debugging check */
  172357. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172358. ptr->mem_buffer == NULL)
  172359. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172360. /* Make the desired part of the virtual array accessible */
  172361. if (start_row < ptr->cur_start_row ||
  172362. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172363. if (! ptr->b_s_open)
  172364. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172365. /* Flush old buffer contents if necessary */
  172366. if (ptr->dirty) {
  172367. do_barray_io(cinfo, ptr, TRUE);
  172368. ptr->dirty = FALSE;
  172369. }
  172370. /* Decide what part of virtual array to access.
  172371. * Algorithm: if target address > current window, assume forward scan,
  172372. * load starting at target address. If target address < current window,
  172373. * assume backward scan, load so that target area is top of window.
  172374. * Note that when switching from forward write to forward read, will have
  172375. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172376. */
  172377. if (start_row > ptr->cur_start_row) {
  172378. ptr->cur_start_row = start_row;
  172379. } else {
  172380. /* use long arithmetic here to avoid overflow & unsigned problems */
  172381. long ltemp;
  172382. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172383. if (ltemp < 0)
  172384. ltemp = 0; /* don't fall off front end of file */
  172385. ptr->cur_start_row = (JDIMENSION) ltemp;
  172386. }
  172387. /* Read in the selected part of the array.
  172388. * During the initial write pass, we will do no actual read
  172389. * because the selected part is all undefined.
  172390. */
  172391. do_barray_io(cinfo, ptr, FALSE);
  172392. }
  172393. /* Ensure the accessed part of the array is defined; prezero if needed.
  172394. * To improve locality of access, we only prezero the part of the array
  172395. * that the caller is about to access, not the entire in-memory array.
  172396. */
  172397. if (ptr->first_undef_row < end_row) {
  172398. if (ptr->first_undef_row < start_row) {
  172399. if (writable) /* writer skipped over a section of array */
  172400. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172401. undef_row = start_row; /* but reader is allowed to read ahead */
  172402. } else {
  172403. undef_row = ptr->first_undef_row;
  172404. }
  172405. if (writable)
  172406. ptr->first_undef_row = end_row;
  172407. if (ptr->pre_zero) {
  172408. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  172409. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172410. end_row -= ptr->cur_start_row;
  172411. while (undef_row < end_row) {
  172412. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172413. undef_row++;
  172414. }
  172415. } else {
  172416. if (! writable) /* reader looking at undefined data */
  172417. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172418. }
  172419. }
  172420. /* Flag the buffer dirty if caller will write in it */
  172421. if (writable)
  172422. ptr->dirty = TRUE;
  172423. /* Return address of proper part of the buffer */
  172424. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172425. }
  172426. /*
  172427. * Release all objects belonging to a specified pool.
  172428. */
  172429. METHODDEF(void)
  172430. free_pool (j_common_ptr cinfo, int pool_id)
  172431. {
  172432. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172433. small_pool_ptr shdr_ptr;
  172434. large_pool_ptr lhdr_ptr;
  172435. size_t space_freed;
  172436. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172437. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172438. #ifdef MEM_STATS
  172439. if (cinfo->err->trace_level > 1)
  172440. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  172441. #endif
  172442. /* If freeing IMAGE pool, close any virtual arrays first */
  172443. if (pool_id == JPOOL_IMAGE) {
  172444. jvirt_sarray_ptr sptr;
  172445. jvirt_barray_ptr bptr;
  172446. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172447. if (sptr->b_s_open) { /* there may be no backing store */
  172448. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  172449. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  172450. }
  172451. }
  172452. mem->virt_sarray_list = NULL;
  172453. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172454. if (bptr->b_s_open) { /* there may be no backing store */
  172455. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  172456. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  172457. }
  172458. }
  172459. mem->virt_barray_list = NULL;
  172460. }
  172461. /* Release large objects */
  172462. lhdr_ptr = mem->large_list[pool_id];
  172463. mem->large_list[pool_id] = NULL;
  172464. while (lhdr_ptr != NULL) {
  172465. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  172466. space_freed = lhdr_ptr->hdr.bytes_used +
  172467. lhdr_ptr->hdr.bytes_left +
  172468. SIZEOF(large_pool_hdr);
  172469. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  172470. mem->total_space_allocated -= space_freed;
  172471. lhdr_ptr = next_lhdr_ptr;
  172472. }
  172473. /* Release small objects */
  172474. shdr_ptr = mem->small_list[pool_id];
  172475. mem->small_list[pool_id] = NULL;
  172476. while (shdr_ptr != NULL) {
  172477. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  172478. space_freed = shdr_ptr->hdr.bytes_used +
  172479. shdr_ptr->hdr.bytes_left +
  172480. SIZEOF(small_pool_hdr);
  172481. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  172482. mem->total_space_allocated -= space_freed;
  172483. shdr_ptr = next_shdr_ptr;
  172484. }
  172485. }
  172486. /*
  172487. * Close up shop entirely.
  172488. * Note that this cannot be called unless cinfo->mem is non-NULL.
  172489. */
  172490. METHODDEF(void)
  172491. self_destruct (j_common_ptr cinfo)
  172492. {
  172493. int pool;
  172494. /* Close all backing store, release all memory.
  172495. * Releasing pools in reverse order might help avoid fragmentation
  172496. * with some (brain-damaged) malloc libraries.
  172497. */
  172498. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172499. free_pool(cinfo, pool);
  172500. }
  172501. /* Release the memory manager control block too. */
  172502. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  172503. cinfo->mem = NULL; /* ensures I will be called only once */
  172504. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172505. }
  172506. /*
  172507. * Memory manager initialization.
  172508. * When this is called, only the error manager pointer is valid in cinfo!
  172509. */
  172510. GLOBAL(void)
  172511. jinit_memory_mgr (j_common_ptr cinfo)
  172512. {
  172513. my_mem_ptr mem;
  172514. long max_to_use;
  172515. int pool;
  172516. size_t test_mac;
  172517. cinfo->mem = NULL; /* for safety if init fails */
  172518. /* Check for configuration errors.
  172519. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  172520. * doesn't reflect any real hardware alignment requirement.
  172521. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  172522. * in common if and only if X is a power of 2, ie has only one one-bit.
  172523. * Some compilers may give an "unreachable code" warning here; ignore it.
  172524. */
  172525. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  172526. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  172527. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  172528. * a multiple of SIZEOF(ALIGN_TYPE).
  172529. * Again, an "unreachable code" warning may be ignored here.
  172530. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  172531. */
  172532. test_mac = (size_t) MAX_ALLOC_CHUNK;
  172533. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  172534. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  172535. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  172536. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  172537. /* Attempt to allocate memory manager's control block */
  172538. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  172539. if (mem == NULL) {
  172540. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172541. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  172542. }
  172543. /* OK, fill in the method pointers */
  172544. mem->pub.alloc_small = alloc_small;
  172545. mem->pub.alloc_large = alloc_large;
  172546. mem->pub.alloc_sarray = alloc_sarray;
  172547. mem->pub.alloc_barray = alloc_barray;
  172548. mem->pub.request_virt_sarray = request_virt_sarray;
  172549. mem->pub.request_virt_barray = request_virt_barray;
  172550. mem->pub.realize_virt_arrays = realize_virt_arrays;
  172551. mem->pub.access_virt_sarray = access_virt_sarray;
  172552. mem->pub.access_virt_barray = access_virt_barray;
  172553. mem->pub.free_pool = free_pool;
  172554. mem->pub.self_destruct = self_destruct;
  172555. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  172556. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  172557. /* Initialize working state */
  172558. mem->pub.max_memory_to_use = max_to_use;
  172559. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172560. mem->small_list[pool] = NULL;
  172561. mem->large_list[pool] = NULL;
  172562. }
  172563. mem->virt_sarray_list = NULL;
  172564. mem->virt_barray_list = NULL;
  172565. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  172566. /* Declare ourselves open for business */
  172567. cinfo->mem = & mem->pub;
  172568. /* Check for an environment variable JPEGMEM; if found, override the
  172569. * default max_memory setting from jpeg_mem_init. Note that the
  172570. * surrounding application may again override this value.
  172571. * If your system doesn't support getenv(), define NO_GETENV to disable
  172572. * this feature.
  172573. */
  172574. #ifndef NO_GETENV
  172575. { char * memenv;
  172576. if ((memenv = getenv("JPEGMEM")) != NULL) {
  172577. char ch = 'x';
  172578. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  172579. if (ch == 'm' || ch == 'M')
  172580. max_to_use *= 1000L;
  172581. mem->pub.max_memory_to_use = max_to_use * 1000L;
  172582. }
  172583. }
  172584. }
  172585. #endif
  172586. }
  172587. /********* End of inlined file: jmemmgr.c *********/
  172588. /********* Start of inlined file: jmemnobs.c *********/
  172589. #define JPEG_INTERNALS
  172590. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  172591. extern void * malloc JPP((size_t size));
  172592. extern void free JPP((void *ptr));
  172593. #endif
  172594. /*
  172595. * Memory allocation and freeing are controlled by the regular library
  172596. * routines malloc() and free().
  172597. */
  172598. GLOBAL(void *)
  172599. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  172600. {
  172601. return (void *) malloc(sizeofobject);
  172602. }
  172603. GLOBAL(void)
  172604. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  172605. {
  172606. free(object);
  172607. }
  172608. /*
  172609. * "Large" objects are treated the same as "small" ones.
  172610. * NB: although we include FAR keywords in the routine declarations,
  172611. * this file won't actually work in 80x86 small/medium model; at least,
  172612. * you probably won't be able to process useful-size images in only 64KB.
  172613. */
  172614. GLOBAL(void FAR *)
  172615. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  172616. {
  172617. return (void FAR *) malloc(sizeofobject);
  172618. }
  172619. GLOBAL(void)
  172620. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  172621. {
  172622. free(object);
  172623. }
  172624. /*
  172625. * This routine computes the total memory space available for allocation.
  172626. * Here we always say, "we got all you want bud!"
  172627. */
  172628. GLOBAL(long)
  172629. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  172630. long max_bytes_needed, long already_allocated)
  172631. {
  172632. return max_bytes_needed;
  172633. }
  172634. /*
  172635. * Backing store (temporary file) management.
  172636. * Since jpeg_mem_available always promised the moon,
  172637. * this should never be called and we can just error out.
  172638. */
  172639. GLOBAL(void)
  172640. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  172641. long total_bytes_needed)
  172642. {
  172643. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  172644. }
  172645. /*
  172646. * These routines take care of any system-dependent initialization and
  172647. * cleanup required. Here, there isn't any.
  172648. */
  172649. GLOBAL(long)
  172650. jpeg_mem_init (j_common_ptr cinfo)
  172651. {
  172652. return 0; /* just set max_memory_to_use to 0 */
  172653. }
  172654. GLOBAL(void)
  172655. jpeg_mem_term (j_common_ptr cinfo)
  172656. {
  172657. /* no work */
  172658. }
  172659. /********* End of inlined file: jmemnobs.c *********/
  172660. /********* Start of inlined file: jquant1.c *********/
  172661. #define JPEG_INTERNALS
  172662. #ifdef QUANT_1PASS_SUPPORTED
  172663. /*
  172664. * The main purpose of 1-pass quantization is to provide a fast, if not very
  172665. * high quality, colormapped output capability. A 2-pass quantizer usually
  172666. * gives better visual quality; however, for quantized grayscale output this
  172667. * quantizer is perfectly adequate. Dithering is highly recommended with this
  172668. * quantizer, though you can turn it off if you really want to.
  172669. *
  172670. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  172671. * image. We use a map consisting of all combinations of Ncolors[i] color
  172672. * values for the i'th component. The Ncolors[] values are chosen so that
  172673. * their product, the total number of colors, is no more than that requested.
  172674. * (In most cases, the product will be somewhat less.)
  172675. *
  172676. * Since the colormap is orthogonal, the representative value for each color
  172677. * component can be determined without considering the other components;
  172678. * then these indexes can be combined into a colormap index by a standard
  172679. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  172680. * can be precalculated and stored in the lookup table colorindex[].
  172681. * colorindex[i][j] maps pixel value j in component i to the nearest
  172682. * representative value (grid plane) for that component; this index is
  172683. * multiplied by the array stride for component i, so that the
  172684. * index of the colormap entry closest to a given pixel value is just
  172685. * sum( colorindex[component-number][pixel-component-value] )
  172686. * Aside from being fast, this scheme allows for variable spacing between
  172687. * representative values with no additional lookup cost.
  172688. *
  172689. * If gamma correction has been applied in color conversion, it might be wise
  172690. * to adjust the color grid spacing so that the representative colors are
  172691. * equidistant in linear space. At this writing, gamma correction is not
  172692. * implemented by jdcolor, so nothing is done here.
  172693. */
  172694. /* Declarations for ordered dithering.
  172695. *
  172696. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  172697. * dithering is described in many references, for instance Dale Schumacher's
  172698. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  172699. * In place of Schumacher's comparisons against a "threshold" value, we add a
  172700. * "dither" value to the input pixel and then round the result to the nearest
  172701. * output value. The dither value is equivalent to (0.5 - threshold) times
  172702. * the distance between output values. For ordered dithering, we assume that
  172703. * the output colors are equally spaced; if not, results will probably be
  172704. * worse, since the dither may be too much or too little at a given point.
  172705. *
  172706. * The normal calculation would be to form pixel value + dither, range-limit
  172707. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  172708. * We can skip the separate range-limiting step by extending the colorindex
  172709. * table in both directions.
  172710. */
  172711. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  172712. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  172713. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  172714. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  172715. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  172716. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  172717. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  172718. /* Bayer's order-4 dither array. Generated by the code given in
  172719. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  172720. * The values in this array must range from 0 to ODITHER_CELLS-1.
  172721. */
  172722. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  172723. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  172724. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  172725. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  172726. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  172727. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  172728. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  172729. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  172730. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  172731. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  172732. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  172733. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  172734. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  172735. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  172736. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  172737. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  172738. };
  172739. /* Declarations for Floyd-Steinberg dithering.
  172740. *
  172741. * Errors are accumulated into the array fserrors[], at a resolution of
  172742. * 1/16th of a pixel count. The error at a given pixel is propagated
  172743. * to its not-yet-processed neighbors using the standard F-S fractions,
  172744. * ... (here) 7/16
  172745. * 3/16 5/16 1/16
  172746. * We work left-to-right on even rows, right-to-left on odd rows.
  172747. *
  172748. * We can get away with a single array (holding one row's worth of errors)
  172749. * by using it to store the current row's errors at pixel columns not yet
  172750. * processed, but the next row's errors at columns already processed. We
  172751. * need only a few extra variables to hold the errors immediately around the
  172752. * current column. (If we are lucky, those variables are in registers, but
  172753. * even if not, they're probably cheaper to access than array elements are.)
  172754. *
  172755. * The fserrors[] array is indexed [component#][position].
  172756. * We provide (#columns + 2) entries per component; the extra entry at each
  172757. * end saves us from special-casing the first and last pixels.
  172758. *
  172759. * Note: on a wide image, we might not have enough room in a PC's near data
  172760. * segment to hold the error array; so it is allocated with alloc_large.
  172761. */
  172762. #if BITS_IN_JSAMPLE == 8
  172763. typedef INT16 FSERROR; /* 16 bits should be enough */
  172764. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172765. #else
  172766. typedef INT32 FSERROR; /* may need more than 16 bits */
  172767. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172768. #endif
  172769. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172770. /* Private subobject */
  172771. #define MAX_Q_COMPS 4 /* max components I can handle */
  172772. typedef struct {
  172773. struct jpeg_color_quantizer pub; /* public fields */
  172774. /* Initially allocated colormap is saved here */
  172775. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  172776. int sv_actual; /* number of entries in use */
  172777. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  172778. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  172779. * premultiplied as described above. Since colormap indexes must fit into
  172780. * JSAMPLEs, the entries of this array will too.
  172781. */
  172782. boolean is_padded; /* is the colorindex padded for odither? */
  172783. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  172784. /* Variables for ordered dithering */
  172785. int row_index; /* cur row's vertical index in dither matrix */
  172786. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  172787. /* Variables for Floyd-Steinberg dithering */
  172788. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  172789. boolean on_odd_row; /* flag to remember which row we are on */
  172790. } my_cquantizer;
  172791. typedef my_cquantizer * my_cquantize_ptr;
  172792. /*
  172793. * Policy-making subroutines for create_colormap and create_colorindex.
  172794. * These routines determine the colormap to be used. The rest of the module
  172795. * only assumes that the colormap is orthogonal.
  172796. *
  172797. * * select_ncolors decides how to divvy up the available colors
  172798. * among the components.
  172799. * * output_value defines the set of representative values for a component.
  172800. * * largest_input_value defines the mapping from input values to
  172801. * representative values for a component.
  172802. * Note that the latter two routines may impose different policies for
  172803. * different components, though this is not currently done.
  172804. */
  172805. LOCAL(int)
  172806. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  172807. /* Determine allocation of desired colors to components, */
  172808. /* and fill in Ncolors[] array to indicate choice. */
  172809. /* Return value is total number of colors (product of Ncolors[] values). */
  172810. {
  172811. int nc = cinfo->out_color_components; /* number of color components */
  172812. int max_colors = cinfo->desired_number_of_colors;
  172813. int total_colors, iroot, i, j;
  172814. boolean changed;
  172815. long temp;
  172816. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  172817. /* We can allocate at least the nc'th root of max_colors per component. */
  172818. /* Compute floor(nc'th root of max_colors). */
  172819. iroot = 1;
  172820. do {
  172821. iroot++;
  172822. temp = iroot; /* set temp = iroot ** nc */
  172823. for (i = 1; i < nc; i++)
  172824. temp *= iroot;
  172825. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  172826. iroot--; /* now iroot = floor(root) */
  172827. /* Must have at least 2 color values per component */
  172828. if (iroot < 2)
  172829. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  172830. /* Initialize to iroot color values for each component */
  172831. total_colors = 1;
  172832. for (i = 0; i < nc; i++) {
  172833. Ncolors[i] = iroot;
  172834. total_colors *= iroot;
  172835. }
  172836. /* We may be able to increment the count for one or more components without
  172837. * exceeding max_colors, though we know not all can be incremented.
  172838. * Sometimes, the first component can be incremented more than once!
  172839. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  172840. * In RGB colorspace, try to increment G first, then R, then B.
  172841. */
  172842. do {
  172843. changed = FALSE;
  172844. for (i = 0; i < nc; i++) {
  172845. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  172846. /* calculate new total_colors if Ncolors[j] is incremented */
  172847. temp = total_colors / Ncolors[j];
  172848. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  172849. if (temp > (long) max_colors)
  172850. break; /* won't fit, done with this pass */
  172851. Ncolors[j]++; /* OK, apply the increment */
  172852. total_colors = (int) temp;
  172853. changed = TRUE;
  172854. }
  172855. } while (changed);
  172856. return total_colors;
  172857. }
  172858. LOCAL(int)
  172859. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172860. /* Return j'th output value, where j will range from 0 to maxj */
  172861. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  172862. {
  172863. /* We always provide values 0 and MAXJSAMPLE for each component;
  172864. * any additional values are equally spaced between these limits.
  172865. * (Forcing the upper and lower values to the limits ensures that
  172866. * dithering can't produce a color outside the selected gamut.)
  172867. */
  172868. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  172869. }
  172870. LOCAL(int)
  172871. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172872. /* Return largest input value that should map to j'th output value */
  172873. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  172874. {
  172875. /* Breakpoints are halfway between values returned by output_value */
  172876. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  172877. }
  172878. /*
  172879. * Create the colormap.
  172880. */
  172881. LOCAL(void)
  172882. create_colormap (j_decompress_ptr cinfo)
  172883. {
  172884. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172885. JSAMPARRAY colormap; /* Created colormap */
  172886. int total_colors; /* Number of distinct output colors */
  172887. int i,j,k, nci, blksize, blkdist, ptr, val;
  172888. /* Select number of colors for each component */
  172889. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  172890. /* Report selected color counts */
  172891. if (cinfo->out_color_components == 3)
  172892. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  172893. total_colors, cquantize->Ncolors[0],
  172894. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  172895. else
  172896. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  172897. /* Allocate and fill in the colormap. */
  172898. /* The colors are ordered in the map in standard row-major order, */
  172899. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  172900. colormap = (*cinfo->mem->alloc_sarray)
  172901. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172902. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  172903. /* blksize is number of adjacent repeated entries for a component */
  172904. /* blkdist is distance between groups of identical entries for a component */
  172905. blkdist = total_colors;
  172906. for (i = 0; i < cinfo->out_color_components; i++) {
  172907. /* fill in colormap entries for i'th color component */
  172908. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172909. blksize = blkdist / nci;
  172910. for (j = 0; j < nci; j++) {
  172911. /* Compute j'th output value (out of nci) for component */
  172912. val = output_value(cinfo, i, j, nci-1);
  172913. /* Fill in all colormap entries that have this value of this component */
  172914. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  172915. /* fill in blksize entries beginning at ptr */
  172916. for (k = 0; k < blksize; k++)
  172917. colormap[i][ptr+k] = (JSAMPLE) val;
  172918. }
  172919. }
  172920. blkdist = blksize; /* blksize of this color is blkdist of next */
  172921. }
  172922. /* Save the colormap in private storage,
  172923. * where it will survive color quantization mode changes.
  172924. */
  172925. cquantize->sv_colormap = colormap;
  172926. cquantize->sv_actual = total_colors;
  172927. }
  172928. /*
  172929. * Create the color index table.
  172930. */
  172931. LOCAL(void)
  172932. create_colorindex (j_decompress_ptr cinfo)
  172933. {
  172934. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172935. JSAMPROW indexptr;
  172936. int i,j,k, nci, blksize, val, pad;
  172937. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  172938. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  172939. * This is not necessary in the other dithering modes. However, we
  172940. * flag whether it was done in case user changes dithering mode.
  172941. */
  172942. if (cinfo->dither_mode == JDITHER_ORDERED) {
  172943. pad = MAXJSAMPLE*2;
  172944. cquantize->is_padded = TRUE;
  172945. } else {
  172946. pad = 0;
  172947. cquantize->is_padded = FALSE;
  172948. }
  172949. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  172950. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172951. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  172952. (JDIMENSION) cinfo->out_color_components);
  172953. /* blksize is number of adjacent repeated entries for a component */
  172954. blksize = cquantize->sv_actual;
  172955. for (i = 0; i < cinfo->out_color_components; i++) {
  172956. /* fill in colorindex entries for i'th color component */
  172957. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172958. blksize = blksize / nci;
  172959. /* adjust colorindex pointers to provide padding at negative indexes. */
  172960. if (pad)
  172961. cquantize->colorindex[i] += MAXJSAMPLE;
  172962. /* in loop, val = index of current output value, */
  172963. /* and k = largest j that maps to current val */
  172964. indexptr = cquantize->colorindex[i];
  172965. val = 0;
  172966. k = largest_input_value(cinfo, i, 0, nci-1);
  172967. for (j = 0; j <= MAXJSAMPLE; j++) {
  172968. while (j > k) /* advance val if past boundary */
  172969. k = largest_input_value(cinfo, i, ++val, nci-1);
  172970. /* premultiply so that no multiplication needed in main processing */
  172971. indexptr[j] = (JSAMPLE) (val * blksize);
  172972. }
  172973. /* Pad at both ends if necessary */
  172974. if (pad)
  172975. for (j = 1; j <= MAXJSAMPLE; j++) {
  172976. indexptr[-j] = indexptr[0];
  172977. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  172978. }
  172979. }
  172980. }
  172981. /*
  172982. * Create an ordered-dither array for a component having ncolors
  172983. * distinct output values.
  172984. */
  172985. LOCAL(ODITHER_MATRIX_PTR)
  172986. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  172987. {
  172988. ODITHER_MATRIX_PTR odither;
  172989. int j,k;
  172990. INT32 num,den;
  172991. odither = (ODITHER_MATRIX_PTR)
  172992. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172993. SIZEOF(ODITHER_MATRIX));
  172994. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  172995. * Hence the dither value for the matrix cell with fill order f
  172996. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  172997. * On 16-bit-int machine, be careful to avoid overflow.
  172998. */
  172999. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  173000. for (j = 0; j < ODITHER_SIZE; j++) {
  173001. for (k = 0; k < ODITHER_SIZE; k++) {
  173002. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  173003. * MAXJSAMPLE;
  173004. /* Ensure round towards zero despite C's lack of consistency
  173005. * about rounding negative values in integer division...
  173006. */
  173007. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  173008. }
  173009. }
  173010. return odither;
  173011. }
  173012. /*
  173013. * Create the ordered-dither tables.
  173014. * Components having the same number of representative colors may
  173015. * share a dither table.
  173016. */
  173017. LOCAL(void)
  173018. create_odither_tables (j_decompress_ptr cinfo)
  173019. {
  173020. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173021. ODITHER_MATRIX_PTR odither;
  173022. int i, j, nci;
  173023. for (i = 0; i < cinfo->out_color_components; i++) {
  173024. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173025. odither = NULL; /* search for matching prior component */
  173026. for (j = 0; j < i; j++) {
  173027. if (nci == cquantize->Ncolors[j]) {
  173028. odither = cquantize->odither[j];
  173029. break;
  173030. }
  173031. }
  173032. if (odither == NULL) /* need a new table? */
  173033. odither = make_odither_array(cinfo, nci);
  173034. cquantize->odither[i] = odither;
  173035. }
  173036. }
  173037. /*
  173038. * Map some rows of pixels to the output colormapped representation.
  173039. */
  173040. METHODDEF(void)
  173041. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173042. JSAMPARRAY output_buf, int num_rows)
  173043. /* General case, no dithering */
  173044. {
  173045. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173046. JSAMPARRAY colorindex = cquantize->colorindex;
  173047. register int pixcode, ci;
  173048. register JSAMPROW ptrin, ptrout;
  173049. int row;
  173050. JDIMENSION col;
  173051. JDIMENSION width = cinfo->output_width;
  173052. register int nc = cinfo->out_color_components;
  173053. for (row = 0; row < num_rows; row++) {
  173054. ptrin = input_buf[row];
  173055. ptrout = output_buf[row];
  173056. for (col = width; col > 0; col--) {
  173057. pixcode = 0;
  173058. for (ci = 0; ci < nc; ci++) {
  173059. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  173060. }
  173061. *ptrout++ = (JSAMPLE) pixcode;
  173062. }
  173063. }
  173064. }
  173065. METHODDEF(void)
  173066. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173067. JSAMPARRAY output_buf, int num_rows)
  173068. /* Fast path for out_color_components==3, no dithering */
  173069. {
  173070. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173071. register int pixcode;
  173072. register JSAMPROW ptrin, ptrout;
  173073. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173074. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173075. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173076. int row;
  173077. JDIMENSION col;
  173078. JDIMENSION width = cinfo->output_width;
  173079. for (row = 0; row < num_rows; row++) {
  173080. ptrin = input_buf[row];
  173081. ptrout = output_buf[row];
  173082. for (col = width; col > 0; col--) {
  173083. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  173084. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  173085. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  173086. *ptrout++ = (JSAMPLE) pixcode;
  173087. }
  173088. }
  173089. }
  173090. METHODDEF(void)
  173091. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173092. JSAMPARRAY output_buf, int num_rows)
  173093. /* General case, with ordered dithering */
  173094. {
  173095. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173096. register JSAMPROW input_ptr;
  173097. register JSAMPROW output_ptr;
  173098. JSAMPROW colorindex_ci;
  173099. int * dither; /* points to active row of dither matrix */
  173100. int row_index, col_index; /* current indexes into dither matrix */
  173101. int nc = cinfo->out_color_components;
  173102. int ci;
  173103. int row;
  173104. JDIMENSION col;
  173105. JDIMENSION width = cinfo->output_width;
  173106. for (row = 0; row < num_rows; row++) {
  173107. /* Initialize output values to 0 so can process components separately */
  173108. jzero_far((void FAR *) output_buf[row],
  173109. (size_t) (width * SIZEOF(JSAMPLE)));
  173110. row_index = cquantize->row_index;
  173111. for (ci = 0; ci < nc; ci++) {
  173112. input_ptr = input_buf[row] + ci;
  173113. output_ptr = output_buf[row];
  173114. colorindex_ci = cquantize->colorindex[ci];
  173115. dither = cquantize->odither[ci][row_index];
  173116. col_index = 0;
  173117. for (col = width; col > 0; col--) {
  173118. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  173119. * select output value, accumulate into output code for this pixel.
  173120. * Range-limiting need not be done explicitly, as we have extended
  173121. * the colorindex table to produce the right answers for out-of-range
  173122. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  173123. * required amount of padding.
  173124. */
  173125. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  173126. input_ptr += nc;
  173127. output_ptr++;
  173128. col_index = (col_index + 1) & ODITHER_MASK;
  173129. }
  173130. }
  173131. /* Advance row index for next row */
  173132. row_index = (row_index + 1) & ODITHER_MASK;
  173133. cquantize->row_index = row_index;
  173134. }
  173135. }
  173136. METHODDEF(void)
  173137. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173138. JSAMPARRAY output_buf, int num_rows)
  173139. /* Fast path for out_color_components==3, with ordered dithering */
  173140. {
  173141. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173142. register int pixcode;
  173143. register JSAMPROW input_ptr;
  173144. register JSAMPROW output_ptr;
  173145. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173146. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173147. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173148. int * dither0; /* points to active row of dither matrix */
  173149. int * dither1;
  173150. int * dither2;
  173151. int row_index, col_index; /* current indexes into dither matrix */
  173152. int row;
  173153. JDIMENSION col;
  173154. JDIMENSION width = cinfo->output_width;
  173155. for (row = 0; row < num_rows; row++) {
  173156. row_index = cquantize->row_index;
  173157. input_ptr = input_buf[row];
  173158. output_ptr = output_buf[row];
  173159. dither0 = cquantize->odither[0][row_index];
  173160. dither1 = cquantize->odither[1][row_index];
  173161. dither2 = cquantize->odither[2][row_index];
  173162. col_index = 0;
  173163. for (col = width; col > 0; col--) {
  173164. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  173165. dither0[col_index]]);
  173166. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  173167. dither1[col_index]]);
  173168. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  173169. dither2[col_index]]);
  173170. *output_ptr++ = (JSAMPLE) pixcode;
  173171. col_index = (col_index + 1) & ODITHER_MASK;
  173172. }
  173173. row_index = (row_index + 1) & ODITHER_MASK;
  173174. cquantize->row_index = row_index;
  173175. }
  173176. }
  173177. METHODDEF(void)
  173178. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173179. JSAMPARRAY output_buf, int num_rows)
  173180. /* General case, with Floyd-Steinberg dithering */
  173181. {
  173182. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173183. register LOCFSERROR cur; /* current error or pixel value */
  173184. LOCFSERROR belowerr; /* error for pixel below cur */
  173185. LOCFSERROR bpreverr; /* error for below/prev col */
  173186. LOCFSERROR bnexterr; /* error for below/next col */
  173187. LOCFSERROR delta;
  173188. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173189. register JSAMPROW input_ptr;
  173190. register JSAMPROW output_ptr;
  173191. JSAMPROW colorindex_ci;
  173192. JSAMPROW colormap_ci;
  173193. int pixcode;
  173194. int nc = cinfo->out_color_components;
  173195. int dir; /* 1 for left-to-right, -1 for right-to-left */
  173196. int dirnc; /* dir * nc */
  173197. int ci;
  173198. int row;
  173199. JDIMENSION col;
  173200. JDIMENSION width = cinfo->output_width;
  173201. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173202. SHIFT_TEMPS
  173203. for (row = 0; row < num_rows; row++) {
  173204. /* Initialize output values to 0 so can process components separately */
  173205. jzero_far((void FAR *) output_buf[row],
  173206. (size_t) (width * SIZEOF(JSAMPLE)));
  173207. for (ci = 0; ci < nc; ci++) {
  173208. input_ptr = input_buf[row] + ci;
  173209. output_ptr = output_buf[row];
  173210. if (cquantize->on_odd_row) {
  173211. /* work right to left in this row */
  173212. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  173213. output_ptr += width-1;
  173214. dir = -1;
  173215. dirnc = -nc;
  173216. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  173217. } else {
  173218. /* work left to right in this row */
  173219. dir = 1;
  173220. dirnc = nc;
  173221. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  173222. }
  173223. colorindex_ci = cquantize->colorindex[ci];
  173224. colormap_ci = cquantize->sv_colormap[ci];
  173225. /* Preset error values: no error propagated to first pixel from left */
  173226. cur = 0;
  173227. /* and no error propagated to row below yet */
  173228. belowerr = bpreverr = 0;
  173229. for (col = width; col > 0; col--) {
  173230. /* cur holds the error propagated from the previous pixel on the
  173231. * current line. Add the error propagated from the previous line
  173232. * to form the complete error correction term for this pixel, and
  173233. * round the error term (which is expressed * 16) to an integer.
  173234. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173235. * for either sign of the error value.
  173236. * Note: errorptr points to *previous* column's array entry.
  173237. */
  173238. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  173239. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173240. * The maximum error is +- MAXJSAMPLE; this sets the required size
  173241. * of the range_limit array.
  173242. */
  173243. cur += GETJSAMPLE(*input_ptr);
  173244. cur = GETJSAMPLE(range_limit[cur]);
  173245. /* Select output value, accumulate into output code for this pixel */
  173246. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  173247. *output_ptr += (JSAMPLE) pixcode;
  173248. /* Compute actual representation error at this pixel */
  173249. /* Note: we can do this even though we don't have the final */
  173250. /* pixel code, because the colormap is orthogonal. */
  173251. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  173252. /* Compute error fractions to be propagated to adjacent pixels.
  173253. * Add these into the running sums, and simultaneously shift the
  173254. * next-line error sums left by 1 column.
  173255. */
  173256. bnexterr = cur;
  173257. delta = cur * 2;
  173258. cur += delta; /* form error * 3 */
  173259. errorptr[0] = (FSERROR) (bpreverr + cur);
  173260. cur += delta; /* form error * 5 */
  173261. bpreverr = belowerr + cur;
  173262. belowerr = bnexterr;
  173263. cur += delta; /* form error * 7 */
  173264. /* At this point cur contains the 7/16 error value to be propagated
  173265. * to the next pixel on the current line, and all the errors for the
  173266. * next line have been shifted over. We are therefore ready to move on.
  173267. */
  173268. input_ptr += dirnc; /* advance input ptr to next column */
  173269. output_ptr += dir; /* advance output ptr to next column */
  173270. errorptr += dir; /* advance errorptr to current column */
  173271. }
  173272. /* Post-loop cleanup: we must unload the final error value into the
  173273. * final fserrors[] entry. Note we need not unload belowerr because
  173274. * it is for the dummy column before or after the actual array.
  173275. */
  173276. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  173277. }
  173278. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  173279. }
  173280. }
  173281. /*
  173282. * Allocate workspace for Floyd-Steinberg errors.
  173283. */
  173284. LOCAL(void)
  173285. alloc_fs_workspace (j_decompress_ptr cinfo)
  173286. {
  173287. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173288. size_t arraysize;
  173289. int i;
  173290. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173291. for (i = 0; i < cinfo->out_color_components; i++) {
  173292. cquantize->fserrors[i] = (FSERRPTR)
  173293. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  173294. }
  173295. }
  173296. /*
  173297. * Initialize for one-pass color quantization.
  173298. */
  173299. METHODDEF(void)
  173300. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  173301. {
  173302. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173303. size_t arraysize;
  173304. int i;
  173305. /* Install my colormap. */
  173306. cinfo->colormap = cquantize->sv_colormap;
  173307. cinfo->actual_number_of_colors = cquantize->sv_actual;
  173308. /* Initialize for desired dithering mode. */
  173309. switch (cinfo->dither_mode) {
  173310. case JDITHER_NONE:
  173311. if (cinfo->out_color_components == 3)
  173312. cquantize->pub.color_quantize = color_quantize3;
  173313. else
  173314. cquantize->pub.color_quantize = color_quantize;
  173315. break;
  173316. case JDITHER_ORDERED:
  173317. if (cinfo->out_color_components == 3)
  173318. cquantize->pub.color_quantize = quantize3_ord_dither;
  173319. else
  173320. cquantize->pub.color_quantize = quantize_ord_dither;
  173321. cquantize->row_index = 0; /* initialize state for ordered dither */
  173322. /* If user changed to ordered dither from another mode,
  173323. * we must recreate the color index table with padding.
  173324. * This will cost extra space, but probably isn't very likely.
  173325. */
  173326. if (! cquantize->is_padded)
  173327. create_colorindex(cinfo);
  173328. /* Create ordered-dither tables if we didn't already. */
  173329. if (cquantize->odither[0] == NULL)
  173330. create_odither_tables(cinfo);
  173331. break;
  173332. case JDITHER_FS:
  173333. cquantize->pub.color_quantize = quantize_fs_dither;
  173334. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  173335. /* Allocate Floyd-Steinberg workspace if didn't already. */
  173336. if (cquantize->fserrors[0] == NULL)
  173337. alloc_fs_workspace(cinfo);
  173338. /* Initialize the propagated errors to zero. */
  173339. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173340. for (i = 0; i < cinfo->out_color_components; i++)
  173341. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  173342. break;
  173343. default:
  173344. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173345. break;
  173346. }
  173347. }
  173348. /*
  173349. * Finish up at the end of the pass.
  173350. */
  173351. METHODDEF(void)
  173352. finish_pass_1_quant (j_decompress_ptr cinfo)
  173353. {
  173354. /* no work in 1-pass case */
  173355. }
  173356. /*
  173357. * Switch to a new external colormap between output passes.
  173358. * Shouldn't get to this module!
  173359. */
  173360. METHODDEF(void)
  173361. new_color_map_1_quant (j_decompress_ptr cinfo)
  173362. {
  173363. ERREXIT(cinfo, JERR_MODE_CHANGE);
  173364. }
  173365. /*
  173366. * Module initialization routine for 1-pass color quantization.
  173367. */
  173368. GLOBAL(void)
  173369. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  173370. {
  173371. my_cquantize_ptr cquantize;
  173372. cquantize = (my_cquantize_ptr)
  173373. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173374. SIZEOF(my_cquantizer));
  173375. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  173376. cquantize->pub.start_pass = start_pass_1_quant;
  173377. cquantize->pub.finish_pass = finish_pass_1_quant;
  173378. cquantize->pub.new_color_map = new_color_map_1_quant;
  173379. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  173380. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  173381. /* Make sure my internal arrays won't overflow */
  173382. if (cinfo->out_color_components > MAX_Q_COMPS)
  173383. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  173384. /* Make sure colormap indexes can be represented by JSAMPLEs */
  173385. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  173386. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  173387. /* Create the colormap and color index table. */
  173388. create_colormap(cinfo);
  173389. create_colorindex(cinfo);
  173390. /* Allocate Floyd-Steinberg workspace now if requested.
  173391. * We do this now since it is FAR storage and may affect the memory
  173392. * manager's space calculations. If the user changes to FS dither
  173393. * mode in a later pass, we will allocate the space then, and will
  173394. * possibly overrun the max_memory_to_use setting.
  173395. */
  173396. if (cinfo->dither_mode == JDITHER_FS)
  173397. alloc_fs_workspace(cinfo);
  173398. }
  173399. #endif /* QUANT_1PASS_SUPPORTED */
  173400. /********* End of inlined file: jquant1.c *********/
  173401. /********* Start of inlined file: jquant2.c *********/
  173402. #define JPEG_INTERNALS
  173403. #ifdef QUANT_2PASS_SUPPORTED
  173404. /*
  173405. * This module implements the well-known Heckbert paradigm for color
  173406. * quantization. Most of the ideas used here can be traced back to
  173407. * Heckbert's seminal paper
  173408. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  173409. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  173410. *
  173411. * In the first pass over the image, we accumulate a histogram showing the
  173412. * usage count of each possible color. To keep the histogram to a reasonable
  173413. * size, we reduce the precision of the input; typical practice is to retain
  173414. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  173415. * in the same histogram cell.
  173416. *
  173417. * Next, the color-selection step begins with a box representing the whole
  173418. * color space, and repeatedly splits the "largest" remaining box until we
  173419. * have as many boxes as desired colors. Then the mean color in each
  173420. * remaining box becomes one of the possible output colors.
  173421. *
  173422. * The second pass over the image maps each input pixel to the closest output
  173423. * color (optionally after applying a Floyd-Steinberg dithering correction).
  173424. * This mapping is logically trivial, but making it go fast enough requires
  173425. * considerable care.
  173426. *
  173427. * Heckbert-style quantizers vary a good deal in their policies for choosing
  173428. * the "largest" box and deciding where to cut it. The particular policies
  173429. * used here have proved out well in experimental comparisons, but better ones
  173430. * may yet be found.
  173431. *
  173432. * In earlier versions of the IJG code, this module quantized in YCbCr color
  173433. * space, processing the raw upsampled data without a color conversion step.
  173434. * This allowed the color conversion math to be done only once per colormap
  173435. * entry, not once per pixel. However, that optimization precluded other
  173436. * useful optimizations (such as merging color conversion with upsampling)
  173437. * and it also interfered with desired capabilities such as quantizing to an
  173438. * externally-supplied colormap. We have therefore abandoned that approach.
  173439. * The present code works in the post-conversion color space, typically RGB.
  173440. *
  173441. * To improve the visual quality of the results, we actually work in scaled
  173442. * RGB space, giving G distances more weight than R, and R in turn more than
  173443. * B. To do everything in integer math, we must use integer scale factors.
  173444. * The 2/3/1 scale factors used here correspond loosely to the relative
  173445. * weights of the colors in the NTSC grayscale equation.
  173446. * If you want to use this code to quantize a non-RGB color space, you'll
  173447. * probably need to change these scale factors.
  173448. */
  173449. #define R_SCALE 2 /* scale R distances by this much */
  173450. #define G_SCALE 3 /* scale G distances by this much */
  173451. #define B_SCALE 1 /* and B by this much */
  173452. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  173453. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  173454. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  173455. * you'll get compile errors until you extend this logic. In that case
  173456. * you'll probably want to tweak the histogram sizes too.
  173457. */
  173458. #if RGB_RED == 0
  173459. #define C0_SCALE R_SCALE
  173460. #endif
  173461. #if RGB_BLUE == 0
  173462. #define C0_SCALE B_SCALE
  173463. #endif
  173464. #if RGB_GREEN == 1
  173465. #define C1_SCALE G_SCALE
  173466. #endif
  173467. #if RGB_RED == 2
  173468. #define C2_SCALE R_SCALE
  173469. #endif
  173470. #if RGB_BLUE == 2
  173471. #define C2_SCALE B_SCALE
  173472. #endif
  173473. /*
  173474. * First we have the histogram data structure and routines for creating it.
  173475. *
  173476. * The number of bits of precision can be adjusted by changing these symbols.
  173477. * We recommend keeping 6 bits for G and 5 each for R and B.
  173478. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  173479. * better results; if you are short of memory, 5 bits all around will save
  173480. * some space but degrade the results.
  173481. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  173482. * (preferably unsigned long) for each cell. In practice this is overkill;
  173483. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  173484. * and clamping those that do overflow to the maximum value will give close-
  173485. * enough results. This reduces the recommended histogram size from 256Kb
  173486. * to 128Kb, which is a useful savings on PC-class machines.
  173487. * (In the second pass the histogram space is re-used for pixel mapping data;
  173488. * in that capacity, each cell must be able to store zero to the number of
  173489. * desired colors. 16 bits/cell is plenty for that too.)
  173490. * Since the JPEG code is intended to run in small memory model on 80x86
  173491. * machines, we can't just allocate the histogram in one chunk. Instead
  173492. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  173493. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  173494. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  173495. * on 80x86 machines, the pointer row is in near memory but the actual
  173496. * arrays are in far memory (same arrangement as we use for image arrays).
  173497. */
  173498. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  173499. /* These will do the right thing for either R,G,B or B,G,R color order,
  173500. * but you may not like the results for other color orders.
  173501. */
  173502. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  173503. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  173504. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  173505. /* Number of elements along histogram axes. */
  173506. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  173507. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  173508. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  173509. /* These are the amounts to shift an input value to get a histogram index. */
  173510. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  173511. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  173512. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  173513. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  173514. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  173515. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  173516. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  173517. typedef hist2d * hist3d; /* type for top-level pointer */
  173518. /* Declarations for Floyd-Steinberg dithering.
  173519. *
  173520. * Errors are accumulated into the array fserrors[], at a resolution of
  173521. * 1/16th of a pixel count. The error at a given pixel is propagated
  173522. * to its not-yet-processed neighbors using the standard F-S fractions,
  173523. * ... (here) 7/16
  173524. * 3/16 5/16 1/16
  173525. * We work left-to-right on even rows, right-to-left on odd rows.
  173526. *
  173527. * We can get away with a single array (holding one row's worth of errors)
  173528. * by using it to store the current row's errors at pixel columns not yet
  173529. * processed, but the next row's errors at columns already processed. We
  173530. * need only a few extra variables to hold the errors immediately around the
  173531. * current column. (If we are lucky, those variables are in registers, but
  173532. * even if not, they're probably cheaper to access than array elements are.)
  173533. *
  173534. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  173535. * each end saves us from special-casing the first and last pixels.
  173536. * Each entry is three values long, one value for each color component.
  173537. *
  173538. * Note: on a wide image, we might not have enough room in a PC's near data
  173539. * segment to hold the error array; so it is allocated with alloc_large.
  173540. */
  173541. #if BITS_IN_JSAMPLE == 8
  173542. typedef INT16 FSERROR; /* 16 bits should be enough */
  173543. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  173544. #else
  173545. typedef INT32 FSERROR; /* may need more than 16 bits */
  173546. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  173547. #endif
  173548. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  173549. /* Private subobject */
  173550. typedef struct {
  173551. struct jpeg_color_quantizer pub; /* public fields */
  173552. /* Space for the eventually created colormap is stashed here */
  173553. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  173554. int desired; /* desired # of colors = size of colormap */
  173555. /* Variables for accumulating image statistics */
  173556. hist3d histogram; /* pointer to the histogram */
  173557. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  173558. /* Variables for Floyd-Steinberg dithering */
  173559. FSERRPTR fserrors; /* accumulated errors */
  173560. boolean on_odd_row; /* flag to remember which row we are on */
  173561. int * error_limiter; /* table for clamping the applied error */
  173562. } my_cquantizer2;
  173563. typedef my_cquantizer2 * my_cquantize_ptr2;
  173564. /*
  173565. * Prescan some rows of pixels.
  173566. * In this module the prescan simply updates the histogram, which has been
  173567. * initialized to zeroes by start_pass.
  173568. * An output_buf parameter is required by the method signature, but no data
  173569. * is actually output (in fact the buffer controller is probably passing a
  173570. * NULL pointer).
  173571. */
  173572. METHODDEF(void)
  173573. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173574. JSAMPARRAY output_buf, int num_rows)
  173575. {
  173576. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173577. register JSAMPROW ptr;
  173578. register histptr histp;
  173579. register hist3d histogram = cquantize->histogram;
  173580. int row;
  173581. JDIMENSION col;
  173582. JDIMENSION width = cinfo->output_width;
  173583. for (row = 0; row < num_rows; row++) {
  173584. ptr = input_buf[row];
  173585. for (col = width; col > 0; col--) {
  173586. /* get pixel value and index into the histogram */
  173587. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  173588. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  173589. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  173590. /* increment, check for overflow and undo increment if so. */
  173591. if (++(*histp) <= 0)
  173592. (*histp)--;
  173593. ptr += 3;
  173594. }
  173595. }
  173596. }
  173597. /*
  173598. * Next we have the really interesting routines: selection of a colormap
  173599. * given the completed histogram.
  173600. * These routines work with a list of "boxes", each representing a rectangular
  173601. * subset of the input color space (to histogram precision).
  173602. */
  173603. typedef struct {
  173604. /* The bounds of the box (inclusive); expressed as histogram indexes */
  173605. int c0min, c0max;
  173606. int c1min, c1max;
  173607. int c2min, c2max;
  173608. /* The volume (actually 2-norm) of the box */
  173609. INT32 volume;
  173610. /* The number of nonzero histogram cells within this box */
  173611. long colorcount;
  173612. } box;
  173613. typedef box * boxptr;
  173614. LOCAL(boxptr)
  173615. find_biggest_color_pop (boxptr boxlist, int numboxes)
  173616. /* Find the splittable box with the largest color population */
  173617. /* Returns NULL if no splittable boxes remain */
  173618. {
  173619. register boxptr boxp;
  173620. register int i;
  173621. register long maxc = 0;
  173622. boxptr which = NULL;
  173623. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173624. if (boxp->colorcount > maxc && boxp->volume > 0) {
  173625. which = boxp;
  173626. maxc = boxp->colorcount;
  173627. }
  173628. }
  173629. return which;
  173630. }
  173631. LOCAL(boxptr)
  173632. find_biggest_volume (boxptr boxlist, int numboxes)
  173633. /* Find the splittable box with the largest (scaled) volume */
  173634. /* Returns NULL if no splittable boxes remain */
  173635. {
  173636. register boxptr boxp;
  173637. register int i;
  173638. register INT32 maxv = 0;
  173639. boxptr which = NULL;
  173640. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173641. if (boxp->volume > maxv) {
  173642. which = boxp;
  173643. maxv = boxp->volume;
  173644. }
  173645. }
  173646. return which;
  173647. }
  173648. LOCAL(void)
  173649. update_box (j_decompress_ptr cinfo, boxptr boxp)
  173650. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  173651. /* and recompute its volume and population */
  173652. {
  173653. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173654. hist3d histogram = cquantize->histogram;
  173655. histptr histp;
  173656. int c0,c1,c2;
  173657. int c0min,c0max,c1min,c1max,c2min,c2max;
  173658. INT32 dist0,dist1,dist2;
  173659. long ccount;
  173660. c0min = boxp->c0min; c0max = boxp->c0max;
  173661. c1min = boxp->c1min; c1max = boxp->c1max;
  173662. c2min = boxp->c2min; c2max = boxp->c2max;
  173663. if (c0max > c0min)
  173664. for (c0 = c0min; c0 <= c0max; c0++)
  173665. for (c1 = c1min; c1 <= c1max; c1++) {
  173666. histp = & histogram[c0][c1][c2min];
  173667. for (c2 = c2min; c2 <= c2max; c2++)
  173668. if (*histp++ != 0) {
  173669. boxp->c0min = c0min = c0;
  173670. goto have_c0min;
  173671. }
  173672. }
  173673. have_c0min:
  173674. if (c0max > c0min)
  173675. for (c0 = c0max; c0 >= c0min; c0--)
  173676. for (c1 = c1min; c1 <= c1max; c1++) {
  173677. histp = & histogram[c0][c1][c2min];
  173678. for (c2 = c2min; c2 <= c2max; c2++)
  173679. if (*histp++ != 0) {
  173680. boxp->c0max = c0max = c0;
  173681. goto have_c0max;
  173682. }
  173683. }
  173684. have_c0max:
  173685. if (c1max > c1min)
  173686. for (c1 = c1min; c1 <= c1max; c1++)
  173687. for (c0 = c0min; c0 <= c0max; c0++) {
  173688. histp = & histogram[c0][c1][c2min];
  173689. for (c2 = c2min; c2 <= c2max; c2++)
  173690. if (*histp++ != 0) {
  173691. boxp->c1min = c1min = c1;
  173692. goto have_c1min;
  173693. }
  173694. }
  173695. have_c1min:
  173696. if (c1max > c1min)
  173697. for (c1 = c1max; c1 >= c1min; c1--)
  173698. for (c0 = c0min; c0 <= c0max; c0++) {
  173699. histp = & histogram[c0][c1][c2min];
  173700. for (c2 = c2min; c2 <= c2max; c2++)
  173701. if (*histp++ != 0) {
  173702. boxp->c1max = c1max = c1;
  173703. goto have_c1max;
  173704. }
  173705. }
  173706. have_c1max:
  173707. if (c2max > c2min)
  173708. for (c2 = c2min; c2 <= c2max; c2++)
  173709. for (c0 = c0min; c0 <= c0max; c0++) {
  173710. histp = & histogram[c0][c1min][c2];
  173711. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173712. if (*histp != 0) {
  173713. boxp->c2min = c2min = c2;
  173714. goto have_c2min;
  173715. }
  173716. }
  173717. have_c2min:
  173718. if (c2max > c2min)
  173719. for (c2 = c2max; c2 >= c2min; c2--)
  173720. for (c0 = c0min; c0 <= c0max; c0++) {
  173721. histp = & histogram[c0][c1min][c2];
  173722. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173723. if (*histp != 0) {
  173724. boxp->c2max = c2max = c2;
  173725. goto have_c2max;
  173726. }
  173727. }
  173728. have_c2max:
  173729. /* Update box volume.
  173730. * We use 2-norm rather than real volume here; this biases the method
  173731. * against making long narrow boxes, and it has the side benefit that
  173732. * a box is splittable iff norm > 0.
  173733. * Since the differences are expressed in histogram-cell units,
  173734. * we have to shift back to JSAMPLE units to get consistent distances;
  173735. * after which, we scale according to the selected distance scale factors.
  173736. */
  173737. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  173738. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  173739. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  173740. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  173741. /* Now scan remaining volume of box and compute population */
  173742. ccount = 0;
  173743. for (c0 = c0min; c0 <= c0max; c0++)
  173744. for (c1 = c1min; c1 <= c1max; c1++) {
  173745. histp = & histogram[c0][c1][c2min];
  173746. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  173747. if (*histp != 0) {
  173748. ccount++;
  173749. }
  173750. }
  173751. boxp->colorcount = ccount;
  173752. }
  173753. LOCAL(int)
  173754. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  173755. int desired_colors)
  173756. /* Repeatedly select and split the largest box until we have enough boxes */
  173757. {
  173758. int n,lb;
  173759. int c0,c1,c2,cmax;
  173760. register boxptr b1,b2;
  173761. while (numboxes < desired_colors) {
  173762. /* Select box to split.
  173763. * Current algorithm: by population for first half, then by volume.
  173764. */
  173765. if (numboxes*2 <= desired_colors) {
  173766. b1 = find_biggest_color_pop(boxlist, numboxes);
  173767. } else {
  173768. b1 = find_biggest_volume(boxlist, numboxes);
  173769. }
  173770. if (b1 == NULL) /* no splittable boxes left! */
  173771. break;
  173772. b2 = &boxlist[numboxes]; /* where new box will go */
  173773. /* Copy the color bounds to the new box. */
  173774. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  173775. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  173776. /* Choose which axis to split the box on.
  173777. * Current algorithm: longest scaled axis.
  173778. * See notes in update_box about scaling distances.
  173779. */
  173780. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  173781. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  173782. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  173783. /* We want to break any ties in favor of green, then red, blue last.
  173784. * This code does the right thing for R,G,B or B,G,R color orders only.
  173785. */
  173786. #if RGB_RED == 0
  173787. cmax = c1; n = 1;
  173788. if (c0 > cmax) { cmax = c0; n = 0; }
  173789. if (c2 > cmax) { n = 2; }
  173790. #else
  173791. cmax = c1; n = 1;
  173792. if (c2 > cmax) { cmax = c2; n = 2; }
  173793. if (c0 > cmax) { n = 0; }
  173794. #endif
  173795. /* Choose split point along selected axis, and update box bounds.
  173796. * Current algorithm: split at halfway point.
  173797. * (Since the box has been shrunk to minimum volume,
  173798. * any split will produce two nonempty subboxes.)
  173799. * Note that lb value is max for lower box, so must be < old max.
  173800. */
  173801. switch (n) {
  173802. case 0:
  173803. lb = (b1->c0max + b1->c0min) / 2;
  173804. b1->c0max = lb;
  173805. b2->c0min = lb+1;
  173806. break;
  173807. case 1:
  173808. lb = (b1->c1max + b1->c1min) / 2;
  173809. b1->c1max = lb;
  173810. b2->c1min = lb+1;
  173811. break;
  173812. case 2:
  173813. lb = (b1->c2max + b1->c2min) / 2;
  173814. b1->c2max = lb;
  173815. b2->c2min = lb+1;
  173816. break;
  173817. }
  173818. /* Update stats for boxes */
  173819. update_box(cinfo, b1);
  173820. update_box(cinfo, b2);
  173821. numboxes++;
  173822. }
  173823. return numboxes;
  173824. }
  173825. LOCAL(void)
  173826. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  173827. /* Compute representative color for a box, put it in colormap[icolor] */
  173828. {
  173829. /* Current algorithm: mean weighted by pixels (not colors) */
  173830. /* Note it is important to get the rounding correct! */
  173831. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173832. hist3d histogram = cquantize->histogram;
  173833. histptr histp;
  173834. int c0,c1,c2;
  173835. int c0min,c0max,c1min,c1max,c2min,c2max;
  173836. long count;
  173837. long total = 0;
  173838. long c0total = 0;
  173839. long c1total = 0;
  173840. long c2total = 0;
  173841. c0min = boxp->c0min; c0max = boxp->c0max;
  173842. c1min = boxp->c1min; c1max = boxp->c1max;
  173843. c2min = boxp->c2min; c2max = boxp->c2max;
  173844. for (c0 = c0min; c0 <= c0max; c0++)
  173845. for (c1 = c1min; c1 <= c1max; c1++) {
  173846. histp = & histogram[c0][c1][c2min];
  173847. for (c2 = c2min; c2 <= c2max; c2++) {
  173848. if ((count = *histp++) != 0) {
  173849. total += count;
  173850. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  173851. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  173852. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  173853. }
  173854. }
  173855. }
  173856. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  173857. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  173858. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  173859. }
  173860. LOCAL(void)
  173861. select_colors (j_decompress_ptr cinfo, int desired_colors)
  173862. /* Master routine for color selection */
  173863. {
  173864. boxptr boxlist;
  173865. int numboxes;
  173866. int i;
  173867. /* Allocate workspace for box list */
  173868. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  173869. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  173870. /* Initialize one box containing whole space */
  173871. numboxes = 1;
  173872. boxlist[0].c0min = 0;
  173873. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  173874. boxlist[0].c1min = 0;
  173875. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  173876. boxlist[0].c2min = 0;
  173877. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  173878. /* Shrink it to actually-used volume and set its statistics */
  173879. update_box(cinfo, & boxlist[0]);
  173880. /* Perform median-cut to produce final box list */
  173881. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  173882. /* Compute the representative color for each box, fill colormap */
  173883. for (i = 0; i < numboxes; i++)
  173884. compute_color(cinfo, & boxlist[i], i);
  173885. cinfo->actual_number_of_colors = numboxes;
  173886. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  173887. }
  173888. /*
  173889. * These routines are concerned with the time-critical task of mapping input
  173890. * colors to the nearest color in the selected colormap.
  173891. *
  173892. * We re-use the histogram space as an "inverse color map", essentially a
  173893. * cache for the results of nearest-color searches. All colors within a
  173894. * histogram cell will be mapped to the same colormap entry, namely the one
  173895. * closest to the cell's center. This may not be quite the closest entry to
  173896. * the actual input color, but it's almost as good. A zero in the cache
  173897. * indicates we haven't found the nearest color for that cell yet; the array
  173898. * is cleared to zeroes before starting the mapping pass. When we find the
  173899. * nearest color for a cell, its colormap index plus one is recorded in the
  173900. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  173901. * when they need to use an unfilled entry in the cache.
  173902. *
  173903. * Our method of efficiently finding nearest colors is based on the "locally
  173904. * sorted search" idea described by Heckbert and on the incremental distance
  173905. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  173906. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  173907. * the distances from a given colormap entry to each cell of the histogram can
  173908. * be computed quickly using an incremental method: the differences between
  173909. * distances to adjacent cells themselves differ by a constant. This allows a
  173910. * fairly fast implementation of the "brute force" approach of computing the
  173911. * distance from every colormap entry to every histogram cell. Unfortunately,
  173912. * it needs a work array to hold the best-distance-so-far for each histogram
  173913. * cell (because the inner loop has to be over cells, not colormap entries).
  173914. * The work array elements have to be INT32s, so the work array would need
  173915. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  173916. *
  173917. * To get around these problems, we apply Thomas' method to compute the
  173918. * nearest colors for only the cells within a small subbox of the histogram.
  173919. * The work array need be only as big as the subbox, so the memory usage
  173920. * problem is solved. Furthermore, we need not fill subboxes that are never
  173921. * referenced in pass2; many images use only part of the color gamut, so a
  173922. * fair amount of work is saved. An additional advantage of this
  173923. * approach is that we can apply Heckbert's locality criterion to quickly
  173924. * eliminate colormap entries that are far away from the subbox; typically
  173925. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  173926. * and we need not compute their distances to individual cells in the subbox.
  173927. * The speed of this approach is heavily influenced by the subbox size: too
  173928. * small means too much overhead, too big loses because Heckbert's criterion
  173929. * can't eliminate as many colormap entries. Empirically the best subbox
  173930. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  173931. *
  173932. * Thomas' article also describes a refined method which is asymptotically
  173933. * faster than the brute-force method, but it is also far more complex and
  173934. * cannot efficiently be applied to small subboxes. It is therefore not
  173935. * useful for programs intended to be portable to DOS machines. On machines
  173936. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  173937. * refined method might be faster than the present code --- but then again,
  173938. * it might not be any faster, and it's certainly more complicated.
  173939. */
  173940. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  173941. #define BOX_C0_LOG (HIST_C0_BITS-3)
  173942. #define BOX_C1_LOG (HIST_C1_BITS-3)
  173943. #define BOX_C2_LOG (HIST_C2_BITS-3)
  173944. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  173945. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  173946. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  173947. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  173948. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  173949. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  173950. /*
  173951. * The next three routines implement inverse colormap filling. They could
  173952. * all be folded into one big routine, but splitting them up this way saves
  173953. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  173954. * and may allow some compilers to produce better code by registerizing more
  173955. * inner-loop variables.
  173956. */
  173957. LOCAL(int)
  173958. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173959. JSAMPLE colorlist[])
  173960. /* Locate the colormap entries close enough to an update box to be candidates
  173961. * for the nearest entry to some cell(s) in the update box. The update box
  173962. * is specified by the center coordinates of its first cell. The number of
  173963. * candidate colormap entries is returned, and their colormap indexes are
  173964. * placed in colorlist[].
  173965. * This routine uses Heckbert's "locally sorted search" criterion to select
  173966. * the colors that need further consideration.
  173967. */
  173968. {
  173969. int numcolors = cinfo->actual_number_of_colors;
  173970. int maxc0, maxc1, maxc2;
  173971. int centerc0, centerc1, centerc2;
  173972. int i, x, ncolors;
  173973. INT32 minmaxdist, min_dist, max_dist, tdist;
  173974. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  173975. /* Compute true coordinates of update box's upper corner and center.
  173976. * Actually we compute the coordinates of the center of the upper-corner
  173977. * histogram cell, which are the upper bounds of the volume we care about.
  173978. * Note that since ">>" rounds down, the "center" values may be closer to
  173979. * min than to max; hence comparisons to them must be "<=", not "<".
  173980. */
  173981. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  173982. centerc0 = (minc0 + maxc0) >> 1;
  173983. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  173984. centerc1 = (minc1 + maxc1) >> 1;
  173985. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  173986. centerc2 = (minc2 + maxc2) >> 1;
  173987. /* For each color in colormap, find:
  173988. * 1. its minimum squared-distance to any point in the update box
  173989. * (zero if color is within update box);
  173990. * 2. its maximum squared-distance to any point in the update box.
  173991. * Both of these can be found by considering only the corners of the box.
  173992. * We save the minimum distance for each color in mindist[];
  173993. * only the smallest maximum distance is of interest.
  173994. */
  173995. minmaxdist = 0x7FFFFFFFL;
  173996. for (i = 0; i < numcolors; i++) {
  173997. /* We compute the squared-c0-distance term, then add in the other two. */
  173998. x = GETJSAMPLE(cinfo->colormap[0][i]);
  173999. if (x < minc0) {
  174000. tdist = (x - minc0) * C0_SCALE;
  174001. min_dist = tdist*tdist;
  174002. tdist = (x - maxc0) * C0_SCALE;
  174003. max_dist = tdist*tdist;
  174004. } else if (x > maxc0) {
  174005. tdist = (x - maxc0) * C0_SCALE;
  174006. min_dist = tdist*tdist;
  174007. tdist = (x - minc0) * C0_SCALE;
  174008. max_dist = tdist*tdist;
  174009. } else {
  174010. /* within cell range so no contribution to min_dist */
  174011. min_dist = 0;
  174012. if (x <= centerc0) {
  174013. tdist = (x - maxc0) * C0_SCALE;
  174014. max_dist = tdist*tdist;
  174015. } else {
  174016. tdist = (x - minc0) * C0_SCALE;
  174017. max_dist = tdist*tdist;
  174018. }
  174019. }
  174020. x = GETJSAMPLE(cinfo->colormap[1][i]);
  174021. if (x < minc1) {
  174022. tdist = (x - minc1) * C1_SCALE;
  174023. min_dist += tdist*tdist;
  174024. tdist = (x - maxc1) * C1_SCALE;
  174025. max_dist += tdist*tdist;
  174026. } else if (x > maxc1) {
  174027. tdist = (x - maxc1) * C1_SCALE;
  174028. min_dist += tdist*tdist;
  174029. tdist = (x - minc1) * C1_SCALE;
  174030. max_dist += tdist*tdist;
  174031. } else {
  174032. /* within cell range so no contribution to min_dist */
  174033. if (x <= centerc1) {
  174034. tdist = (x - maxc1) * C1_SCALE;
  174035. max_dist += tdist*tdist;
  174036. } else {
  174037. tdist = (x - minc1) * C1_SCALE;
  174038. max_dist += tdist*tdist;
  174039. }
  174040. }
  174041. x = GETJSAMPLE(cinfo->colormap[2][i]);
  174042. if (x < minc2) {
  174043. tdist = (x - minc2) * C2_SCALE;
  174044. min_dist += tdist*tdist;
  174045. tdist = (x - maxc2) * C2_SCALE;
  174046. max_dist += tdist*tdist;
  174047. } else if (x > maxc2) {
  174048. tdist = (x - maxc2) * C2_SCALE;
  174049. min_dist += tdist*tdist;
  174050. tdist = (x - minc2) * C2_SCALE;
  174051. max_dist += tdist*tdist;
  174052. } else {
  174053. /* within cell range so no contribution to min_dist */
  174054. if (x <= centerc2) {
  174055. tdist = (x - maxc2) * C2_SCALE;
  174056. max_dist += tdist*tdist;
  174057. } else {
  174058. tdist = (x - minc2) * C2_SCALE;
  174059. max_dist += tdist*tdist;
  174060. }
  174061. }
  174062. mindist[i] = min_dist; /* save away the results */
  174063. if (max_dist < minmaxdist)
  174064. minmaxdist = max_dist;
  174065. }
  174066. /* Now we know that no cell in the update box is more than minmaxdist
  174067. * away from some colormap entry. Therefore, only colors that are
  174068. * within minmaxdist of some part of the box need be considered.
  174069. */
  174070. ncolors = 0;
  174071. for (i = 0; i < numcolors; i++) {
  174072. if (mindist[i] <= minmaxdist)
  174073. colorlist[ncolors++] = (JSAMPLE) i;
  174074. }
  174075. return ncolors;
  174076. }
  174077. LOCAL(void)
  174078. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174079. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  174080. /* Find the closest colormap entry for each cell in the update box,
  174081. * given the list of candidate colors prepared by find_nearby_colors.
  174082. * Return the indexes of the closest entries in the bestcolor[] array.
  174083. * This routine uses Thomas' incremental distance calculation method to
  174084. * find the distance from a colormap entry to successive cells in the box.
  174085. */
  174086. {
  174087. int ic0, ic1, ic2;
  174088. int i, icolor;
  174089. register INT32 * bptr; /* pointer into bestdist[] array */
  174090. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174091. INT32 dist0, dist1; /* initial distance values */
  174092. register INT32 dist2; /* current distance in inner loop */
  174093. INT32 xx0, xx1; /* distance increments */
  174094. register INT32 xx2;
  174095. INT32 inc0, inc1, inc2; /* initial values for increments */
  174096. /* This array holds the distance to the nearest-so-far color for each cell */
  174097. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174098. /* Initialize best-distance for each cell of the update box */
  174099. bptr = bestdist;
  174100. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  174101. *bptr++ = 0x7FFFFFFFL;
  174102. /* For each color selected by find_nearby_colors,
  174103. * compute its distance to the center of each cell in the box.
  174104. * If that's less than best-so-far, update best distance and color number.
  174105. */
  174106. /* Nominal steps between cell centers ("x" in Thomas article) */
  174107. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  174108. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  174109. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  174110. for (i = 0; i < numcolors; i++) {
  174111. icolor = GETJSAMPLE(colorlist[i]);
  174112. /* Compute (square of) distance from minc0/c1/c2 to this color */
  174113. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  174114. dist0 = inc0*inc0;
  174115. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  174116. dist0 += inc1*inc1;
  174117. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  174118. dist0 += inc2*inc2;
  174119. /* Form the initial difference increments */
  174120. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  174121. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  174122. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  174123. /* Now loop over all cells in box, updating distance per Thomas method */
  174124. bptr = bestdist;
  174125. cptr = bestcolor;
  174126. xx0 = inc0;
  174127. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  174128. dist1 = dist0;
  174129. xx1 = inc1;
  174130. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  174131. dist2 = dist1;
  174132. xx2 = inc2;
  174133. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  174134. if (dist2 < *bptr) {
  174135. *bptr = dist2;
  174136. *cptr = (JSAMPLE) icolor;
  174137. }
  174138. dist2 += xx2;
  174139. xx2 += 2 * STEP_C2 * STEP_C2;
  174140. bptr++;
  174141. cptr++;
  174142. }
  174143. dist1 += xx1;
  174144. xx1 += 2 * STEP_C1 * STEP_C1;
  174145. }
  174146. dist0 += xx0;
  174147. xx0 += 2 * STEP_C0 * STEP_C0;
  174148. }
  174149. }
  174150. }
  174151. LOCAL(void)
  174152. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  174153. /* Fill the inverse-colormap entries in the update box that contains */
  174154. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  174155. /* we can fill as many others as we wish.) */
  174156. {
  174157. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174158. hist3d histogram = cquantize->histogram;
  174159. int minc0, minc1, minc2; /* lower left corner of update box */
  174160. int ic0, ic1, ic2;
  174161. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174162. register histptr cachep; /* pointer into main cache array */
  174163. /* This array lists the candidate colormap indexes. */
  174164. JSAMPLE colorlist[MAXNUMCOLORS];
  174165. int numcolors; /* number of candidate colors */
  174166. /* This array holds the actually closest colormap index for each cell. */
  174167. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174168. /* Convert cell coordinates to update box ID */
  174169. c0 >>= BOX_C0_LOG;
  174170. c1 >>= BOX_C1_LOG;
  174171. c2 >>= BOX_C2_LOG;
  174172. /* Compute true coordinates of update box's origin corner.
  174173. * Actually we compute the coordinates of the center of the corner
  174174. * histogram cell, which are the lower bounds of the volume we care about.
  174175. */
  174176. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  174177. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  174178. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  174179. /* Determine which colormap entries are close enough to be candidates
  174180. * for the nearest entry to some cell in the update box.
  174181. */
  174182. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  174183. /* Determine the actually nearest colors. */
  174184. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  174185. bestcolor);
  174186. /* Save the best color numbers (plus 1) in the main cache array */
  174187. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  174188. c1 <<= BOX_C1_LOG;
  174189. c2 <<= BOX_C2_LOG;
  174190. cptr = bestcolor;
  174191. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  174192. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  174193. cachep = & histogram[c0+ic0][c1+ic1][c2];
  174194. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  174195. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  174196. }
  174197. }
  174198. }
  174199. }
  174200. /*
  174201. * Map some rows of pixels to the output colormapped representation.
  174202. */
  174203. METHODDEF(void)
  174204. pass2_no_dither (j_decompress_ptr cinfo,
  174205. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174206. /* This version performs no dithering */
  174207. {
  174208. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174209. hist3d histogram = cquantize->histogram;
  174210. register JSAMPROW inptr, outptr;
  174211. register histptr cachep;
  174212. register int c0, c1, c2;
  174213. int row;
  174214. JDIMENSION col;
  174215. JDIMENSION width = cinfo->output_width;
  174216. for (row = 0; row < num_rows; row++) {
  174217. inptr = input_buf[row];
  174218. outptr = output_buf[row];
  174219. for (col = width; col > 0; col--) {
  174220. /* get pixel value and index into the cache */
  174221. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  174222. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  174223. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  174224. cachep = & histogram[c0][c1][c2];
  174225. /* If we have not seen this color before, find nearest colormap entry */
  174226. /* and update the cache */
  174227. if (*cachep == 0)
  174228. fill_inverse_cmap(cinfo, c0,c1,c2);
  174229. /* Now emit the colormap index for this cell */
  174230. *outptr++ = (JSAMPLE) (*cachep - 1);
  174231. }
  174232. }
  174233. }
  174234. METHODDEF(void)
  174235. pass2_fs_dither (j_decompress_ptr cinfo,
  174236. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174237. /* This version performs Floyd-Steinberg dithering */
  174238. {
  174239. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174240. hist3d histogram = cquantize->histogram;
  174241. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  174242. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  174243. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  174244. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  174245. JSAMPROW inptr; /* => current input pixel */
  174246. JSAMPROW outptr; /* => current output pixel */
  174247. histptr cachep;
  174248. int dir; /* +1 or -1 depending on direction */
  174249. int dir3; /* 3*dir, for advancing inptr & errorptr */
  174250. int row;
  174251. JDIMENSION col;
  174252. JDIMENSION width = cinfo->output_width;
  174253. JSAMPLE *range_limit = cinfo->sample_range_limit;
  174254. int *error_limit = cquantize->error_limiter;
  174255. JSAMPROW colormap0 = cinfo->colormap[0];
  174256. JSAMPROW colormap1 = cinfo->colormap[1];
  174257. JSAMPROW colormap2 = cinfo->colormap[2];
  174258. SHIFT_TEMPS
  174259. for (row = 0; row < num_rows; row++) {
  174260. inptr = input_buf[row];
  174261. outptr = output_buf[row];
  174262. if (cquantize->on_odd_row) {
  174263. /* work right to left in this row */
  174264. inptr += (width-1) * 3; /* so point to rightmost pixel */
  174265. outptr += width-1;
  174266. dir = -1;
  174267. dir3 = -3;
  174268. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  174269. cquantize->on_odd_row = FALSE; /* flip for next time */
  174270. } else {
  174271. /* work left to right in this row */
  174272. dir = 1;
  174273. dir3 = 3;
  174274. errorptr = cquantize->fserrors; /* => entry before first real column */
  174275. cquantize->on_odd_row = TRUE; /* flip for next time */
  174276. }
  174277. /* Preset error values: no error propagated to first pixel from left */
  174278. cur0 = cur1 = cur2 = 0;
  174279. /* and no error propagated to row below yet */
  174280. belowerr0 = belowerr1 = belowerr2 = 0;
  174281. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  174282. for (col = width; col > 0; col--) {
  174283. /* curN holds the error propagated from the previous pixel on the
  174284. * current line. Add the error propagated from the previous line
  174285. * to form the complete error correction term for this pixel, and
  174286. * round the error term (which is expressed * 16) to an integer.
  174287. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174288. * for either sign of the error value.
  174289. * Note: errorptr points to *previous* column's array entry.
  174290. */
  174291. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  174292. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  174293. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  174294. /* Limit the error using transfer function set by init_error_limit.
  174295. * See comments with init_error_limit for rationale.
  174296. */
  174297. cur0 = error_limit[cur0];
  174298. cur1 = error_limit[cur1];
  174299. cur2 = error_limit[cur2];
  174300. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174301. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  174302. * this sets the required size of the range_limit array.
  174303. */
  174304. cur0 += GETJSAMPLE(inptr[0]);
  174305. cur1 += GETJSAMPLE(inptr[1]);
  174306. cur2 += GETJSAMPLE(inptr[2]);
  174307. cur0 = GETJSAMPLE(range_limit[cur0]);
  174308. cur1 = GETJSAMPLE(range_limit[cur1]);
  174309. cur2 = GETJSAMPLE(range_limit[cur2]);
  174310. /* Index into the cache with adjusted pixel value */
  174311. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  174312. /* If we have not seen this color before, find nearest colormap */
  174313. /* entry and update the cache */
  174314. if (*cachep == 0)
  174315. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  174316. /* Now emit the colormap index for this cell */
  174317. { register int pixcode = *cachep - 1;
  174318. *outptr = (JSAMPLE) pixcode;
  174319. /* Compute representation error for this pixel */
  174320. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  174321. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  174322. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  174323. }
  174324. /* Compute error fractions to be propagated to adjacent pixels.
  174325. * Add these into the running sums, and simultaneously shift the
  174326. * next-line error sums left by 1 column.
  174327. */
  174328. { register LOCFSERROR bnexterr, delta;
  174329. bnexterr = cur0; /* Process component 0 */
  174330. delta = cur0 * 2;
  174331. cur0 += delta; /* form error * 3 */
  174332. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  174333. cur0 += delta; /* form error * 5 */
  174334. bpreverr0 = belowerr0 + cur0;
  174335. belowerr0 = bnexterr;
  174336. cur0 += delta; /* form error * 7 */
  174337. bnexterr = cur1; /* Process component 1 */
  174338. delta = cur1 * 2;
  174339. cur1 += delta; /* form error * 3 */
  174340. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  174341. cur1 += delta; /* form error * 5 */
  174342. bpreverr1 = belowerr1 + cur1;
  174343. belowerr1 = bnexterr;
  174344. cur1 += delta; /* form error * 7 */
  174345. bnexterr = cur2; /* Process component 2 */
  174346. delta = cur2 * 2;
  174347. cur2 += delta; /* form error * 3 */
  174348. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  174349. cur2 += delta; /* form error * 5 */
  174350. bpreverr2 = belowerr2 + cur2;
  174351. belowerr2 = bnexterr;
  174352. cur2 += delta; /* form error * 7 */
  174353. }
  174354. /* At this point curN contains the 7/16 error value to be propagated
  174355. * to the next pixel on the current line, and all the errors for the
  174356. * next line have been shifted over. We are therefore ready to move on.
  174357. */
  174358. inptr += dir3; /* Advance pixel pointers to next column */
  174359. outptr += dir;
  174360. errorptr += dir3; /* advance errorptr to current column */
  174361. }
  174362. /* Post-loop cleanup: we must unload the final error values into the
  174363. * final fserrors[] entry. Note we need not unload belowerrN because
  174364. * it is for the dummy column before or after the actual array.
  174365. */
  174366. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  174367. errorptr[1] = (FSERROR) bpreverr1;
  174368. errorptr[2] = (FSERROR) bpreverr2;
  174369. }
  174370. }
  174371. /*
  174372. * Initialize the error-limiting transfer function (lookup table).
  174373. * The raw F-S error computation can potentially compute error values of up to
  174374. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  174375. * much less, otherwise obviously wrong pixels will be created. (Typical
  174376. * effects include weird fringes at color-area boundaries, isolated bright
  174377. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  174378. * is to ensure that the "corners" of the color cube are allocated as output
  174379. * colors; then repeated errors in the same direction cannot cause cascading
  174380. * error buildup. However, that only prevents the error from getting
  174381. * completely out of hand; Aaron Giles reports that error limiting improves
  174382. * the results even with corner colors allocated.
  174383. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  174384. * well, but the smoother transfer function used below is even better. Thanks
  174385. * to Aaron Giles for this idea.
  174386. */
  174387. LOCAL(void)
  174388. init_error_limit (j_decompress_ptr cinfo)
  174389. /* Allocate and fill in the error_limiter table */
  174390. {
  174391. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174392. int * table;
  174393. int in, out;
  174394. table = (int *) (*cinfo->mem->alloc_small)
  174395. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  174396. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  174397. cquantize->error_limiter = table;
  174398. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  174399. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  174400. out = 0;
  174401. for (in = 0; in < STEPSIZE; in++, out++) {
  174402. table[in] = out; table[-in] = -out;
  174403. }
  174404. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  174405. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  174406. table[in] = out; table[-in] = -out;
  174407. }
  174408. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  174409. for (; in <= MAXJSAMPLE; in++) {
  174410. table[in] = out; table[-in] = -out;
  174411. }
  174412. #undef STEPSIZE
  174413. }
  174414. /*
  174415. * Finish up at the end of each pass.
  174416. */
  174417. METHODDEF(void)
  174418. finish_pass1 (j_decompress_ptr cinfo)
  174419. {
  174420. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174421. /* Select the representative colors and fill in cinfo->colormap */
  174422. cinfo->colormap = cquantize->sv_colormap;
  174423. select_colors(cinfo, cquantize->desired);
  174424. /* Force next pass to zero the color index table */
  174425. cquantize->needs_zeroed = TRUE;
  174426. }
  174427. METHODDEF(void)
  174428. finish_pass2 (j_decompress_ptr cinfo)
  174429. {
  174430. /* no work */
  174431. }
  174432. /*
  174433. * Initialize for each processing pass.
  174434. */
  174435. METHODDEF(void)
  174436. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  174437. {
  174438. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174439. hist3d histogram = cquantize->histogram;
  174440. int i;
  174441. /* Only F-S dithering or no dithering is supported. */
  174442. /* If user asks for ordered dither, give him F-S. */
  174443. if (cinfo->dither_mode != JDITHER_NONE)
  174444. cinfo->dither_mode = JDITHER_FS;
  174445. if (is_pre_scan) {
  174446. /* Set up method pointers */
  174447. cquantize->pub.color_quantize = prescan_quantize;
  174448. cquantize->pub.finish_pass = finish_pass1;
  174449. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  174450. } else {
  174451. /* Set up method pointers */
  174452. if (cinfo->dither_mode == JDITHER_FS)
  174453. cquantize->pub.color_quantize = pass2_fs_dither;
  174454. else
  174455. cquantize->pub.color_quantize = pass2_no_dither;
  174456. cquantize->pub.finish_pass = finish_pass2;
  174457. /* Make sure color count is acceptable */
  174458. i = cinfo->actual_number_of_colors;
  174459. if (i < 1)
  174460. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  174461. if (i > MAXNUMCOLORS)
  174462. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174463. if (cinfo->dither_mode == JDITHER_FS) {
  174464. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  174465. (3 * SIZEOF(FSERROR)));
  174466. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  174467. if (cquantize->fserrors == NULL)
  174468. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174469. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174470. /* Initialize the propagated errors to zero. */
  174471. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  174472. /* Make the error-limit table if we didn't already. */
  174473. if (cquantize->error_limiter == NULL)
  174474. init_error_limit(cinfo);
  174475. cquantize->on_odd_row = FALSE;
  174476. }
  174477. }
  174478. /* Zero the histogram or inverse color map, if necessary */
  174479. if (cquantize->needs_zeroed) {
  174480. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174481. jzero_far((void FAR *) histogram[i],
  174482. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174483. }
  174484. cquantize->needs_zeroed = FALSE;
  174485. }
  174486. }
  174487. /*
  174488. * Switch to a new external colormap between output passes.
  174489. */
  174490. METHODDEF(void)
  174491. new_color_map_2_quant (j_decompress_ptr cinfo)
  174492. {
  174493. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174494. /* Reset the inverse color map */
  174495. cquantize->needs_zeroed = TRUE;
  174496. }
  174497. /*
  174498. * Module initialization routine for 2-pass color quantization.
  174499. */
  174500. GLOBAL(void)
  174501. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  174502. {
  174503. my_cquantize_ptr2 cquantize;
  174504. int i;
  174505. cquantize = (my_cquantize_ptr2)
  174506. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174507. SIZEOF(my_cquantizer2));
  174508. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174509. cquantize->pub.start_pass = start_pass_2_quant;
  174510. cquantize->pub.new_color_map = new_color_map_2_quant;
  174511. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  174512. cquantize->error_limiter = NULL;
  174513. /* Make sure jdmaster didn't give me a case I can't handle */
  174514. if (cinfo->out_color_components != 3)
  174515. ERREXIT(cinfo, JERR_NOTIMPL);
  174516. /* Allocate the histogram/inverse colormap storage */
  174517. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  174518. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  174519. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174520. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  174521. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174522. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174523. }
  174524. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  174525. /* Allocate storage for the completed colormap, if required.
  174526. * We do this now since it is FAR storage and may affect
  174527. * the memory manager's space calculations.
  174528. */
  174529. if (cinfo->enable_2pass_quant) {
  174530. /* Make sure color count is acceptable */
  174531. int desired = cinfo->desired_number_of_colors;
  174532. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  174533. if (desired < 8)
  174534. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  174535. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174536. if (desired > MAXNUMCOLORS)
  174537. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174538. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  174539. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  174540. cquantize->desired = desired;
  174541. } else
  174542. cquantize->sv_colormap = NULL;
  174543. /* Only F-S dithering or no dithering is supported. */
  174544. /* If user asks for ordered dither, give him F-S. */
  174545. if (cinfo->dither_mode != JDITHER_NONE)
  174546. cinfo->dither_mode = JDITHER_FS;
  174547. /* Allocate Floyd-Steinberg workspace if necessary.
  174548. * This isn't really needed until pass 2, but again it is FAR storage.
  174549. * Although we will cope with a later change in dither_mode,
  174550. * we do not promise to honor max_memory_to_use if dither_mode changes.
  174551. */
  174552. if (cinfo->dither_mode == JDITHER_FS) {
  174553. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174554. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174555. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  174556. /* Might as well create the error-limiting table too. */
  174557. init_error_limit(cinfo);
  174558. }
  174559. }
  174560. #endif /* QUANT_2PASS_SUPPORTED */
  174561. /********* End of inlined file: jquant2.c *********/
  174562. /********* Start of inlined file: jutils.c *********/
  174563. #define JPEG_INTERNALS
  174564. /*
  174565. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  174566. * of a DCT block read in natural order (left to right, top to bottom).
  174567. */
  174568. #if 0 /* This table is not actually needed in v6a */
  174569. const int jpeg_zigzag_order[DCTSIZE2] = {
  174570. 0, 1, 5, 6, 14, 15, 27, 28,
  174571. 2, 4, 7, 13, 16, 26, 29, 42,
  174572. 3, 8, 12, 17, 25, 30, 41, 43,
  174573. 9, 11, 18, 24, 31, 40, 44, 53,
  174574. 10, 19, 23, 32, 39, 45, 52, 54,
  174575. 20, 22, 33, 38, 46, 51, 55, 60,
  174576. 21, 34, 37, 47, 50, 56, 59, 61,
  174577. 35, 36, 48, 49, 57, 58, 62, 63
  174578. };
  174579. #endif
  174580. /*
  174581. * jpeg_natural_order[i] is the natural-order position of the i'th element
  174582. * of zigzag order.
  174583. *
  174584. * When reading corrupted data, the Huffman decoders could attempt
  174585. * to reference an entry beyond the end of this array (if the decoded
  174586. * zero run length reaches past the end of the block). To prevent
  174587. * wild stores without adding an inner-loop test, we put some extra
  174588. * "63"s after the real entries. This will cause the extra coefficient
  174589. * to be stored in location 63 of the block, not somewhere random.
  174590. * The worst case would be a run-length of 15, which means we need 16
  174591. * fake entries.
  174592. */
  174593. const int jpeg_natural_order[DCTSIZE2+16] = {
  174594. 0, 1, 8, 16, 9, 2, 3, 10,
  174595. 17, 24, 32, 25, 18, 11, 4, 5,
  174596. 12, 19, 26, 33, 40, 48, 41, 34,
  174597. 27, 20, 13, 6, 7, 14, 21, 28,
  174598. 35, 42, 49, 56, 57, 50, 43, 36,
  174599. 29, 22, 15, 23, 30, 37, 44, 51,
  174600. 58, 59, 52, 45, 38, 31, 39, 46,
  174601. 53, 60, 61, 54, 47, 55, 62, 63,
  174602. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  174603. 63, 63, 63, 63, 63, 63, 63, 63
  174604. };
  174605. /*
  174606. * Arithmetic utilities
  174607. */
  174608. GLOBAL(long)
  174609. jdiv_round_up (long a, long b)
  174610. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  174611. /* Assumes a >= 0, b > 0 */
  174612. {
  174613. return (a + b - 1L) / b;
  174614. }
  174615. GLOBAL(long)
  174616. jround_up (long a, long b)
  174617. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  174618. /* Assumes a >= 0, b > 0 */
  174619. {
  174620. a += b - 1L;
  174621. return a - (a % b);
  174622. }
  174623. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  174624. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  174625. * are FAR and we're assuming a small-pointer memory model. However, some
  174626. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  174627. * in the small-model libraries. These will be used if USE_FMEM is defined.
  174628. * Otherwise, the routines below do it the hard way. (The performance cost
  174629. * is not all that great, because these routines aren't very heavily used.)
  174630. */
  174631. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  174632. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  174633. #define FMEMZERO(target,size) MEMZERO(target,size)
  174634. #else /* 80x86 case, define if we can */
  174635. #ifdef USE_FMEM
  174636. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  174637. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  174638. #endif
  174639. #endif
  174640. GLOBAL(void)
  174641. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  174642. JSAMPARRAY output_array, int dest_row,
  174643. int num_rows, JDIMENSION num_cols)
  174644. /* Copy some rows of samples from one place to another.
  174645. * num_rows rows are copied from input_array[source_row++]
  174646. * to output_array[dest_row++]; these areas may overlap for duplication.
  174647. * The source and destination arrays must be at least as wide as num_cols.
  174648. */
  174649. {
  174650. register JSAMPROW inptr, outptr;
  174651. #ifdef FMEMCOPY
  174652. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  174653. #else
  174654. register JDIMENSION count;
  174655. #endif
  174656. register int row;
  174657. input_array += source_row;
  174658. output_array += dest_row;
  174659. for (row = num_rows; row > 0; row--) {
  174660. inptr = *input_array++;
  174661. outptr = *output_array++;
  174662. #ifdef FMEMCOPY
  174663. FMEMCOPY(outptr, inptr, count);
  174664. #else
  174665. for (count = num_cols; count > 0; count--)
  174666. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  174667. #endif
  174668. }
  174669. }
  174670. GLOBAL(void)
  174671. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  174672. JDIMENSION num_blocks)
  174673. /* Copy a row of coefficient blocks from one place to another. */
  174674. {
  174675. #ifdef FMEMCOPY
  174676. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  174677. #else
  174678. register JCOEFPTR inptr, outptr;
  174679. register long count;
  174680. inptr = (JCOEFPTR) input_row;
  174681. outptr = (JCOEFPTR) output_row;
  174682. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  174683. *outptr++ = *inptr++;
  174684. }
  174685. #endif
  174686. }
  174687. GLOBAL(void)
  174688. jzero_far (void FAR * target, size_t bytestozero)
  174689. /* Zero out a chunk of FAR memory. */
  174690. /* This might be sample-array data, block-array data, or alloc_large data. */
  174691. {
  174692. #ifdef FMEMZERO
  174693. FMEMZERO(target, bytestozero);
  174694. #else
  174695. register char FAR * ptr = (char FAR *) target;
  174696. register size_t count;
  174697. for (count = bytestozero; count > 0; count--) {
  174698. *ptr++ = 0;
  174699. }
  174700. #endif
  174701. }
  174702. /********* End of inlined file: jutils.c *********/
  174703. /********* Start of inlined file: transupp.c *********/
  174704. /* Although this file really shouldn't have access to the library internals,
  174705. * it's helpful to let it call jround_up() and jcopy_block_row().
  174706. */
  174707. #define JPEG_INTERNALS
  174708. /********* Start of inlined file: transupp.h *********/
  174709. /* If you happen not to want the image transform support, disable it here */
  174710. #ifndef TRANSFORMS_SUPPORTED
  174711. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  174712. #endif
  174713. /* Short forms of external names for systems with brain-damaged linkers. */
  174714. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174715. #define jtransform_request_workspace jTrRequest
  174716. #define jtransform_adjust_parameters jTrAdjust
  174717. #define jtransform_execute_transformation jTrExec
  174718. #define jcopy_markers_setup jCMrkSetup
  174719. #define jcopy_markers_execute jCMrkExec
  174720. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174721. /*
  174722. * Codes for supported types of image transformations.
  174723. */
  174724. typedef enum {
  174725. JXFORM_NONE, /* no transformation */
  174726. JXFORM_FLIP_H, /* horizontal flip */
  174727. JXFORM_FLIP_V, /* vertical flip */
  174728. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  174729. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  174730. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  174731. JXFORM_ROT_180, /* 180-degree rotation */
  174732. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  174733. } JXFORM_CODE;
  174734. /*
  174735. * Although rotating and flipping data expressed as DCT coefficients is not
  174736. * hard, there is an asymmetry in the JPEG format specification for images
  174737. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  174738. * image edges are padded out to the next iMCU boundary with junk data; but
  174739. * no padding is possible at the top and left edges. If we were to flip
  174740. * the whole image including the pad data, then pad garbage would become
  174741. * visible at the top and/or left, and real pixels would disappear into the
  174742. * pad margins --- perhaps permanently, since encoders & decoders may not
  174743. * bother to preserve DCT blocks that appear to be completely outside the
  174744. * nominal image area. So, we have to exclude any partial iMCUs from the
  174745. * basic transformation.
  174746. *
  174747. * Transpose is the only transformation that can handle partial iMCUs at the
  174748. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  174749. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  174750. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  174751. * The other transforms are defined as combinations of these basic transforms
  174752. * and process edge blocks in a way that preserves the equivalence.
  174753. *
  174754. * The "trim" option causes untransformable partial iMCUs to be dropped;
  174755. * this is not strictly lossless, but it usually gives the best-looking
  174756. * result for odd-size images. Note that when this option is active,
  174757. * the expected mathematical equivalences between the transforms may not hold.
  174758. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  174759. * followed by -rot 180 -trim trims both edges.)
  174760. *
  174761. * We also offer a "force to grayscale" option, which simply discards the
  174762. * chrominance channels of a YCbCr image. This is lossless in the sense that
  174763. * the luminance channel is preserved exactly. It's not the same kind of
  174764. * thing as the rotate/flip transformations, but it's convenient to handle it
  174765. * as part of this package, mainly because the transformation routines have to
  174766. * be aware of the option to know how many components to work on.
  174767. */
  174768. typedef struct {
  174769. /* Options: set by caller */
  174770. JXFORM_CODE transform; /* image transform operator */
  174771. boolean trim; /* if TRUE, trim partial MCUs as needed */
  174772. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  174773. /* Internal workspace: caller should not touch these */
  174774. int num_components; /* # of components in workspace */
  174775. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  174776. } jpeg_transform_info;
  174777. #if TRANSFORMS_SUPPORTED
  174778. /* Request any required workspace */
  174779. EXTERN(void) jtransform_request_workspace
  174780. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  174781. /* Adjust output image parameters */
  174782. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  174783. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174784. jvirt_barray_ptr *src_coef_arrays,
  174785. jpeg_transform_info *info));
  174786. /* Execute the actual transformation, if any */
  174787. EXTERN(void) jtransform_execute_transformation
  174788. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174789. jvirt_barray_ptr *src_coef_arrays,
  174790. jpeg_transform_info *info));
  174791. #endif /* TRANSFORMS_SUPPORTED */
  174792. /*
  174793. * Support for copying optional markers from source to destination file.
  174794. */
  174795. typedef enum {
  174796. JCOPYOPT_NONE, /* copy no optional markers */
  174797. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  174798. JCOPYOPT_ALL /* copy all optional markers */
  174799. } JCOPY_OPTION;
  174800. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  174801. /* Setup decompression object to save desired markers in memory */
  174802. EXTERN(void) jcopy_markers_setup
  174803. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  174804. /* Copy markers saved in the given source object to the destination object */
  174805. EXTERN(void) jcopy_markers_execute
  174806. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174807. JCOPY_OPTION option));
  174808. /********* End of inlined file: transupp.h *********/
  174809. /* My own external interface */
  174810. #if TRANSFORMS_SUPPORTED
  174811. /*
  174812. * Lossless image transformation routines. These routines work on DCT
  174813. * coefficient arrays and thus do not require any lossy decompression
  174814. * or recompression of the image.
  174815. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  174816. *
  174817. * Horizontal flipping is done in-place, using a single top-to-bottom
  174818. * pass through the virtual source array. It will thus be much the
  174819. * fastest option for images larger than main memory.
  174820. *
  174821. * The other routines require a set of destination virtual arrays, so they
  174822. * need twice as much memory as jpegtran normally does. The destination
  174823. * arrays are always written in normal scan order (top to bottom) because
  174824. * the virtual array manager expects this. The source arrays will be scanned
  174825. * in the corresponding order, which means multiple passes through the source
  174826. * arrays for most of the transforms. That could result in much thrashing
  174827. * if the image is larger than main memory.
  174828. *
  174829. * Some notes about the operating environment of the individual transform
  174830. * routines:
  174831. * 1. Both the source and destination virtual arrays are allocated from the
  174832. * source JPEG object, and therefore should be manipulated by calling the
  174833. * source's memory manager.
  174834. * 2. The destination's component count should be used. It may be smaller
  174835. * than the source's when forcing to grayscale.
  174836. * 3. Likewise the destination's sampling factors should be used. When
  174837. * forcing to grayscale the destination's sampling factors will be all 1,
  174838. * and we may as well take that as the effective iMCU size.
  174839. * 4. When "trim" is in effect, the destination's dimensions will be the
  174840. * trimmed values but the source's will be untrimmed.
  174841. * 5. All the routines assume that the source and destination buffers are
  174842. * padded out to a full iMCU boundary. This is true, although for the
  174843. * source buffer it is an undocumented property of jdcoefct.c.
  174844. * Notes 2,3,4 boil down to this: generally we should use the destination's
  174845. * dimensions and ignore the source's.
  174846. */
  174847. LOCAL(void)
  174848. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174849. jvirt_barray_ptr *src_coef_arrays)
  174850. /* Horizontal flip; done in-place, so no separate dest array is required */
  174851. {
  174852. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  174853. int ci, k, offset_y;
  174854. JBLOCKARRAY buffer;
  174855. JCOEFPTR ptr1, ptr2;
  174856. JCOEF temp1, temp2;
  174857. jpeg_component_info *compptr;
  174858. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  174859. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  174860. * mirroring by changing the signs of odd-numbered columns.
  174861. * Partial iMCUs at the right edge are left untouched.
  174862. */
  174863. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174864. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174865. compptr = dstinfo->comp_info + ci;
  174866. comp_width = MCU_cols * compptr->h_samp_factor;
  174867. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  174868. blk_y += compptr->v_samp_factor) {
  174869. buffer = (*srcinfo->mem->access_virt_barray)
  174870. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  174871. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174872. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174873. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  174874. ptr1 = buffer[offset_y][blk_x];
  174875. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  174876. /* this unrolled loop doesn't need to know which row it's on... */
  174877. for (k = 0; k < DCTSIZE2; k += 2) {
  174878. temp1 = *ptr1; /* swap even column */
  174879. temp2 = *ptr2;
  174880. *ptr1++ = temp2;
  174881. *ptr2++ = temp1;
  174882. temp1 = *ptr1; /* swap odd column with sign change */
  174883. temp2 = *ptr2;
  174884. *ptr1++ = -temp2;
  174885. *ptr2++ = -temp1;
  174886. }
  174887. }
  174888. }
  174889. }
  174890. }
  174891. }
  174892. LOCAL(void)
  174893. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174894. jvirt_barray_ptr *src_coef_arrays,
  174895. jvirt_barray_ptr *dst_coef_arrays)
  174896. /* Vertical flip */
  174897. {
  174898. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174899. int ci, i, j, offset_y;
  174900. JBLOCKARRAY src_buffer, dst_buffer;
  174901. JBLOCKROW src_row_ptr, dst_row_ptr;
  174902. JCOEFPTR src_ptr, dst_ptr;
  174903. jpeg_component_info *compptr;
  174904. /* We output into a separate array because we can't touch different
  174905. * rows of the source virtual array simultaneously. Otherwise, this
  174906. * is a pretty straightforward analog of horizontal flip.
  174907. * Within a DCT block, vertical mirroring is done by changing the signs
  174908. * of odd-numbered rows.
  174909. * Partial iMCUs at the bottom edge are copied verbatim.
  174910. */
  174911. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174912. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174913. compptr = dstinfo->comp_info + ci;
  174914. comp_height = MCU_rows * compptr->v_samp_factor;
  174915. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174916. dst_blk_y += compptr->v_samp_factor) {
  174917. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174918. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174919. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174920. if (dst_blk_y < comp_height) {
  174921. /* Row is within the mirrorable area. */
  174922. src_buffer = (*srcinfo->mem->access_virt_barray)
  174923. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174924. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174925. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174926. } else {
  174927. /* Bottom-edge blocks will be copied verbatim. */
  174928. src_buffer = (*srcinfo->mem->access_virt_barray)
  174929. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174930. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174931. }
  174932. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174933. if (dst_blk_y < comp_height) {
  174934. /* Row is within the mirrorable area. */
  174935. dst_row_ptr = dst_buffer[offset_y];
  174936. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174937. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174938. dst_blk_x++) {
  174939. dst_ptr = dst_row_ptr[dst_blk_x];
  174940. src_ptr = src_row_ptr[dst_blk_x];
  174941. for (i = 0; i < DCTSIZE; i += 2) {
  174942. /* copy even row */
  174943. for (j = 0; j < DCTSIZE; j++)
  174944. *dst_ptr++ = *src_ptr++;
  174945. /* copy odd row with sign change */
  174946. for (j = 0; j < DCTSIZE; j++)
  174947. *dst_ptr++ = - *src_ptr++;
  174948. }
  174949. }
  174950. } else {
  174951. /* Just copy row verbatim. */
  174952. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  174953. compptr->width_in_blocks);
  174954. }
  174955. }
  174956. }
  174957. }
  174958. }
  174959. LOCAL(void)
  174960. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174961. jvirt_barray_ptr *src_coef_arrays,
  174962. jvirt_barray_ptr *dst_coef_arrays)
  174963. /* Transpose source into destination */
  174964. {
  174965. JDIMENSION dst_blk_x, dst_blk_y;
  174966. int ci, i, j, offset_x, offset_y;
  174967. JBLOCKARRAY src_buffer, dst_buffer;
  174968. JCOEFPTR src_ptr, dst_ptr;
  174969. jpeg_component_info *compptr;
  174970. /* Transposing pixels within a block just requires transposing the
  174971. * DCT coefficients.
  174972. * Partial iMCUs at the edges require no special treatment; we simply
  174973. * process all the available DCT blocks for every component.
  174974. */
  174975. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174976. compptr = dstinfo->comp_info + ci;
  174977. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174978. dst_blk_y += compptr->v_samp_factor) {
  174979. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174980. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174981. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174982. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174983. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174984. dst_blk_x += compptr->h_samp_factor) {
  174985. src_buffer = (*srcinfo->mem->access_virt_barray)
  174986. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174987. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174988. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174989. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174990. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174991. for (i = 0; i < DCTSIZE; i++)
  174992. for (j = 0; j < DCTSIZE; j++)
  174993. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174994. }
  174995. }
  174996. }
  174997. }
  174998. }
  174999. }
  175000. LOCAL(void)
  175001. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175002. jvirt_barray_ptr *src_coef_arrays,
  175003. jvirt_barray_ptr *dst_coef_arrays)
  175004. /* 90 degree rotation is equivalent to
  175005. * 1. Transposing the image;
  175006. * 2. Horizontal mirroring.
  175007. * These two steps are merged into a single processing routine.
  175008. */
  175009. {
  175010. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  175011. int ci, i, j, offset_x, offset_y;
  175012. JBLOCKARRAY src_buffer, dst_buffer;
  175013. JCOEFPTR src_ptr, dst_ptr;
  175014. jpeg_component_info *compptr;
  175015. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175016. * at the (output) right edge properly. They just get transposed and
  175017. * not mirrored.
  175018. */
  175019. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175020. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175021. compptr = dstinfo->comp_info + ci;
  175022. comp_width = MCU_cols * compptr->h_samp_factor;
  175023. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175024. dst_blk_y += compptr->v_samp_factor) {
  175025. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175026. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175027. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175028. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175029. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175030. dst_blk_x += compptr->h_samp_factor) {
  175031. src_buffer = (*srcinfo->mem->access_virt_barray)
  175032. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175033. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175034. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175035. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175036. if (dst_blk_x < comp_width) {
  175037. /* Block is within the mirrorable area. */
  175038. dst_ptr = dst_buffer[offset_y]
  175039. [comp_width - dst_blk_x - offset_x - 1];
  175040. for (i = 0; i < DCTSIZE; i++) {
  175041. for (j = 0; j < DCTSIZE; j++)
  175042. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175043. i++;
  175044. for (j = 0; j < DCTSIZE; j++)
  175045. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175046. }
  175047. } else {
  175048. /* Edge blocks are transposed but not mirrored. */
  175049. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175050. for (i = 0; i < DCTSIZE; i++)
  175051. for (j = 0; j < DCTSIZE; j++)
  175052. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175053. }
  175054. }
  175055. }
  175056. }
  175057. }
  175058. }
  175059. }
  175060. LOCAL(void)
  175061. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175062. jvirt_barray_ptr *src_coef_arrays,
  175063. jvirt_barray_ptr *dst_coef_arrays)
  175064. /* 270 degree rotation is equivalent to
  175065. * 1. Horizontal mirroring;
  175066. * 2. Transposing the image.
  175067. * These two steps are merged into a single processing routine.
  175068. */
  175069. {
  175070. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  175071. int ci, i, j, offset_x, offset_y;
  175072. JBLOCKARRAY src_buffer, dst_buffer;
  175073. JCOEFPTR src_ptr, dst_ptr;
  175074. jpeg_component_info *compptr;
  175075. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175076. * at the (output) bottom edge properly. They just get transposed and
  175077. * not mirrored.
  175078. */
  175079. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175080. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175081. compptr = dstinfo->comp_info + ci;
  175082. comp_height = MCU_rows * compptr->v_samp_factor;
  175083. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175084. dst_blk_y += compptr->v_samp_factor) {
  175085. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175086. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175087. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175088. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175089. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175090. dst_blk_x += compptr->h_samp_factor) {
  175091. src_buffer = (*srcinfo->mem->access_virt_barray)
  175092. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175093. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175094. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175095. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175096. if (dst_blk_y < comp_height) {
  175097. /* Block is within the mirrorable area. */
  175098. src_ptr = src_buffer[offset_x]
  175099. [comp_height - dst_blk_y - offset_y - 1];
  175100. for (i = 0; i < DCTSIZE; i++) {
  175101. for (j = 0; j < DCTSIZE; j++) {
  175102. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175103. j++;
  175104. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175105. }
  175106. }
  175107. } else {
  175108. /* Edge blocks are transposed but not mirrored. */
  175109. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175110. for (i = 0; i < DCTSIZE; i++)
  175111. for (j = 0; j < DCTSIZE; j++)
  175112. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175113. }
  175114. }
  175115. }
  175116. }
  175117. }
  175118. }
  175119. }
  175120. LOCAL(void)
  175121. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175122. jvirt_barray_ptr *src_coef_arrays,
  175123. jvirt_barray_ptr *dst_coef_arrays)
  175124. /* 180 degree rotation is equivalent to
  175125. * 1. Vertical mirroring;
  175126. * 2. Horizontal mirroring.
  175127. * These two steps are merged into a single processing routine.
  175128. */
  175129. {
  175130. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175131. int ci, i, j, offset_y;
  175132. JBLOCKARRAY src_buffer, dst_buffer;
  175133. JBLOCKROW src_row_ptr, dst_row_ptr;
  175134. JCOEFPTR src_ptr, dst_ptr;
  175135. jpeg_component_info *compptr;
  175136. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175137. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175138. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175139. compptr = dstinfo->comp_info + ci;
  175140. comp_width = MCU_cols * compptr->h_samp_factor;
  175141. comp_height = MCU_rows * compptr->v_samp_factor;
  175142. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175143. dst_blk_y += compptr->v_samp_factor) {
  175144. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175145. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175146. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175147. if (dst_blk_y < comp_height) {
  175148. /* Row is within the vertically mirrorable area. */
  175149. src_buffer = (*srcinfo->mem->access_virt_barray)
  175150. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175151. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175152. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175153. } else {
  175154. /* Bottom-edge rows are only mirrored horizontally. */
  175155. src_buffer = (*srcinfo->mem->access_virt_barray)
  175156. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175157. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175158. }
  175159. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175160. if (dst_blk_y < comp_height) {
  175161. /* Row is within the mirrorable area. */
  175162. dst_row_ptr = dst_buffer[offset_y];
  175163. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175164. /* Process the blocks that can be mirrored both ways. */
  175165. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175166. dst_ptr = dst_row_ptr[dst_blk_x];
  175167. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175168. for (i = 0; i < DCTSIZE; i += 2) {
  175169. /* For even row, negate every odd column. */
  175170. for (j = 0; j < DCTSIZE; j += 2) {
  175171. *dst_ptr++ = *src_ptr++;
  175172. *dst_ptr++ = - *src_ptr++;
  175173. }
  175174. /* For odd row, negate every even column. */
  175175. for (j = 0; j < DCTSIZE; j += 2) {
  175176. *dst_ptr++ = - *src_ptr++;
  175177. *dst_ptr++ = *src_ptr++;
  175178. }
  175179. }
  175180. }
  175181. /* Any remaining right-edge blocks are only mirrored vertically. */
  175182. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175183. dst_ptr = dst_row_ptr[dst_blk_x];
  175184. src_ptr = src_row_ptr[dst_blk_x];
  175185. for (i = 0; i < DCTSIZE; i += 2) {
  175186. for (j = 0; j < DCTSIZE; j++)
  175187. *dst_ptr++ = *src_ptr++;
  175188. for (j = 0; j < DCTSIZE; j++)
  175189. *dst_ptr++ = - *src_ptr++;
  175190. }
  175191. }
  175192. } else {
  175193. /* Remaining rows are just mirrored horizontally. */
  175194. dst_row_ptr = dst_buffer[offset_y];
  175195. src_row_ptr = src_buffer[offset_y];
  175196. /* Process the blocks that can be mirrored. */
  175197. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175198. dst_ptr = dst_row_ptr[dst_blk_x];
  175199. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175200. for (i = 0; i < DCTSIZE2; i += 2) {
  175201. *dst_ptr++ = *src_ptr++;
  175202. *dst_ptr++ = - *src_ptr++;
  175203. }
  175204. }
  175205. /* Any remaining right-edge blocks are only copied. */
  175206. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175207. dst_ptr = dst_row_ptr[dst_blk_x];
  175208. src_ptr = src_row_ptr[dst_blk_x];
  175209. for (i = 0; i < DCTSIZE2; i++)
  175210. *dst_ptr++ = *src_ptr++;
  175211. }
  175212. }
  175213. }
  175214. }
  175215. }
  175216. }
  175217. LOCAL(void)
  175218. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175219. jvirt_barray_ptr *src_coef_arrays,
  175220. jvirt_barray_ptr *dst_coef_arrays)
  175221. /* Transverse transpose is equivalent to
  175222. * 1. 180 degree rotation;
  175223. * 2. Transposition;
  175224. * or
  175225. * 1. Horizontal mirroring;
  175226. * 2. Transposition;
  175227. * 3. Horizontal mirroring.
  175228. * These steps are merged into a single processing routine.
  175229. */
  175230. {
  175231. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175232. int ci, i, j, offset_x, offset_y;
  175233. JBLOCKARRAY src_buffer, dst_buffer;
  175234. JCOEFPTR src_ptr, dst_ptr;
  175235. jpeg_component_info *compptr;
  175236. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175237. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175238. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175239. compptr = dstinfo->comp_info + ci;
  175240. comp_width = MCU_cols * compptr->h_samp_factor;
  175241. comp_height = MCU_rows * compptr->v_samp_factor;
  175242. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175243. dst_blk_y += compptr->v_samp_factor) {
  175244. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175245. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175246. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175247. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175248. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175249. dst_blk_x += compptr->h_samp_factor) {
  175250. src_buffer = (*srcinfo->mem->access_virt_barray)
  175251. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175252. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175253. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175254. if (dst_blk_y < comp_height) {
  175255. src_ptr = src_buffer[offset_x]
  175256. [comp_height - dst_blk_y - offset_y - 1];
  175257. if (dst_blk_x < comp_width) {
  175258. /* Block is within the mirrorable area. */
  175259. dst_ptr = dst_buffer[offset_y]
  175260. [comp_width - dst_blk_x - offset_x - 1];
  175261. for (i = 0; i < DCTSIZE; i++) {
  175262. for (j = 0; j < DCTSIZE; j++) {
  175263. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175264. j++;
  175265. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175266. }
  175267. i++;
  175268. for (j = 0; j < DCTSIZE; j++) {
  175269. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175270. j++;
  175271. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175272. }
  175273. }
  175274. } else {
  175275. /* Right-edge blocks are mirrored in y only */
  175276. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175277. for (i = 0; i < DCTSIZE; i++) {
  175278. for (j = 0; j < DCTSIZE; j++) {
  175279. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175280. j++;
  175281. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175282. }
  175283. }
  175284. }
  175285. } else {
  175286. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175287. if (dst_blk_x < comp_width) {
  175288. /* Bottom-edge blocks are mirrored in x only */
  175289. dst_ptr = dst_buffer[offset_y]
  175290. [comp_width - dst_blk_x - offset_x - 1];
  175291. for (i = 0; i < DCTSIZE; i++) {
  175292. for (j = 0; j < DCTSIZE; j++)
  175293. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175294. i++;
  175295. for (j = 0; j < DCTSIZE; j++)
  175296. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175297. }
  175298. } else {
  175299. /* At lower right corner, just transpose, no mirroring */
  175300. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175301. for (i = 0; i < DCTSIZE; i++)
  175302. for (j = 0; j < DCTSIZE; j++)
  175303. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175304. }
  175305. }
  175306. }
  175307. }
  175308. }
  175309. }
  175310. }
  175311. }
  175312. /* Request any required workspace.
  175313. *
  175314. * We allocate the workspace virtual arrays from the source decompression
  175315. * object, so that all the arrays (both the original data and the workspace)
  175316. * will be taken into account while making memory management decisions.
  175317. * Hence, this routine must be called after jpeg_read_header (which reads
  175318. * the image dimensions) and before jpeg_read_coefficients (which realizes
  175319. * the source's virtual arrays).
  175320. */
  175321. GLOBAL(void)
  175322. jtransform_request_workspace (j_decompress_ptr srcinfo,
  175323. jpeg_transform_info *info)
  175324. {
  175325. jvirt_barray_ptr *coef_arrays = NULL;
  175326. jpeg_component_info *compptr;
  175327. int ci;
  175328. if (info->force_grayscale &&
  175329. srcinfo->jpeg_color_space == JCS_YCbCr &&
  175330. srcinfo->num_components == 3) {
  175331. /* We'll only process the first component */
  175332. info->num_components = 1;
  175333. } else {
  175334. /* Process all the components */
  175335. info->num_components = srcinfo->num_components;
  175336. }
  175337. switch (info->transform) {
  175338. case JXFORM_NONE:
  175339. case JXFORM_FLIP_H:
  175340. /* Don't need a workspace array */
  175341. break;
  175342. case JXFORM_FLIP_V:
  175343. case JXFORM_ROT_180:
  175344. /* Need workspace arrays having same dimensions as source image.
  175345. * Note that we allocate arrays padded out to the next iMCU boundary,
  175346. * so that transform routines need not worry about missing edge blocks.
  175347. */
  175348. coef_arrays = (jvirt_barray_ptr *)
  175349. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175350. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175351. for (ci = 0; ci < info->num_components; ci++) {
  175352. compptr = srcinfo->comp_info + ci;
  175353. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175354. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175355. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175356. (long) compptr->h_samp_factor),
  175357. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175358. (long) compptr->v_samp_factor),
  175359. (JDIMENSION) compptr->v_samp_factor);
  175360. }
  175361. break;
  175362. case JXFORM_TRANSPOSE:
  175363. case JXFORM_TRANSVERSE:
  175364. case JXFORM_ROT_90:
  175365. case JXFORM_ROT_270:
  175366. /* Need workspace arrays having transposed dimensions.
  175367. * Note that we allocate arrays padded out to the next iMCU boundary,
  175368. * so that transform routines need not worry about missing edge blocks.
  175369. */
  175370. coef_arrays = (jvirt_barray_ptr *)
  175371. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175372. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175373. for (ci = 0; ci < info->num_components; ci++) {
  175374. compptr = srcinfo->comp_info + ci;
  175375. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175376. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175377. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175378. (long) compptr->v_samp_factor),
  175379. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175380. (long) compptr->h_samp_factor),
  175381. (JDIMENSION) compptr->h_samp_factor);
  175382. }
  175383. break;
  175384. }
  175385. info->workspace_coef_arrays = coef_arrays;
  175386. }
  175387. /* Transpose destination image parameters */
  175388. LOCAL(void)
  175389. transpose_critical_parameters (j_compress_ptr dstinfo)
  175390. {
  175391. int tblno, i, j, ci, itemp;
  175392. jpeg_component_info *compptr;
  175393. JQUANT_TBL *qtblptr;
  175394. JDIMENSION dtemp;
  175395. UINT16 qtemp;
  175396. /* Transpose basic image dimensions */
  175397. dtemp = dstinfo->image_width;
  175398. dstinfo->image_width = dstinfo->image_height;
  175399. dstinfo->image_height = dtemp;
  175400. /* Transpose sampling factors */
  175401. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175402. compptr = dstinfo->comp_info + ci;
  175403. itemp = compptr->h_samp_factor;
  175404. compptr->h_samp_factor = compptr->v_samp_factor;
  175405. compptr->v_samp_factor = itemp;
  175406. }
  175407. /* Transpose quantization tables */
  175408. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  175409. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  175410. if (qtblptr != NULL) {
  175411. for (i = 0; i < DCTSIZE; i++) {
  175412. for (j = 0; j < i; j++) {
  175413. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  175414. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  175415. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  175416. }
  175417. }
  175418. }
  175419. }
  175420. }
  175421. /* Trim off any partial iMCUs on the indicated destination edge */
  175422. LOCAL(void)
  175423. trim_right_edge (j_compress_ptr dstinfo)
  175424. {
  175425. int ci, max_h_samp_factor;
  175426. JDIMENSION MCU_cols;
  175427. /* We have to compute max_h_samp_factor ourselves,
  175428. * because it hasn't been set yet in the destination
  175429. * (and we don't want to use the source's value).
  175430. */
  175431. max_h_samp_factor = 1;
  175432. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175433. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  175434. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  175435. }
  175436. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  175437. if (MCU_cols > 0) /* can't trim to 0 pixels */
  175438. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  175439. }
  175440. LOCAL(void)
  175441. trim_bottom_edge (j_compress_ptr dstinfo)
  175442. {
  175443. int ci, max_v_samp_factor;
  175444. JDIMENSION MCU_rows;
  175445. /* We have to compute max_v_samp_factor ourselves,
  175446. * because it hasn't been set yet in the destination
  175447. * (and we don't want to use the source's value).
  175448. */
  175449. max_v_samp_factor = 1;
  175450. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175451. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  175452. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  175453. }
  175454. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  175455. if (MCU_rows > 0) /* can't trim to 0 pixels */
  175456. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  175457. }
  175458. /* Adjust output image parameters as needed.
  175459. *
  175460. * This must be called after jpeg_copy_critical_parameters()
  175461. * and before jpeg_write_coefficients().
  175462. *
  175463. * The return value is the set of virtual coefficient arrays to be written
  175464. * (either the ones allocated by jtransform_request_workspace, or the
  175465. * original source data arrays). The caller will need to pass this value
  175466. * to jpeg_write_coefficients().
  175467. */
  175468. GLOBAL(jvirt_barray_ptr *)
  175469. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  175470. j_compress_ptr dstinfo,
  175471. jvirt_barray_ptr *src_coef_arrays,
  175472. jpeg_transform_info *info)
  175473. {
  175474. /* If force-to-grayscale is requested, adjust destination parameters */
  175475. if (info->force_grayscale) {
  175476. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  175477. * properly. Among other things, the target h_samp_factor & v_samp_factor
  175478. * will get set to 1, which typically won't match the source.
  175479. * In fact we do this even if the source is already grayscale; that
  175480. * provides an easy way of coercing a grayscale JPEG with funny sampling
  175481. * factors to the customary 1,1. (Some decoders fail on other factors.)
  175482. */
  175483. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  175484. dstinfo->num_components == 3) ||
  175485. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  175486. dstinfo->num_components == 1)) {
  175487. /* We have to preserve the source's quantization table number. */
  175488. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  175489. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  175490. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  175491. } else {
  175492. /* Sorry, can't do it */
  175493. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  175494. }
  175495. }
  175496. /* Correct the destination's image dimensions etc if necessary */
  175497. switch (info->transform) {
  175498. case JXFORM_NONE:
  175499. /* Nothing to do */
  175500. break;
  175501. case JXFORM_FLIP_H:
  175502. if (info->trim)
  175503. trim_right_edge(dstinfo);
  175504. break;
  175505. case JXFORM_FLIP_V:
  175506. if (info->trim)
  175507. trim_bottom_edge(dstinfo);
  175508. break;
  175509. case JXFORM_TRANSPOSE:
  175510. transpose_critical_parameters(dstinfo);
  175511. /* transpose does NOT have to trim anything */
  175512. break;
  175513. case JXFORM_TRANSVERSE:
  175514. transpose_critical_parameters(dstinfo);
  175515. if (info->trim) {
  175516. trim_right_edge(dstinfo);
  175517. trim_bottom_edge(dstinfo);
  175518. }
  175519. break;
  175520. case JXFORM_ROT_90:
  175521. transpose_critical_parameters(dstinfo);
  175522. if (info->trim)
  175523. trim_right_edge(dstinfo);
  175524. break;
  175525. case JXFORM_ROT_180:
  175526. if (info->trim) {
  175527. trim_right_edge(dstinfo);
  175528. trim_bottom_edge(dstinfo);
  175529. }
  175530. break;
  175531. case JXFORM_ROT_270:
  175532. transpose_critical_parameters(dstinfo);
  175533. if (info->trim)
  175534. trim_bottom_edge(dstinfo);
  175535. break;
  175536. }
  175537. /* Return the appropriate output data set */
  175538. if (info->workspace_coef_arrays != NULL)
  175539. return info->workspace_coef_arrays;
  175540. return src_coef_arrays;
  175541. }
  175542. /* Execute the actual transformation, if any.
  175543. *
  175544. * This must be called *after* jpeg_write_coefficients, because it depends
  175545. * on jpeg_write_coefficients to have computed subsidiary values such as
  175546. * the per-component width and height fields in the destination object.
  175547. *
  175548. * Note that some transformations will modify the source data arrays!
  175549. */
  175550. GLOBAL(void)
  175551. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  175552. j_compress_ptr dstinfo,
  175553. jvirt_barray_ptr *src_coef_arrays,
  175554. jpeg_transform_info *info)
  175555. {
  175556. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  175557. switch (info->transform) {
  175558. case JXFORM_NONE:
  175559. break;
  175560. case JXFORM_FLIP_H:
  175561. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  175562. break;
  175563. case JXFORM_FLIP_V:
  175564. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175565. break;
  175566. case JXFORM_TRANSPOSE:
  175567. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175568. break;
  175569. case JXFORM_TRANSVERSE:
  175570. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175571. break;
  175572. case JXFORM_ROT_90:
  175573. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175574. break;
  175575. case JXFORM_ROT_180:
  175576. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175577. break;
  175578. case JXFORM_ROT_270:
  175579. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175580. break;
  175581. }
  175582. }
  175583. #endif /* TRANSFORMS_SUPPORTED */
  175584. /* Setup decompression object to save desired markers in memory.
  175585. * This must be called before jpeg_read_header() to have the desired effect.
  175586. */
  175587. GLOBAL(void)
  175588. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  175589. {
  175590. #ifdef SAVE_MARKERS_SUPPORTED
  175591. int m;
  175592. /* Save comments except under NONE option */
  175593. if (option != JCOPYOPT_NONE) {
  175594. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  175595. }
  175596. /* Save all types of APPn markers iff ALL option */
  175597. if (option == JCOPYOPT_ALL) {
  175598. for (m = 0; m < 16; m++)
  175599. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  175600. }
  175601. #endif /* SAVE_MARKERS_SUPPORTED */
  175602. }
  175603. /* Copy markers saved in the given source object to the destination object.
  175604. * This should be called just after jpeg_start_compress() or
  175605. * jpeg_write_coefficients().
  175606. * Note that those routines will have written the SOI, and also the
  175607. * JFIF APP0 or Adobe APP14 markers if selected.
  175608. */
  175609. GLOBAL(void)
  175610. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175611. JCOPY_OPTION option)
  175612. {
  175613. jpeg_saved_marker_ptr marker;
  175614. /* In the current implementation, we don't actually need to examine the
  175615. * option flag here; we just copy everything that got saved.
  175616. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  175617. * if the encoder library already wrote one.
  175618. */
  175619. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  175620. if (dstinfo->write_JFIF_header &&
  175621. marker->marker == JPEG_APP0 &&
  175622. marker->data_length >= 5 &&
  175623. GETJOCTET(marker->data[0]) == 0x4A &&
  175624. GETJOCTET(marker->data[1]) == 0x46 &&
  175625. GETJOCTET(marker->data[2]) == 0x49 &&
  175626. GETJOCTET(marker->data[3]) == 0x46 &&
  175627. GETJOCTET(marker->data[4]) == 0)
  175628. continue; /* reject duplicate JFIF */
  175629. if (dstinfo->write_Adobe_marker &&
  175630. marker->marker == JPEG_APP0+14 &&
  175631. marker->data_length >= 5 &&
  175632. GETJOCTET(marker->data[0]) == 0x41 &&
  175633. GETJOCTET(marker->data[1]) == 0x64 &&
  175634. GETJOCTET(marker->data[2]) == 0x6F &&
  175635. GETJOCTET(marker->data[3]) == 0x62 &&
  175636. GETJOCTET(marker->data[4]) == 0x65)
  175637. continue; /* reject duplicate Adobe */
  175638. #ifdef NEED_FAR_POINTERS
  175639. /* We could use jpeg_write_marker if the data weren't FAR... */
  175640. {
  175641. unsigned int i;
  175642. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  175643. for (i = 0; i < marker->data_length; i++)
  175644. jpeg_write_m_byte(dstinfo, marker->data[i]);
  175645. }
  175646. #else
  175647. jpeg_write_marker(dstinfo, marker->marker,
  175648. marker->data, marker->data_length);
  175649. #endif
  175650. }
  175651. }
  175652. /********* End of inlined file: transupp.c *********/
  175653. }
  175654. #else
  175655. #define JPEG_INTERNALS
  175656. #undef FAR
  175657. #include <jpeglib.h>
  175658. #endif
  175659. }
  175660. #if JUCE_MSVC
  175661. #pragma warning (pop)
  175662. #endif
  175663. BEGIN_JUCE_NAMESPACE
  175664. using namespace jpeglibNamespace;
  175665. #if ! JUCE_MSVC
  175666. using jpeglibNamespace::boolean;
  175667. #endif
  175668. struct JPEGDecodingFailure {};
  175669. static void fatalErrorHandler (j_common_ptr)
  175670. {
  175671. throw JPEGDecodingFailure();
  175672. }
  175673. static void silentErrorCallback1 (j_common_ptr) {}
  175674. static void silentErrorCallback2 (j_common_ptr, int) {}
  175675. static void silentErrorCallback3 (j_common_ptr, char*) {}
  175676. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  175677. {
  175678. zerostruct (err);
  175679. err.error_exit = fatalErrorHandler;
  175680. err.emit_message = silentErrorCallback2;
  175681. err.output_message = silentErrorCallback1;
  175682. err.format_message = silentErrorCallback3;
  175683. err.reset_error_mgr = silentErrorCallback1;
  175684. }
  175685. static void dummyCallback1 (j_decompress_ptr) throw()
  175686. {
  175687. }
  175688. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  175689. {
  175690. decompStruct->src->next_input_byte += num;
  175691. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  175692. decompStruct->src->bytes_in_buffer -= num;
  175693. }
  175694. static boolean jpegFill (j_decompress_ptr) throw()
  175695. {
  175696. return 0;
  175697. }
  175698. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  175699. {
  175700. MemoryBlock mb;
  175701. in.readIntoMemoryBlock (mb);
  175702. Image* image = 0;
  175703. if (mb.getSize() > 16)
  175704. {
  175705. struct jpeg_decompress_struct jpegDecompStruct;
  175706. struct jpeg_error_mgr jerr;
  175707. setupSilentErrorHandler (jerr);
  175708. jpegDecompStruct.err = &jerr;
  175709. jpeg_create_decompress (&jpegDecompStruct);
  175710. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  175711. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  175712. jpegDecompStruct.src->init_source = dummyCallback1;
  175713. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  175714. jpegDecompStruct.src->skip_input_data = jpegSkip;
  175715. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  175716. jpegDecompStruct.src->term_source = dummyCallback1;
  175717. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  175718. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  175719. try
  175720. {
  175721. jpeg_read_header (&jpegDecompStruct, TRUE);
  175722. jpeg_calc_output_dimensions (&jpegDecompStruct);
  175723. const int width = jpegDecompStruct.output_width;
  175724. const int height = jpegDecompStruct.output_height;
  175725. jpegDecompStruct.out_color_space = JCS_RGB;
  175726. JSAMPARRAY buffer
  175727. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  175728. JPOOL_IMAGE,
  175729. width * 3, 1);
  175730. if (jpeg_start_decompress (&jpegDecompStruct))
  175731. {
  175732. image = new Image (Image::RGB, width, height, false);
  175733. for (int y = 0; y < height; ++y)
  175734. {
  175735. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  175736. int stride, pixelStride;
  175737. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  175738. const uint8* src = *buffer;
  175739. uint8* dest = pixels;
  175740. for (int i = width; --i >= 0;)
  175741. {
  175742. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  175743. dest += pixelStride;
  175744. src += 3;
  175745. }
  175746. image->releasePixelDataReadWrite (pixels);
  175747. }
  175748. jpeg_finish_decompress (&jpegDecompStruct);
  175749. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  175750. }
  175751. jpeg_destroy_decompress (&jpegDecompStruct);
  175752. }
  175753. catch (...)
  175754. {}
  175755. }
  175756. return image;
  175757. }
  175758. static const int bufferSize = 512;
  175759. struct JuceJpegDest : public jpeg_destination_mgr
  175760. {
  175761. OutputStream* output;
  175762. char* buffer;
  175763. };
  175764. static void jpegWriteInit (j_compress_ptr) throw()
  175765. {
  175766. }
  175767. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  175768. {
  175769. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175770. const int numToWrite = bufferSize - dest->free_in_buffer;
  175771. dest->output->write (dest->buffer, numToWrite);
  175772. }
  175773. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  175774. {
  175775. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175776. const int numToWrite = bufferSize;
  175777. dest->next_output_byte = (JOCTET*) dest->buffer;
  175778. dest->free_in_buffer = bufferSize;
  175779. return dest->output->write (dest->buffer, numToWrite);
  175780. }
  175781. bool juce_writeJPEGImageToStream (const Image& image,
  175782. OutputStream& out,
  175783. float quality) throw()
  175784. {
  175785. if (image.hasAlphaChannel())
  175786. {
  175787. // this method could fill the background in white and still save the image..
  175788. jassertfalse
  175789. return true;
  175790. }
  175791. struct jpeg_compress_struct jpegCompStruct;
  175792. struct jpeg_error_mgr jerr;
  175793. setupSilentErrorHandler (jerr);
  175794. jpegCompStruct.err = &jerr;
  175795. jpeg_create_compress (&jpegCompStruct);
  175796. JuceJpegDest dest;
  175797. jpegCompStruct.dest = &dest;
  175798. dest.output = &out;
  175799. dest.buffer = (char*) juce_malloc (bufferSize);
  175800. dest.next_output_byte = (JOCTET*) dest.buffer;
  175801. dest.free_in_buffer = bufferSize;
  175802. dest.init_destination = jpegWriteInit;
  175803. dest.empty_output_buffer = jpegWriteFlush;
  175804. dest.term_destination = jpegWriteTerminate;
  175805. jpegCompStruct.image_width = image.getWidth();
  175806. jpegCompStruct.image_height = image.getHeight();
  175807. jpegCompStruct.input_components = 3;
  175808. jpegCompStruct.in_color_space = JCS_RGB;
  175809. jpegCompStruct.write_JFIF_header = 1;
  175810. jpegCompStruct.X_density = 72;
  175811. jpegCompStruct.Y_density = 72;
  175812. jpeg_set_defaults (&jpegCompStruct);
  175813. jpegCompStruct.dct_method = JDCT_FLOAT;
  175814. jpegCompStruct.optimize_coding = 1;
  175815. // jpegCompStruct.smoothing_factor = 10;
  175816. if (quality < 0.0f)
  175817. quality = 0.85f;
  175818. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  175819. jpeg_start_compress (&jpegCompStruct, TRUE);
  175820. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  175821. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  175822. JPOOL_IMAGE,
  175823. strideBytes, 1);
  175824. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  175825. {
  175826. int stride, pixelStride;
  175827. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  175828. const uint8* src = pixels;
  175829. uint8* dst = *buffer;
  175830. for (int i = jpegCompStruct.image_width; --i >= 0;)
  175831. {
  175832. *dst++ = ((const PixelRGB*) src)->getRed();
  175833. *dst++ = ((const PixelRGB*) src)->getGreen();
  175834. *dst++ = ((const PixelRGB*) src)->getBlue();
  175835. src += pixelStride;
  175836. }
  175837. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  175838. image.releasePixelDataReadOnly (pixels);
  175839. }
  175840. jpeg_finish_compress (&jpegCompStruct);
  175841. jpeg_destroy_compress (&jpegCompStruct);
  175842. juce_free (dest.buffer);
  175843. out.flush();
  175844. return true;
  175845. }
  175846. END_JUCE_NAMESPACE
  175847. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  175848. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  175849. #ifdef _MSC_VER
  175850. #pragma warning (push)
  175851. #pragma warning (disable: 4390 4611)
  175852. #endif
  175853. namespace zlibNamespace
  175854. {
  175855. #if JUCE_INCLUDE_ZLIB_CODE
  175856. #undef OS_CODE
  175857. #undef fdopen
  175858. #undef OS_CODE
  175859. #else
  175860. #include <zlib.h>
  175861. #endif
  175862. }
  175863. namespace pnglibNamespace
  175864. {
  175865. using namespace zlibNamespace;
  175866. #if JUCE_INCLUDE_PNGLIB_CODE
  175867. #if _MSC_VER != 1310
  175868. using ::calloc; // (causes conflict in VS.NET 2003)
  175869. using ::malloc;
  175870. using ::free;
  175871. #endif
  175872. extern "C"
  175873. {
  175874. using ::abs;
  175875. #define PNG_INTERNAL
  175876. #define NO_DUMMY_DECL
  175877. #define PNG_SETJMP_NOT_SUPPORTED
  175878. /********* Start of inlined file: png.h *********/
  175879. /* png.h - header file for PNG reference library
  175880. *
  175881. * libpng version 1.2.21 - October 4, 2007
  175882. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175883. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175884. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175885. *
  175886. * Authors and maintainers:
  175887. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  175888. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  175889. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  175890. * See also "Contributing Authors", below.
  175891. *
  175892. * Note about libpng version numbers:
  175893. *
  175894. * Due to various miscommunications, unforeseen code incompatibilities
  175895. * and occasional factors outside the authors' control, version numbering
  175896. * on the library has not always been consistent and straightforward.
  175897. * The following table summarizes matters since version 0.89c, which was
  175898. * the first widely used release:
  175899. *
  175900. * source png.h png.h shared-lib
  175901. * version string int version
  175902. * ------- ------ ----- ----------
  175903. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  175904. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  175905. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  175906. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  175907. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  175908. * 0.97c 0.97 97 2.0.97
  175909. * 0.98 0.98 98 2.0.98
  175910. * 0.99 0.99 98 2.0.99
  175911. * 0.99a-m 0.99 99 2.0.99
  175912. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  175913. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  175914. * 1.0.1 png.h string is 10001 2.1.0
  175915. * 1.0.1a-e identical to the 10002 from here on, the shared library
  175916. * 1.0.2 source version) 10002 is 2.V where V is the source code
  175917. * 1.0.2a-b 10003 version, except as noted.
  175918. * 1.0.3 10003
  175919. * 1.0.3a-d 10004
  175920. * 1.0.4 10004
  175921. * 1.0.4a-f 10005
  175922. * 1.0.5 (+ 2 patches) 10005
  175923. * 1.0.5a-d 10006
  175924. * 1.0.5e-r 10100 (not source compatible)
  175925. * 1.0.5s-v 10006 (not binary compatible)
  175926. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  175927. * 1.0.6d-f 10007 (still binary incompatible)
  175928. * 1.0.6g 10007
  175929. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  175930. * 1.0.6i 10007 10.6i
  175931. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  175932. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  175933. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  175934. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  175935. * 1.0.7 1 10007 (still compatible)
  175936. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  175937. * 1.0.8rc1 1 10008 2.1.0.8rc1
  175938. * 1.0.8 1 10008 2.1.0.8
  175939. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  175940. * 1.0.9rc1 1 10009 2.1.0.9rc1
  175941. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  175942. * 1.0.9rc2 1 10009 2.1.0.9rc2
  175943. * 1.0.9 1 10009 2.1.0.9
  175944. * 1.0.10beta1 1 10010 2.1.0.10beta1
  175945. * 1.0.10rc1 1 10010 2.1.0.10rc1
  175946. * 1.0.10 1 10010 2.1.0.10
  175947. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  175948. * 1.0.11rc1 1 10011 2.1.0.11rc1
  175949. * 1.0.11 1 10011 2.1.0.11
  175950. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  175951. * 1.0.12rc1 2 10012 2.1.0.12rc1
  175952. * 1.0.12 2 10012 2.1.0.12
  175953. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  175954. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  175955. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  175956. * 1.2.0rc1 3 10200 3.1.2.0rc1
  175957. * 1.2.0 3 10200 3.1.2.0
  175958. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  175959. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  175960. * 1.2.1 3 10201 3.1.2.1
  175961. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  175962. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  175963. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  175964. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  175965. * 1.0.13 10 10013 10.so.0.1.0.13
  175966. * 1.2.2 12 10202 12.so.0.1.2.2
  175967. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  175968. * 1.2.3 12 10203 12.so.0.1.2.3
  175969. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  175970. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  175971. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  175972. * 1.0.14 10 10014 10.so.0.1.0.14
  175973. * 1.2.4 13 10204 12.so.0.1.2.4
  175974. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  175975. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  175976. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  175977. * 1.0.15 10 10015 10.so.0.1.0.15
  175978. * 1.2.5 13 10205 12.so.0.1.2.5
  175979. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  175980. * 1.0.16 10 10016 10.so.0.1.0.16
  175981. * 1.2.6 13 10206 12.so.0.1.2.6
  175982. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  175983. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  175984. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  175985. * 1.0.17 10 10017 10.so.0.1.0.17
  175986. * 1.2.7 13 10207 12.so.0.1.2.7
  175987. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  175988. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  175989. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  175990. * 1.0.18 10 10018 10.so.0.1.0.18
  175991. * 1.2.8 13 10208 12.so.0.1.2.8
  175992. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  175993. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  175994. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  175995. * 1.2.9 13 10209 12.so.0.9[.0]
  175996. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  175997. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  175998. * 1.2.10 13 10210 12.so.0.10[.0]
  175999. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  176000. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  176001. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  176002. * 1.0.19 10 10019 10.so.0.19[.0]
  176003. * 1.2.11 13 10211 12.so.0.11[.0]
  176004. * 1.0.20 10 10020 10.so.0.20[.0]
  176005. * 1.2.12 13 10212 12.so.0.12[.0]
  176006. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  176007. * 1.0.21 10 10021 10.so.0.21[.0]
  176008. * 1.2.13 13 10213 12.so.0.13[.0]
  176009. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  176010. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  176011. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  176012. * 1.0.22 10 10022 10.so.0.22[.0]
  176013. * 1.2.14 13 10214 12.so.0.14[.0]
  176014. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  176015. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  176016. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  176017. * 1.0.23 10 10023 10.so.0.23[.0]
  176018. * 1.2.15 13 10215 12.so.0.15[.0]
  176019. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  176020. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  176021. * 1.0.24 10 10024 10.so.0.24[.0]
  176022. * 1.2.16 13 10216 12.so.0.16[.0]
  176023. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  176024. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  176025. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  176026. * 1.0.25 10 10025 10.so.0.25[.0]
  176027. * 1.2.17 13 10217 12.so.0.17[.0]
  176028. * 1.0.26 10 10026 10.so.0.26[.0]
  176029. * 1.2.18 13 10218 12.so.0.18[.0]
  176030. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  176031. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  176032. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  176033. * 1.0.27 10 10027 10.so.0.27[.0]
  176034. * 1.2.19 13 10219 12.so.0.19[.0]
  176035. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  176036. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  176037. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  176038. * 1.0.28 10 10028 10.so.0.28[.0]
  176039. * 1.2.20 13 10220 12.so.0.20[.0]
  176040. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  176041. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  176042. * 1.0.29 10 10029 10.so.0.29[.0]
  176043. * 1.2.21 13 10221 12.so.0.21[.0]
  176044. *
  176045. * Henceforth the source version will match the shared-library major
  176046. * and minor numbers; the shared-library major version number will be
  176047. * used for changes in backward compatibility, as it is intended. The
  176048. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  176049. * for applications, is an unsigned integer of the form xyyzz corresponding
  176050. * to the source version x.y.z (leading zeros in y and z). Beta versions
  176051. * were given the previous public release number plus a letter, until
  176052. * version 1.0.6j; from then on they were given the upcoming public
  176053. * release number plus "betaNN" or "rcN".
  176054. *
  176055. * Binary incompatibility exists only when applications make direct access
  176056. * to the info_ptr or png_ptr members through png.h, and the compiled
  176057. * application is loaded with a different version of the library.
  176058. *
  176059. * DLLNUM will change each time there are forward or backward changes
  176060. * in binary compatibility (e.g., when a new feature is added).
  176061. *
  176062. * See libpng.txt or libpng.3 for more information. The PNG specification
  176063. * is available as a W3C Recommendation and as an ISO Specification,
  176064. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  176065. */
  176066. /*
  176067. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  176068. *
  176069. * If you modify libpng you may insert additional notices immediately following
  176070. * this sentence.
  176071. *
  176072. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  176073. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  176074. * distributed according to the same disclaimer and license as libpng-1.2.5
  176075. * with the following individual added to the list of Contributing Authors:
  176076. *
  176077. * Cosmin Truta
  176078. *
  176079. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  176080. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  176081. * distributed according to the same disclaimer and license as libpng-1.0.6
  176082. * with the following individuals added to the list of Contributing Authors:
  176083. *
  176084. * Simon-Pierre Cadieux
  176085. * Eric S. Raymond
  176086. * Gilles Vollant
  176087. *
  176088. * and with the following additions to the disclaimer:
  176089. *
  176090. * There is no warranty against interference with your enjoyment of the
  176091. * library or against infringement. There is no warranty that our
  176092. * efforts or the library will fulfill any of your particular purposes
  176093. * or needs. This library is provided with all faults, and the entire
  176094. * risk of satisfactory quality, performance, accuracy, and effort is with
  176095. * the user.
  176096. *
  176097. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  176098. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  176099. * distributed according to the same disclaimer and license as libpng-0.96,
  176100. * with the following individuals added to the list of Contributing Authors:
  176101. *
  176102. * Tom Lane
  176103. * Glenn Randers-Pehrson
  176104. * Willem van Schaik
  176105. *
  176106. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  176107. * Copyright (c) 1996, 1997 Andreas Dilger
  176108. * Distributed according to the same disclaimer and license as libpng-0.88,
  176109. * with the following individuals added to the list of Contributing Authors:
  176110. *
  176111. * John Bowler
  176112. * Kevin Bracey
  176113. * Sam Bushell
  176114. * Magnus Holmgren
  176115. * Greg Roelofs
  176116. * Tom Tanner
  176117. *
  176118. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  176119. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  176120. *
  176121. * For the purposes of this copyright and license, "Contributing Authors"
  176122. * is defined as the following set of individuals:
  176123. *
  176124. * Andreas Dilger
  176125. * Dave Martindale
  176126. * Guy Eric Schalnat
  176127. * Paul Schmidt
  176128. * Tim Wegner
  176129. *
  176130. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  176131. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  176132. * including, without limitation, the warranties of merchantability and of
  176133. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  176134. * assume no liability for direct, indirect, incidental, special, exemplary,
  176135. * or consequential damages, which may result from the use of the PNG
  176136. * Reference Library, even if advised of the possibility of such damage.
  176137. *
  176138. * Permission is hereby granted to use, copy, modify, and distribute this
  176139. * source code, or portions hereof, for any purpose, without fee, subject
  176140. * to the following restrictions:
  176141. *
  176142. * 1. The origin of this source code must not be misrepresented.
  176143. *
  176144. * 2. Altered versions must be plainly marked as such and
  176145. * must not be misrepresented as being the original source.
  176146. *
  176147. * 3. This Copyright notice may not be removed or altered from
  176148. * any source or altered source distribution.
  176149. *
  176150. * The Contributing Authors and Group 42, Inc. specifically permit, without
  176151. * fee, and encourage the use of this source code as a component to
  176152. * supporting the PNG file format in commercial products. If you use this
  176153. * source code in a product, acknowledgment is not required but would be
  176154. * appreciated.
  176155. */
  176156. /*
  176157. * A "png_get_copyright" function is available, for convenient use in "about"
  176158. * boxes and the like:
  176159. *
  176160. * printf("%s",png_get_copyright(NULL));
  176161. *
  176162. * Also, the PNG logo (in PNG format, of course) is supplied in the
  176163. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  176164. */
  176165. /*
  176166. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  176167. * certification mark of the Open Source Initiative.
  176168. */
  176169. /*
  176170. * The contributing authors would like to thank all those who helped
  176171. * with testing, bug fixes, and patience. This wouldn't have been
  176172. * possible without all of you.
  176173. *
  176174. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  176175. */
  176176. /*
  176177. * Y2K compliance in libpng:
  176178. * =========================
  176179. *
  176180. * October 4, 2007
  176181. *
  176182. * Since the PNG Development group is an ad-hoc body, we can't make
  176183. * an official declaration.
  176184. *
  176185. * This is your unofficial assurance that libpng from version 0.71 and
  176186. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  176187. * versions were also Y2K compliant.
  176188. *
  176189. * Libpng only has three year fields. One is a 2-byte unsigned integer
  176190. * that will hold years up to 65535. The other two hold the date in text
  176191. * format, and will hold years up to 9999.
  176192. *
  176193. * The integer is
  176194. * "png_uint_16 year" in png_time_struct.
  176195. *
  176196. * The strings are
  176197. * "png_charp time_buffer" in png_struct and
  176198. * "near_time_buffer", which is a local character string in png.c.
  176199. *
  176200. * There are seven time-related functions:
  176201. * png.c: png_convert_to_rfc_1123() in png.c
  176202. * (formerly png_convert_to_rfc_1152() in error)
  176203. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  176204. * png_convert_from_time_t() in pngwrite.c
  176205. * png_get_tIME() in pngget.c
  176206. * png_handle_tIME() in pngrutil.c, called in pngread.c
  176207. * png_set_tIME() in pngset.c
  176208. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  176209. *
  176210. * All handle dates properly in a Y2K environment. The
  176211. * png_convert_from_time_t() function calls gmtime() to convert from system
  176212. * clock time, which returns (year - 1900), which we properly convert to
  176213. * the full 4-digit year. There is a possibility that applications using
  176214. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  176215. * function, or that they are incorrectly passing only a 2-digit year
  176216. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  176217. * but this is not under our control. The libpng documentation has always
  176218. * stated that it works with 4-digit years, and the APIs have been
  176219. * documented as such.
  176220. *
  176221. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  176222. * integer to hold the year, and can hold years as large as 65535.
  176223. *
  176224. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  176225. * no date-related code.
  176226. *
  176227. * Glenn Randers-Pehrson
  176228. * libpng maintainer
  176229. * PNG Development Group
  176230. */
  176231. #ifndef PNG_H
  176232. #define PNG_H
  176233. /* This is not the place to learn how to use libpng. The file libpng.txt
  176234. * describes how to use libpng, and the file example.c summarizes it
  176235. * with some code on which to build. This file is useful for looking
  176236. * at the actual function definitions and structure components.
  176237. */
  176238. /* Version information for png.h - this should match the version in png.c */
  176239. #define PNG_LIBPNG_VER_STRING "1.2.21"
  176240. #define PNG_HEADER_VERSION_STRING \
  176241. " libpng version 1.2.21 - October 4, 2007\n"
  176242. #define PNG_LIBPNG_VER_SONUM 0
  176243. #define PNG_LIBPNG_VER_DLLNUM 13
  176244. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  176245. #define PNG_LIBPNG_VER_MAJOR 1
  176246. #define PNG_LIBPNG_VER_MINOR 2
  176247. #define PNG_LIBPNG_VER_RELEASE 21
  176248. /* This should match the numeric part of the final component of
  176249. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  176250. #define PNG_LIBPNG_VER_BUILD 0
  176251. /* Release Status */
  176252. #define PNG_LIBPNG_BUILD_ALPHA 1
  176253. #define PNG_LIBPNG_BUILD_BETA 2
  176254. #define PNG_LIBPNG_BUILD_RC 3
  176255. #define PNG_LIBPNG_BUILD_STABLE 4
  176256. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  176257. /* Release-Specific Flags */
  176258. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  176259. PNG_LIBPNG_BUILD_STABLE only */
  176260. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  176261. PNG_LIBPNG_BUILD_SPECIAL */
  176262. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  176263. PNG_LIBPNG_BUILD_PRIVATE */
  176264. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  176265. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  176266. * We must not include leading zeros.
  176267. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  176268. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  176269. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  176270. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  176271. #ifndef PNG_VERSION_INFO_ONLY
  176272. /* include the compression library's header */
  176273. #endif
  176274. /* include all user configurable info, including optional assembler routines */
  176275. /********* Start of inlined file: pngconf.h *********/
  176276. /* pngconf.h - machine configurable file for libpng
  176277. *
  176278. * libpng version 1.2.21 - October 4, 2007
  176279. * For conditions of distribution and use, see copyright notice in png.h
  176280. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  176281. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  176282. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  176283. */
  176284. /* Any machine specific code is near the front of this file, so if you
  176285. * are configuring libpng for a machine, you may want to read the section
  176286. * starting here down to where it starts to typedef png_color, png_text,
  176287. * and png_info.
  176288. */
  176289. #ifndef PNGCONF_H
  176290. #define PNGCONF_H
  176291. #define PNG_1_2_X
  176292. // These are some Juce config settings that should remove any unnecessary code bloat..
  176293. #define PNG_NO_STDIO 1
  176294. #define PNG_DEBUG 0
  176295. #define PNG_NO_WARNINGS 1
  176296. #define PNG_NO_ERROR_TEXT 1
  176297. #define PNG_NO_ERROR_NUMBERS 1
  176298. #define PNG_NO_USER_MEM 1
  176299. #define PNG_NO_READ_iCCP 1
  176300. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  176301. #define PNG_NO_READ_USER_CHUNKS 1
  176302. #define PNG_NO_READ_iTXt 1
  176303. #define PNG_NO_READ_sCAL 1
  176304. #define PNG_NO_READ_sPLT 1
  176305. #define png_error(a, b) png_err(a)
  176306. #define png_warning(a, b)
  176307. #define png_chunk_error(a, b) png_err(a)
  176308. #define png_chunk_warning(a, b)
  176309. /*
  176310. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  176311. * includes the resource compiler for Windows DLL configurations.
  176312. */
  176313. #ifdef PNG_USER_CONFIG
  176314. # ifndef PNG_USER_PRIVATEBUILD
  176315. # define PNG_USER_PRIVATEBUILD
  176316. # endif
  176317. #include "pngusr.h"
  176318. #endif
  176319. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  176320. #ifdef PNG_CONFIGURE_LIBPNG
  176321. #ifdef HAVE_CONFIG_H
  176322. #include "config.h"
  176323. #endif
  176324. #endif
  176325. /*
  176326. * Added at libpng-1.2.8
  176327. *
  176328. * If you create a private DLL you need to define in "pngusr.h" the followings:
  176329. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  176330. * the DLL was built>
  176331. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  176332. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  176333. * distinguish your DLL from those of the official release. These
  176334. * correspond to the trailing letters that come after the version
  176335. * number and must match your private DLL name>
  176336. * e.g. // private DLL "libpng13gx.dll"
  176337. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  176338. *
  176339. * The following macros are also at your disposal if you want to complete the
  176340. * DLL VERSIONINFO structure.
  176341. * - PNG_USER_VERSIONINFO_COMMENTS
  176342. * - PNG_USER_VERSIONINFO_COMPANYNAME
  176343. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  176344. */
  176345. #ifdef __STDC__
  176346. #ifdef SPECIALBUILD
  176347. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  176348. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  176349. #endif
  176350. #ifdef PRIVATEBUILD
  176351. # pragma message("PRIVATEBUILD is deprecated.\
  176352. Use PNG_USER_PRIVATEBUILD instead.")
  176353. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  176354. #endif
  176355. #endif /* __STDC__ */
  176356. #ifndef PNG_VERSION_INFO_ONLY
  176357. /* End of material added to libpng-1.2.8 */
  176358. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  176359. Restored at libpng-1.2.21 */
  176360. # define PNG_WARN_UNINITIALIZED_ROW 1
  176361. /* End of material added at libpng-1.2.19/1.2.21 */
  176362. /* This is the size of the compression buffer, and thus the size of
  176363. * an IDAT chunk. Make this whatever size you feel is best for your
  176364. * machine. One of these will be allocated per png_struct. When this
  176365. * is full, it writes the data to the disk, and does some other
  176366. * calculations. Making this an extremely small size will slow
  176367. * the library down, but you may want to experiment to determine
  176368. * where it becomes significant, if you are concerned with memory
  176369. * usage. Note that zlib allocates at least 32Kb also. For readers,
  176370. * this describes the size of the buffer available to read the data in.
  176371. * Unless this gets smaller than the size of a row (compressed),
  176372. * it should not make much difference how big this is.
  176373. */
  176374. #ifndef PNG_ZBUF_SIZE
  176375. # define PNG_ZBUF_SIZE 8192
  176376. #endif
  176377. /* Enable if you want a write-only libpng */
  176378. #ifndef PNG_NO_READ_SUPPORTED
  176379. # define PNG_READ_SUPPORTED
  176380. #endif
  176381. /* Enable if you want a read-only libpng */
  176382. #ifndef PNG_NO_WRITE_SUPPORTED
  176383. # define PNG_WRITE_SUPPORTED
  176384. #endif
  176385. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  176386. support PNGs that are embedded in MNG datastreams */
  176387. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  176388. # ifndef PNG_MNG_FEATURES_SUPPORTED
  176389. # define PNG_MNG_FEATURES_SUPPORTED
  176390. # endif
  176391. #endif
  176392. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  176393. # ifndef PNG_FLOATING_POINT_SUPPORTED
  176394. # define PNG_FLOATING_POINT_SUPPORTED
  176395. # endif
  176396. #endif
  176397. /* If you are running on a machine where you cannot allocate more
  176398. * than 64K of memory at once, uncomment this. While libpng will not
  176399. * normally need that much memory in a chunk (unless you load up a very
  176400. * large file), zlib needs to know how big of a chunk it can use, and
  176401. * libpng thus makes sure to check any memory allocation to verify it
  176402. * will fit into memory.
  176403. #define PNG_MAX_MALLOC_64K
  176404. */
  176405. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  176406. # define PNG_MAX_MALLOC_64K
  176407. #endif
  176408. /* Special munging to support doing things the 'cygwin' way:
  176409. * 'Normal' png-on-win32 defines/defaults:
  176410. * PNG_BUILD_DLL -- building dll
  176411. * PNG_USE_DLL -- building an application, linking to dll
  176412. * (no define) -- building static library, or building an
  176413. * application and linking to the static lib
  176414. * 'Cygwin' defines/defaults:
  176415. * PNG_BUILD_DLL -- (ignored) building the dll
  176416. * (no define) -- (ignored) building an application, linking to the dll
  176417. * PNG_STATIC -- (ignored) building the static lib, or building an
  176418. * application that links to the static lib.
  176419. * ALL_STATIC -- (ignored) building various static libs, or building an
  176420. * application that links to the static libs.
  176421. * Thus,
  176422. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  176423. * this bit of #ifdefs will define the 'correct' config variables based on
  176424. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  176425. * unnecessary.
  176426. *
  176427. * Also, the precedence order is:
  176428. * ALL_STATIC (since we can't #undef something outside our namespace)
  176429. * PNG_BUILD_DLL
  176430. * PNG_STATIC
  176431. * (nothing) == PNG_USE_DLL
  176432. *
  176433. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  176434. * of auto-import in binutils, we no longer need to worry about
  176435. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  176436. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  176437. * to __declspec() stuff. However, we DO need to worry about
  176438. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  176439. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  176440. */
  176441. #if defined(__CYGWIN__)
  176442. # if defined(ALL_STATIC)
  176443. # if defined(PNG_BUILD_DLL)
  176444. # undef PNG_BUILD_DLL
  176445. # endif
  176446. # if defined(PNG_USE_DLL)
  176447. # undef PNG_USE_DLL
  176448. # endif
  176449. # if defined(PNG_DLL)
  176450. # undef PNG_DLL
  176451. # endif
  176452. # if !defined(PNG_STATIC)
  176453. # define PNG_STATIC
  176454. # endif
  176455. # else
  176456. # if defined (PNG_BUILD_DLL)
  176457. # if defined(PNG_STATIC)
  176458. # undef PNG_STATIC
  176459. # endif
  176460. # if defined(PNG_USE_DLL)
  176461. # undef PNG_USE_DLL
  176462. # endif
  176463. # if !defined(PNG_DLL)
  176464. # define PNG_DLL
  176465. # endif
  176466. # else
  176467. # if defined(PNG_STATIC)
  176468. # if defined(PNG_USE_DLL)
  176469. # undef PNG_USE_DLL
  176470. # endif
  176471. # if defined(PNG_DLL)
  176472. # undef PNG_DLL
  176473. # endif
  176474. # else
  176475. # if !defined(PNG_USE_DLL)
  176476. # define PNG_USE_DLL
  176477. # endif
  176478. # if !defined(PNG_DLL)
  176479. # define PNG_DLL
  176480. # endif
  176481. # endif
  176482. # endif
  176483. # endif
  176484. #endif
  176485. /* This protects us against compilers that run on a windowing system
  176486. * and thus don't have or would rather us not use the stdio types:
  176487. * stdin, stdout, and stderr. The only one currently used is stderr
  176488. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  176489. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  176490. * will also prevent these, plus will prevent the entire set of stdio
  176491. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  176492. * unless (PNG_DEBUG > 0) has been #defined.
  176493. *
  176494. * #define PNG_NO_CONSOLE_IO
  176495. * #define PNG_NO_STDIO
  176496. */
  176497. #if defined(_WIN32_WCE)
  176498. # include <windows.h>
  176499. /* Console I/O functions are not supported on WindowsCE */
  176500. # define PNG_NO_CONSOLE_IO
  176501. # ifdef PNG_DEBUG
  176502. # undef PNG_DEBUG
  176503. # endif
  176504. #endif
  176505. #ifdef PNG_BUILD_DLL
  176506. # ifndef PNG_CONSOLE_IO_SUPPORTED
  176507. # ifndef PNG_NO_CONSOLE_IO
  176508. # define PNG_NO_CONSOLE_IO
  176509. # endif
  176510. # endif
  176511. #endif
  176512. # ifdef PNG_NO_STDIO
  176513. # ifndef PNG_NO_CONSOLE_IO
  176514. # define PNG_NO_CONSOLE_IO
  176515. # endif
  176516. # ifdef PNG_DEBUG
  176517. # if (PNG_DEBUG > 0)
  176518. # include <stdio.h>
  176519. # endif
  176520. # endif
  176521. # else
  176522. # if !defined(_WIN32_WCE)
  176523. /* "stdio.h" functions are not supported on WindowsCE */
  176524. # include <stdio.h>
  176525. # endif
  176526. # endif
  176527. /* This macro protects us against machines that don't have function
  176528. * prototypes (ie K&R style headers). If your compiler does not handle
  176529. * function prototypes, define this macro and use the included ansi2knr.
  176530. * I've always been able to use _NO_PROTO as the indicator, but you may
  176531. * need to drag the empty declaration out in front of here, or change the
  176532. * ifdef to suit your own needs.
  176533. */
  176534. #ifndef PNGARG
  176535. #ifdef OF /* zlib prototype munger */
  176536. # define PNGARG(arglist) OF(arglist)
  176537. #else
  176538. #ifdef _NO_PROTO
  176539. # define PNGARG(arglist) ()
  176540. # ifndef PNG_TYPECAST_NULL
  176541. # define PNG_TYPECAST_NULL
  176542. # endif
  176543. #else
  176544. # define PNGARG(arglist) arglist
  176545. #endif /* _NO_PROTO */
  176546. #endif /* OF */
  176547. #endif /* PNGARG */
  176548. /* Try to determine if we are compiling on a Mac. Note that testing for
  176549. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  176550. * on non-Mac platforms.
  176551. */
  176552. #ifndef MACOS
  176553. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  176554. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  176555. # define MACOS
  176556. # endif
  176557. #endif
  176558. /* enough people need this for various reasons to include it here */
  176559. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  176560. # include <sys/types.h>
  176561. #endif
  176562. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  176563. # define PNG_SETJMP_SUPPORTED
  176564. #endif
  176565. #ifdef PNG_SETJMP_SUPPORTED
  176566. /* This is an attempt to force a single setjmp behaviour on Linux. If
  176567. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  176568. */
  176569. # ifdef __linux__
  176570. # ifdef _BSD_SOURCE
  176571. # define PNG_SAVE_BSD_SOURCE
  176572. # undef _BSD_SOURCE
  176573. # endif
  176574. # ifdef _SETJMP_H
  176575. /* If you encounter a compiler error here, see the explanation
  176576. * near the end of INSTALL.
  176577. */
  176578. __png.h__ already includes setjmp.h;
  176579. __dont__ include it again.;
  176580. # endif
  176581. # endif /* __linux__ */
  176582. /* include setjmp.h for error handling */
  176583. # include <setjmp.h>
  176584. # ifdef __linux__
  176585. # ifdef PNG_SAVE_BSD_SOURCE
  176586. # define _BSD_SOURCE
  176587. # undef PNG_SAVE_BSD_SOURCE
  176588. # endif
  176589. # endif /* __linux__ */
  176590. #endif /* PNG_SETJMP_SUPPORTED */
  176591. #ifdef BSD
  176592. #if ! JUCE_MAC
  176593. # include <strings.h>
  176594. #endif
  176595. #else
  176596. # include <string.h>
  176597. #endif
  176598. /* Other defines for things like memory and the like can go here. */
  176599. #ifdef PNG_INTERNAL
  176600. #include <stdlib.h>
  176601. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  176602. * aren't usually used outside the library (as far as I know), so it is
  176603. * debatable if they should be exported at all. In the future, when it is
  176604. * possible to have run-time registry of chunk-handling functions, some of
  176605. * these will be made available again.
  176606. #define PNG_EXTERN extern
  176607. */
  176608. #define PNG_EXTERN
  176609. /* Other defines specific to compilers can go here. Try to keep
  176610. * them inside an appropriate ifdef/endif pair for portability.
  176611. */
  176612. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  176613. # if defined(MACOS)
  176614. /* We need to check that <math.h> hasn't already been included earlier
  176615. * as it seems it doesn't agree with <fp.h>, yet we should really use
  176616. * <fp.h> if possible.
  176617. */
  176618. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  176619. # include <fp.h>
  176620. # endif
  176621. # else
  176622. # include <math.h>
  176623. # endif
  176624. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  176625. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  176626. * MATH=68881
  176627. */
  176628. # include <m68881.h>
  176629. # endif
  176630. #endif
  176631. /* Codewarrior on NT has linking problems without this. */
  176632. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  176633. # define PNG_ALWAYS_EXTERN
  176634. #endif
  176635. /* This provides the non-ANSI (far) memory allocation routines. */
  176636. #if defined(__TURBOC__) && defined(__MSDOS__)
  176637. # include <mem.h>
  176638. # include <alloc.h>
  176639. #endif
  176640. /* I have no idea why is this necessary... */
  176641. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  176642. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  176643. # include <malloc.h>
  176644. #endif
  176645. /* This controls how fine the dithering gets. As this allocates
  176646. * a largish chunk of memory (32K), those who are not as concerned
  176647. * with dithering quality can decrease some or all of these.
  176648. */
  176649. #ifndef PNG_DITHER_RED_BITS
  176650. # define PNG_DITHER_RED_BITS 5
  176651. #endif
  176652. #ifndef PNG_DITHER_GREEN_BITS
  176653. # define PNG_DITHER_GREEN_BITS 5
  176654. #endif
  176655. #ifndef PNG_DITHER_BLUE_BITS
  176656. # define PNG_DITHER_BLUE_BITS 5
  176657. #endif
  176658. /* This controls how fine the gamma correction becomes when you
  176659. * are only interested in 8 bits anyway. Increasing this value
  176660. * results in more memory being used, and more pow() functions
  176661. * being called to fill in the gamma tables. Don't set this value
  176662. * less then 8, and even that may not work (I haven't tested it).
  176663. */
  176664. #ifndef PNG_MAX_GAMMA_8
  176665. # define PNG_MAX_GAMMA_8 11
  176666. #endif
  176667. /* This controls how much a difference in gamma we can tolerate before
  176668. * we actually start doing gamma conversion.
  176669. */
  176670. #ifndef PNG_GAMMA_THRESHOLD
  176671. # define PNG_GAMMA_THRESHOLD 0.05
  176672. #endif
  176673. #endif /* PNG_INTERNAL */
  176674. /* The following uses const char * instead of char * for error
  176675. * and warning message functions, so some compilers won't complain.
  176676. * If you do not want to use const, define PNG_NO_CONST here.
  176677. */
  176678. #ifndef PNG_NO_CONST
  176679. # define PNG_CONST const
  176680. #else
  176681. # define PNG_CONST
  176682. #endif
  176683. /* The following defines give you the ability to remove code from the
  176684. * library that you will not be using. I wish I could figure out how to
  176685. * automate this, but I can't do that without making it seriously hard
  176686. * on the users. So if you are not using an ability, change the #define
  176687. * to and #undef, and that part of the library will not be compiled. If
  176688. * your linker can't find a function, you may want to make sure the
  176689. * ability is defined here. Some of these depend upon some others being
  176690. * defined. I haven't figured out all the interactions here, so you may
  176691. * have to experiment awhile to get everything to compile. If you are
  176692. * creating or using a shared library, you probably shouldn't touch this,
  176693. * as it will affect the size of the structures, and this will cause bad
  176694. * things to happen if the library and/or application ever change.
  176695. */
  176696. /* Any features you will not be using can be undef'ed here */
  176697. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  176698. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  176699. * on the compile line, then pick and choose which ones to define without
  176700. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  176701. * if you only want to have a png-compliant reader/writer but don't need
  176702. * any of the extra transformations. This saves about 80 kbytes in a
  176703. * typical installation of the library. (PNG_NO_* form added in version
  176704. * 1.0.1c, for consistency)
  176705. */
  176706. /* The size of the png_text structure changed in libpng-1.0.6 when
  176707. * iTXt support was added. iTXt support was turned off by default through
  176708. * libpng-1.2.x, to support old apps that malloc the png_text structure
  176709. * instead of calling png_set_text() and letting libpng malloc it. It
  176710. * was turned on by default in libpng-1.3.0.
  176711. */
  176712. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176713. # ifndef PNG_NO_iTXt_SUPPORTED
  176714. # define PNG_NO_iTXt_SUPPORTED
  176715. # endif
  176716. # ifndef PNG_NO_READ_iTXt
  176717. # define PNG_NO_READ_iTXt
  176718. # endif
  176719. # ifndef PNG_NO_WRITE_iTXt
  176720. # define PNG_NO_WRITE_iTXt
  176721. # endif
  176722. #endif
  176723. #if !defined(PNG_NO_iTXt_SUPPORTED)
  176724. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  176725. # define PNG_READ_iTXt
  176726. # endif
  176727. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  176728. # define PNG_WRITE_iTXt
  176729. # endif
  176730. #endif
  176731. /* The following support, added after version 1.0.0, can be turned off here en
  176732. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  176733. * with old applications that require the length of png_struct and png_info
  176734. * to remain unchanged.
  176735. */
  176736. #ifdef PNG_LEGACY_SUPPORTED
  176737. # define PNG_NO_FREE_ME
  176738. # define PNG_NO_READ_UNKNOWN_CHUNKS
  176739. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  176740. # define PNG_NO_READ_USER_CHUNKS
  176741. # define PNG_NO_READ_iCCP
  176742. # define PNG_NO_WRITE_iCCP
  176743. # define PNG_NO_READ_iTXt
  176744. # define PNG_NO_WRITE_iTXt
  176745. # define PNG_NO_READ_sCAL
  176746. # define PNG_NO_WRITE_sCAL
  176747. # define PNG_NO_READ_sPLT
  176748. # define PNG_NO_WRITE_sPLT
  176749. # define PNG_NO_INFO_IMAGE
  176750. # define PNG_NO_READ_RGB_TO_GRAY
  176751. # define PNG_NO_READ_USER_TRANSFORM
  176752. # define PNG_NO_WRITE_USER_TRANSFORM
  176753. # define PNG_NO_USER_MEM
  176754. # define PNG_NO_READ_EMPTY_PLTE
  176755. # define PNG_NO_MNG_FEATURES
  176756. # define PNG_NO_FIXED_POINT_SUPPORTED
  176757. #endif
  176758. /* Ignore attempt to turn off both floating and fixed point support */
  176759. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  176760. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  176761. # define PNG_FIXED_POINT_SUPPORTED
  176762. #endif
  176763. #ifndef PNG_NO_FREE_ME
  176764. # define PNG_FREE_ME_SUPPORTED
  176765. #endif
  176766. #if defined(PNG_READ_SUPPORTED)
  176767. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  176768. !defined(PNG_NO_READ_TRANSFORMS)
  176769. # define PNG_READ_TRANSFORMS_SUPPORTED
  176770. #endif
  176771. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  176772. # ifndef PNG_NO_READ_EXPAND
  176773. # define PNG_READ_EXPAND_SUPPORTED
  176774. # endif
  176775. # ifndef PNG_NO_READ_SHIFT
  176776. # define PNG_READ_SHIFT_SUPPORTED
  176777. # endif
  176778. # ifndef PNG_NO_READ_PACK
  176779. # define PNG_READ_PACK_SUPPORTED
  176780. # endif
  176781. # ifndef PNG_NO_READ_BGR
  176782. # define PNG_READ_BGR_SUPPORTED
  176783. # endif
  176784. # ifndef PNG_NO_READ_SWAP
  176785. # define PNG_READ_SWAP_SUPPORTED
  176786. # endif
  176787. # ifndef PNG_NO_READ_PACKSWAP
  176788. # define PNG_READ_PACKSWAP_SUPPORTED
  176789. # endif
  176790. # ifndef PNG_NO_READ_INVERT
  176791. # define PNG_READ_INVERT_SUPPORTED
  176792. # endif
  176793. # ifndef PNG_NO_READ_DITHER
  176794. # define PNG_READ_DITHER_SUPPORTED
  176795. # endif
  176796. # ifndef PNG_NO_READ_BACKGROUND
  176797. # define PNG_READ_BACKGROUND_SUPPORTED
  176798. # endif
  176799. # ifndef PNG_NO_READ_16_TO_8
  176800. # define PNG_READ_16_TO_8_SUPPORTED
  176801. # endif
  176802. # ifndef PNG_NO_READ_FILLER
  176803. # define PNG_READ_FILLER_SUPPORTED
  176804. # endif
  176805. # ifndef PNG_NO_READ_GAMMA
  176806. # define PNG_READ_GAMMA_SUPPORTED
  176807. # endif
  176808. # ifndef PNG_NO_READ_GRAY_TO_RGB
  176809. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  176810. # endif
  176811. # ifndef PNG_NO_READ_SWAP_ALPHA
  176812. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  176813. # endif
  176814. # ifndef PNG_NO_READ_INVERT_ALPHA
  176815. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  176816. # endif
  176817. # ifndef PNG_NO_READ_STRIP_ALPHA
  176818. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  176819. # endif
  176820. # ifndef PNG_NO_READ_USER_TRANSFORM
  176821. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  176822. # endif
  176823. # ifndef PNG_NO_READ_RGB_TO_GRAY
  176824. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  176825. # endif
  176826. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  176827. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  176828. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  176829. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  176830. #endif /* about interlacing capability! You'll */
  176831. /* still have interlacing unless you change the following line: */
  176832. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  176833. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  176834. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  176835. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  176836. # endif
  176837. #endif
  176838. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176839. /* Deprecated, will be removed from version 2.0.0.
  176840. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  176841. #ifndef PNG_NO_READ_EMPTY_PLTE
  176842. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  176843. #endif
  176844. #endif
  176845. #endif /* PNG_READ_SUPPORTED */
  176846. #if defined(PNG_WRITE_SUPPORTED)
  176847. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  176848. !defined(PNG_NO_WRITE_TRANSFORMS)
  176849. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  176850. #endif
  176851. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  176852. # ifndef PNG_NO_WRITE_SHIFT
  176853. # define PNG_WRITE_SHIFT_SUPPORTED
  176854. # endif
  176855. # ifndef PNG_NO_WRITE_PACK
  176856. # define PNG_WRITE_PACK_SUPPORTED
  176857. # endif
  176858. # ifndef PNG_NO_WRITE_BGR
  176859. # define PNG_WRITE_BGR_SUPPORTED
  176860. # endif
  176861. # ifndef PNG_NO_WRITE_SWAP
  176862. # define PNG_WRITE_SWAP_SUPPORTED
  176863. # endif
  176864. # ifndef PNG_NO_WRITE_PACKSWAP
  176865. # define PNG_WRITE_PACKSWAP_SUPPORTED
  176866. # endif
  176867. # ifndef PNG_NO_WRITE_INVERT
  176868. # define PNG_WRITE_INVERT_SUPPORTED
  176869. # endif
  176870. # ifndef PNG_NO_WRITE_FILLER
  176871. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  176872. # endif
  176873. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  176874. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  176875. # endif
  176876. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  176877. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  176878. # endif
  176879. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  176880. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  176881. # endif
  176882. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  176883. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  176884. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176885. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  176886. encoders, but can cause trouble
  176887. if left undefined */
  176888. #endif
  176889. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  176890. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  176891. defined(PNG_FLOATING_POINT_SUPPORTED)
  176892. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  176893. #endif
  176894. #ifndef PNG_NO_WRITE_FLUSH
  176895. # define PNG_WRITE_FLUSH_SUPPORTED
  176896. #endif
  176897. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176898. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  176899. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  176900. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  176901. #endif
  176902. #endif
  176903. #endif /* PNG_WRITE_SUPPORTED */
  176904. #ifndef PNG_1_0_X
  176905. # ifndef PNG_NO_ERROR_NUMBERS
  176906. # define PNG_ERROR_NUMBERS_SUPPORTED
  176907. # endif
  176908. #endif /* PNG_1_0_X */
  176909. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176910. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176911. # ifndef PNG_NO_USER_TRANSFORM_PTR
  176912. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  176913. # endif
  176914. #endif
  176915. #ifndef PNG_NO_STDIO
  176916. # define PNG_TIME_RFC1123_SUPPORTED
  176917. #endif
  176918. /* This adds extra functions in pngget.c for accessing data from the
  176919. * info pointer (added in version 0.99)
  176920. * png_get_image_width()
  176921. * png_get_image_height()
  176922. * png_get_bit_depth()
  176923. * png_get_color_type()
  176924. * png_get_compression_type()
  176925. * png_get_filter_type()
  176926. * png_get_interlace_type()
  176927. * png_get_pixel_aspect_ratio()
  176928. * png_get_pixels_per_meter()
  176929. * png_get_x_offset_pixels()
  176930. * png_get_y_offset_pixels()
  176931. * png_get_x_offset_microns()
  176932. * png_get_y_offset_microns()
  176933. */
  176934. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  176935. # define PNG_EASY_ACCESS_SUPPORTED
  176936. #endif
  176937. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  176938. * and removed from version 1.2.20. The following will be removed
  176939. * from libpng-1.4.0
  176940. */
  176941. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  176942. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  176943. # define PNG_OPTIMIZED_CODE_SUPPORTED
  176944. # endif
  176945. #endif
  176946. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  176947. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  176948. # define PNG_ASSEMBLER_CODE_SUPPORTED
  176949. # endif
  176950. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  176951. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  176952. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176953. # define PNG_NO_MMX_CODE
  176954. # endif
  176955. # endif
  176956. # if defined(__APPLE__)
  176957. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176958. # define PNG_NO_MMX_CODE
  176959. # endif
  176960. # endif
  176961. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  176962. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176963. # define PNG_NO_MMX_CODE
  176964. # endif
  176965. # endif
  176966. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176967. # define PNG_MMX_CODE_SUPPORTED
  176968. # endif
  176969. #endif
  176970. /* end of obsolete code to be removed from libpng-1.4.0 */
  176971. #if !defined(PNG_1_0_X)
  176972. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  176973. # define PNG_USER_MEM_SUPPORTED
  176974. #endif
  176975. #endif /* PNG_1_0_X */
  176976. /* Added at libpng-1.2.6 */
  176977. #if !defined(PNG_1_0_X)
  176978. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  176979. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  176980. # define PNG_SET_USER_LIMITS_SUPPORTED
  176981. #endif
  176982. #endif
  176983. #endif /* PNG_1_0_X */
  176984. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  176985. * how large, set these limits to 0x7fffffffL
  176986. */
  176987. #ifndef PNG_USER_WIDTH_MAX
  176988. # define PNG_USER_WIDTH_MAX 1000000L
  176989. #endif
  176990. #ifndef PNG_USER_HEIGHT_MAX
  176991. # define PNG_USER_HEIGHT_MAX 1000000L
  176992. #endif
  176993. /* These are currently experimental features, define them if you want */
  176994. /* very little testing */
  176995. /*
  176996. #ifdef PNG_READ_SUPPORTED
  176997. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176998. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176999. # endif
  177000. #endif
  177001. */
  177002. /* This is only for PowerPC big-endian and 680x0 systems */
  177003. /* some testing */
  177004. /*
  177005. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  177006. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  177007. #endif
  177008. */
  177009. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  177010. /*
  177011. #define PNG_NO_POINTER_INDEXING
  177012. */
  177013. /* These functions are turned off by default, as they will be phased out. */
  177014. /*
  177015. #define PNG_USELESS_TESTS_SUPPORTED
  177016. #define PNG_CORRECT_PALETTE_SUPPORTED
  177017. */
  177018. /* Any chunks you are not interested in, you can undef here. The
  177019. * ones that allocate memory may be expecially important (hIST,
  177020. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  177021. * a bit smaller.
  177022. */
  177023. #if defined(PNG_READ_SUPPORTED) && \
  177024. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177025. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  177026. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177027. #endif
  177028. #if defined(PNG_WRITE_SUPPORTED) && \
  177029. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177030. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  177031. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177032. #endif
  177033. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177034. #ifdef PNG_NO_READ_TEXT
  177035. # define PNG_NO_READ_iTXt
  177036. # define PNG_NO_READ_tEXt
  177037. # define PNG_NO_READ_zTXt
  177038. #endif
  177039. #ifndef PNG_NO_READ_bKGD
  177040. # define PNG_READ_bKGD_SUPPORTED
  177041. # define PNG_bKGD_SUPPORTED
  177042. #endif
  177043. #ifndef PNG_NO_READ_cHRM
  177044. # define PNG_READ_cHRM_SUPPORTED
  177045. # define PNG_cHRM_SUPPORTED
  177046. #endif
  177047. #ifndef PNG_NO_READ_gAMA
  177048. # define PNG_READ_gAMA_SUPPORTED
  177049. # define PNG_gAMA_SUPPORTED
  177050. #endif
  177051. #ifndef PNG_NO_READ_hIST
  177052. # define PNG_READ_hIST_SUPPORTED
  177053. # define PNG_hIST_SUPPORTED
  177054. #endif
  177055. #ifndef PNG_NO_READ_iCCP
  177056. # define PNG_READ_iCCP_SUPPORTED
  177057. # define PNG_iCCP_SUPPORTED
  177058. #endif
  177059. #ifndef PNG_NO_READ_iTXt
  177060. # ifndef PNG_READ_iTXt_SUPPORTED
  177061. # define PNG_READ_iTXt_SUPPORTED
  177062. # endif
  177063. # ifndef PNG_iTXt_SUPPORTED
  177064. # define PNG_iTXt_SUPPORTED
  177065. # endif
  177066. #endif
  177067. #ifndef PNG_NO_READ_oFFs
  177068. # define PNG_READ_oFFs_SUPPORTED
  177069. # define PNG_oFFs_SUPPORTED
  177070. #endif
  177071. #ifndef PNG_NO_READ_pCAL
  177072. # define PNG_READ_pCAL_SUPPORTED
  177073. # define PNG_pCAL_SUPPORTED
  177074. #endif
  177075. #ifndef PNG_NO_READ_sCAL
  177076. # define PNG_READ_sCAL_SUPPORTED
  177077. # define PNG_sCAL_SUPPORTED
  177078. #endif
  177079. #ifndef PNG_NO_READ_pHYs
  177080. # define PNG_READ_pHYs_SUPPORTED
  177081. # define PNG_pHYs_SUPPORTED
  177082. #endif
  177083. #ifndef PNG_NO_READ_sBIT
  177084. # define PNG_READ_sBIT_SUPPORTED
  177085. # define PNG_sBIT_SUPPORTED
  177086. #endif
  177087. #ifndef PNG_NO_READ_sPLT
  177088. # define PNG_READ_sPLT_SUPPORTED
  177089. # define PNG_sPLT_SUPPORTED
  177090. #endif
  177091. #ifndef PNG_NO_READ_sRGB
  177092. # define PNG_READ_sRGB_SUPPORTED
  177093. # define PNG_sRGB_SUPPORTED
  177094. #endif
  177095. #ifndef PNG_NO_READ_tEXt
  177096. # define PNG_READ_tEXt_SUPPORTED
  177097. # define PNG_tEXt_SUPPORTED
  177098. #endif
  177099. #ifndef PNG_NO_READ_tIME
  177100. # define PNG_READ_tIME_SUPPORTED
  177101. # define PNG_tIME_SUPPORTED
  177102. #endif
  177103. #ifndef PNG_NO_READ_tRNS
  177104. # define PNG_READ_tRNS_SUPPORTED
  177105. # define PNG_tRNS_SUPPORTED
  177106. #endif
  177107. #ifndef PNG_NO_READ_zTXt
  177108. # define PNG_READ_zTXt_SUPPORTED
  177109. # define PNG_zTXt_SUPPORTED
  177110. #endif
  177111. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  177112. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  177113. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177114. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177115. # endif
  177116. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177117. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177118. # endif
  177119. #endif
  177120. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  177121. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  177122. # define PNG_READ_USER_CHUNKS_SUPPORTED
  177123. # define PNG_USER_CHUNKS_SUPPORTED
  177124. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  177125. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  177126. # endif
  177127. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  177128. # undef PNG_NO_HANDLE_AS_UNKNOWN
  177129. # endif
  177130. #endif
  177131. #ifndef PNG_NO_READ_OPT_PLTE
  177132. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  177133. #endif /* optional PLTE chunk in RGB and RGBA images */
  177134. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  177135. defined(PNG_READ_zTXt_SUPPORTED)
  177136. # define PNG_READ_TEXT_SUPPORTED
  177137. # define PNG_TEXT_SUPPORTED
  177138. #endif
  177139. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  177140. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177141. #ifdef PNG_NO_WRITE_TEXT
  177142. # define PNG_NO_WRITE_iTXt
  177143. # define PNG_NO_WRITE_tEXt
  177144. # define PNG_NO_WRITE_zTXt
  177145. #endif
  177146. #ifndef PNG_NO_WRITE_bKGD
  177147. # define PNG_WRITE_bKGD_SUPPORTED
  177148. # ifndef PNG_bKGD_SUPPORTED
  177149. # define PNG_bKGD_SUPPORTED
  177150. # endif
  177151. #endif
  177152. #ifndef PNG_NO_WRITE_cHRM
  177153. # define PNG_WRITE_cHRM_SUPPORTED
  177154. # ifndef PNG_cHRM_SUPPORTED
  177155. # define PNG_cHRM_SUPPORTED
  177156. # endif
  177157. #endif
  177158. #ifndef PNG_NO_WRITE_gAMA
  177159. # define PNG_WRITE_gAMA_SUPPORTED
  177160. # ifndef PNG_gAMA_SUPPORTED
  177161. # define PNG_gAMA_SUPPORTED
  177162. # endif
  177163. #endif
  177164. #ifndef PNG_NO_WRITE_hIST
  177165. # define PNG_WRITE_hIST_SUPPORTED
  177166. # ifndef PNG_hIST_SUPPORTED
  177167. # define PNG_hIST_SUPPORTED
  177168. # endif
  177169. #endif
  177170. #ifndef PNG_NO_WRITE_iCCP
  177171. # define PNG_WRITE_iCCP_SUPPORTED
  177172. # ifndef PNG_iCCP_SUPPORTED
  177173. # define PNG_iCCP_SUPPORTED
  177174. # endif
  177175. #endif
  177176. #ifndef PNG_NO_WRITE_iTXt
  177177. # ifndef PNG_WRITE_iTXt_SUPPORTED
  177178. # define PNG_WRITE_iTXt_SUPPORTED
  177179. # endif
  177180. # ifndef PNG_iTXt_SUPPORTED
  177181. # define PNG_iTXt_SUPPORTED
  177182. # endif
  177183. #endif
  177184. #ifndef PNG_NO_WRITE_oFFs
  177185. # define PNG_WRITE_oFFs_SUPPORTED
  177186. # ifndef PNG_oFFs_SUPPORTED
  177187. # define PNG_oFFs_SUPPORTED
  177188. # endif
  177189. #endif
  177190. #ifndef PNG_NO_WRITE_pCAL
  177191. # define PNG_WRITE_pCAL_SUPPORTED
  177192. # ifndef PNG_pCAL_SUPPORTED
  177193. # define PNG_pCAL_SUPPORTED
  177194. # endif
  177195. #endif
  177196. #ifndef PNG_NO_WRITE_sCAL
  177197. # define PNG_WRITE_sCAL_SUPPORTED
  177198. # ifndef PNG_sCAL_SUPPORTED
  177199. # define PNG_sCAL_SUPPORTED
  177200. # endif
  177201. #endif
  177202. #ifndef PNG_NO_WRITE_pHYs
  177203. # define PNG_WRITE_pHYs_SUPPORTED
  177204. # ifndef PNG_pHYs_SUPPORTED
  177205. # define PNG_pHYs_SUPPORTED
  177206. # endif
  177207. #endif
  177208. #ifndef PNG_NO_WRITE_sBIT
  177209. # define PNG_WRITE_sBIT_SUPPORTED
  177210. # ifndef PNG_sBIT_SUPPORTED
  177211. # define PNG_sBIT_SUPPORTED
  177212. # endif
  177213. #endif
  177214. #ifndef PNG_NO_WRITE_sPLT
  177215. # define PNG_WRITE_sPLT_SUPPORTED
  177216. # ifndef PNG_sPLT_SUPPORTED
  177217. # define PNG_sPLT_SUPPORTED
  177218. # endif
  177219. #endif
  177220. #ifndef PNG_NO_WRITE_sRGB
  177221. # define PNG_WRITE_sRGB_SUPPORTED
  177222. # ifndef PNG_sRGB_SUPPORTED
  177223. # define PNG_sRGB_SUPPORTED
  177224. # endif
  177225. #endif
  177226. #ifndef PNG_NO_WRITE_tEXt
  177227. # define PNG_WRITE_tEXt_SUPPORTED
  177228. # ifndef PNG_tEXt_SUPPORTED
  177229. # define PNG_tEXt_SUPPORTED
  177230. # endif
  177231. #endif
  177232. #ifndef PNG_NO_WRITE_tIME
  177233. # define PNG_WRITE_tIME_SUPPORTED
  177234. # ifndef PNG_tIME_SUPPORTED
  177235. # define PNG_tIME_SUPPORTED
  177236. # endif
  177237. #endif
  177238. #ifndef PNG_NO_WRITE_tRNS
  177239. # define PNG_WRITE_tRNS_SUPPORTED
  177240. # ifndef PNG_tRNS_SUPPORTED
  177241. # define PNG_tRNS_SUPPORTED
  177242. # endif
  177243. #endif
  177244. #ifndef PNG_NO_WRITE_zTXt
  177245. # define PNG_WRITE_zTXt_SUPPORTED
  177246. # ifndef PNG_zTXt_SUPPORTED
  177247. # define PNG_zTXt_SUPPORTED
  177248. # endif
  177249. #endif
  177250. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  177251. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  177252. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177253. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177254. # endif
  177255. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177256. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177257. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177258. # endif
  177259. # endif
  177260. #endif
  177261. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  177262. defined(PNG_WRITE_zTXt_SUPPORTED)
  177263. # define PNG_WRITE_TEXT_SUPPORTED
  177264. # ifndef PNG_TEXT_SUPPORTED
  177265. # define PNG_TEXT_SUPPORTED
  177266. # endif
  177267. #endif
  177268. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  177269. /* Turn this off to disable png_read_png() and
  177270. * png_write_png() and leave the row_pointers member
  177271. * out of the info structure.
  177272. */
  177273. #ifndef PNG_NO_INFO_IMAGE
  177274. # define PNG_INFO_IMAGE_SUPPORTED
  177275. #endif
  177276. /* need the time information for reading tIME chunks */
  177277. #if defined(PNG_tIME_SUPPORTED)
  177278. # if !defined(_WIN32_WCE)
  177279. /* "time.h" functions are not supported on WindowsCE */
  177280. # include <time.h>
  177281. # endif
  177282. #endif
  177283. /* Some typedefs to get us started. These should be safe on most of the
  177284. * common platforms. The typedefs should be at least as large as the
  177285. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  177286. * don't have to be exactly that size. Some compilers dislike passing
  177287. * unsigned shorts as function parameters, so you may be better off using
  177288. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  177289. * want to have unsigned int for png_uint_32 instead of unsigned long.
  177290. */
  177291. typedef unsigned long png_uint_32;
  177292. typedef long png_int_32;
  177293. typedef unsigned short png_uint_16;
  177294. typedef short png_int_16;
  177295. typedef unsigned char png_byte;
  177296. /* This is usually size_t. It is typedef'ed just in case you need it to
  177297. change (I'm not sure if you will or not, so I thought I'd be safe) */
  177298. #ifdef PNG_SIZE_T
  177299. typedef PNG_SIZE_T png_size_t;
  177300. # define png_sizeof(x) png_convert_size(sizeof (x))
  177301. #else
  177302. typedef size_t png_size_t;
  177303. # define png_sizeof(x) sizeof (x)
  177304. #endif
  177305. /* The following is needed for medium model support. It cannot be in the
  177306. * PNG_INTERNAL section. Needs modification for other compilers besides
  177307. * MSC. Model independent support declares all arrays and pointers to be
  177308. * large using the far keyword. The zlib version used must also support
  177309. * model independent data. As of version zlib 1.0.4, the necessary changes
  177310. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  177311. * changes that are needed. (Tim Wegner)
  177312. */
  177313. /* Separate compiler dependencies (problem here is that zlib.h always
  177314. defines FAR. (SJT) */
  177315. #ifdef __BORLANDC__
  177316. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  177317. # define LDATA 1
  177318. # else
  177319. # define LDATA 0
  177320. # endif
  177321. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  177322. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  177323. # define PNG_MAX_MALLOC_64K
  177324. # if (LDATA != 1)
  177325. # ifndef FAR
  177326. # define FAR __far
  177327. # endif
  177328. # define USE_FAR_KEYWORD
  177329. # endif /* LDATA != 1 */
  177330. /* Possibly useful for moving data out of default segment.
  177331. * Uncomment it if you want. Could also define FARDATA as
  177332. * const if your compiler supports it. (SJT)
  177333. # define FARDATA FAR
  177334. */
  177335. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  177336. #endif /* __BORLANDC__ */
  177337. /* Suggest testing for specific compiler first before testing for
  177338. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  177339. * making reliance oncertain keywords suspect. (SJT)
  177340. */
  177341. /* MSC Medium model */
  177342. #if defined(FAR)
  177343. # if defined(M_I86MM)
  177344. # define USE_FAR_KEYWORD
  177345. # define FARDATA FAR
  177346. # include <dos.h>
  177347. # endif
  177348. #endif
  177349. /* SJT: default case */
  177350. #ifndef FAR
  177351. # define FAR
  177352. #endif
  177353. /* At this point FAR is always defined */
  177354. #ifndef FARDATA
  177355. # define FARDATA
  177356. #endif
  177357. /* Typedef for floating-point numbers that are converted
  177358. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  177359. typedef png_int_32 png_fixed_point;
  177360. /* Add typedefs for pointers */
  177361. typedef void FAR * png_voidp;
  177362. typedef png_byte FAR * png_bytep;
  177363. typedef png_uint_32 FAR * png_uint_32p;
  177364. typedef png_int_32 FAR * png_int_32p;
  177365. typedef png_uint_16 FAR * png_uint_16p;
  177366. typedef png_int_16 FAR * png_int_16p;
  177367. typedef PNG_CONST char FAR * png_const_charp;
  177368. typedef char FAR * png_charp;
  177369. typedef png_fixed_point FAR * png_fixed_point_p;
  177370. #ifndef PNG_NO_STDIO
  177371. #if defined(_WIN32_WCE)
  177372. typedef HANDLE png_FILE_p;
  177373. #else
  177374. typedef FILE * png_FILE_p;
  177375. #endif
  177376. #endif
  177377. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177378. typedef double FAR * png_doublep;
  177379. #endif
  177380. /* Pointers to pointers; i.e. arrays */
  177381. typedef png_byte FAR * FAR * png_bytepp;
  177382. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  177383. typedef png_int_32 FAR * FAR * png_int_32pp;
  177384. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  177385. typedef png_int_16 FAR * FAR * png_int_16pp;
  177386. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  177387. typedef char FAR * FAR * png_charpp;
  177388. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  177389. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177390. typedef double FAR * FAR * png_doublepp;
  177391. #endif
  177392. /* Pointers to pointers to pointers; i.e., pointer to array */
  177393. typedef char FAR * FAR * FAR * png_charppp;
  177394. #if 0
  177395. /* SPC - Is this stuff deprecated? */
  177396. /* It'll be removed as of libpng-1.3.0 - GR-P */
  177397. /* libpng typedefs for types in zlib. If zlib changes
  177398. * or another compression library is used, then change these.
  177399. * Eliminates need to change all the source files.
  177400. */
  177401. typedef charf * png_zcharp;
  177402. typedef charf * FAR * png_zcharpp;
  177403. typedef z_stream FAR * png_zstreamp;
  177404. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  177405. /*
  177406. * Define PNG_BUILD_DLL if the module being built is a Windows
  177407. * LIBPNG DLL.
  177408. *
  177409. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  177410. * It is equivalent to Microsoft predefined macro _DLL that is
  177411. * automatically defined when you compile using the share
  177412. * version of the CRT (C Run-Time library)
  177413. *
  177414. * The cygwin mods make this behavior a little different:
  177415. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  177416. * Define PNG_STATIC if you are building a static library for use with cygwin,
  177417. * -or- if you are building an application that you want to link to the
  177418. * static library.
  177419. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  177420. * the other flags is defined.
  177421. */
  177422. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  177423. # define PNG_DLL
  177424. #endif
  177425. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  177426. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  177427. * command-line override
  177428. */
  177429. #if defined(__CYGWIN__)
  177430. # if !defined(PNG_STATIC)
  177431. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177432. # undef PNG_USE_GLOBAL_ARRAYS
  177433. # endif
  177434. # if !defined(PNG_USE_LOCAL_ARRAYS)
  177435. # define PNG_USE_LOCAL_ARRAYS
  177436. # endif
  177437. # else
  177438. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  177439. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177440. # undef PNG_USE_GLOBAL_ARRAYS
  177441. # endif
  177442. # endif
  177443. # endif
  177444. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177445. # define PNG_USE_LOCAL_ARRAYS
  177446. # endif
  177447. #endif
  177448. /* Do not use global arrays (helps with building DLL's)
  177449. * They are no longer used in libpng itself, since version 1.0.5c,
  177450. * but might be required for some pre-1.0.5c applications.
  177451. */
  177452. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177453. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  177454. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  177455. # define PNG_USE_LOCAL_ARRAYS
  177456. # else
  177457. # define PNG_USE_GLOBAL_ARRAYS
  177458. # endif
  177459. #endif
  177460. #if defined(__CYGWIN__)
  177461. # undef PNGAPI
  177462. # define PNGAPI __cdecl
  177463. # undef PNG_IMPEXP
  177464. # define PNG_IMPEXP
  177465. #endif
  177466. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  177467. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  177468. * Don't ignore those warnings; you must also reset the default calling
  177469. * convention in your compiler to match your PNGAPI, and you must build
  177470. * zlib and your applications the same way you build libpng.
  177471. */
  177472. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  177473. # ifndef PNG_NO_MODULEDEF
  177474. # define PNG_NO_MODULEDEF
  177475. # endif
  177476. #endif
  177477. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  177478. # define PNG_IMPEXP
  177479. #endif
  177480. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  177481. (( defined(_Windows) || defined(_WINDOWS) || \
  177482. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  177483. # ifndef PNGAPI
  177484. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  177485. # define PNGAPI __cdecl
  177486. # else
  177487. # define PNGAPI _cdecl
  177488. # endif
  177489. # endif
  177490. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  177491. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  177492. # define PNG_IMPEXP
  177493. # endif
  177494. # if !defined(PNG_IMPEXP)
  177495. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177496. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  177497. /* Borland/Microsoft */
  177498. # if defined(_MSC_VER) || defined(__BORLANDC__)
  177499. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  177500. # define PNG_EXPORT PNG_EXPORT_TYPE1
  177501. # else
  177502. # define PNG_EXPORT PNG_EXPORT_TYPE2
  177503. # if defined(PNG_BUILD_DLL)
  177504. # define PNG_IMPEXP __export
  177505. # else
  177506. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  177507. VC++ */
  177508. # endif /* Exists in Borland C++ for
  177509. C++ classes (== huge) */
  177510. # endif
  177511. # endif
  177512. # if !defined(PNG_IMPEXP)
  177513. # if defined(PNG_BUILD_DLL)
  177514. # define PNG_IMPEXP __declspec(dllexport)
  177515. # else
  177516. # define PNG_IMPEXP __declspec(dllimport)
  177517. # endif
  177518. # endif
  177519. # endif /* PNG_IMPEXP */
  177520. #else /* !(DLL || non-cygwin WINDOWS) */
  177521. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  177522. # ifndef PNGAPI
  177523. # define PNGAPI _System
  177524. # endif
  177525. # else
  177526. # if 0 /* ... other platforms, with other meanings */
  177527. # endif
  177528. # endif
  177529. #endif
  177530. #ifndef PNGAPI
  177531. # define PNGAPI
  177532. #endif
  177533. #ifndef PNG_IMPEXP
  177534. # define PNG_IMPEXP
  177535. #endif
  177536. #ifdef PNG_BUILDSYMS
  177537. # ifndef PNG_EXPORT
  177538. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  177539. # endif
  177540. # ifdef PNG_USE_GLOBAL_ARRAYS
  177541. # ifndef PNG_EXPORT_VAR
  177542. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  177543. # endif
  177544. # endif
  177545. #endif
  177546. #ifndef PNG_EXPORT
  177547. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177548. #endif
  177549. #ifdef PNG_USE_GLOBAL_ARRAYS
  177550. # ifndef PNG_EXPORT_VAR
  177551. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  177552. # endif
  177553. #endif
  177554. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  177555. * functions that are passed far data must be model independent.
  177556. */
  177557. #ifndef PNG_ABORT
  177558. # define PNG_ABORT() abort()
  177559. #endif
  177560. #ifdef PNG_SETJMP_SUPPORTED
  177561. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  177562. #else
  177563. # define png_jmpbuf(png_ptr) \
  177564. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  177565. #endif
  177566. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  177567. /* use this to make far-to-near assignments */
  177568. # define CHECK 1
  177569. # define NOCHECK 0
  177570. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  177571. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  177572. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  177573. # define png_strcpy _fstrcpy
  177574. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  177575. # define png_strlen _fstrlen
  177576. # define png_memcmp _fmemcmp /* SJT: added */
  177577. # define png_memcpy _fmemcpy
  177578. # define png_memset _fmemset
  177579. #else /* use the usual functions */
  177580. # define CVT_PTR(ptr) (ptr)
  177581. # define CVT_PTR_NOCHECK(ptr) (ptr)
  177582. # ifndef PNG_NO_SNPRINTF
  177583. # ifdef _MSC_VER
  177584. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  177585. # define png_snprintf2 _snprintf
  177586. # define png_snprintf6 _snprintf
  177587. # else
  177588. # define png_snprintf snprintf /* Added to v 1.2.19 */
  177589. # define png_snprintf2 snprintf
  177590. # define png_snprintf6 snprintf
  177591. # endif
  177592. # else
  177593. /* You don't have or don't want to use snprintf(). Caution: Using
  177594. * sprintf instead of snprintf exposes your application to accidental
  177595. * or malevolent buffer overflows. If you don't have snprintf()
  177596. * as a general rule you should provide one (you can get one from
  177597. * Portable OpenSSH). */
  177598. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  177599. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  177600. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  177601. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  177602. # endif
  177603. # define png_strcpy strcpy
  177604. # define png_strncpy strncpy /* Added to v 1.2.6 */
  177605. # define png_strlen strlen
  177606. # define png_memcmp memcmp /* SJT: added */
  177607. # define png_memcpy memcpy
  177608. # define png_memset memset
  177609. #endif
  177610. /* End of memory model independent support */
  177611. /* Just a little check that someone hasn't tried to define something
  177612. * contradictory.
  177613. */
  177614. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  177615. # undef PNG_ZBUF_SIZE
  177616. # define PNG_ZBUF_SIZE 65536L
  177617. #endif
  177618. /* Added at libpng-1.2.8 */
  177619. #endif /* PNG_VERSION_INFO_ONLY */
  177620. #endif /* PNGCONF_H */
  177621. /********* End of inlined file: pngconf.h *********/
  177622. #ifdef _MSC_VER
  177623. #pragma warning (disable: 4996 4100)
  177624. #endif
  177625. /*
  177626. * Added at libpng-1.2.8 */
  177627. /* Ref MSDN: Private as priority over Special
  177628. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  177629. * procedures. If this value is given, the StringFileInfo block must
  177630. * contain a PrivateBuild string.
  177631. *
  177632. * VS_FF_SPECIALBUILD File *was* built by the original company using
  177633. * standard release procedures but is a variation of the standard
  177634. * file of the same version number. If this value is given, the
  177635. * StringFileInfo block must contain a SpecialBuild string.
  177636. */
  177637. #if defined(PNG_USER_PRIVATEBUILD)
  177638. # define PNG_LIBPNG_BUILD_TYPE \
  177639. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  177640. #else
  177641. # if defined(PNG_LIBPNG_SPECIALBUILD)
  177642. # define PNG_LIBPNG_BUILD_TYPE \
  177643. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  177644. # else
  177645. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  177646. # endif
  177647. #endif
  177648. #ifndef PNG_VERSION_INFO_ONLY
  177649. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  177650. #ifdef __cplusplus
  177651. extern "C" {
  177652. #endif /* __cplusplus */
  177653. /* This file is arranged in several sections. The first section contains
  177654. * structure and type definitions. The second section contains the external
  177655. * library functions, while the third has the internal library functions,
  177656. * which applications aren't expected to use directly.
  177657. */
  177658. #ifndef PNG_NO_TYPECAST_NULL
  177659. #define int_p_NULL (int *)NULL
  177660. #define png_bytep_NULL (png_bytep)NULL
  177661. #define png_bytepp_NULL (png_bytepp)NULL
  177662. #define png_doublep_NULL (png_doublep)NULL
  177663. #define png_error_ptr_NULL (png_error_ptr)NULL
  177664. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  177665. #define png_free_ptr_NULL (png_free_ptr)NULL
  177666. #define png_infopp_NULL (png_infopp)NULL
  177667. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  177668. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  177669. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  177670. #define png_structp_NULL (png_structp)NULL
  177671. #define png_uint_16p_NULL (png_uint_16p)NULL
  177672. #define png_voidp_NULL (png_voidp)NULL
  177673. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  177674. #else
  177675. #define int_p_NULL NULL
  177676. #define png_bytep_NULL NULL
  177677. #define png_bytepp_NULL NULL
  177678. #define png_doublep_NULL NULL
  177679. #define png_error_ptr_NULL NULL
  177680. #define png_flush_ptr_NULL NULL
  177681. #define png_free_ptr_NULL NULL
  177682. #define png_infopp_NULL NULL
  177683. #define png_malloc_ptr_NULL NULL
  177684. #define png_read_status_ptr_NULL NULL
  177685. #define png_rw_ptr_NULL NULL
  177686. #define png_structp_NULL NULL
  177687. #define png_uint_16p_NULL NULL
  177688. #define png_voidp_NULL NULL
  177689. #define png_write_status_ptr_NULL NULL
  177690. #endif
  177691. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177692. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177693. /* Version information for C files, stored in png.c. This had better match
  177694. * the version above.
  177695. */
  177696. #ifdef PNG_USE_GLOBAL_ARRAYS
  177697. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  177698. /* need room for 99.99.99beta99z */
  177699. #else
  177700. #define png_libpng_ver png_get_header_ver(NULL)
  177701. #endif
  177702. #ifdef PNG_USE_GLOBAL_ARRAYS
  177703. /* This was removed in version 1.0.5c */
  177704. /* Structures to facilitate easy interlacing. See png.c for more details */
  177705. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  177706. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  177707. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  177708. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  177709. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  177710. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  177711. /* This isn't currently used. If you need it, see png.c for more details.
  177712. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  177713. */
  177714. #endif
  177715. #endif /* PNG_NO_EXTERN */
  177716. /* Three color definitions. The order of the red, green, and blue, (and the
  177717. * exact size) is not important, although the size of the fields need to
  177718. * be png_byte or png_uint_16 (as defined below).
  177719. */
  177720. typedef struct png_color_struct
  177721. {
  177722. png_byte red;
  177723. png_byte green;
  177724. png_byte blue;
  177725. } png_color;
  177726. typedef png_color FAR * png_colorp;
  177727. typedef png_color FAR * FAR * png_colorpp;
  177728. typedef struct png_color_16_struct
  177729. {
  177730. png_byte index; /* used for palette files */
  177731. png_uint_16 red; /* for use in red green blue files */
  177732. png_uint_16 green;
  177733. png_uint_16 blue;
  177734. png_uint_16 gray; /* for use in grayscale files */
  177735. } png_color_16;
  177736. typedef png_color_16 FAR * png_color_16p;
  177737. typedef png_color_16 FAR * FAR * png_color_16pp;
  177738. typedef struct png_color_8_struct
  177739. {
  177740. png_byte red; /* for use in red green blue files */
  177741. png_byte green;
  177742. png_byte blue;
  177743. png_byte gray; /* for use in grayscale files */
  177744. png_byte alpha; /* for alpha channel files */
  177745. } png_color_8;
  177746. typedef png_color_8 FAR * png_color_8p;
  177747. typedef png_color_8 FAR * FAR * png_color_8pp;
  177748. /*
  177749. * The following two structures are used for the in-core representation
  177750. * of sPLT chunks.
  177751. */
  177752. typedef struct png_sPLT_entry_struct
  177753. {
  177754. png_uint_16 red;
  177755. png_uint_16 green;
  177756. png_uint_16 blue;
  177757. png_uint_16 alpha;
  177758. png_uint_16 frequency;
  177759. } png_sPLT_entry;
  177760. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  177761. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  177762. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  177763. * occupy the LSB of their respective members, and the MSB of each member
  177764. * is zero-filled. The frequency member always occupies the full 16 bits.
  177765. */
  177766. typedef struct png_sPLT_struct
  177767. {
  177768. png_charp name; /* palette name */
  177769. png_byte depth; /* depth of palette samples */
  177770. png_sPLT_entryp entries; /* palette entries */
  177771. png_int_32 nentries; /* number of palette entries */
  177772. } png_sPLT_t;
  177773. typedef png_sPLT_t FAR * png_sPLT_tp;
  177774. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  177775. #ifdef PNG_TEXT_SUPPORTED
  177776. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  177777. * and whether that contents is compressed or not. The "key" field
  177778. * points to a regular zero-terminated C string. The "text", "lang", and
  177779. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  177780. * However, the * structure returned by png_get_text() will always contain
  177781. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  177782. * so they can be safely used in printf() and other string-handling functions.
  177783. */
  177784. typedef struct png_text_struct
  177785. {
  177786. int compression; /* compression value:
  177787. -1: tEXt, none
  177788. 0: zTXt, deflate
  177789. 1: iTXt, none
  177790. 2: iTXt, deflate */
  177791. png_charp key; /* keyword, 1-79 character description of "text" */
  177792. png_charp text; /* comment, may be an empty string (ie "")
  177793. or a NULL pointer */
  177794. png_size_t text_length; /* length of the text string */
  177795. #ifdef PNG_iTXt_SUPPORTED
  177796. png_size_t itxt_length; /* length of the itxt string */
  177797. png_charp lang; /* language code, 0-79 characters
  177798. or a NULL pointer */
  177799. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  177800. chars or a NULL pointer */
  177801. #endif
  177802. } png_text;
  177803. typedef png_text FAR * png_textp;
  177804. typedef png_text FAR * FAR * png_textpp;
  177805. #endif
  177806. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  177807. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  177808. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  177809. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  177810. #define PNG_TEXT_COMPRESSION_NONE -1
  177811. #define PNG_TEXT_COMPRESSION_zTXt 0
  177812. #define PNG_ITXT_COMPRESSION_NONE 1
  177813. #define PNG_ITXT_COMPRESSION_zTXt 2
  177814. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  177815. /* png_time is a way to hold the time in an machine independent way.
  177816. * Two conversions are provided, both from time_t and struct tm. There
  177817. * is no portable way to convert to either of these structures, as far
  177818. * as I know. If you know of a portable way, send it to me. As a side
  177819. * note - PNG has always been Year 2000 compliant!
  177820. */
  177821. typedef struct png_time_struct
  177822. {
  177823. png_uint_16 year; /* full year, as in, 1995 */
  177824. png_byte month; /* month of year, 1 - 12 */
  177825. png_byte day; /* day of month, 1 - 31 */
  177826. png_byte hour; /* hour of day, 0 - 23 */
  177827. png_byte minute; /* minute of hour, 0 - 59 */
  177828. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  177829. } png_time;
  177830. typedef png_time FAR * png_timep;
  177831. typedef png_time FAR * FAR * png_timepp;
  177832. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177833. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  177834. * no specific support. The idea is that we can use this to queue
  177835. * up private chunks for output even though the library doesn't actually
  177836. * know about their semantics.
  177837. */
  177838. typedef struct png_unknown_chunk_t
  177839. {
  177840. png_byte name[5];
  177841. png_byte *data;
  177842. png_size_t size;
  177843. /* libpng-using applications should NOT directly modify this byte. */
  177844. png_byte location; /* mode of operation at read time */
  177845. }
  177846. png_unknown_chunk;
  177847. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  177848. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  177849. #endif
  177850. /* png_info is a structure that holds the information in a PNG file so
  177851. * that the application can find out the characteristics of the image.
  177852. * If you are reading the file, this structure will tell you what is
  177853. * in the PNG file. If you are writing the file, fill in the information
  177854. * you want to put into the PNG file, then call png_write_info().
  177855. * The names chosen should be very close to the PNG specification, so
  177856. * consult that document for information about the meaning of each field.
  177857. *
  177858. * With libpng < 0.95, it was only possible to directly set and read the
  177859. * the values in the png_info_struct, which meant that the contents and
  177860. * order of the values had to remain fixed. With libpng 0.95 and later,
  177861. * however, there are now functions that abstract the contents of
  177862. * png_info_struct from the application, so this makes it easier to use
  177863. * libpng with dynamic libraries, and even makes it possible to use
  177864. * libraries that don't have all of the libpng ancillary chunk-handing
  177865. * functionality.
  177866. *
  177867. * In any case, the order of the parameters in png_info_struct should NOT
  177868. * be changed for as long as possible to keep compatibility with applications
  177869. * that use the old direct-access method with png_info_struct.
  177870. *
  177871. * The following members may have allocated storage attached that should be
  177872. * cleaned up before the structure is discarded: palette, trans, text,
  177873. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  177874. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  177875. * are automatically freed when the info structure is deallocated, if they were
  177876. * allocated internally by libpng. This behavior can be changed by means
  177877. * of the png_data_freer() function.
  177878. *
  177879. * More allocation details: all the chunk-reading functions that
  177880. * change these members go through the corresponding png_set_*
  177881. * functions. A function to clear these members is available: see
  177882. * png_free_data(). The png_set_* functions do not depend on being
  177883. * able to point info structure members to any of the storage they are
  177884. * passed (they make their own copies), EXCEPT that the png_set_text
  177885. * functions use the same storage passed to them in the text_ptr or
  177886. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  177887. * functions do not make their own copies.
  177888. */
  177889. typedef struct png_info_struct
  177890. {
  177891. /* the following are necessary for every PNG file */
  177892. png_uint_32 width; /* width of image in pixels (from IHDR) */
  177893. png_uint_32 height; /* height of image in pixels (from IHDR) */
  177894. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  177895. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  177896. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  177897. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  177898. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  177899. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  177900. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  177901. /* The following three should have been named *_method not *_type */
  177902. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  177903. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  177904. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177905. /* The following is informational only on read, and not used on writes. */
  177906. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  177907. png_byte pixel_depth; /* number of bits per pixel */
  177908. png_byte spare_byte; /* to align the data, and for future use */
  177909. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  177910. /* The rest of the data is optional. If you are reading, check the
  177911. * valid field to see if the information in these are valid. If you
  177912. * are writing, set the valid field to those chunks you want written,
  177913. * and initialize the appropriate fields below.
  177914. */
  177915. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177916. /* The gAMA chunk describes the gamma characteristics of the system
  177917. * on which the image was created, normally in the range [1.0, 2.5].
  177918. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  177919. */
  177920. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  177921. #endif
  177922. #if defined(PNG_sRGB_SUPPORTED)
  177923. /* GR-P, 0.96a */
  177924. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  177925. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  177926. #endif
  177927. #if defined(PNG_TEXT_SUPPORTED)
  177928. /* The tEXt, and zTXt chunks contain human-readable textual data in
  177929. * uncompressed, compressed, and optionally compressed forms, respectively.
  177930. * The data in "text" is an array of pointers to uncompressed,
  177931. * null-terminated C strings. Each chunk has a keyword that describes the
  177932. * textual data contained in that chunk. Keywords are not required to be
  177933. * unique, and the text string may be empty. Any number of text chunks may
  177934. * be in an image.
  177935. */
  177936. int num_text; /* number of comments read/to write */
  177937. int max_text; /* current size of text array */
  177938. png_textp text; /* array of comments read/to write */
  177939. #endif /* PNG_TEXT_SUPPORTED */
  177940. #if defined(PNG_tIME_SUPPORTED)
  177941. /* The tIME chunk holds the last time the displayed image data was
  177942. * modified. See the png_time struct for the contents of this struct.
  177943. */
  177944. png_time mod_time;
  177945. #endif
  177946. #if defined(PNG_sBIT_SUPPORTED)
  177947. /* The sBIT chunk specifies the number of significant high-order bits
  177948. * in the pixel data. Values are in the range [1, bit_depth], and are
  177949. * only specified for the channels in the pixel data. The contents of
  177950. * the low-order bits is not specified. Data is valid if
  177951. * (valid & PNG_INFO_sBIT) is non-zero.
  177952. */
  177953. png_color_8 sig_bit; /* significant bits in color channels */
  177954. #endif
  177955. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  177956. defined(PNG_READ_BACKGROUND_SUPPORTED)
  177957. /* The tRNS chunk supplies transparency data for paletted images and
  177958. * other image types that don't need a full alpha channel. There are
  177959. * "num_trans" transparency values for a paletted image, stored in the
  177960. * same order as the palette colors, starting from index 0. Values
  177961. * for the data are in the range [0, 255], ranging from fully transparent
  177962. * to fully opaque, respectively. For non-paletted images, there is a
  177963. * single color specified that should be treated as fully transparent.
  177964. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  177965. */
  177966. png_bytep trans; /* transparent values for paletted image */
  177967. png_color_16 trans_values; /* transparent color for non-palette image */
  177968. #endif
  177969. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177970. /* The bKGD chunk gives the suggested image background color if the
  177971. * display program does not have its own background color and the image
  177972. * is needs to composited onto a background before display. The colors
  177973. * in "background" are normally in the same color space/depth as the
  177974. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  177975. */
  177976. png_color_16 background;
  177977. #endif
  177978. #if defined(PNG_oFFs_SUPPORTED)
  177979. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  177980. * and downwards from the top-left corner of the display, page, or other
  177981. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  177982. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  177983. */
  177984. png_int_32 x_offset; /* x offset on page */
  177985. png_int_32 y_offset; /* y offset on page */
  177986. png_byte offset_unit_type; /* offset units type */
  177987. #endif
  177988. #if defined(PNG_pHYs_SUPPORTED)
  177989. /* The pHYs chunk gives the physical pixel density of the image for
  177990. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  177991. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  177992. */
  177993. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  177994. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  177995. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  177996. #endif
  177997. #if defined(PNG_hIST_SUPPORTED)
  177998. /* The hIST chunk contains the relative frequency or importance of the
  177999. * various palette entries, so that a viewer can intelligently select a
  178000. * reduced-color palette, if required. Data is an array of "num_palette"
  178001. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  178002. * is non-zero.
  178003. */
  178004. png_uint_16p hist;
  178005. #endif
  178006. #ifdef PNG_cHRM_SUPPORTED
  178007. /* The cHRM chunk describes the CIE color characteristics of the monitor
  178008. * on which the PNG was created. This data allows the viewer to do gamut
  178009. * mapping of the input image to ensure that the viewer sees the same
  178010. * colors in the image as the creator. Values are in the range
  178011. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  178012. */
  178013. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178014. float x_white;
  178015. float y_white;
  178016. float x_red;
  178017. float y_red;
  178018. float x_green;
  178019. float y_green;
  178020. float x_blue;
  178021. float y_blue;
  178022. #endif
  178023. #endif
  178024. #if defined(PNG_pCAL_SUPPORTED)
  178025. /* The pCAL chunk describes a transformation between the stored pixel
  178026. * values and original physical data values used to create the image.
  178027. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  178028. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  178029. * (possibly non-linear) transformation function given by "pcal_type"
  178030. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  178031. * defines below, and the PNG-Group's PNG extensions document for a
  178032. * complete description of the transformations and how they should be
  178033. * implemented, and for a description of the ASCII parameter strings.
  178034. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  178035. */
  178036. png_charp pcal_purpose; /* pCAL chunk description string */
  178037. png_int_32 pcal_X0; /* minimum value */
  178038. png_int_32 pcal_X1; /* maximum value */
  178039. png_charp pcal_units; /* Latin-1 string giving physical units */
  178040. png_charpp pcal_params; /* ASCII strings containing parameter values */
  178041. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  178042. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  178043. #endif
  178044. /* New members added in libpng-1.0.6 */
  178045. #ifdef PNG_FREE_ME_SUPPORTED
  178046. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178047. #endif
  178048. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178049. /* storage for unknown chunks that the library doesn't recognize. */
  178050. png_unknown_chunkp unknown_chunks;
  178051. png_size_t unknown_chunks_num;
  178052. #endif
  178053. #if defined(PNG_iCCP_SUPPORTED)
  178054. /* iCCP chunk data. */
  178055. png_charp iccp_name; /* profile name */
  178056. png_charp iccp_profile; /* International Color Consortium profile data */
  178057. /* Note to maintainer: should be png_bytep */
  178058. png_uint_32 iccp_proflen; /* ICC profile data length */
  178059. png_byte iccp_compression; /* Always zero */
  178060. #endif
  178061. #if defined(PNG_sPLT_SUPPORTED)
  178062. /* data on sPLT chunks (there may be more than one). */
  178063. png_sPLT_tp splt_palettes;
  178064. png_uint_32 splt_palettes_num;
  178065. #endif
  178066. #if defined(PNG_sCAL_SUPPORTED)
  178067. /* The sCAL chunk describes the actual physical dimensions of the
  178068. * subject matter of the graphic. The chunk contains a unit specification
  178069. * a byte value, and two ASCII strings representing floating-point
  178070. * values. The values are width and height corresponsing to one pixel
  178071. * in the image. This external representation is converted to double
  178072. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  178073. */
  178074. png_byte scal_unit; /* unit of physical scale */
  178075. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178076. double scal_pixel_width; /* width of one pixel */
  178077. double scal_pixel_height; /* height of one pixel */
  178078. #endif
  178079. #ifdef PNG_FIXED_POINT_SUPPORTED
  178080. png_charp scal_s_width; /* string containing height */
  178081. png_charp scal_s_height; /* string containing width */
  178082. #endif
  178083. #endif
  178084. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178085. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  178086. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  178087. png_bytepp row_pointers; /* the image bits */
  178088. #endif
  178089. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  178090. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  178091. #endif
  178092. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  178093. png_fixed_point int_x_white;
  178094. png_fixed_point int_y_white;
  178095. png_fixed_point int_x_red;
  178096. png_fixed_point int_y_red;
  178097. png_fixed_point int_x_green;
  178098. png_fixed_point int_y_green;
  178099. png_fixed_point int_x_blue;
  178100. png_fixed_point int_y_blue;
  178101. #endif
  178102. } png_info;
  178103. typedef png_info FAR * png_infop;
  178104. typedef png_info FAR * FAR * png_infopp;
  178105. /* Maximum positive integer used in PNG is (2^31)-1 */
  178106. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  178107. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  178108. #define PNG_SIZE_MAX ((png_size_t)(-1))
  178109. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178110. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  178111. #define PNG_MAX_UINT PNG_UINT_31_MAX
  178112. #endif
  178113. /* These describe the color_type field in png_info. */
  178114. /* color type masks */
  178115. #define PNG_COLOR_MASK_PALETTE 1
  178116. #define PNG_COLOR_MASK_COLOR 2
  178117. #define PNG_COLOR_MASK_ALPHA 4
  178118. /* color types. Note that not all combinations are legal */
  178119. #define PNG_COLOR_TYPE_GRAY 0
  178120. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  178121. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  178122. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  178123. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  178124. /* aliases */
  178125. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  178126. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  178127. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  178128. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  178129. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  178130. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  178131. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  178132. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  178133. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  178134. /* These are for the interlacing type. These values should NOT be changed. */
  178135. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  178136. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  178137. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  178138. /* These are for the oFFs chunk. These values should NOT be changed. */
  178139. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  178140. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  178141. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  178142. /* These are for the pCAL chunk. These values should NOT be changed. */
  178143. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  178144. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  178145. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  178146. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  178147. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  178148. /* These are for the sCAL chunk. These values should NOT be changed. */
  178149. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  178150. #define PNG_SCALE_METER 1 /* meters per pixel */
  178151. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  178152. #define PNG_SCALE_LAST 3 /* Not a valid value */
  178153. /* These are for the pHYs chunk. These values should NOT be changed. */
  178154. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  178155. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  178156. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  178157. /* These are for the sRGB chunk. These values should NOT be changed. */
  178158. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  178159. #define PNG_sRGB_INTENT_RELATIVE 1
  178160. #define PNG_sRGB_INTENT_SATURATION 2
  178161. #define PNG_sRGB_INTENT_ABSOLUTE 3
  178162. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  178163. /* This is for text chunks */
  178164. #define PNG_KEYWORD_MAX_LENGTH 79
  178165. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  178166. #define PNG_MAX_PALETTE_LENGTH 256
  178167. /* These determine if an ancillary chunk's data has been successfully read
  178168. * from the PNG header, or if the application has filled in the corresponding
  178169. * data in the info_struct to be written into the output file. The values
  178170. * of the PNG_INFO_<chunk> defines should NOT be changed.
  178171. */
  178172. #define PNG_INFO_gAMA 0x0001
  178173. #define PNG_INFO_sBIT 0x0002
  178174. #define PNG_INFO_cHRM 0x0004
  178175. #define PNG_INFO_PLTE 0x0008
  178176. #define PNG_INFO_tRNS 0x0010
  178177. #define PNG_INFO_bKGD 0x0020
  178178. #define PNG_INFO_hIST 0x0040
  178179. #define PNG_INFO_pHYs 0x0080
  178180. #define PNG_INFO_oFFs 0x0100
  178181. #define PNG_INFO_tIME 0x0200
  178182. #define PNG_INFO_pCAL 0x0400
  178183. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  178184. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  178185. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  178186. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  178187. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  178188. /* This is used for the transformation routines, as some of them
  178189. * change these values for the row. It also should enable using
  178190. * the routines for other purposes.
  178191. */
  178192. typedef struct png_row_info_struct
  178193. {
  178194. png_uint_32 width; /* width of row */
  178195. png_uint_32 rowbytes; /* number of bytes in row */
  178196. png_byte color_type; /* color type of row */
  178197. png_byte bit_depth; /* bit depth of row */
  178198. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  178199. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  178200. } png_row_info;
  178201. typedef png_row_info FAR * png_row_infop;
  178202. typedef png_row_info FAR * FAR * png_row_infopp;
  178203. /* These are the function types for the I/O functions and for the functions
  178204. * that allow the user to override the default I/O functions with his or her
  178205. * own. The png_error_ptr type should match that of user-supplied warning
  178206. * and error functions, while the png_rw_ptr type should match that of the
  178207. * user read/write data functions.
  178208. */
  178209. typedef struct png_struct_def png_struct;
  178210. typedef png_struct FAR * png_structp;
  178211. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  178212. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  178213. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  178214. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  178215. int));
  178216. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  178217. int));
  178218. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178219. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  178220. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  178221. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  178222. png_uint_32, int));
  178223. #endif
  178224. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178225. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178226. defined(PNG_LEGACY_SUPPORTED)
  178227. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  178228. png_row_infop, png_bytep));
  178229. #endif
  178230. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178231. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  178232. #endif
  178233. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178234. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  178235. #endif
  178236. /* Transform masks for the high-level interface */
  178237. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  178238. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  178239. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  178240. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  178241. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  178242. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  178243. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  178244. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  178245. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  178246. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  178247. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  178248. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  178249. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  178250. /* Flags for MNG supported features */
  178251. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  178252. #define PNG_FLAG_MNG_FILTER_64 0x04
  178253. #define PNG_ALL_MNG_FEATURES 0x05
  178254. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  178255. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  178256. /* The structure that holds the information to read and write PNG files.
  178257. * The only people who need to care about what is inside of this are the
  178258. * people who will be modifying the library for their own special needs.
  178259. * It should NOT be accessed directly by an application, except to store
  178260. * the jmp_buf.
  178261. */
  178262. struct png_struct_def
  178263. {
  178264. #ifdef PNG_SETJMP_SUPPORTED
  178265. jmp_buf jmpbuf; /* used in png_error */
  178266. #endif
  178267. png_error_ptr error_fn; /* function for printing errors and aborting */
  178268. png_error_ptr warning_fn; /* function for printing warnings */
  178269. png_voidp error_ptr; /* user supplied struct for error functions */
  178270. png_rw_ptr write_data_fn; /* function for writing output data */
  178271. png_rw_ptr read_data_fn; /* function for reading input data */
  178272. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  178273. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  178274. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  178275. #endif
  178276. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178277. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  178278. #endif
  178279. /* These were added in libpng-1.0.2 */
  178280. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  178281. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178282. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178283. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  178284. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  178285. png_byte user_transform_channels; /* channels in user transformed pixels */
  178286. #endif
  178287. #endif
  178288. png_uint_32 mode; /* tells us where we are in the PNG file */
  178289. png_uint_32 flags; /* flags indicating various things to libpng */
  178290. png_uint_32 transformations; /* which transformations to perform */
  178291. z_stream zstream; /* pointer to decompression structure (below) */
  178292. png_bytep zbuf; /* buffer for zlib */
  178293. png_size_t zbuf_size; /* size of zbuf */
  178294. int zlib_level; /* holds zlib compression level */
  178295. int zlib_method; /* holds zlib compression method */
  178296. int zlib_window_bits; /* holds zlib compression window bits */
  178297. int zlib_mem_level; /* holds zlib compression memory level */
  178298. int zlib_strategy; /* holds zlib compression strategy */
  178299. png_uint_32 width; /* width of image in pixels */
  178300. png_uint_32 height; /* height of image in pixels */
  178301. png_uint_32 num_rows; /* number of rows in current pass */
  178302. png_uint_32 usr_width; /* width of row at start of write */
  178303. png_uint_32 rowbytes; /* size of row in bytes */
  178304. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  178305. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  178306. png_uint_32 row_number; /* current row in interlace pass */
  178307. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  178308. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  178309. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  178310. png_bytep up_row; /* buffer to save "up" row when filtering */
  178311. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  178312. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  178313. png_row_info row_info; /* used for transformation routines */
  178314. png_uint_32 idat_size; /* current IDAT size for read */
  178315. png_uint_32 crc; /* current chunk CRC value */
  178316. png_colorp palette; /* palette from the input file */
  178317. png_uint_16 num_palette; /* number of color entries in palette */
  178318. png_uint_16 num_trans; /* number of transparency values */
  178319. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  178320. png_byte compression; /* file compression type (always 0) */
  178321. png_byte filter; /* file filter type (always 0) */
  178322. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  178323. png_byte pass; /* current interlace pass (0 - 6) */
  178324. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  178325. png_byte color_type; /* color type of file */
  178326. png_byte bit_depth; /* bit depth of file */
  178327. png_byte usr_bit_depth; /* bit depth of users row */
  178328. png_byte pixel_depth; /* number of bits per pixel */
  178329. png_byte channels; /* number of channels in file */
  178330. png_byte usr_channels; /* channels at start of write */
  178331. png_byte sig_bytes; /* magic bytes read/written from start of file */
  178332. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178333. #ifdef PNG_LEGACY_SUPPORTED
  178334. png_byte filler; /* filler byte for pixel expansion */
  178335. #else
  178336. png_uint_16 filler; /* filler bytes for pixel expansion */
  178337. #endif
  178338. #endif
  178339. #if defined(PNG_bKGD_SUPPORTED)
  178340. png_byte background_gamma_type;
  178341. # ifdef PNG_FLOATING_POINT_SUPPORTED
  178342. float background_gamma;
  178343. # endif
  178344. png_color_16 background; /* background color in screen gamma space */
  178345. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178346. png_color_16 background_1; /* background normalized to gamma 1.0 */
  178347. #endif
  178348. #endif /* PNG_bKGD_SUPPORTED */
  178349. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178350. png_flush_ptr output_flush_fn;/* Function for flushing output */
  178351. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  178352. png_uint_32 flush_rows; /* number of rows written since last flush */
  178353. #endif
  178354. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178355. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  178356. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178357. float gamma; /* file gamma value */
  178358. float screen_gamma; /* screen gamma value (display_exponent) */
  178359. #endif
  178360. #endif
  178361. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178362. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  178363. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  178364. png_bytep gamma_to_1; /* converts from file to 1.0 */
  178365. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  178366. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  178367. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  178368. #endif
  178369. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  178370. png_color_8 sig_bit; /* significant bits in each available channel */
  178371. #endif
  178372. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178373. png_color_8 shift; /* shift for significant bit tranformation */
  178374. #endif
  178375. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  178376. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178377. png_bytep trans; /* transparency values for paletted files */
  178378. png_color_16 trans_values; /* transparency values for non-paletted files */
  178379. #endif
  178380. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  178381. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  178382. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178383. png_progressive_info_ptr info_fn; /* called after header data fully read */
  178384. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  178385. png_progressive_end_ptr end_fn; /* called after image is complete */
  178386. png_bytep save_buffer_ptr; /* current location in save_buffer */
  178387. png_bytep save_buffer; /* buffer for previously read data */
  178388. png_bytep current_buffer_ptr; /* current location in current_buffer */
  178389. png_bytep current_buffer; /* buffer for recently used data */
  178390. png_uint_32 push_length; /* size of current input chunk */
  178391. png_uint_32 skip_length; /* bytes to skip in input data */
  178392. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  178393. png_size_t save_buffer_max; /* total size of save_buffer */
  178394. png_size_t buffer_size; /* total amount of available input data */
  178395. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  178396. int process_mode; /* what push library is currently doing */
  178397. int cur_palette; /* current push library palette index */
  178398. # if defined(PNG_TEXT_SUPPORTED)
  178399. png_size_t current_text_size; /* current size of text input data */
  178400. png_size_t current_text_left; /* how much text left to read in input */
  178401. png_charp current_text; /* current text chunk buffer */
  178402. png_charp current_text_ptr; /* current location in current_text */
  178403. # endif /* PNG_TEXT_SUPPORTED */
  178404. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178405. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  178406. /* for the Borland special 64K segment handler */
  178407. png_bytepp offset_table_ptr;
  178408. png_bytep offset_table;
  178409. png_uint_16 offset_table_number;
  178410. png_uint_16 offset_table_count;
  178411. png_uint_16 offset_table_count_free;
  178412. #endif
  178413. #if defined(PNG_READ_DITHER_SUPPORTED)
  178414. png_bytep palette_lookup; /* lookup table for dithering */
  178415. png_bytep dither_index; /* index translation for palette files */
  178416. #endif
  178417. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  178418. png_uint_16p hist; /* histogram */
  178419. #endif
  178420. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  178421. png_byte heuristic_method; /* heuristic for row filter selection */
  178422. png_byte num_prev_filters; /* number of weights for previous rows */
  178423. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  178424. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  178425. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  178426. png_uint_16p filter_costs; /* relative filter calculation cost */
  178427. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  178428. #endif
  178429. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178430. png_charp time_buffer; /* String to hold RFC 1123 time text */
  178431. #endif
  178432. /* New members added in libpng-1.0.6 */
  178433. #ifdef PNG_FREE_ME_SUPPORTED
  178434. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178435. #endif
  178436. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178437. png_voidp user_chunk_ptr;
  178438. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  178439. #endif
  178440. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178441. int num_chunk_list;
  178442. png_bytep chunk_list;
  178443. #endif
  178444. /* New members added in libpng-1.0.3 */
  178445. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178446. png_byte rgb_to_gray_status;
  178447. /* These were changed from png_byte in libpng-1.0.6 */
  178448. png_uint_16 rgb_to_gray_red_coeff;
  178449. png_uint_16 rgb_to_gray_green_coeff;
  178450. png_uint_16 rgb_to_gray_blue_coeff;
  178451. #endif
  178452. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  178453. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  178454. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178455. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178456. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  178457. #ifdef PNG_1_0_X
  178458. png_byte mng_features_permitted;
  178459. #else
  178460. png_uint_32 mng_features_permitted;
  178461. #endif /* PNG_1_0_X */
  178462. #endif
  178463. /* New member added in libpng-1.0.7 */
  178464. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178465. png_fixed_point int_gamma;
  178466. #endif
  178467. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  178468. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  178469. png_byte filter_type;
  178470. #endif
  178471. #if defined(PNG_1_0_X)
  178472. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  178473. png_uint_32 row_buf_size;
  178474. #endif
  178475. /* New members added in libpng-1.2.0 */
  178476. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178477. # if !defined(PNG_1_0_X)
  178478. # if defined(PNG_MMX_CODE_SUPPORTED)
  178479. png_byte mmx_bitdepth_threshold;
  178480. png_uint_32 mmx_rowbytes_threshold;
  178481. # endif
  178482. png_uint_32 asm_flags;
  178483. # endif
  178484. #endif
  178485. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  178486. #ifdef PNG_USER_MEM_SUPPORTED
  178487. png_voidp mem_ptr; /* user supplied struct for mem functions */
  178488. png_malloc_ptr malloc_fn; /* function for allocating memory */
  178489. png_free_ptr free_fn; /* function for freeing memory */
  178490. #endif
  178491. /* New member added in libpng-1.0.13 and 1.2.0 */
  178492. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  178493. #if defined(PNG_READ_DITHER_SUPPORTED)
  178494. /* The following three members were added at version 1.0.14 and 1.2.4 */
  178495. png_bytep dither_sort; /* working sort array */
  178496. png_bytep index_to_palette; /* where the original index currently is */
  178497. /* in the palette */
  178498. png_bytep palette_to_index; /* which original index points to this */
  178499. /* palette color */
  178500. #endif
  178501. /* New members added in libpng-1.0.16 and 1.2.6 */
  178502. png_byte compression_type;
  178503. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  178504. png_uint_32 user_width_max;
  178505. png_uint_32 user_height_max;
  178506. #endif
  178507. /* New member added in libpng-1.0.25 and 1.2.17 */
  178508. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178509. /* storage for unknown chunk that the library doesn't recognize. */
  178510. png_unknown_chunk unknown_chunk;
  178511. #endif
  178512. };
  178513. /* This triggers a compiler error in png.c, if png.c and png.h
  178514. * do not agree upon the version number.
  178515. */
  178516. typedef png_structp version_1_2_21;
  178517. typedef png_struct FAR * FAR * png_structpp;
  178518. /* Here are the function definitions most commonly used. This is not
  178519. * the place to find out how to use libpng. See libpng.txt for the
  178520. * full explanation, see example.c for the summary. This just provides
  178521. * a simple one line description of the use of each function.
  178522. */
  178523. /* Returns the version number of the library */
  178524. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  178525. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  178526. * Handling more than 8 bytes from the beginning of the file is an error.
  178527. */
  178528. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  178529. int num_bytes));
  178530. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  178531. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  178532. * signature, and non-zero otherwise. Having num_to_check == 0 or
  178533. * start > 7 will always fail (ie return non-zero).
  178534. */
  178535. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  178536. png_size_t num_to_check));
  178537. /* Simple signature checking function. This is the same as calling
  178538. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  178539. */
  178540. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  178541. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  178542. extern PNG_EXPORT(png_structp,png_create_read_struct)
  178543. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178544. png_error_ptr error_fn, png_error_ptr warn_fn));
  178545. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  178546. extern PNG_EXPORT(png_structp,png_create_write_struct)
  178547. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178548. png_error_ptr error_fn, png_error_ptr warn_fn));
  178549. #ifdef PNG_WRITE_SUPPORTED
  178550. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  178551. PNGARG((png_structp png_ptr));
  178552. #endif
  178553. #ifdef PNG_WRITE_SUPPORTED
  178554. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  178555. PNGARG((png_structp png_ptr, png_uint_32 size));
  178556. #endif
  178557. /* Reset the compression stream */
  178558. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  178559. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  178560. #ifdef PNG_USER_MEM_SUPPORTED
  178561. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  178562. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178563. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178564. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178565. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  178566. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178567. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178568. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178569. #endif
  178570. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  178571. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  178572. png_bytep chunk_name, png_bytep data, png_size_t length));
  178573. /* Write the start of a PNG chunk - length and chunk name. */
  178574. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  178575. png_bytep chunk_name, png_uint_32 length));
  178576. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  178577. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  178578. png_bytep data, png_size_t length));
  178579. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  178580. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  178581. /* Allocate and initialize the info structure */
  178582. extern PNG_EXPORT(png_infop,png_create_info_struct)
  178583. PNGARG((png_structp png_ptr));
  178584. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178585. /* Initialize the info structure (old interface - DEPRECATED) */
  178586. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  178587. #undef png_info_init
  178588. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  178589. png_sizeof(png_info));
  178590. #endif
  178591. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  178592. png_size_t png_info_struct_size));
  178593. /* Writes all the PNG information before the image. */
  178594. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  178595. png_infop info_ptr));
  178596. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  178597. png_infop info_ptr));
  178598. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178599. /* read the information before the actual image data. */
  178600. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  178601. png_infop info_ptr));
  178602. #endif
  178603. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178604. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  178605. PNGARG((png_structp png_ptr, png_timep ptime));
  178606. #endif
  178607. #if !defined(_WIN32_WCE)
  178608. /* "time.h" functions are not supported on WindowsCE */
  178609. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178610. /* convert from a struct tm to png_time */
  178611. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  178612. struct tm FAR * ttime));
  178613. /* convert from time_t to png_time. Uses gmtime() */
  178614. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  178615. time_t ttime));
  178616. #endif /* PNG_WRITE_tIME_SUPPORTED */
  178617. #endif /* _WIN32_WCE */
  178618. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178619. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  178620. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  178621. #if !defined(PNG_1_0_X)
  178622. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  178623. png_ptr));
  178624. #endif
  178625. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  178626. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  178627. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178628. /* Deprecated */
  178629. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  178630. #endif
  178631. #endif
  178632. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178633. /* Use blue, green, red order for pixels. */
  178634. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  178635. #endif
  178636. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178637. /* Expand the grayscale to 24-bit RGB if necessary. */
  178638. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  178639. #endif
  178640. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178641. /* Reduce RGB to grayscale. */
  178642. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178643. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  178644. int error_action, double red, double green ));
  178645. #endif
  178646. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  178647. int error_action, png_fixed_point red, png_fixed_point green ));
  178648. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  178649. png_ptr));
  178650. #endif
  178651. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  178652. png_colorp palette));
  178653. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178654. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  178655. #endif
  178656. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  178657. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178658. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  178659. #endif
  178660. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  178661. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178662. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  178663. #endif
  178664. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178665. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  178666. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  178667. png_uint_32 filler, int flags));
  178668. /* The values of the PNG_FILLER_ defines should NOT be changed */
  178669. #define PNG_FILLER_BEFORE 0
  178670. #define PNG_FILLER_AFTER 1
  178671. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  178672. #if !defined(PNG_1_0_X)
  178673. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  178674. png_uint_32 filler, int flags));
  178675. #endif
  178676. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  178677. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178678. /* Swap bytes in 16-bit depth files. */
  178679. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  178680. #endif
  178681. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  178682. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  178683. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  178684. #endif
  178685. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178686. /* Swap packing order of pixels in bytes. */
  178687. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  178688. #endif
  178689. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178690. /* Converts files to legal bit depths. */
  178691. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  178692. png_color_8p true_bits));
  178693. #endif
  178694. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  178695. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178696. /* Have the code handle the interlacing. Returns the number of passes. */
  178697. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  178698. #endif
  178699. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178700. /* Invert monochrome files */
  178701. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  178702. #endif
  178703. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178704. /* Handle alpha and tRNS by replacing with a background color. */
  178705. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178706. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  178707. png_color_16p background_color, int background_gamma_code,
  178708. int need_expand, double background_gamma));
  178709. #endif
  178710. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  178711. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  178712. #define PNG_BACKGROUND_GAMMA_FILE 2
  178713. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  178714. #endif
  178715. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178716. /* strip the second byte of information from a 16-bit depth file. */
  178717. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  178718. #endif
  178719. #if defined(PNG_READ_DITHER_SUPPORTED)
  178720. /* Turn on dithering, and reduce the palette to the number of colors available. */
  178721. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  178722. png_colorp palette, int num_palette, int maximum_colors,
  178723. png_uint_16p histogram, int full_dither));
  178724. #endif
  178725. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178726. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  178727. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178728. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  178729. double screen_gamma, double default_file_gamma));
  178730. #endif
  178731. #endif
  178732. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178733. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178734. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178735. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  178736. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  178737. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  178738. int empty_plte_permitted));
  178739. #endif
  178740. #endif
  178741. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178742. /* Set how many lines between output flushes - 0 for no flushing */
  178743. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  178744. /* Flush the current PNG output buffer */
  178745. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  178746. #endif
  178747. /* optional update palette with requested transformations */
  178748. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  178749. /* optional call to update the users info structure */
  178750. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  178751. png_infop info_ptr));
  178752. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178753. /* read one or more rows of image data. */
  178754. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  178755. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  178756. #endif
  178757. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178758. /* read a row of data. */
  178759. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  178760. png_bytep row,
  178761. png_bytep display_row));
  178762. #endif
  178763. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178764. /* read the whole image into memory at once. */
  178765. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  178766. png_bytepp image));
  178767. #endif
  178768. /* write a row of image data */
  178769. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  178770. png_bytep row));
  178771. /* write a few rows of image data */
  178772. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  178773. png_bytepp row, png_uint_32 num_rows));
  178774. /* write the image data */
  178775. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  178776. png_bytepp image));
  178777. /* writes the end of the PNG file. */
  178778. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  178779. png_infop info_ptr));
  178780. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178781. /* read the end of the PNG file. */
  178782. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  178783. png_infop info_ptr));
  178784. #endif
  178785. /* free any memory associated with the png_info_struct */
  178786. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  178787. png_infopp info_ptr_ptr));
  178788. /* free any memory associated with the png_struct and the png_info_structs */
  178789. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  178790. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  178791. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  178792. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  178793. png_infop end_info_ptr));
  178794. /* free any memory associated with the png_struct and the png_info_structs */
  178795. extern PNG_EXPORT(void,png_destroy_write_struct)
  178796. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  178797. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  178798. extern void png_write_destroy PNGARG((png_structp png_ptr));
  178799. /* set the libpng method of handling chunk CRC errors */
  178800. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  178801. int crit_action, int ancil_action));
  178802. /* Values for png_set_crc_action() to say how to handle CRC errors in
  178803. * ancillary and critical chunks, and whether to use the data contained
  178804. * therein. Note that it is impossible to "discard" data in a critical
  178805. * chunk. For versions prior to 0.90, the action was always error/quit,
  178806. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  178807. * chunks is warn/discard. These values should NOT be changed.
  178808. *
  178809. * value action:critical action:ancillary
  178810. */
  178811. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  178812. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  178813. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  178814. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  178815. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  178816. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  178817. /* These functions give the user control over the scan-line filtering in
  178818. * libpng and the compression methods used by zlib. These functions are
  178819. * mainly useful for testing, as the defaults should work with most users.
  178820. * Those users who are tight on memory or want faster performance at the
  178821. * expense of compression can modify them. See the compression library
  178822. * header file (zlib.h) for an explination of the compression functions.
  178823. */
  178824. /* set the filtering method(s) used by libpng. Currently, the only valid
  178825. * value for "method" is 0.
  178826. */
  178827. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  178828. int filters));
  178829. /* Flags for png_set_filter() to say which filters to use. The flags
  178830. * are chosen so that they don't conflict with real filter types
  178831. * below, in case they are supplied instead of the #defined constants.
  178832. * These values should NOT be changed.
  178833. */
  178834. #define PNG_NO_FILTERS 0x00
  178835. #define PNG_FILTER_NONE 0x08
  178836. #define PNG_FILTER_SUB 0x10
  178837. #define PNG_FILTER_UP 0x20
  178838. #define PNG_FILTER_AVG 0x40
  178839. #define PNG_FILTER_PAETH 0x80
  178840. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  178841. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  178842. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  178843. * These defines should NOT be changed.
  178844. */
  178845. #define PNG_FILTER_VALUE_NONE 0
  178846. #define PNG_FILTER_VALUE_SUB 1
  178847. #define PNG_FILTER_VALUE_UP 2
  178848. #define PNG_FILTER_VALUE_AVG 3
  178849. #define PNG_FILTER_VALUE_PAETH 4
  178850. #define PNG_FILTER_VALUE_LAST 5
  178851. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  178852. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  178853. * defines, either the default (minimum-sum-of-absolute-differences), or
  178854. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  178855. *
  178856. * Weights are factors >= 1.0, indicating how important it is to keep the
  178857. * filter type consistent between rows. Larger numbers mean the current
  178858. * filter is that many times as likely to be the same as the "num_weights"
  178859. * previous filters. This is cumulative for each previous row with a weight.
  178860. * There needs to be "num_weights" values in "filter_weights", or it can be
  178861. * NULL if the weights aren't being specified. Weights have no influence on
  178862. * the selection of the first row filter. Well chosen weights can (in theory)
  178863. * improve the compression for a given image.
  178864. *
  178865. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  178866. * filter type. Higher costs indicate more decoding expense, and are
  178867. * therefore less likely to be selected over a filter with lower computational
  178868. * costs. There needs to be a value in "filter_costs" for each valid filter
  178869. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  178870. * setting the costs. Costs try to improve the speed of decompression without
  178871. * unduly increasing the compressed image size.
  178872. *
  178873. * A negative weight or cost indicates the default value is to be used, and
  178874. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  178875. * The default values for both weights and costs are currently 1.0, but may
  178876. * change if good general weighting/cost heuristics can be found. If both
  178877. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  178878. * to the UNWEIGHTED method, but with added encoding time/computation.
  178879. */
  178880. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178881. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  178882. int heuristic_method, int num_weights, png_doublep filter_weights,
  178883. png_doublep filter_costs));
  178884. #endif
  178885. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  178886. /* Heuristic used for row filter selection. These defines should NOT be
  178887. * changed.
  178888. */
  178889. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  178890. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  178891. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  178892. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  178893. /* Set the library compression level. Currently, valid values range from
  178894. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  178895. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  178896. * shown that zlib compression levels 3-6 usually perform as well as level 9
  178897. * for PNG images, and do considerably fewer caclulations. In the future,
  178898. * these values may not correspond directly to the zlib compression levels.
  178899. */
  178900. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  178901. int level));
  178902. extern PNG_EXPORT(void,png_set_compression_mem_level)
  178903. PNGARG((png_structp png_ptr, int mem_level));
  178904. extern PNG_EXPORT(void,png_set_compression_strategy)
  178905. PNGARG((png_structp png_ptr, int strategy));
  178906. extern PNG_EXPORT(void,png_set_compression_window_bits)
  178907. PNGARG((png_structp png_ptr, int window_bits));
  178908. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  178909. int method));
  178910. /* These next functions are called for input/output, memory, and error
  178911. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  178912. * and call standard C I/O routines such as fread(), fwrite(), and
  178913. * fprintf(). These functions can be made to use other I/O routines
  178914. * at run time for those applications that need to handle I/O in a
  178915. * different manner by calling png_set_???_fn(). See libpng.txt for
  178916. * more information.
  178917. */
  178918. #if !defined(PNG_NO_STDIO)
  178919. /* Initialize the input/output for the PNG file to the default functions. */
  178920. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  178921. #endif
  178922. /* Replace the (error and abort), and warning functions with user
  178923. * supplied functions. If no messages are to be printed you must still
  178924. * write and use replacement functions. The replacement error_fn should
  178925. * still do a longjmp to the last setjmp location if you are using this
  178926. * method of error handling. If error_fn or warning_fn is NULL, the
  178927. * default function will be used.
  178928. */
  178929. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  178930. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  178931. /* Return the user pointer associated with the error functions */
  178932. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  178933. /* Replace the default data output functions with a user supplied one(s).
  178934. * If buffered output is not used, then output_flush_fn can be set to NULL.
  178935. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  178936. * output_flush_fn will be ignored (and thus can be NULL).
  178937. */
  178938. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  178939. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  178940. /* Replace the default data input function with a user supplied one. */
  178941. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  178942. png_voidp io_ptr, png_rw_ptr read_data_fn));
  178943. /* Return the user pointer associated with the I/O functions */
  178944. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  178945. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  178946. png_read_status_ptr read_row_fn));
  178947. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  178948. png_write_status_ptr write_row_fn));
  178949. #ifdef PNG_USER_MEM_SUPPORTED
  178950. /* Replace the default memory allocation functions with user supplied one(s). */
  178951. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  178952. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178953. /* Return the user pointer associated with the memory functions */
  178954. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  178955. #endif
  178956. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178957. defined(PNG_LEGACY_SUPPORTED)
  178958. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  178959. png_ptr, png_user_transform_ptr read_user_transform_fn));
  178960. #endif
  178961. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178962. defined(PNG_LEGACY_SUPPORTED)
  178963. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  178964. png_ptr, png_user_transform_ptr write_user_transform_fn));
  178965. #endif
  178966. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178967. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178968. defined(PNG_LEGACY_SUPPORTED)
  178969. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  178970. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  178971. int user_transform_channels));
  178972. /* Return the user pointer associated with the user transform functions */
  178973. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  178974. PNGARG((png_structp png_ptr));
  178975. #endif
  178976. #ifdef PNG_USER_CHUNKS_SUPPORTED
  178977. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  178978. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  178979. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  178980. png_ptr));
  178981. #endif
  178982. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178983. /* Sets the function callbacks for the push reader, and a pointer to a
  178984. * user-defined structure available to the callback functions.
  178985. */
  178986. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  178987. png_voidp progressive_ptr,
  178988. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  178989. png_progressive_end_ptr end_fn));
  178990. /* returns the user pointer associated with the push read functions */
  178991. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  178992. PNGARG((png_structp png_ptr));
  178993. /* function to be called when data becomes available */
  178994. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  178995. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  178996. /* function that combines rows. Not very much different than the
  178997. * png_combine_row() call. Is this even used?????
  178998. */
  178999. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  179000. png_bytep old_row, png_bytep new_row));
  179001. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179002. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  179003. png_uint_32 size));
  179004. #if defined(PNG_1_0_X)
  179005. # define png_malloc_warn png_malloc
  179006. #else
  179007. /* Added at libpng version 1.2.4 */
  179008. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  179009. png_uint_32 size));
  179010. #endif
  179011. /* frees a pointer allocated by png_malloc() */
  179012. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  179013. #if defined(PNG_1_0_X)
  179014. /* Function to allocate memory for zlib. */
  179015. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  179016. uInt size));
  179017. /* Function to free memory for zlib */
  179018. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  179019. #endif
  179020. /* Free data that was allocated internally */
  179021. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  179022. png_infop info_ptr, png_uint_32 free_me, int num));
  179023. #ifdef PNG_FREE_ME_SUPPORTED
  179024. /* Reassign responsibility for freeing existing data, whether allocated
  179025. * by libpng or by the application */
  179026. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  179027. png_infop info_ptr, int freer, png_uint_32 mask));
  179028. #endif
  179029. /* assignments for png_data_freer */
  179030. #define PNG_DESTROY_WILL_FREE_DATA 1
  179031. #define PNG_SET_WILL_FREE_DATA 1
  179032. #define PNG_USER_WILL_FREE_DATA 2
  179033. /* Flags for png_ptr->free_me and info_ptr->free_me */
  179034. #define PNG_FREE_HIST 0x0008
  179035. #define PNG_FREE_ICCP 0x0010
  179036. #define PNG_FREE_SPLT 0x0020
  179037. #define PNG_FREE_ROWS 0x0040
  179038. #define PNG_FREE_PCAL 0x0080
  179039. #define PNG_FREE_SCAL 0x0100
  179040. #define PNG_FREE_UNKN 0x0200
  179041. #define PNG_FREE_LIST 0x0400
  179042. #define PNG_FREE_PLTE 0x1000
  179043. #define PNG_FREE_TRNS 0x2000
  179044. #define PNG_FREE_TEXT 0x4000
  179045. #define PNG_FREE_ALL 0x7fff
  179046. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  179047. #ifdef PNG_USER_MEM_SUPPORTED
  179048. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  179049. png_uint_32 size));
  179050. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  179051. png_voidp ptr));
  179052. #endif
  179053. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  179054. png_voidp s1, png_voidp s2, png_uint_32 size));
  179055. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  179056. png_voidp s1, int value, png_uint_32 size));
  179057. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  179058. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  179059. int check));
  179060. #endif /* USE_FAR_KEYWORD */
  179061. #ifndef PNG_NO_ERROR_TEXT
  179062. /* Fatal error in PNG image of libpng - can't continue */
  179063. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  179064. png_const_charp error_message));
  179065. /* The same, but the chunk name is prepended to the error string. */
  179066. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  179067. png_const_charp error_message));
  179068. #else
  179069. /* Fatal error in PNG image of libpng - can't continue */
  179070. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  179071. #endif
  179072. #ifndef PNG_NO_WARNINGS
  179073. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  179074. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  179075. png_const_charp warning_message));
  179076. #ifdef PNG_READ_SUPPORTED
  179077. /* Non-fatal error in libpng, chunk name is prepended to message. */
  179078. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  179079. png_const_charp warning_message));
  179080. #endif /* PNG_READ_SUPPORTED */
  179081. #endif /* PNG_NO_WARNINGS */
  179082. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  179083. * Similarly, the png_get_<chunk> calls are used to read values from the
  179084. * png_info_struct, either storing the parameters in the passed variables, or
  179085. * setting pointers into the png_info_struct where the data is stored. The
  179086. * png_get_<chunk> functions return a non-zero value if the data was available
  179087. * in info_ptr, or return zero and do not change any of the parameters if the
  179088. * data was not available.
  179089. *
  179090. * These functions should be used instead of directly accessing png_info
  179091. * to avoid problems with future changes in the size and internal layout of
  179092. * png_info_struct.
  179093. */
  179094. /* Returns "flag" if chunk data is valid in info_ptr. */
  179095. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  179096. png_infop info_ptr, png_uint_32 flag));
  179097. /* Returns number of bytes needed to hold a transformed row. */
  179098. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  179099. png_infop info_ptr));
  179100. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179101. /* Returns row_pointers, which is an array of pointers to scanlines that was
  179102. returned from png_read_png(). */
  179103. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  179104. png_infop info_ptr));
  179105. /* Set row_pointers, which is an array of pointers to scanlines for use
  179106. by png_write_png(). */
  179107. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  179108. png_infop info_ptr, png_bytepp row_pointers));
  179109. #endif
  179110. /* Returns number of color channels in image. */
  179111. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  179112. png_infop info_ptr));
  179113. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179114. /* Returns image width in pixels. */
  179115. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  179116. png_ptr, png_infop info_ptr));
  179117. /* Returns image height in pixels. */
  179118. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  179119. png_ptr, png_infop info_ptr));
  179120. /* Returns image bit_depth. */
  179121. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  179122. png_ptr, png_infop info_ptr));
  179123. /* Returns image color_type. */
  179124. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  179125. png_ptr, png_infop info_ptr));
  179126. /* Returns image filter_type. */
  179127. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  179128. png_ptr, png_infop info_ptr));
  179129. /* Returns image interlace_type. */
  179130. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  179131. png_ptr, png_infop info_ptr));
  179132. /* Returns image compression_type. */
  179133. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  179134. png_ptr, png_infop info_ptr));
  179135. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  179136. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  179137. png_ptr, png_infop info_ptr));
  179138. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  179139. png_ptr, png_infop info_ptr));
  179140. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  179141. png_ptr, png_infop info_ptr));
  179142. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  179143. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179144. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  179145. png_ptr, png_infop info_ptr));
  179146. #endif
  179147. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  179148. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  179149. png_ptr, png_infop info_ptr));
  179150. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  179151. png_ptr, png_infop info_ptr));
  179152. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  179153. png_ptr, png_infop info_ptr));
  179154. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  179155. png_ptr, png_infop info_ptr));
  179156. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179157. /* Returns pointer to signature string read from PNG header */
  179158. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  179159. png_infop info_ptr));
  179160. #if defined(PNG_bKGD_SUPPORTED)
  179161. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  179162. png_infop info_ptr, png_color_16p *background));
  179163. #endif
  179164. #if defined(PNG_bKGD_SUPPORTED)
  179165. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  179166. png_infop info_ptr, png_color_16p background));
  179167. #endif
  179168. #if defined(PNG_cHRM_SUPPORTED)
  179169. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179170. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  179171. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  179172. double *red_y, double *green_x, double *green_y, double *blue_x,
  179173. double *blue_y));
  179174. #endif
  179175. #ifdef PNG_FIXED_POINT_SUPPORTED
  179176. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  179177. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  179178. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  179179. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  179180. *int_blue_x, png_fixed_point *int_blue_y));
  179181. #endif
  179182. #endif
  179183. #if defined(PNG_cHRM_SUPPORTED)
  179184. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179185. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  179186. png_infop info_ptr, double white_x, double white_y, double red_x,
  179187. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  179188. #endif
  179189. #ifdef PNG_FIXED_POINT_SUPPORTED
  179190. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  179191. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  179192. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179193. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179194. png_fixed_point int_blue_y));
  179195. #endif
  179196. #endif
  179197. #if defined(PNG_gAMA_SUPPORTED)
  179198. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179199. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  179200. png_infop info_ptr, double *file_gamma));
  179201. #endif
  179202. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  179203. png_infop info_ptr, png_fixed_point *int_file_gamma));
  179204. #endif
  179205. #if defined(PNG_gAMA_SUPPORTED)
  179206. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179207. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  179208. png_infop info_ptr, double file_gamma));
  179209. #endif
  179210. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  179211. png_infop info_ptr, png_fixed_point int_file_gamma));
  179212. #endif
  179213. #if defined(PNG_hIST_SUPPORTED)
  179214. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  179215. png_infop info_ptr, png_uint_16p *hist));
  179216. #endif
  179217. #if defined(PNG_hIST_SUPPORTED)
  179218. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  179219. png_infop info_ptr, png_uint_16p hist));
  179220. #endif
  179221. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  179222. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  179223. int *bit_depth, int *color_type, int *interlace_method,
  179224. int *compression_method, int *filter_method));
  179225. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  179226. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  179227. int color_type, int interlace_method, int compression_method,
  179228. int filter_method));
  179229. #if defined(PNG_oFFs_SUPPORTED)
  179230. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  179231. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  179232. int *unit_type));
  179233. #endif
  179234. #if defined(PNG_oFFs_SUPPORTED)
  179235. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  179236. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  179237. int unit_type));
  179238. #endif
  179239. #if defined(PNG_pCAL_SUPPORTED)
  179240. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  179241. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  179242. int *type, int *nparams, png_charp *units, png_charpp *params));
  179243. #endif
  179244. #if defined(PNG_pCAL_SUPPORTED)
  179245. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  179246. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  179247. int type, int nparams, png_charp units, png_charpp params));
  179248. #endif
  179249. #if defined(PNG_pHYs_SUPPORTED)
  179250. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  179251. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  179252. #endif
  179253. #if defined(PNG_pHYs_SUPPORTED)
  179254. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  179255. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  179256. #endif
  179257. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  179258. png_infop info_ptr, png_colorp *palette, int *num_palette));
  179259. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  179260. png_infop info_ptr, png_colorp palette, int num_palette));
  179261. #if defined(PNG_sBIT_SUPPORTED)
  179262. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  179263. png_infop info_ptr, png_color_8p *sig_bit));
  179264. #endif
  179265. #if defined(PNG_sBIT_SUPPORTED)
  179266. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  179267. png_infop info_ptr, png_color_8p sig_bit));
  179268. #endif
  179269. #if defined(PNG_sRGB_SUPPORTED)
  179270. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  179271. png_infop info_ptr, int *intent));
  179272. #endif
  179273. #if defined(PNG_sRGB_SUPPORTED)
  179274. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  179275. png_infop info_ptr, int intent));
  179276. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  179277. png_infop info_ptr, int intent));
  179278. #endif
  179279. #if defined(PNG_iCCP_SUPPORTED)
  179280. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  179281. png_infop info_ptr, png_charpp name, int *compression_type,
  179282. png_charpp profile, png_uint_32 *proflen));
  179283. /* Note to maintainer: profile should be png_bytepp */
  179284. #endif
  179285. #if defined(PNG_iCCP_SUPPORTED)
  179286. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  179287. png_infop info_ptr, png_charp name, int compression_type,
  179288. png_charp profile, png_uint_32 proflen));
  179289. /* Note to maintainer: profile should be png_bytep */
  179290. #endif
  179291. #if defined(PNG_sPLT_SUPPORTED)
  179292. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  179293. png_infop info_ptr, png_sPLT_tpp entries));
  179294. #endif
  179295. #if defined(PNG_sPLT_SUPPORTED)
  179296. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  179297. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  179298. #endif
  179299. #if defined(PNG_TEXT_SUPPORTED)
  179300. /* png_get_text also returns the number of text chunks in *num_text */
  179301. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  179302. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  179303. #endif
  179304. /*
  179305. * Note while png_set_text() will accept a structure whose text,
  179306. * language, and translated keywords are NULL pointers, the structure
  179307. * returned by png_get_text will always contain regular
  179308. * zero-terminated C strings. They might be empty strings but
  179309. * they will never be NULL pointers.
  179310. */
  179311. #if defined(PNG_TEXT_SUPPORTED)
  179312. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  179313. png_infop info_ptr, png_textp text_ptr, int num_text));
  179314. #endif
  179315. #if defined(PNG_tIME_SUPPORTED)
  179316. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  179317. png_infop info_ptr, png_timep *mod_time));
  179318. #endif
  179319. #if defined(PNG_tIME_SUPPORTED)
  179320. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  179321. png_infop info_ptr, png_timep mod_time));
  179322. #endif
  179323. #if defined(PNG_tRNS_SUPPORTED)
  179324. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  179325. png_infop info_ptr, png_bytep *trans, int *num_trans,
  179326. png_color_16p *trans_values));
  179327. #endif
  179328. #if defined(PNG_tRNS_SUPPORTED)
  179329. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  179330. png_infop info_ptr, png_bytep trans, int num_trans,
  179331. png_color_16p trans_values));
  179332. #endif
  179333. #if defined(PNG_tRNS_SUPPORTED)
  179334. #endif
  179335. #if defined(PNG_sCAL_SUPPORTED)
  179336. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179337. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  179338. png_infop info_ptr, int *unit, double *width, double *height));
  179339. #else
  179340. #ifdef PNG_FIXED_POINT_SUPPORTED
  179341. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  179342. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  179343. #endif
  179344. #endif
  179345. #endif /* PNG_sCAL_SUPPORTED */
  179346. #if defined(PNG_sCAL_SUPPORTED)
  179347. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179348. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  179349. png_infop info_ptr, int unit, double width, double height));
  179350. #else
  179351. #ifdef PNG_FIXED_POINT_SUPPORTED
  179352. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  179353. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  179354. #endif
  179355. #endif
  179356. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  179357. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179358. /* provide a list of chunks and how they are to be handled, if the built-in
  179359. handling or default unknown chunk handling is not desired. Any chunks not
  179360. listed will be handled in the default manner. The IHDR and IEND chunks
  179361. must not be listed.
  179362. keep = 0: follow default behaviour
  179363. = 1: do not keep
  179364. = 2: keep only if safe-to-copy
  179365. = 3: keep even if unsafe-to-copy
  179366. */
  179367. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  179368. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  179369. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  179370. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  179371. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  179372. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  179373. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  179374. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  179375. #endif
  179376. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179377. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  179378. chunk_name));
  179379. #endif
  179380. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  179381. If you need to turn it off for a chunk that your application has freed,
  179382. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  179383. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  179384. png_infop info_ptr, int mask));
  179385. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179386. /* The "params" pointer is currently not used and is for future expansion. */
  179387. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  179388. png_infop info_ptr,
  179389. int transforms,
  179390. png_voidp params));
  179391. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  179392. png_infop info_ptr,
  179393. int transforms,
  179394. png_voidp params));
  179395. #endif
  179396. /* Define PNG_DEBUG at compile time for debugging information. Higher
  179397. * numbers for PNG_DEBUG mean more debugging information. This has
  179398. * only been added since version 0.95 so it is not implemented throughout
  179399. * libpng yet, but more support will be added as needed.
  179400. */
  179401. #ifdef PNG_DEBUG
  179402. #if (PNG_DEBUG > 0)
  179403. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  179404. #include <crtdbg.h>
  179405. #if (PNG_DEBUG > 1)
  179406. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  179407. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  179408. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  179409. #endif
  179410. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  179411. #ifndef PNG_DEBUG_FILE
  179412. #define PNG_DEBUG_FILE stderr
  179413. #endif /* PNG_DEBUG_FILE */
  179414. #if (PNG_DEBUG > 1)
  179415. #define png_debug(l,m) \
  179416. { \
  179417. int num_tabs=l; \
  179418. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179419. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  179420. }
  179421. #define png_debug1(l,m,p1) \
  179422. { \
  179423. int num_tabs=l; \
  179424. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179425. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  179426. }
  179427. #define png_debug2(l,m,p1,p2) \
  179428. { \
  179429. int num_tabs=l; \
  179430. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179431. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  179432. }
  179433. #endif /* (PNG_DEBUG > 1) */
  179434. #endif /* _MSC_VER */
  179435. #endif /* (PNG_DEBUG > 0) */
  179436. #endif /* PNG_DEBUG */
  179437. #ifndef png_debug
  179438. #define png_debug(l, m)
  179439. #endif
  179440. #ifndef png_debug1
  179441. #define png_debug1(l, m, p1)
  179442. #endif
  179443. #ifndef png_debug2
  179444. #define png_debug2(l, m, p1, p2)
  179445. #endif
  179446. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  179447. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  179448. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  179449. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  179450. #ifdef PNG_MNG_FEATURES_SUPPORTED
  179451. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  179452. png_ptr, png_uint_32 mng_features_permitted));
  179453. #endif
  179454. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  179455. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  179456. #define PNG_HANDLE_CHUNK_NEVER 1
  179457. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  179458. #define PNG_HANDLE_CHUNK_ALWAYS 3
  179459. /* Added to version 1.2.0 */
  179460. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179461. #if defined(PNG_MMX_CODE_SUPPORTED)
  179462. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  179463. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  179464. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  179465. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  179466. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  179467. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  179468. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  179469. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  179470. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  179471. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  179472. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  179473. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  179474. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  179475. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  179476. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  179477. #define PNG_MMX_WRITE_FLAGS ( 0 )
  179478. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  179479. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  179480. | PNG_MMX_READ_FLAGS \
  179481. | PNG_MMX_WRITE_FLAGS )
  179482. #define PNG_SELECT_READ 1
  179483. #define PNG_SELECT_WRITE 2
  179484. #endif /* PNG_MMX_CODE_SUPPORTED */
  179485. #if !defined(PNG_1_0_X)
  179486. /* pngget.c */
  179487. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  179488. PNGARG((int flag_select, int *compilerID));
  179489. /* pngget.c */
  179490. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  179491. PNGARG((int flag_select));
  179492. /* pngget.c */
  179493. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  179494. PNGARG((png_structp png_ptr));
  179495. /* pngget.c */
  179496. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  179497. PNGARG((png_structp png_ptr));
  179498. /* pngget.c */
  179499. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  179500. PNGARG((png_structp png_ptr));
  179501. /* pngset.c */
  179502. extern PNG_EXPORT(void,png_set_asm_flags)
  179503. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  179504. /* pngset.c */
  179505. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  179506. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  179507. png_uint_32 mmx_rowbytes_threshold));
  179508. #endif /* PNG_1_0_X */
  179509. #if !defined(PNG_1_0_X)
  179510. /* png.c, pnggccrd.c, or pngvcrd.c */
  179511. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  179512. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  179513. /* Strip the prepended error numbers ("#nnn ") from error and warning
  179514. * messages before passing them to the error or warning handler. */
  179515. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179516. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  179517. png_ptr, png_uint_32 strip_mode));
  179518. #endif
  179519. #endif /* PNG_1_0_X */
  179520. /* Added at libpng-1.2.6 */
  179521. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179522. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  179523. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  179524. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  179525. png_ptr));
  179526. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  179527. png_ptr));
  179528. #endif
  179529. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  179530. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  179531. /* With these routines we avoid an integer divide, which will be slower on
  179532. * most machines. However, it does take more operations than the corresponding
  179533. * divide method, so it may be slower on a few RISC systems. There are two
  179534. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  179535. *
  179536. * Note that the rounding factors are NOT supposed to be the same! 128 and
  179537. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  179538. * standard method.
  179539. *
  179540. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  179541. */
  179542. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  179543. # define png_composite(composite, fg, alpha, bg) \
  179544. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  179545. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  179546. (png_uint_16)(alpha)) + (png_uint_16)128); \
  179547. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  179548. # define png_composite_16(composite, fg, alpha, bg) \
  179549. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  179550. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  179551. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  179552. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  179553. #else /* standard method using integer division */
  179554. # define png_composite(composite, fg, alpha, bg) \
  179555. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  179556. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  179557. (png_uint_16)127) / 255)
  179558. # define png_composite_16(composite, fg, alpha, bg) \
  179559. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  179560. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  179561. (png_uint_32)32767) / (png_uint_32)65535L)
  179562. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  179563. /* Inline macros to do direct reads of bytes from the input buffer. These
  179564. * require that you are using an architecture that uses PNG byte ordering
  179565. * (MSB first) and supports unaligned data storage. I think that PowerPC
  179566. * in big-endian mode and 680x0 are the only ones that will support this.
  179567. * The x86 line of processors definitely do not. The png_get_int_32()
  179568. * routine also assumes we are using two's complement format for negative
  179569. * values, which is almost certainly true.
  179570. */
  179571. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  179572. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  179573. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  179574. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  179575. #else
  179576. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  179577. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  179578. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  179579. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  179580. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  179581. PNGARG((png_structp png_ptr, png_bytep buf));
  179582. /* No png_get_int_16 -- may be added if there's a real need for it. */
  179583. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  179584. */
  179585. extern PNG_EXPORT(void,png_save_uint_32)
  179586. PNGARG((png_bytep buf, png_uint_32 i));
  179587. extern PNG_EXPORT(void,png_save_int_32)
  179588. PNGARG((png_bytep buf, png_int_32 i));
  179589. /* Place a 16-bit number into a buffer in PNG byte order.
  179590. * The parameter is declared unsigned int, not png_uint_16,
  179591. * just to avoid potential problems on pre-ANSI C compilers.
  179592. */
  179593. extern PNG_EXPORT(void,png_save_uint_16)
  179594. PNGARG((png_bytep buf, unsigned int i));
  179595. /* No png_save_int_16 -- may be added if there's a real need for it. */
  179596. /* ************************************************************************* */
  179597. /* These next functions are used internally in the code. They generally
  179598. * shouldn't be used unless you are writing code to add or replace some
  179599. * functionality in libpng. More information about most functions can
  179600. * be found in the files where the functions are located.
  179601. */
  179602. /* Various modes of operation, that are visible to applications because
  179603. * they are used for unknown chunk location.
  179604. */
  179605. #define PNG_HAVE_IHDR 0x01
  179606. #define PNG_HAVE_PLTE 0x02
  179607. #define PNG_HAVE_IDAT 0x04
  179608. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  179609. #define PNG_HAVE_IEND 0x10
  179610. #if defined(PNG_INTERNAL)
  179611. /* More modes of operation. Note that after an init, mode is set to
  179612. * zero automatically when the structure is created.
  179613. */
  179614. #define PNG_HAVE_gAMA 0x20
  179615. #define PNG_HAVE_cHRM 0x40
  179616. #define PNG_HAVE_sRGB 0x80
  179617. #define PNG_HAVE_CHUNK_HEADER 0x100
  179618. #define PNG_WROTE_tIME 0x200
  179619. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  179620. #define PNG_BACKGROUND_IS_GRAY 0x800
  179621. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  179622. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  179623. /* flags for the transformations the PNG library does on the image data */
  179624. #define PNG_BGR 0x0001
  179625. #define PNG_INTERLACE 0x0002
  179626. #define PNG_PACK 0x0004
  179627. #define PNG_SHIFT 0x0008
  179628. #define PNG_SWAP_BYTES 0x0010
  179629. #define PNG_INVERT_MONO 0x0020
  179630. #define PNG_DITHER 0x0040
  179631. #define PNG_BACKGROUND 0x0080
  179632. #define PNG_BACKGROUND_EXPAND 0x0100
  179633. /* 0x0200 unused */
  179634. #define PNG_16_TO_8 0x0400
  179635. #define PNG_RGBA 0x0800
  179636. #define PNG_EXPAND 0x1000
  179637. #define PNG_GAMMA 0x2000
  179638. #define PNG_GRAY_TO_RGB 0x4000
  179639. #define PNG_FILLER 0x8000L
  179640. #define PNG_PACKSWAP 0x10000L
  179641. #define PNG_SWAP_ALPHA 0x20000L
  179642. #define PNG_STRIP_ALPHA 0x40000L
  179643. #define PNG_INVERT_ALPHA 0x80000L
  179644. #define PNG_USER_TRANSFORM 0x100000L
  179645. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  179646. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  179647. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  179648. /* 0x800000L Unused */
  179649. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  179650. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  179651. /* 0x4000000L unused */
  179652. /* 0x8000000L unused */
  179653. /* 0x10000000L unused */
  179654. /* 0x20000000L unused */
  179655. /* 0x40000000L unused */
  179656. /* flags for png_create_struct */
  179657. #define PNG_STRUCT_PNG 0x0001
  179658. #define PNG_STRUCT_INFO 0x0002
  179659. /* Scaling factor for filter heuristic weighting calculations */
  179660. #define PNG_WEIGHT_SHIFT 8
  179661. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  179662. #define PNG_COST_SHIFT 3
  179663. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  179664. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  179665. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  179666. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  179667. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  179668. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  179669. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  179670. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  179671. #define PNG_FLAG_ROW_INIT 0x0040
  179672. #define PNG_FLAG_FILLER_AFTER 0x0080
  179673. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  179674. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  179675. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  179676. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  179677. #define PNG_FLAG_FREE_PLTE 0x1000
  179678. #define PNG_FLAG_FREE_TRNS 0x2000
  179679. #define PNG_FLAG_FREE_HIST 0x4000
  179680. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  179681. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  179682. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  179683. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  179684. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  179685. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  179686. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  179687. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  179688. /* 0x800000L unused */
  179689. /* 0x1000000L unused */
  179690. /* 0x2000000L unused */
  179691. /* 0x4000000L unused */
  179692. /* 0x8000000L unused */
  179693. /* 0x10000000L unused */
  179694. /* 0x20000000L unused */
  179695. /* 0x40000000L unused */
  179696. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  179697. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  179698. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  179699. PNG_FLAG_CRC_CRITICAL_IGNORE)
  179700. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  179701. PNG_FLAG_CRC_CRITICAL_MASK)
  179702. /* save typing and make code easier to understand */
  179703. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  179704. abs((int)((c1).green) - (int)((c2).green)) + \
  179705. abs((int)((c1).blue) - (int)((c2).blue)))
  179706. /* Added to libpng-1.2.6 JB */
  179707. #define PNG_ROWBYTES(pixel_bits, width) \
  179708. ((pixel_bits) >= 8 ? \
  179709. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  179710. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  179711. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  179712. ideal-delta..ideal+delta. Each argument is evaluated twice.
  179713. "ideal" and "delta" should be constants, normally simple
  179714. integers, "value" a variable. Added to libpng-1.2.6 JB */
  179715. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  179716. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  179717. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179718. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179719. /* place to hold the signature string for a PNG file. */
  179720. #ifdef PNG_USE_GLOBAL_ARRAYS
  179721. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  179722. #else
  179723. #endif
  179724. #endif /* PNG_NO_EXTERN */
  179725. /* Constant strings for known chunk types. If you need to add a chunk,
  179726. * define the name here, and add an invocation of the macro in png.c and
  179727. * wherever it's needed.
  179728. */
  179729. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  179730. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  179731. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  179732. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  179733. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  179734. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  179735. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  179736. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  179737. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  179738. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  179739. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  179740. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  179741. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  179742. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  179743. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  179744. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  179745. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  179746. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  179747. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  179748. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  179749. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  179750. #ifdef PNG_USE_GLOBAL_ARRAYS
  179751. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  179752. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  179753. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  179754. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  179755. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  179756. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  179757. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  179758. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  179759. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  179760. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  179761. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  179762. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  179763. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  179764. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  179765. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  179766. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  179767. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  179768. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  179769. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  179770. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  179771. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  179772. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179773. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179774. /* Initialize png_ptr struct for reading, and allocate any other memory.
  179775. * (old interface - DEPRECATED - use png_create_read_struct instead).
  179776. */
  179777. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  179778. #undef png_read_init
  179779. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  179780. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179781. #endif
  179782. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  179783. png_const_charp user_png_ver, png_size_t png_struct_size));
  179784. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179785. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  179786. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179787. png_info_size));
  179788. #endif
  179789. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179790. /* Initialize png_ptr struct for writing, and allocate any other memory.
  179791. * (old interface - DEPRECATED - use png_create_write_struct instead).
  179792. */
  179793. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  179794. #undef png_write_init
  179795. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  179796. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179797. #endif
  179798. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  179799. png_const_charp user_png_ver, png_size_t png_struct_size));
  179800. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  179801. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179802. png_info_size));
  179803. /* Allocate memory for an internal libpng struct */
  179804. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  179805. /* Free memory from internal libpng struct */
  179806. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  179807. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  179808. malloc_fn, png_voidp mem_ptr));
  179809. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  179810. png_free_ptr free_fn, png_voidp mem_ptr));
  179811. /* Free any memory that info_ptr points to and reset struct. */
  179812. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  179813. png_infop info_ptr));
  179814. #ifndef PNG_1_0_X
  179815. /* Function to allocate memory for zlib. */
  179816. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  179817. /* Function to free memory for zlib */
  179818. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  179819. #ifdef PNG_SIZE_T
  179820. /* Function to convert a sizeof an item to png_sizeof item */
  179821. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179822. #endif
  179823. /* Next four functions are used internally as callbacks. PNGAPI is required
  179824. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  179825. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  179826. png_bytep data, png_size_t length));
  179827. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179828. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  179829. png_bytep buffer, png_size_t length));
  179830. #endif
  179831. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  179832. png_bytep data, png_size_t length));
  179833. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179834. #if !defined(PNG_NO_STDIO)
  179835. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  179836. #endif
  179837. #endif
  179838. #else /* PNG_1_0_X */
  179839. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179840. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  179841. png_bytep buffer, png_size_t length));
  179842. #endif
  179843. #endif /* PNG_1_0_X */
  179844. /* Reset the CRC variable */
  179845. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  179846. /* Write the "data" buffer to whatever output you are using. */
  179847. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  179848. png_size_t length));
  179849. /* Read data from whatever input you are using into the "data" buffer */
  179850. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  179851. png_size_t length));
  179852. /* Read bytes into buf, and update png_ptr->crc */
  179853. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  179854. png_size_t length));
  179855. /* Decompress data in a chunk that uses compression */
  179856. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  179857. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  179858. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  179859. int comp_type, png_charp chunkdata, png_size_t chunklength,
  179860. png_size_t prefix_length, png_size_t *data_length));
  179861. #endif
  179862. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  179863. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  179864. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  179865. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  179866. /* Calculate the CRC over a section of data. Note that we are only
  179867. * passing a maximum of 64K on systems that have this as a memory limit,
  179868. * since this is the maximum buffer size we can specify.
  179869. */
  179870. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  179871. png_size_t length));
  179872. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179873. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  179874. #endif
  179875. /* simple function to write the signature */
  179876. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  179877. /* write various chunks */
  179878. /* Write the IHDR chunk, and update the png_struct with the necessary
  179879. * information.
  179880. */
  179881. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  179882. png_uint_32 height,
  179883. int bit_depth, int color_type, int compression_method, int filter_method,
  179884. int interlace_method));
  179885. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  179886. png_uint_32 num_pal));
  179887. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  179888. png_size_t length));
  179889. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  179890. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  179891. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179892. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  179893. #endif
  179894. #ifdef PNG_FIXED_POINT_SUPPORTED
  179895. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  179896. file_gamma));
  179897. #endif
  179898. #endif
  179899. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  179900. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  179901. int color_type));
  179902. #endif
  179903. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  179904. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179905. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  179906. double white_x, double white_y,
  179907. double red_x, double red_y, double green_x, double green_y,
  179908. double blue_x, double blue_y));
  179909. #endif
  179910. #ifdef PNG_FIXED_POINT_SUPPORTED
  179911. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  179912. png_fixed_point int_white_x, png_fixed_point int_white_y,
  179913. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179914. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179915. png_fixed_point int_blue_y));
  179916. #endif
  179917. #endif
  179918. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  179919. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  179920. int intent));
  179921. #endif
  179922. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  179923. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  179924. png_charp name, int compression_type,
  179925. png_charp profile, int proflen));
  179926. /* Note to maintainer: profile should be png_bytep */
  179927. #endif
  179928. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  179929. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  179930. png_sPLT_tp palette));
  179931. #endif
  179932. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  179933. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  179934. png_color_16p values, int number, int color_type));
  179935. #endif
  179936. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  179937. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  179938. png_color_16p values, int color_type));
  179939. #endif
  179940. #if defined(PNG_WRITE_hIST_SUPPORTED)
  179941. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  179942. int num_hist));
  179943. #endif
  179944. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  179945. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  179946. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  179947. png_charp key, png_charpp new_key));
  179948. #endif
  179949. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  179950. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  179951. png_charp text, png_size_t text_len));
  179952. #endif
  179953. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  179954. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  179955. png_charp text, png_size_t text_len, int compression));
  179956. #endif
  179957. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  179958. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  179959. int compression, png_charp key, png_charp lang, png_charp lang_key,
  179960. png_charp text));
  179961. #endif
  179962. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  179963. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  179964. png_infop info_ptr, png_textp text_ptr, int num_text));
  179965. #endif
  179966. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  179967. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  179968. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  179969. #endif
  179970. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  179971. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  179972. png_int_32 X0, png_int_32 X1, int type, int nparams,
  179973. png_charp units, png_charpp params));
  179974. #endif
  179975. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  179976. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  179977. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  179978. int unit_type));
  179979. #endif
  179980. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179981. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  179982. png_timep mod_time));
  179983. #endif
  179984. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  179985. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  179986. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  179987. int unit, double width, double height));
  179988. #else
  179989. #ifdef PNG_FIXED_POINT_SUPPORTED
  179990. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  179991. int unit, png_charp width, png_charp height));
  179992. #endif
  179993. #endif
  179994. #endif
  179995. /* Called when finished processing a row of data */
  179996. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  179997. /* Internal use only. Called before first row of data */
  179998. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  179999. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180000. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  180001. #endif
  180002. /* combine a row of data, dealing with alpha, etc. if requested */
  180003. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  180004. int mask));
  180005. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  180006. /* expand an interlaced row */
  180007. /* OLD pre-1.0.9 interface:
  180008. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  180009. png_bytep row, int pass, png_uint_32 transformations));
  180010. */
  180011. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  180012. #endif
  180013. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  180014. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180015. /* grab pixels out of a row for an interlaced pass */
  180016. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  180017. png_bytep row, int pass));
  180018. #endif
  180019. /* unfilter a row */
  180020. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  180021. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  180022. /* Choose the best filter to use and filter the row data */
  180023. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  180024. png_row_infop row_info));
  180025. /* Write out the filtered row. */
  180026. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  180027. png_bytep filtered_row));
  180028. /* finish a row while reading, dealing with interlacing passes, etc. */
  180029. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  180030. /* initialize the row buffers, etc. */
  180031. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  180032. /* optional call to update the users info structure */
  180033. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  180034. png_infop info_ptr));
  180035. /* these are the functions that do the transformations */
  180036. #if defined(PNG_READ_FILLER_SUPPORTED)
  180037. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  180038. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  180039. #endif
  180040. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  180041. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  180042. png_bytep row));
  180043. #endif
  180044. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  180045. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  180046. png_bytep row));
  180047. #endif
  180048. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  180049. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  180050. png_bytep row));
  180051. #endif
  180052. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  180053. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  180054. png_bytep row));
  180055. #endif
  180056. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  180057. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  180058. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  180059. png_bytep row, png_uint_32 flags));
  180060. #endif
  180061. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  180062. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  180063. #endif
  180064. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  180065. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  180066. #endif
  180067. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180068. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  180069. row_info, png_bytep row));
  180070. #endif
  180071. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  180072. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  180073. png_bytep row));
  180074. #endif
  180075. #if defined(PNG_READ_PACK_SUPPORTED)
  180076. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  180077. #endif
  180078. #if defined(PNG_READ_SHIFT_SUPPORTED)
  180079. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  180080. png_color_8p sig_bits));
  180081. #endif
  180082. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  180083. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  180084. #endif
  180085. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  180086. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  180087. #endif
  180088. #if defined(PNG_READ_DITHER_SUPPORTED)
  180089. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  180090. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  180091. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  180092. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  180093. png_colorp palette, int num_palette));
  180094. # endif
  180095. #endif
  180096. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  180097. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  180098. #endif
  180099. #if defined(PNG_WRITE_PACK_SUPPORTED)
  180100. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  180101. png_bytep row, png_uint_32 bit_depth));
  180102. #endif
  180103. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  180104. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  180105. png_color_8p bit_depth));
  180106. #endif
  180107. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  180108. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180109. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180110. png_color_16p trans_values, png_color_16p background,
  180111. png_color_16p background_1,
  180112. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  180113. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  180114. png_uint_16pp gamma_16_to_1, int gamma_shift));
  180115. #else
  180116. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180117. png_color_16p trans_values, png_color_16p background));
  180118. #endif
  180119. #endif
  180120. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180121. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  180122. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  180123. int gamma_shift));
  180124. #endif
  180125. #if defined(PNG_READ_EXPAND_SUPPORTED)
  180126. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  180127. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  180128. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  180129. png_bytep row, png_color_16p trans_value));
  180130. #endif
  180131. /* The following decodes the appropriate chunks, and does error correction,
  180132. * then calls the appropriate callback for the chunk if it is valid.
  180133. */
  180134. /* decode the IHDR chunk */
  180135. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  180136. png_uint_32 length));
  180137. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  180138. png_uint_32 length));
  180139. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  180140. png_uint_32 length));
  180141. #if defined(PNG_READ_bKGD_SUPPORTED)
  180142. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  180143. png_uint_32 length));
  180144. #endif
  180145. #if defined(PNG_READ_cHRM_SUPPORTED)
  180146. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  180147. png_uint_32 length));
  180148. #endif
  180149. #if defined(PNG_READ_gAMA_SUPPORTED)
  180150. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  180151. png_uint_32 length));
  180152. #endif
  180153. #if defined(PNG_READ_hIST_SUPPORTED)
  180154. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  180155. png_uint_32 length));
  180156. #endif
  180157. #if defined(PNG_READ_iCCP_SUPPORTED)
  180158. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  180159. png_uint_32 length));
  180160. #endif /* PNG_READ_iCCP_SUPPORTED */
  180161. #if defined(PNG_READ_iTXt_SUPPORTED)
  180162. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180163. png_uint_32 length));
  180164. #endif
  180165. #if defined(PNG_READ_oFFs_SUPPORTED)
  180166. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180167. png_uint_32 length));
  180168. #endif
  180169. #if defined(PNG_READ_pCAL_SUPPORTED)
  180170. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180171. png_uint_32 length));
  180172. #endif
  180173. #if defined(PNG_READ_pHYs_SUPPORTED)
  180174. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180175. png_uint_32 length));
  180176. #endif
  180177. #if defined(PNG_READ_sBIT_SUPPORTED)
  180178. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180179. png_uint_32 length));
  180180. #endif
  180181. #if defined(PNG_READ_sCAL_SUPPORTED)
  180182. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180183. png_uint_32 length));
  180184. #endif
  180185. #if defined(PNG_READ_sPLT_SUPPORTED)
  180186. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180187. png_uint_32 length));
  180188. #endif /* PNG_READ_sPLT_SUPPORTED */
  180189. #if defined(PNG_READ_sRGB_SUPPORTED)
  180190. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  180191. png_uint_32 length));
  180192. #endif
  180193. #if defined(PNG_READ_tEXt_SUPPORTED)
  180194. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180195. png_uint_32 length));
  180196. #endif
  180197. #if defined(PNG_READ_tIME_SUPPORTED)
  180198. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  180199. png_uint_32 length));
  180200. #endif
  180201. #if defined(PNG_READ_tRNS_SUPPORTED)
  180202. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  180203. png_uint_32 length));
  180204. #endif
  180205. #if defined(PNG_READ_zTXt_SUPPORTED)
  180206. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180207. png_uint_32 length));
  180208. #endif
  180209. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  180210. png_infop info_ptr, png_uint_32 length));
  180211. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  180212. png_bytep chunk_name));
  180213. /* handle the transformations for reading and writing */
  180214. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  180215. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  180216. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  180217. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180218. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  180219. png_infop info_ptr));
  180220. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  180221. png_infop info_ptr));
  180222. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  180223. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  180224. png_uint_32 length));
  180225. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  180226. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  180227. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  180228. png_bytep buffer, png_size_t buffer_length));
  180229. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  180230. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  180231. png_bytep buffer, png_size_t buffer_length));
  180232. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  180233. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  180234. png_infop info_ptr, png_uint_32 length));
  180235. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  180236. png_infop info_ptr));
  180237. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  180238. png_infop info_ptr));
  180239. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  180240. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  180241. png_infop info_ptr));
  180242. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  180243. png_infop info_ptr));
  180244. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  180245. #if defined(PNG_READ_tEXt_SUPPORTED)
  180246. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  180247. png_infop info_ptr, png_uint_32 length));
  180248. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  180249. png_infop info_ptr));
  180250. #endif
  180251. #if defined(PNG_READ_zTXt_SUPPORTED)
  180252. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  180253. png_infop info_ptr, png_uint_32 length));
  180254. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  180255. png_infop info_ptr));
  180256. #endif
  180257. #if defined(PNG_READ_iTXt_SUPPORTED)
  180258. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  180259. png_infop info_ptr, png_uint_32 length));
  180260. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  180261. png_infop info_ptr));
  180262. #endif
  180263. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  180264. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180265. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  180266. png_bytep row));
  180267. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  180268. png_bytep row));
  180269. #endif
  180270. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180271. #if defined(PNG_MMX_CODE_SUPPORTED)
  180272. /* png.c */ /* PRIVATE */
  180273. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  180274. #endif
  180275. #endif
  180276. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  180277. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  180278. png_infop info_ptr));
  180279. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  180280. png_infop info_ptr));
  180281. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  180282. png_infop info_ptr));
  180283. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  180284. png_infop info_ptr));
  180285. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  180286. png_infop info_ptr));
  180287. #if defined(PNG_pHYs_SUPPORTED)
  180288. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  180289. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180290. #endif /* PNG_pHYs_SUPPORTED */
  180291. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180292. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  180293. #endif /* PNG_INTERNAL */
  180294. #ifdef __cplusplus
  180295. }
  180296. #endif
  180297. #endif /* PNG_VERSION_INFO_ONLY */
  180298. /* do not put anything past this line */
  180299. #endif /* PNG_H */
  180300. /********* End of inlined file: png.h *********/
  180301. #define PNG_NO_EXTERN
  180302. /********* Start of inlined file: png.c *********/
  180303. /* png.c - location for general purpose libpng functions
  180304. *
  180305. * Last changed in libpng 1.2.21 [October 4, 2007]
  180306. * For conditions of distribution and use, see copyright notice in png.h
  180307. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180308. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180309. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180310. */
  180311. #define PNG_INTERNAL
  180312. #define PNG_NO_EXTERN
  180313. /* Generate a compiler error if there is an old png.h in the search path. */
  180314. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  180315. /* Version information for C files. This had better match the version
  180316. * string defined in png.h. */
  180317. #ifdef PNG_USE_GLOBAL_ARRAYS
  180318. /* png_libpng_ver was changed to a function in version 1.0.5c */
  180319. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  180320. #ifdef PNG_READ_SUPPORTED
  180321. /* png_sig was changed to a function in version 1.0.5c */
  180322. /* Place to hold the signature string for a PNG file. */
  180323. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180324. #endif /* PNG_READ_SUPPORTED */
  180325. /* Invoke global declarations for constant strings for known chunk types */
  180326. PNG_IHDR;
  180327. PNG_IDAT;
  180328. PNG_IEND;
  180329. PNG_PLTE;
  180330. PNG_bKGD;
  180331. PNG_cHRM;
  180332. PNG_gAMA;
  180333. PNG_hIST;
  180334. PNG_iCCP;
  180335. PNG_iTXt;
  180336. PNG_oFFs;
  180337. PNG_pCAL;
  180338. PNG_sCAL;
  180339. PNG_pHYs;
  180340. PNG_sBIT;
  180341. PNG_sPLT;
  180342. PNG_sRGB;
  180343. PNG_tEXt;
  180344. PNG_tIME;
  180345. PNG_tRNS;
  180346. PNG_zTXt;
  180347. #ifdef PNG_READ_SUPPORTED
  180348. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  180349. /* start of interlace block */
  180350. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  180351. /* offset to next interlace block */
  180352. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  180353. /* start of interlace block in the y direction */
  180354. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  180355. /* offset to next interlace block in the y direction */
  180356. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  180357. /* Height of interlace block. This is not currently used - if you need
  180358. * it, uncomment it here and in png.h
  180359. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  180360. */
  180361. /* Mask to determine which pixels are valid in a pass */
  180362. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  180363. /* Mask to determine which pixels to overwrite while displaying */
  180364. PNG_CONST int FARDATA png_pass_dsp_mask[]
  180365. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  180366. #endif /* PNG_READ_SUPPORTED */
  180367. #endif /* PNG_USE_GLOBAL_ARRAYS */
  180368. /* Tells libpng that we have already handled the first "num_bytes" bytes
  180369. * of the PNG file signature. If the PNG data is embedded into another
  180370. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  180371. * or write any of the magic bytes before it starts on the IHDR.
  180372. */
  180373. #ifdef PNG_READ_SUPPORTED
  180374. void PNGAPI
  180375. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  180376. {
  180377. if(png_ptr == NULL) return;
  180378. png_debug(1, "in png_set_sig_bytes\n");
  180379. if (num_bytes > 8)
  180380. png_error(png_ptr, "Too many bytes for PNG signature.");
  180381. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  180382. }
  180383. /* Checks whether the supplied bytes match the PNG signature. We allow
  180384. * checking less than the full 8-byte signature so that those apps that
  180385. * already read the first few bytes of a file to determine the file type
  180386. * can simply check the remaining bytes for extra assurance. Returns
  180387. * an integer less than, equal to, or greater than zero if sig is found,
  180388. * respectively, to be less than, to match, or be greater than the correct
  180389. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  180390. */
  180391. int PNGAPI
  180392. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  180393. {
  180394. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180395. if (num_to_check > 8)
  180396. num_to_check = 8;
  180397. else if (num_to_check < 1)
  180398. return (-1);
  180399. if (start > 7)
  180400. return (-1);
  180401. if (start + num_to_check > 8)
  180402. num_to_check = 8 - start;
  180403. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  180404. }
  180405. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180406. /* (Obsolete) function to check signature bytes. It does not allow one
  180407. * to check a partial signature. This function might be removed in the
  180408. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  180409. */
  180410. int PNGAPI
  180411. png_check_sig(png_bytep sig, int num)
  180412. {
  180413. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  180414. }
  180415. #endif
  180416. #endif /* PNG_READ_SUPPORTED */
  180417. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180418. /* Function to allocate memory for zlib and clear it to 0. */
  180419. #ifdef PNG_1_0_X
  180420. voidpf PNGAPI
  180421. #else
  180422. voidpf /* private */
  180423. #endif
  180424. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  180425. {
  180426. png_voidp ptr;
  180427. png_structp p=(png_structp)png_ptr;
  180428. png_uint_32 save_flags=p->flags;
  180429. png_uint_32 num_bytes;
  180430. if(png_ptr == NULL) return (NULL);
  180431. if (items > PNG_UINT_32_MAX/size)
  180432. {
  180433. png_warning (p, "Potential overflow in png_zalloc()");
  180434. return (NULL);
  180435. }
  180436. num_bytes = (png_uint_32)items * size;
  180437. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180438. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  180439. p->flags=save_flags;
  180440. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  180441. if (ptr == NULL)
  180442. return ((voidpf)ptr);
  180443. if (num_bytes > (png_uint_32)0x8000L)
  180444. {
  180445. png_memset(ptr, 0, (png_size_t)0x8000L);
  180446. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  180447. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  180448. }
  180449. else
  180450. {
  180451. png_memset(ptr, 0, (png_size_t)num_bytes);
  180452. }
  180453. #endif
  180454. return ((voidpf)ptr);
  180455. }
  180456. /* function to free memory for zlib */
  180457. #ifdef PNG_1_0_X
  180458. void PNGAPI
  180459. #else
  180460. void /* private */
  180461. #endif
  180462. png_zfree(voidpf png_ptr, voidpf ptr)
  180463. {
  180464. png_free((png_structp)png_ptr, (png_voidp)ptr);
  180465. }
  180466. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  180467. * in case CRC is > 32 bits to leave the top bits 0.
  180468. */
  180469. void /* PRIVATE */
  180470. png_reset_crc(png_structp png_ptr)
  180471. {
  180472. png_ptr->crc = crc32(0, Z_NULL, 0);
  180473. }
  180474. /* Calculate the CRC over a section of data. We can only pass as
  180475. * much data to this routine as the largest single buffer size. We
  180476. * also check that this data will actually be used before going to the
  180477. * trouble of calculating it.
  180478. */
  180479. void /* PRIVATE */
  180480. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  180481. {
  180482. int need_crc = 1;
  180483. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  180484. {
  180485. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  180486. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  180487. need_crc = 0;
  180488. }
  180489. else /* critical */
  180490. {
  180491. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  180492. need_crc = 0;
  180493. }
  180494. if (need_crc)
  180495. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  180496. }
  180497. /* Allocate the memory for an info_struct for the application. We don't
  180498. * really need the png_ptr, but it could potentially be useful in the
  180499. * future. This should be used in favour of malloc(png_sizeof(png_info))
  180500. * and png_info_init() so that applications that want to use a shared
  180501. * libpng don't have to be recompiled if png_info changes size.
  180502. */
  180503. png_infop PNGAPI
  180504. png_create_info_struct(png_structp png_ptr)
  180505. {
  180506. png_infop info_ptr;
  180507. png_debug(1, "in png_create_info_struct\n");
  180508. if(png_ptr == NULL) return (NULL);
  180509. #ifdef PNG_USER_MEM_SUPPORTED
  180510. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  180511. png_ptr->malloc_fn, png_ptr->mem_ptr);
  180512. #else
  180513. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180514. #endif
  180515. if (info_ptr != NULL)
  180516. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180517. return (info_ptr);
  180518. }
  180519. /* This function frees the memory associated with a single info struct.
  180520. * Normally, one would use either png_destroy_read_struct() or
  180521. * png_destroy_write_struct() to free an info struct, but this may be
  180522. * useful for some applications.
  180523. */
  180524. void PNGAPI
  180525. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  180526. {
  180527. png_infop info_ptr = NULL;
  180528. if(png_ptr == NULL) return;
  180529. png_debug(1, "in png_destroy_info_struct\n");
  180530. if (info_ptr_ptr != NULL)
  180531. info_ptr = *info_ptr_ptr;
  180532. if (info_ptr != NULL)
  180533. {
  180534. png_info_destroy(png_ptr, info_ptr);
  180535. #ifdef PNG_USER_MEM_SUPPORTED
  180536. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  180537. png_ptr->mem_ptr);
  180538. #else
  180539. png_destroy_struct((png_voidp)info_ptr);
  180540. #endif
  180541. *info_ptr_ptr = NULL;
  180542. }
  180543. }
  180544. /* Initialize the info structure. This is now an internal function (0.89)
  180545. * and applications using it are urged to use png_create_info_struct()
  180546. * instead.
  180547. */
  180548. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180549. #undef png_info_init
  180550. void PNGAPI
  180551. png_info_init(png_infop info_ptr)
  180552. {
  180553. /* We only come here via pre-1.0.12-compiled applications */
  180554. png_info_init_3(&info_ptr, 0);
  180555. }
  180556. #endif
  180557. void PNGAPI
  180558. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  180559. {
  180560. png_infop info_ptr = *ptr_ptr;
  180561. if(info_ptr == NULL) return;
  180562. png_debug(1, "in png_info_init_3\n");
  180563. if(png_sizeof(png_info) > png_info_struct_size)
  180564. {
  180565. png_destroy_struct(info_ptr);
  180566. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180567. *ptr_ptr = info_ptr;
  180568. }
  180569. /* set everything to 0 */
  180570. png_memset(info_ptr, 0, png_sizeof (png_info));
  180571. }
  180572. #ifdef PNG_FREE_ME_SUPPORTED
  180573. void PNGAPI
  180574. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  180575. int freer, png_uint_32 mask)
  180576. {
  180577. png_debug(1, "in png_data_freer\n");
  180578. if (png_ptr == NULL || info_ptr == NULL)
  180579. return;
  180580. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  180581. info_ptr->free_me |= mask;
  180582. else if(freer == PNG_USER_WILL_FREE_DATA)
  180583. info_ptr->free_me &= ~mask;
  180584. else
  180585. png_warning(png_ptr,
  180586. "Unknown freer parameter in png_data_freer.");
  180587. }
  180588. #endif
  180589. void PNGAPI
  180590. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  180591. int num)
  180592. {
  180593. png_debug(1, "in png_free_data\n");
  180594. if (png_ptr == NULL || info_ptr == NULL)
  180595. return;
  180596. #if defined(PNG_TEXT_SUPPORTED)
  180597. /* free text item num or (if num == -1) all text items */
  180598. #ifdef PNG_FREE_ME_SUPPORTED
  180599. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  180600. #else
  180601. if (mask & PNG_FREE_TEXT)
  180602. #endif
  180603. {
  180604. if (num != -1)
  180605. {
  180606. if (info_ptr->text && info_ptr->text[num].key)
  180607. {
  180608. png_free(png_ptr, info_ptr->text[num].key);
  180609. info_ptr->text[num].key = NULL;
  180610. }
  180611. }
  180612. else
  180613. {
  180614. int i;
  180615. for (i = 0; i < info_ptr->num_text; i++)
  180616. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  180617. png_free(png_ptr, info_ptr->text);
  180618. info_ptr->text = NULL;
  180619. info_ptr->num_text=0;
  180620. }
  180621. }
  180622. #endif
  180623. #if defined(PNG_tRNS_SUPPORTED)
  180624. /* free any tRNS entry */
  180625. #ifdef PNG_FREE_ME_SUPPORTED
  180626. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  180627. #else
  180628. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  180629. #endif
  180630. {
  180631. png_free(png_ptr, info_ptr->trans);
  180632. info_ptr->valid &= ~PNG_INFO_tRNS;
  180633. #ifndef PNG_FREE_ME_SUPPORTED
  180634. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  180635. #endif
  180636. info_ptr->trans = NULL;
  180637. }
  180638. #endif
  180639. #if defined(PNG_sCAL_SUPPORTED)
  180640. /* free any sCAL entry */
  180641. #ifdef PNG_FREE_ME_SUPPORTED
  180642. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  180643. #else
  180644. if (mask & PNG_FREE_SCAL)
  180645. #endif
  180646. {
  180647. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  180648. png_free(png_ptr, info_ptr->scal_s_width);
  180649. png_free(png_ptr, info_ptr->scal_s_height);
  180650. info_ptr->scal_s_width = NULL;
  180651. info_ptr->scal_s_height = NULL;
  180652. #endif
  180653. info_ptr->valid &= ~PNG_INFO_sCAL;
  180654. }
  180655. #endif
  180656. #if defined(PNG_pCAL_SUPPORTED)
  180657. /* free any pCAL entry */
  180658. #ifdef PNG_FREE_ME_SUPPORTED
  180659. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  180660. #else
  180661. if (mask & PNG_FREE_PCAL)
  180662. #endif
  180663. {
  180664. png_free(png_ptr, info_ptr->pcal_purpose);
  180665. png_free(png_ptr, info_ptr->pcal_units);
  180666. info_ptr->pcal_purpose = NULL;
  180667. info_ptr->pcal_units = NULL;
  180668. if (info_ptr->pcal_params != NULL)
  180669. {
  180670. int i;
  180671. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  180672. {
  180673. png_free(png_ptr, info_ptr->pcal_params[i]);
  180674. info_ptr->pcal_params[i]=NULL;
  180675. }
  180676. png_free(png_ptr, info_ptr->pcal_params);
  180677. info_ptr->pcal_params = NULL;
  180678. }
  180679. info_ptr->valid &= ~PNG_INFO_pCAL;
  180680. }
  180681. #endif
  180682. #if defined(PNG_iCCP_SUPPORTED)
  180683. /* free any iCCP entry */
  180684. #ifdef PNG_FREE_ME_SUPPORTED
  180685. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  180686. #else
  180687. if (mask & PNG_FREE_ICCP)
  180688. #endif
  180689. {
  180690. png_free(png_ptr, info_ptr->iccp_name);
  180691. png_free(png_ptr, info_ptr->iccp_profile);
  180692. info_ptr->iccp_name = NULL;
  180693. info_ptr->iccp_profile = NULL;
  180694. info_ptr->valid &= ~PNG_INFO_iCCP;
  180695. }
  180696. #endif
  180697. #if defined(PNG_sPLT_SUPPORTED)
  180698. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  180699. #ifdef PNG_FREE_ME_SUPPORTED
  180700. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  180701. #else
  180702. if (mask & PNG_FREE_SPLT)
  180703. #endif
  180704. {
  180705. if (num != -1)
  180706. {
  180707. if(info_ptr->splt_palettes)
  180708. {
  180709. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  180710. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  180711. info_ptr->splt_palettes[num].name = NULL;
  180712. info_ptr->splt_palettes[num].entries = NULL;
  180713. }
  180714. }
  180715. else
  180716. {
  180717. if(info_ptr->splt_palettes_num)
  180718. {
  180719. int i;
  180720. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  180721. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  180722. png_free(png_ptr, info_ptr->splt_palettes);
  180723. info_ptr->splt_palettes = NULL;
  180724. info_ptr->splt_palettes_num = 0;
  180725. }
  180726. info_ptr->valid &= ~PNG_INFO_sPLT;
  180727. }
  180728. }
  180729. #endif
  180730. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180731. if(png_ptr->unknown_chunk.data)
  180732. {
  180733. png_free(png_ptr, png_ptr->unknown_chunk.data);
  180734. png_ptr->unknown_chunk.data = NULL;
  180735. }
  180736. #ifdef PNG_FREE_ME_SUPPORTED
  180737. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  180738. #else
  180739. if (mask & PNG_FREE_UNKN)
  180740. #endif
  180741. {
  180742. if (num != -1)
  180743. {
  180744. if(info_ptr->unknown_chunks)
  180745. {
  180746. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  180747. info_ptr->unknown_chunks[num].data = NULL;
  180748. }
  180749. }
  180750. else
  180751. {
  180752. int i;
  180753. if(info_ptr->unknown_chunks_num)
  180754. {
  180755. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  180756. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  180757. png_free(png_ptr, info_ptr->unknown_chunks);
  180758. info_ptr->unknown_chunks = NULL;
  180759. info_ptr->unknown_chunks_num = 0;
  180760. }
  180761. }
  180762. }
  180763. #endif
  180764. #if defined(PNG_hIST_SUPPORTED)
  180765. /* free any hIST entry */
  180766. #ifdef PNG_FREE_ME_SUPPORTED
  180767. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  180768. #else
  180769. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  180770. #endif
  180771. {
  180772. png_free(png_ptr, info_ptr->hist);
  180773. info_ptr->hist = NULL;
  180774. info_ptr->valid &= ~PNG_INFO_hIST;
  180775. #ifndef PNG_FREE_ME_SUPPORTED
  180776. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  180777. #endif
  180778. }
  180779. #endif
  180780. /* free any PLTE entry that was internally allocated */
  180781. #ifdef PNG_FREE_ME_SUPPORTED
  180782. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  180783. #else
  180784. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  180785. #endif
  180786. {
  180787. png_zfree(png_ptr, info_ptr->palette);
  180788. info_ptr->palette = NULL;
  180789. info_ptr->valid &= ~PNG_INFO_PLTE;
  180790. #ifndef PNG_FREE_ME_SUPPORTED
  180791. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  180792. #endif
  180793. info_ptr->num_palette = 0;
  180794. }
  180795. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180796. /* free any image bits attached to the info structure */
  180797. #ifdef PNG_FREE_ME_SUPPORTED
  180798. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  180799. #else
  180800. if (mask & PNG_FREE_ROWS)
  180801. #endif
  180802. {
  180803. if(info_ptr->row_pointers)
  180804. {
  180805. int row;
  180806. for (row = 0; row < (int)info_ptr->height; row++)
  180807. {
  180808. png_free(png_ptr, info_ptr->row_pointers[row]);
  180809. info_ptr->row_pointers[row]=NULL;
  180810. }
  180811. png_free(png_ptr, info_ptr->row_pointers);
  180812. info_ptr->row_pointers=NULL;
  180813. }
  180814. info_ptr->valid &= ~PNG_INFO_IDAT;
  180815. }
  180816. #endif
  180817. #ifdef PNG_FREE_ME_SUPPORTED
  180818. if(num == -1)
  180819. info_ptr->free_me &= ~mask;
  180820. else
  180821. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  180822. #endif
  180823. }
  180824. /* This is an internal routine to free any memory that the info struct is
  180825. * pointing to before re-using it or freeing the struct itself. Recall
  180826. * that png_free() checks for NULL pointers for us.
  180827. */
  180828. void /* PRIVATE */
  180829. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  180830. {
  180831. png_debug(1, "in png_info_destroy\n");
  180832. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  180833. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180834. if (png_ptr->num_chunk_list)
  180835. {
  180836. png_free(png_ptr, png_ptr->chunk_list);
  180837. png_ptr->chunk_list=NULL;
  180838. png_ptr->num_chunk_list=0;
  180839. }
  180840. #endif
  180841. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180842. }
  180843. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180844. /* This function returns a pointer to the io_ptr associated with the user
  180845. * functions. The application should free any memory associated with this
  180846. * pointer before png_write_destroy() or png_read_destroy() are called.
  180847. */
  180848. png_voidp PNGAPI
  180849. png_get_io_ptr(png_structp png_ptr)
  180850. {
  180851. if(png_ptr == NULL) return (NULL);
  180852. return (png_ptr->io_ptr);
  180853. }
  180854. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180855. #if !defined(PNG_NO_STDIO)
  180856. /* Initialize the default input/output functions for the PNG file. If you
  180857. * use your own read or write routines, you can call either png_set_read_fn()
  180858. * or png_set_write_fn() instead of png_init_io(). If you have defined
  180859. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  180860. * necessarily available.
  180861. */
  180862. void PNGAPI
  180863. png_init_io(png_structp png_ptr, png_FILE_p fp)
  180864. {
  180865. png_debug(1, "in png_init_io\n");
  180866. if(png_ptr == NULL) return;
  180867. png_ptr->io_ptr = (png_voidp)fp;
  180868. }
  180869. #endif
  180870. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180871. /* Convert the supplied time into an RFC 1123 string suitable for use in
  180872. * a "Creation Time" or other text-based time string.
  180873. */
  180874. png_charp PNGAPI
  180875. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  180876. {
  180877. static PNG_CONST char short_months[12][4] =
  180878. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  180879. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  180880. if(png_ptr == NULL) return (NULL);
  180881. if (png_ptr->time_buffer == NULL)
  180882. {
  180883. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  180884. png_sizeof(char)));
  180885. }
  180886. #if defined(_WIN32_WCE)
  180887. {
  180888. wchar_t time_buf[29];
  180889. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  180890. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180891. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180892. ptime->second % 61);
  180893. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  180894. NULL, NULL);
  180895. }
  180896. #else
  180897. #ifdef USE_FAR_KEYWORD
  180898. {
  180899. char near_time_buf[29];
  180900. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  180901. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180902. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180903. ptime->second % 61);
  180904. png_memcpy(png_ptr->time_buffer, near_time_buf,
  180905. 29*png_sizeof(char));
  180906. }
  180907. #else
  180908. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  180909. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180910. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180911. ptime->second % 61);
  180912. #endif
  180913. #endif /* _WIN32_WCE */
  180914. return ((png_charp)png_ptr->time_buffer);
  180915. }
  180916. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  180917. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180918. png_charp PNGAPI
  180919. png_get_copyright(png_structp png_ptr)
  180920. {
  180921. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180922. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  180923. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  180924. Copyright (c) 1996-1997 Andreas Dilger\n\
  180925. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  180926. }
  180927. /* The following return the library version as a short string in the
  180928. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  180929. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  180930. * is defined in png.h.
  180931. * Note: now there is no difference between png_get_libpng_ver() and
  180932. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  180933. * it is guaranteed that png.c uses the correct version of png.h.
  180934. */
  180935. png_charp PNGAPI
  180936. png_get_libpng_ver(png_structp png_ptr)
  180937. {
  180938. /* Version of *.c files used when building libpng */
  180939. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180940. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180941. }
  180942. png_charp PNGAPI
  180943. png_get_header_ver(png_structp png_ptr)
  180944. {
  180945. /* Version of *.h files used when building libpng */
  180946. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180947. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180948. }
  180949. png_charp PNGAPI
  180950. png_get_header_version(png_structp png_ptr)
  180951. {
  180952. /* Returns longer string containing both version and date */
  180953. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180954. return ((png_charp) PNG_HEADER_VERSION_STRING
  180955. #ifndef PNG_READ_SUPPORTED
  180956. " (NO READ SUPPORT)"
  180957. #endif
  180958. "\n");
  180959. }
  180960. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180961. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180962. int PNGAPI
  180963. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  180964. {
  180965. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  180966. int i;
  180967. png_bytep p;
  180968. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  180969. return 0;
  180970. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  180971. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  180972. if (!png_memcmp(chunk_name, p, 4))
  180973. return ((int)*(p+4));
  180974. return 0;
  180975. }
  180976. #endif
  180977. /* This function, added to libpng-1.0.6g, is untested. */
  180978. int PNGAPI
  180979. png_reset_zstream(png_structp png_ptr)
  180980. {
  180981. if (png_ptr == NULL) return Z_STREAM_ERROR;
  180982. return (inflateReset(&png_ptr->zstream));
  180983. }
  180984. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180985. /* This function was added to libpng-1.0.7 */
  180986. png_uint_32 PNGAPI
  180987. png_access_version_number(void)
  180988. {
  180989. /* Version of *.c files used when building libpng */
  180990. return((png_uint_32) PNG_LIBPNG_VER);
  180991. }
  180992. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180993. #if !defined(PNG_1_0_X)
  180994. /* this function was added to libpng 1.2.0 */
  180995. int PNGAPI
  180996. png_mmx_support(void)
  180997. {
  180998. /* obsolete, to be removed from libpng-1.4.0 */
  180999. return -1;
  181000. }
  181001. #endif /* PNG_1_0_X */
  181002. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  181003. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181004. #ifdef PNG_SIZE_T
  181005. /* Added at libpng version 1.2.6 */
  181006. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  181007. png_size_t PNGAPI
  181008. png_convert_size(size_t size)
  181009. {
  181010. if (size > (png_size_t)-1)
  181011. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  181012. return ((png_size_t)size);
  181013. }
  181014. #endif /* PNG_SIZE_T */
  181015. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181016. /********* End of inlined file: png.c *********/
  181017. /********* Start of inlined file: pngerror.c *********/
  181018. /* pngerror.c - stub functions for i/o and memory allocation
  181019. *
  181020. * Last changed in libpng 1.2.20 October 4, 2007
  181021. * For conditions of distribution and use, see copyright notice in png.h
  181022. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181023. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181024. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181025. *
  181026. * This file provides a location for all error handling. Users who
  181027. * need special error handling are expected to write replacement functions
  181028. * and use png_set_error_fn() to use those functions. See the instructions
  181029. * at each function.
  181030. */
  181031. #define PNG_INTERNAL
  181032. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181033. static void /* PRIVATE */
  181034. png_default_error PNGARG((png_structp png_ptr,
  181035. png_const_charp error_message));
  181036. #ifndef PNG_NO_WARNINGS
  181037. static void /* PRIVATE */
  181038. png_default_warning PNGARG((png_structp png_ptr,
  181039. png_const_charp warning_message));
  181040. #endif /* PNG_NO_WARNINGS */
  181041. /* This function is called whenever there is a fatal error. This function
  181042. * should not be changed. If there is a need to handle errors differently,
  181043. * you should supply a replacement error function and use png_set_error_fn()
  181044. * to replace the error function at run-time.
  181045. */
  181046. #ifndef PNG_NO_ERROR_TEXT
  181047. void PNGAPI
  181048. png_error(png_structp png_ptr, png_const_charp error_message)
  181049. {
  181050. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181051. char msg[16];
  181052. if (png_ptr != NULL)
  181053. {
  181054. if (png_ptr->flags&
  181055. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181056. {
  181057. if (*error_message == '#')
  181058. {
  181059. int offset;
  181060. for (offset=1; offset<15; offset++)
  181061. if (*(error_message+offset) == ' ')
  181062. break;
  181063. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181064. {
  181065. int i;
  181066. for (i=0; i<offset-1; i++)
  181067. msg[i]=error_message[i+1];
  181068. msg[i]='\0';
  181069. error_message=msg;
  181070. }
  181071. else
  181072. error_message+=offset;
  181073. }
  181074. else
  181075. {
  181076. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181077. {
  181078. msg[0]='0';
  181079. msg[1]='\0';
  181080. error_message=msg;
  181081. }
  181082. }
  181083. }
  181084. }
  181085. #endif
  181086. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181087. (*(png_ptr->error_fn))(png_ptr, error_message);
  181088. /* If the custom handler doesn't exist, or if it returns,
  181089. use the default handler, which will not return. */
  181090. png_default_error(png_ptr, error_message);
  181091. }
  181092. #else
  181093. void PNGAPI
  181094. png_err(png_structp png_ptr)
  181095. {
  181096. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181097. (*(png_ptr->error_fn))(png_ptr, '\0');
  181098. /* If the custom handler doesn't exist, or if it returns,
  181099. use the default handler, which will not return. */
  181100. png_default_error(png_ptr, '\0');
  181101. }
  181102. #endif /* PNG_NO_ERROR_TEXT */
  181103. #ifndef PNG_NO_WARNINGS
  181104. /* This function is called whenever there is a non-fatal error. This function
  181105. * should not be changed. If there is a need to handle warnings differently,
  181106. * you should supply a replacement warning function and use
  181107. * png_set_error_fn() to replace the warning function at run-time.
  181108. */
  181109. void PNGAPI
  181110. png_warning(png_structp png_ptr, png_const_charp warning_message)
  181111. {
  181112. int offset = 0;
  181113. if (png_ptr != NULL)
  181114. {
  181115. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181116. if (png_ptr->flags&
  181117. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181118. #endif
  181119. {
  181120. if (*warning_message == '#')
  181121. {
  181122. for (offset=1; offset<15; offset++)
  181123. if (*(warning_message+offset) == ' ')
  181124. break;
  181125. }
  181126. }
  181127. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  181128. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  181129. }
  181130. else
  181131. png_default_warning(png_ptr, warning_message+offset);
  181132. }
  181133. #endif /* PNG_NO_WARNINGS */
  181134. /* These utilities are used internally to build an error message that relates
  181135. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  181136. * this is used to prefix the message. The message is limited in length
  181137. * to 63 bytes, the name characters are output as hex digits wrapped in []
  181138. * if the character is invalid.
  181139. */
  181140. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  181141. /*static PNG_CONST char png_digit[16] = {
  181142. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  181143. 'A', 'B', 'C', 'D', 'E', 'F'
  181144. };*/
  181145. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  181146. static void /* PRIVATE */
  181147. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  181148. error_message)
  181149. {
  181150. int iout = 0, iin = 0;
  181151. while (iin < 4)
  181152. {
  181153. int c = png_ptr->chunk_name[iin++];
  181154. if (isnonalpha(c))
  181155. {
  181156. buffer[iout++] = '[';
  181157. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  181158. buffer[iout++] = png_digit[c & 0x0f];
  181159. buffer[iout++] = ']';
  181160. }
  181161. else
  181162. {
  181163. buffer[iout++] = (png_byte)c;
  181164. }
  181165. }
  181166. if (error_message == NULL)
  181167. buffer[iout] = 0;
  181168. else
  181169. {
  181170. buffer[iout++] = ':';
  181171. buffer[iout++] = ' ';
  181172. png_strncpy(buffer+iout, error_message, 63);
  181173. buffer[iout+63] = 0;
  181174. }
  181175. }
  181176. #ifdef PNG_READ_SUPPORTED
  181177. void PNGAPI
  181178. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  181179. {
  181180. char msg[18+64];
  181181. if (png_ptr == NULL)
  181182. png_error(png_ptr, error_message);
  181183. else
  181184. {
  181185. png_format_buffer(png_ptr, msg, error_message);
  181186. png_error(png_ptr, msg);
  181187. }
  181188. }
  181189. #endif /* PNG_READ_SUPPORTED */
  181190. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  181191. #ifndef PNG_NO_WARNINGS
  181192. void PNGAPI
  181193. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  181194. {
  181195. char msg[18+64];
  181196. if (png_ptr == NULL)
  181197. png_warning(png_ptr, warning_message);
  181198. else
  181199. {
  181200. png_format_buffer(png_ptr, msg, warning_message);
  181201. png_warning(png_ptr, msg);
  181202. }
  181203. }
  181204. #endif /* PNG_NO_WARNINGS */
  181205. /* This is the default error handling function. Note that replacements for
  181206. * this function MUST NOT RETURN, or the program will likely crash. This
  181207. * function is used by default, or if the program supplies NULL for the
  181208. * error function pointer in png_set_error_fn().
  181209. */
  181210. static void /* PRIVATE */
  181211. png_default_error(png_structp png_ptr, png_const_charp error_message)
  181212. {
  181213. #ifndef PNG_NO_CONSOLE_IO
  181214. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181215. if (*error_message == '#')
  181216. {
  181217. int offset;
  181218. char error_number[16];
  181219. for (offset=0; offset<15; offset++)
  181220. {
  181221. error_number[offset] = *(error_message+offset+1);
  181222. if (*(error_message+offset) == ' ')
  181223. break;
  181224. }
  181225. if((offset > 1) && (offset < 15))
  181226. {
  181227. error_number[offset-1]='\0';
  181228. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  181229. error_message+offset);
  181230. }
  181231. else
  181232. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  181233. }
  181234. else
  181235. #endif
  181236. fprintf(stderr, "libpng error: %s\n", error_message);
  181237. #endif
  181238. #ifdef PNG_SETJMP_SUPPORTED
  181239. if (png_ptr)
  181240. {
  181241. # ifdef USE_FAR_KEYWORD
  181242. {
  181243. jmp_buf jmpbuf;
  181244. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  181245. longjmp(jmpbuf, 1);
  181246. }
  181247. # else
  181248. longjmp(png_ptr->jmpbuf, 1);
  181249. # endif
  181250. }
  181251. #else
  181252. PNG_ABORT();
  181253. #endif
  181254. #ifdef PNG_NO_CONSOLE_IO
  181255. error_message = error_message; /* make compiler happy */
  181256. #endif
  181257. }
  181258. #ifndef PNG_NO_WARNINGS
  181259. /* This function is called when there is a warning, but the library thinks
  181260. * it can continue anyway. Replacement functions don't have to do anything
  181261. * here if you don't want them to. In the default configuration, png_ptr is
  181262. * not used, but it is passed in case it may be useful.
  181263. */
  181264. static void /* PRIVATE */
  181265. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  181266. {
  181267. #ifndef PNG_NO_CONSOLE_IO
  181268. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181269. if (*warning_message == '#')
  181270. {
  181271. int offset;
  181272. char warning_number[16];
  181273. for (offset=0; offset<15; offset++)
  181274. {
  181275. warning_number[offset]=*(warning_message+offset+1);
  181276. if (*(warning_message+offset) == ' ')
  181277. break;
  181278. }
  181279. if((offset > 1) && (offset < 15))
  181280. {
  181281. warning_number[offset-1]='\0';
  181282. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  181283. warning_message+offset);
  181284. }
  181285. else
  181286. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181287. }
  181288. else
  181289. # endif
  181290. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181291. #else
  181292. warning_message = warning_message; /* make compiler happy */
  181293. #endif
  181294. png_ptr = png_ptr; /* make compiler happy */
  181295. }
  181296. #endif /* PNG_NO_WARNINGS */
  181297. /* This function is called when the application wants to use another method
  181298. * of handling errors and warnings. Note that the error function MUST NOT
  181299. * return to the calling routine or serious problems will occur. The return
  181300. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  181301. */
  181302. void PNGAPI
  181303. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  181304. png_error_ptr error_fn, png_error_ptr warning_fn)
  181305. {
  181306. if (png_ptr == NULL)
  181307. return;
  181308. png_ptr->error_ptr = error_ptr;
  181309. png_ptr->error_fn = error_fn;
  181310. png_ptr->warning_fn = warning_fn;
  181311. }
  181312. /* This function returns a pointer to the error_ptr associated with the user
  181313. * functions. The application should free any memory associated with this
  181314. * pointer before png_write_destroy and png_read_destroy are called.
  181315. */
  181316. png_voidp PNGAPI
  181317. png_get_error_ptr(png_structp png_ptr)
  181318. {
  181319. if (png_ptr == NULL)
  181320. return NULL;
  181321. return ((png_voidp)png_ptr->error_ptr);
  181322. }
  181323. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181324. void PNGAPI
  181325. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  181326. {
  181327. if(png_ptr != NULL)
  181328. {
  181329. png_ptr->flags &=
  181330. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  181331. }
  181332. }
  181333. #endif
  181334. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181335. /********* End of inlined file: pngerror.c *********/
  181336. /********* Start of inlined file: pngget.c *********/
  181337. /* pngget.c - retrieval of values from info struct
  181338. *
  181339. * Last changed in libpng 1.2.15 January 5, 2007
  181340. * For conditions of distribution and use, see copyright notice in png.h
  181341. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181342. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181343. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181344. */
  181345. #define PNG_INTERNAL
  181346. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181347. png_uint_32 PNGAPI
  181348. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  181349. {
  181350. if (png_ptr != NULL && info_ptr != NULL)
  181351. return(info_ptr->valid & flag);
  181352. else
  181353. return(0);
  181354. }
  181355. png_uint_32 PNGAPI
  181356. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  181357. {
  181358. if (png_ptr != NULL && info_ptr != NULL)
  181359. return(info_ptr->rowbytes);
  181360. else
  181361. return(0);
  181362. }
  181363. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181364. png_bytepp PNGAPI
  181365. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  181366. {
  181367. if (png_ptr != NULL && info_ptr != NULL)
  181368. return(info_ptr->row_pointers);
  181369. else
  181370. return(0);
  181371. }
  181372. #endif
  181373. #ifdef PNG_EASY_ACCESS_SUPPORTED
  181374. /* easy access to info, added in libpng-0.99 */
  181375. png_uint_32 PNGAPI
  181376. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  181377. {
  181378. if (png_ptr != NULL && info_ptr != NULL)
  181379. {
  181380. return info_ptr->width;
  181381. }
  181382. return (0);
  181383. }
  181384. png_uint_32 PNGAPI
  181385. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  181386. {
  181387. if (png_ptr != NULL && info_ptr != NULL)
  181388. {
  181389. return info_ptr->height;
  181390. }
  181391. return (0);
  181392. }
  181393. png_byte PNGAPI
  181394. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  181395. {
  181396. if (png_ptr != NULL && info_ptr != NULL)
  181397. {
  181398. return info_ptr->bit_depth;
  181399. }
  181400. return (0);
  181401. }
  181402. png_byte PNGAPI
  181403. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  181404. {
  181405. if (png_ptr != NULL && info_ptr != NULL)
  181406. {
  181407. return info_ptr->color_type;
  181408. }
  181409. return (0);
  181410. }
  181411. png_byte PNGAPI
  181412. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  181413. {
  181414. if (png_ptr != NULL && info_ptr != NULL)
  181415. {
  181416. return info_ptr->filter_type;
  181417. }
  181418. return (0);
  181419. }
  181420. png_byte PNGAPI
  181421. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  181422. {
  181423. if (png_ptr != NULL && info_ptr != NULL)
  181424. {
  181425. return info_ptr->interlace_type;
  181426. }
  181427. return (0);
  181428. }
  181429. png_byte PNGAPI
  181430. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  181431. {
  181432. if (png_ptr != NULL && info_ptr != NULL)
  181433. {
  181434. return info_ptr->compression_type;
  181435. }
  181436. return (0);
  181437. }
  181438. png_uint_32 PNGAPI
  181439. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181440. {
  181441. if (png_ptr != NULL && info_ptr != NULL)
  181442. #if defined(PNG_pHYs_SUPPORTED)
  181443. if (info_ptr->valid & PNG_INFO_pHYs)
  181444. {
  181445. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  181446. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181447. return (0);
  181448. else return (info_ptr->x_pixels_per_unit);
  181449. }
  181450. #else
  181451. return (0);
  181452. #endif
  181453. return (0);
  181454. }
  181455. png_uint_32 PNGAPI
  181456. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181457. {
  181458. if (png_ptr != NULL && info_ptr != NULL)
  181459. #if defined(PNG_pHYs_SUPPORTED)
  181460. if (info_ptr->valid & PNG_INFO_pHYs)
  181461. {
  181462. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  181463. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181464. return (0);
  181465. else return (info_ptr->y_pixels_per_unit);
  181466. }
  181467. #else
  181468. return (0);
  181469. #endif
  181470. return (0);
  181471. }
  181472. png_uint_32 PNGAPI
  181473. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181474. {
  181475. if (png_ptr != NULL && info_ptr != NULL)
  181476. #if defined(PNG_pHYs_SUPPORTED)
  181477. if (info_ptr->valid & PNG_INFO_pHYs)
  181478. {
  181479. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  181480. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  181481. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  181482. return (0);
  181483. else return (info_ptr->x_pixels_per_unit);
  181484. }
  181485. #else
  181486. return (0);
  181487. #endif
  181488. return (0);
  181489. }
  181490. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181491. float PNGAPI
  181492. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  181493. {
  181494. if (png_ptr != NULL && info_ptr != NULL)
  181495. #if defined(PNG_pHYs_SUPPORTED)
  181496. if (info_ptr->valid & PNG_INFO_pHYs)
  181497. {
  181498. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  181499. if (info_ptr->x_pixels_per_unit == 0)
  181500. return ((float)0.0);
  181501. else
  181502. return ((float)((float)info_ptr->y_pixels_per_unit
  181503. /(float)info_ptr->x_pixels_per_unit));
  181504. }
  181505. #else
  181506. return (0.0);
  181507. #endif
  181508. return ((float)0.0);
  181509. }
  181510. #endif
  181511. png_int_32 PNGAPI
  181512. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181513. {
  181514. if (png_ptr != NULL && info_ptr != NULL)
  181515. #if defined(PNG_oFFs_SUPPORTED)
  181516. if (info_ptr->valid & PNG_INFO_oFFs)
  181517. {
  181518. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181519. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181520. return (0);
  181521. else return (info_ptr->x_offset);
  181522. }
  181523. #else
  181524. return (0);
  181525. #endif
  181526. return (0);
  181527. }
  181528. png_int_32 PNGAPI
  181529. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181530. {
  181531. if (png_ptr != NULL && info_ptr != NULL)
  181532. #if defined(PNG_oFFs_SUPPORTED)
  181533. if (info_ptr->valid & PNG_INFO_oFFs)
  181534. {
  181535. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181536. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181537. return (0);
  181538. else return (info_ptr->y_offset);
  181539. }
  181540. #else
  181541. return (0);
  181542. #endif
  181543. return (0);
  181544. }
  181545. png_int_32 PNGAPI
  181546. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181547. {
  181548. if (png_ptr != NULL && info_ptr != NULL)
  181549. #if defined(PNG_oFFs_SUPPORTED)
  181550. if (info_ptr->valid & PNG_INFO_oFFs)
  181551. {
  181552. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181553. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181554. return (0);
  181555. else return (info_ptr->x_offset);
  181556. }
  181557. #else
  181558. return (0);
  181559. #endif
  181560. return (0);
  181561. }
  181562. png_int_32 PNGAPI
  181563. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181564. {
  181565. if (png_ptr != NULL && info_ptr != NULL)
  181566. #if defined(PNG_oFFs_SUPPORTED)
  181567. if (info_ptr->valid & PNG_INFO_oFFs)
  181568. {
  181569. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181570. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181571. return (0);
  181572. else return (info_ptr->y_offset);
  181573. }
  181574. #else
  181575. return (0);
  181576. #endif
  181577. return (0);
  181578. }
  181579. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181580. png_uint_32 PNGAPI
  181581. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181582. {
  181583. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  181584. *.0254 +.5));
  181585. }
  181586. png_uint_32 PNGAPI
  181587. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181588. {
  181589. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  181590. *.0254 +.5));
  181591. }
  181592. png_uint_32 PNGAPI
  181593. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181594. {
  181595. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  181596. *.0254 +.5));
  181597. }
  181598. float PNGAPI
  181599. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181600. {
  181601. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  181602. *.00003937);
  181603. }
  181604. float PNGAPI
  181605. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181606. {
  181607. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  181608. *.00003937);
  181609. }
  181610. #if defined(PNG_pHYs_SUPPORTED)
  181611. png_uint_32 PNGAPI
  181612. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  181613. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181614. {
  181615. png_uint_32 retval = 0;
  181616. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  181617. {
  181618. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181619. if (res_x != NULL)
  181620. {
  181621. *res_x = info_ptr->x_pixels_per_unit;
  181622. retval |= PNG_INFO_pHYs;
  181623. }
  181624. if (res_y != NULL)
  181625. {
  181626. *res_y = info_ptr->y_pixels_per_unit;
  181627. retval |= PNG_INFO_pHYs;
  181628. }
  181629. if (unit_type != NULL)
  181630. {
  181631. *unit_type = (int)info_ptr->phys_unit_type;
  181632. retval |= PNG_INFO_pHYs;
  181633. if(*unit_type == 1)
  181634. {
  181635. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  181636. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  181637. }
  181638. }
  181639. }
  181640. return (retval);
  181641. }
  181642. #endif /* PNG_pHYs_SUPPORTED */
  181643. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181644. /* png_get_channels really belongs in here, too, but it's been around longer */
  181645. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  181646. png_byte PNGAPI
  181647. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  181648. {
  181649. if (png_ptr != NULL && info_ptr != NULL)
  181650. return(info_ptr->channels);
  181651. else
  181652. return (0);
  181653. }
  181654. png_bytep PNGAPI
  181655. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  181656. {
  181657. if (png_ptr != NULL && info_ptr != NULL)
  181658. return(info_ptr->signature);
  181659. else
  181660. return (NULL);
  181661. }
  181662. #if defined(PNG_bKGD_SUPPORTED)
  181663. png_uint_32 PNGAPI
  181664. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  181665. png_color_16p *background)
  181666. {
  181667. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  181668. && background != NULL)
  181669. {
  181670. png_debug1(1, "in %s retrieval function\n", "bKGD");
  181671. *background = &(info_ptr->background);
  181672. return (PNG_INFO_bKGD);
  181673. }
  181674. return (0);
  181675. }
  181676. #endif
  181677. #if defined(PNG_cHRM_SUPPORTED)
  181678. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181679. png_uint_32 PNGAPI
  181680. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  181681. double *white_x, double *white_y, double *red_x, double *red_y,
  181682. double *green_x, double *green_y, double *blue_x, double *blue_y)
  181683. {
  181684. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181685. {
  181686. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181687. if (white_x != NULL)
  181688. *white_x = (double)info_ptr->x_white;
  181689. if (white_y != NULL)
  181690. *white_y = (double)info_ptr->y_white;
  181691. if (red_x != NULL)
  181692. *red_x = (double)info_ptr->x_red;
  181693. if (red_y != NULL)
  181694. *red_y = (double)info_ptr->y_red;
  181695. if (green_x != NULL)
  181696. *green_x = (double)info_ptr->x_green;
  181697. if (green_y != NULL)
  181698. *green_y = (double)info_ptr->y_green;
  181699. if (blue_x != NULL)
  181700. *blue_x = (double)info_ptr->x_blue;
  181701. if (blue_y != NULL)
  181702. *blue_y = (double)info_ptr->y_blue;
  181703. return (PNG_INFO_cHRM);
  181704. }
  181705. return (0);
  181706. }
  181707. #endif
  181708. #ifdef PNG_FIXED_POINT_SUPPORTED
  181709. png_uint_32 PNGAPI
  181710. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  181711. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  181712. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  181713. png_fixed_point *blue_x, png_fixed_point *blue_y)
  181714. {
  181715. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181716. {
  181717. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181718. if (white_x != NULL)
  181719. *white_x = info_ptr->int_x_white;
  181720. if (white_y != NULL)
  181721. *white_y = info_ptr->int_y_white;
  181722. if (red_x != NULL)
  181723. *red_x = info_ptr->int_x_red;
  181724. if (red_y != NULL)
  181725. *red_y = info_ptr->int_y_red;
  181726. if (green_x != NULL)
  181727. *green_x = info_ptr->int_x_green;
  181728. if (green_y != NULL)
  181729. *green_y = info_ptr->int_y_green;
  181730. if (blue_x != NULL)
  181731. *blue_x = info_ptr->int_x_blue;
  181732. if (blue_y != NULL)
  181733. *blue_y = info_ptr->int_y_blue;
  181734. return (PNG_INFO_cHRM);
  181735. }
  181736. return (0);
  181737. }
  181738. #endif
  181739. #endif
  181740. #if defined(PNG_gAMA_SUPPORTED)
  181741. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181742. png_uint_32 PNGAPI
  181743. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  181744. {
  181745. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181746. && file_gamma != NULL)
  181747. {
  181748. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181749. *file_gamma = (double)info_ptr->gamma;
  181750. return (PNG_INFO_gAMA);
  181751. }
  181752. return (0);
  181753. }
  181754. #endif
  181755. #ifdef PNG_FIXED_POINT_SUPPORTED
  181756. png_uint_32 PNGAPI
  181757. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  181758. png_fixed_point *int_file_gamma)
  181759. {
  181760. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181761. && int_file_gamma != NULL)
  181762. {
  181763. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181764. *int_file_gamma = info_ptr->int_gamma;
  181765. return (PNG_INFO_gAMA);
  181766. }
  181767. return (0);
  181768. }
  181769. #endif
  181770. #endif
  181771. #if defined(PNG_sRGB_SUPPORTED)
  181772. png_uint_32 PNGAPI
  181773. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  181774. {
  181775. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  181776. && file_srgb_intent != NULL)
  181777. {
  181778. png_debug1(1, "in %s retrieval function\n", "sRGB");
  181779. *file_srgb_intent = (int)info_ptr->srgb_intent;
  181780. return (PNG_INFO_sRGB);
  181781. }
  181782. return (0);
  181783. }
  181784. #endif
  181785. #if defined(PNG_iCCP_SUPPORTED)
  181786. png_uint_32 PNGAPI
  181787. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  181788. png_charpp name, int *compression_type,
  181789. png_charpp profile, png_uint_32 *proflen)
  181790. {
  181791. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  181792. && name != NULL && profile != NULL && proflen != NULL)
  181793. {
  181794. png_debug1(1, "in %s retrieval function\n", "iCCP");
  181795. *name = info_ptr->iccp_name;
  181796. *profile = info_ptr->iccp_profile;
  181797. /* compression_type is a dummy so the API won't have to change
  181798. if we introduce multiple compression types later. */
  181799. *proflen = (int)info_ptr->iccp_proflen;
  181800. *compression_type = (int)info_ptr->iccp_compression;
  181801. return (PNG_INFO_iCCP);
  181802. }
  181803. return (0);
  181804. }
  181805. #endif
  181806. #if defined(PNG_sPLT_SUPPORTED)
  181807. png_uint_32 PNGAPI
  181808. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  181809. png_sPLT_tpp spalettes)
  181810. {
  181811. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  181812. {
  181813. *spalettes = info_ptr->splt_palettes;
  181814. return ((png_uint_32)info_ptr->splt_palettes_num);
  181815. }
  181816. return (0);
  181817. }
  181818. #endif
  181819. #if defined(PNG_hIST_SUPPORTED)
  181820. png_uint_32 PNGAPI
  181821. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  181822. {
  181823. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  181824. && hist != NULL)
  181825. {
  181826. png_debug1(1, "in %s retrieval function\n", "hIST");
  181827. *hist = info_ptr->hist;
  181828. return (PNG_INFO_hIST);
  181829. }
  181830. return (0);
  181831. }
  181832. #endif
  181833. png_uint_32 PNGAPI
  181834. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  181835. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  181836. int *color_type, int *interlace_type, int *compression_type,
  181837. int *filter_type)
  181838. {
  181839. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  181840. bit_depth != NULL && color_type != NULL)
  181841. {
  181842. png_debug1(1, "in %s retrieval function\n", "IHDR");
  181843. *width = info_ptr->width;
  181844. *height = info_ptr->height;
  181845. *bit_depth = info_ptr->bit_depth;
  181846. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  181847. png_error(png_ptr, "Invalid bit depth");
  181848. *color_type = info_ptr->color_type;
  181849. if (info_ptr->color_type > 6)
  181850. png_error(png_ptr, "Invalid color type");
  181851. if (compression_type != NULL)
  181852. *compression_type = info_ptr->compression_type;
  181853. if (filter_type != NULL)
  181854. *filter_type = info_ptr->filter_type;
  181855. if (interlace_type != NULL)
  181856. *interlace_type = info_ptr->interlace_type;
  181857. /* check for potential overflow of rowbytes */
  181858. if (*width == 0 || *width > PNG_UINT_31_MAX)
  181859. png_error(png_ptr, "Invalid image width");
  181860. if (*height == 0 || *height > PNG_UINT_31_MAX)
  181861. png_error(png_ptr, "Invalid image height");
  181862. if (info_ptr->width > (PNG_UINT_32_MAX
  181863. >> 3) /* 8-byte RGBA pixels */
  181864. - 64 /* bigrowbuf hack */
  181865. - 1 /* filter byte */
  181866. - 7*8 /* rounding of width to multiple of 8 pixels */
  181867. - 8) /* extra max_pixel_depth pad */
  181868. {
  181869. png_warning(png_ptr,
  181870. "Width too large for libpng to process image data.");
  181871. }
  181872. return (1);
  181873. }
  181874. return (0);
  181875. }
  181876. #if defined(PNG_oFFs_SUPPORTED)
  181877. png_uint_32 PNGAPI
  181878. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  181879. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  181880. {
  181881. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  181882. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  181883. {
  181884. png_debug1(1, "in %s retrieval function\n", "oFFs");
  181885. *offset_x = info_ptr->x_offset;
  181886. *offset_y = info_ptr->y_offset;
  181887. *unit_type = (int)info_ptr->offset_unit_type;
  181888. return (PNG_INFO_oFFs);
  181889. }
  181890. return (0);
  181891. }
  181892. #endif
  181893. #if defined(PNG_pCAL_SUPPORTED)
  181894. png_uint_32 PNGAPI
  181895. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  181896. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  181897. png_charp *units, png_charpp *params)
  181898. {
  181899. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  181900. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  181901. nparams != NULL && units != NULL && params != NULL)
  181902. {
  181903. png_debug1(1, "in %s retrieval function\n", "pCAL");
  181904. *purpose = info_ptr->pcal_purpose;
  181905. *X0 = info_ptr->pcal_X0;
  181906. *X1 = info_ptr->pcal_X1;
  181907. *type = (int)info_ptr->pcal_type;
  181908. *nparams = (int)info_ptr->pcal_nparams;
  181909. *units = info_ptr->pcal_units;
  181910. *params = info_ptr->pcal_params;
  181911. return (PNG_INFO_pCAL);
  181912. }
  181913. return (0);
  181914. }
  181915. #endif
  181916. #if defined(PNG_sCAL_SUPPORTED)
  181917. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181918. png_uint_32 PNGAPI
  181919. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  181920. int *unit, double *width, double *height)
  181921. {
  181922. if (png_ptr != NULL && info_ptr != NULL &&
  181923. (info_ptr->valid & PNG_INFO_sCAL))
  181924. {
  181925. *unit = info_ptr->scal_unit;
  181926. *width = info_ptr->scal_pixel_width;
  181927. *height = info_ptr->scal_pixel_height;
  181928. return (PNG_INFO_sCAL);
  181929. }
  181930. return(0);
  181931. }
  181932. #else
  181933. #ifdef PNG_FIXED_POINT_SUPPORTED
  181934. png_uint_32 PNGAPI
  181935. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  181936. int *unit, png_charpp width, png_charpp height)
  181937. {
  181938. if (png_ptr != NULL && info_ptr != NULL &&
  181939. (info_ptr->valid & PNG_INFO_sCAL))
  181940. {
  181941. *unit = info_ptr->scal_unit;
  181942. *width = info_ptr->scal_s_width;
  181943. *height = info_ptr->scal_s_height;
  181944. return (PNG_INFO_sCAL);
  181945. }
  181946. return(0);
  181947. }
  181948. #endif
  181949. #endif
  181950. #endif
  181951. #if defined(PNG_pHYs_SUPPORTED)
  181952. png_uint_32 PNGAPI
  181953. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  181954. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181955. {
  181956. png_uint_32 retval = 0;
  181957. if (png_ptr != NULL && info_ptr != NULL &&
  181958. (info_ptr->valid & PNG_INFO_pHYs))
  181959. {
  181960. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181961. if (res_x != NULL)
  181962. {
  181963. *res_x = info_ptr->x_pixels_per_unit;
  181964. retval |= PNG_INFO_pHYs;
  181965. }
  181966. if (res_y != NULL)
  181967. {
  181968. *res_y = info_ptr->y_pixels_per_unit;
  181969. retval |= PNG_INFO_pHYs;
  181970. }
  181971. if (unit_type != NULL)
  181972. {
  181973. *unit_type = (int)info_ptr->phys_unit_type;
  181974. retval |= PNG_INFO_pHYs;
  181975. }
  181976. }
  181977. return (retval);
  181978. }
  181979. #endif
  181980. png_uint_32 PNGAPI
  181981. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  181982. int *num_palette)
  181983. {
  181984. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  181985. && palette != NULL)
  181986. {
  181987. png_debug1(1, "in %s retrieval function\n", "PLTE");
  181988. *palette = info_ptr->palette;
  181989. *num_palette = info_ptr->num_palette;
  181990. png_debug1(3, "num_palette = %d\n", *num_palette);
  181991. return (PNG_INFO_PLTE);
  181992. }
  181993. return (0);
  181994. }
  181995. #if defined(PNG_sBIT_SUPPORTED)
  181996. png_uint_32 PNGAPI
  181997. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  181998. {
  181999. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  182000. && sig_bit != NULL)
  182001. {
  182002. png_debug1(1, "in %s retrieval function\n", "sBIT");
  182003. *sig_bit = &(info_ptr->sig_bit);
  182004. return (PNG_INFO_sBIT);
  182005. }
  182006. return (0);
  182007. }
  182008. #endif
  182009. #if defined(PNG_TEXT_SUPPORTED)
  182010. png_uint_32 PNGAPI
  182011. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  182012. int *num_text)
  182013. {
  182014. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  182015. {
  182016. png_debug1(1, "in %s retrieval function\n",
  182017. (png_ptr->chunk_name[0] == '\0' ? "text"
  182018. : (png_const_charp)png_ptr->chunk_name));
  182019. if (text_ptr != NULL)
  182020. *text_ptr = info_ptr->text;
  182021. if (num_text != NULL)
  182022. *num_text = info_ptr->num_text;
  182023. return ((png_uint_32)info_ptr->num_text);
  182024. }
  182025. if (num_text != NULL)
  182026. *num_text = 0;
  182027. return(0);
  182028. }
  182029. #endif
  182030. #if defined(PNG_tIME_SUPPORTED)
  182031. png_uint_32 PNGAPI
  182032. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  182033. {
  182034. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  182035. && mod_time != NULL)
  182036. {
  182037. png_debug1(1, "in %s retrieval function\n", "tIME");
  182038. *mod_time = &(info_ptr->mod_time);
  182039. return (PNG_INFO_tIME);
  182040. }
  182041. return (0);
  182042. }
  182043. #endif
  182044. #if defined(PNG_tRNS_SUPPORTED)
  182045. png_uint_32 PNGAPI
  182046. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  182047. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  182048. {
  182049. png_uint_32 retval = 0;
  182050. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  182051. {
  182052. png_debug1(1, "in %s retrieval function\n", "tRNS");
  182053. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  182054. {
  182055. if (trans != NULL)
  182056. {
  182057. *trans = info_ptr->trans;
  182058. retval |= PNG_INFO_tRNS;
  182059. }
  182060. if (trans_values != NULL)
  182061. *trans_values = &(info_ptr->trans_values);
  182062. }
  182063. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  182064. {
  182065. if (trans_values != NULL)
  182066. {
  182067. *trans_values = &(info_ptr->trans_values);
  182068. retval |= PNG_INFO_tRNS;
  182069. }
  182070. if(trans != NULL)
  182071. *trans = NULL;
  182072. }
  182073. if(num_trans != NULL)
  182074. {
  182075. *num_trans = info_ptr->num_trans;
  182076. retval |= PNG_INFO_tRNS;
  182077. }
  182078. }
  182079. return (retval);
  182080. }
  182081. #endif
  182082. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182083. png_uint_32 PNGAPI
  182084. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  182085. png_unknown_chunkpp unknowns)
  182086. {
  182087. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  182088. {
  182089. *unknowns = info_ptr->unknown_chunks;
  182090. return ((png_uint_32)info_ptr->unknown_chunks_num);
  182091. }
  182092. return (0);
  182093. }
  182094. #endif
  182095. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182096. png_byte PNGAPI
  182097. png_get_rgb_to_gray_status (png_structp png_ptr)
  182098. {
  182099. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  182100. }
  182101. #endif
  182102. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182103. png_voidp PNGAPI
  182104. png_get_user_chunk_ptr(png_structp png_ptr)
  182105. {
  182106. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  182107. }
  182108. #endif
  182109. #ifdef PNG_WRITE_SUPPORTED
  182110. png_uint_32 PNGAPI
  182111. png_get_compression_buffer_size(png_structp png_ptr)
  182112. {
  182113. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  182114. }
  182115. #endif
  182116. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  182117. #ifndef PNG_1_0_X
  182118. /* this function was added to libpng 1.2.0 and should exist by default */
  182119. png_uint_32 PNGAPI
  182120. png_get_asm_flags (png_structp png_ptr)
  182121. {
  182122. /* obsolete, to be removed from libpng-1.4.0 */
  182123. return (png_ptr? 0L: 0L);
  182124. }
  182125. /* this function was added to libpng 1.2.0 and should exist by default */
  182126. png_uint_32 PNGAPI
  182127. png_get_asm_flagmask (int flag_select)
  182128. {
  182129. /* obsolete, to be removed from libpng-1.4.0 */
  182130. flag_select=flag_select;
  182131. return 0L;
  182132. }
  182133. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  182134. /* this function was added to libpng 1.2.0 */
  182135. png_uint_32 PNGAPI
  182136. png_get_mmx_flagmask (int flag_select, int *compilerID)
  182137. {
  182138. /* obsolete, to be removed from libpng-1.4.0 */
  182139. flag_select=flag_select;
  182140. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  182141. return 0L;
  182142. }
  182143. /* this function was added to libpng 1.2.0 */
  182144. png_byte PNGAPI
  182145. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  182146. {
  182147. /* obsolete, to be removed from libpng-1.4.0 */
  182148. return (png_ptr? 0: 0);
  182149. }
  182150. /* this function was added to libpng 1.2.0 */
  182151. png_uint_32 PNGAPI
  182152. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  182153. {
  182154. /* obsolete, to be removed from libpng-1.4.0 */
  182155. return (png_ptr? 0L: 0L);
  182156. }
  182157. #endif /* ?PNG_1_0_X */
  182158. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  182159. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182160. /* these functions were added to libpng 1.2.6 */
  182161. png_uint_32 PNGAPI
  182162. png_get_user_width_max (png_structp png_ptr)
  182163. {
  182164. return (png_ptr? png_ptr->user_width_max : 0);
  182165. }
  182166. png_uint_32 PNGAPI
  182167. png_get_user_height_max (png_structp png_ptr)
  182168. {
  182169. return (png_ptr? png_ptr->user_height_max : 0);
  182170. }
  182171. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  182172. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182173. /********* End of inlined file: pngget.c *********/
  182174. /********* Start of inlined file: pngmem.c *********/
  182175. /* pngmem.c - stub functions for memory allocation
  182176. *
  182177. * Last changed in libpng 1.2.13 November 13, 2006
  182178. * For conditions of distribution and use, see copyright notice in png.h
  182179. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  182180. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182181. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182182. *
  182183. * This file provides a location for all memory allocation. Users who
  182184. * need special memory handling are expected to supply replacement
  182185. * functions for png_malloc() and png_free(), and to use
  182186. * png_create_read_struct_2() and png_create_write_struct_2() to
  182187. * identify the replacement functions.
  182188. */
  182189. #define PNG_INTERNAL
  182190. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182191. /* Borland DOS special memory handler */
  182192. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182193. /* if you change this, be sure to change the one in png.h also */
  182194. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  182195. by a single call to calloc() if this is thought to improve performance. */
  182196. png_voidp /* PRIVATE */
  182197. png_create_struct(int type)
  182198. {
  182199. #ifdef PNG_USER_MEM_SUPPORTED
  182200. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182201. }
  182202. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  182203. png_voidp /* PRIVATE */
  182204. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182205. {
  182206. #endif /* PNG_USER_MEM_SUPPORTED */
  182207. png_size_t size;
  182208. png_voidp struct_ptr;
  182209. if (type == PNG_STRUCT_INFO)
  182210. size = png_sizeof(png_info);
  182211. else if (type == PNG_STRUCT_PNG)
  182212. size = png_sizeof(png_struct);
  182213. else
  182214. return (png_get_copyright(NULL));
  182215. #ifdef PNG_USER_MEM_SUPPORTED
  182216. if(malloc_fn != NULL)
  182217. {
  182218. png_struct dummy_struct;
  182219. png_structp png_ptr = &dummy_struct;
  182220. png_ptr->mem_ptr=mem_ptr;
  182221. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  182222. }
  182223. else
  182224. #endif /* PNG_USER_MEM_SUPPORTED */
  182225. struct_ptr = (png_voidp)farmalloc(size);
  182226. if (struct_ptr != NULL)
  182227. png_memset(struct_ptr, 0, size);
  182228. return (struct_ptr);
  182229. }
  182230. /* Free memory allocated by a png_create_struct() call */
  182231. void /* PRIVATE */
  182232. png_destroy_struct(png_voidp struct_ptr)
  182233. {
  182234. #ifdef PNG_USER_MEM_SUPPORTED
  182235. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182236. }
  182237. /* Free memory allocated by a png_create_struct() call */
  182238. void /* PRIVATE */
  182239. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182240. png_voidp mem_ptr)
  182241. {
  182242. #endif
  182243. if (struct_ptr != NULL)
  182244. {
  182245. #ifdef PNG_USER_MEM_SUPPORTED
  182246. if(free_fn != NULL)
  182247. {
  182248. png_struct dummy_struct;
  182249. png_structp png_ptr = &dummy_struct;
  182250. png_ptr->mem_ptr=mem_ptr;
  182251. (*(free_fn))(png_ptr, struct_ptr);
  182252. return;
  182253. }
  182254. #endif /* PNG_USER_MEM_SUPPORTED */
  182255. farfree (struct_ptr);
  182256. }
  182257. }
  182258. /* Allocate memory. For reasonable files, size should never exceed
  182259. * 64K. However, zlib may allocate more then 64K if you don't tell
  182260. * it not to. See zconf.h and png.h for more information. zlib does
  182261. * need to allocate exactly 64K, so whatever you call here must
  182262. * have the ability to do that.
  182263. *
  182264. * Borland seems to have a problem in DOS mode for exactly 64K.
  182265. * It gives you a segment with an offset of 8 (perhaps to store its
  182266. * memory stuff). zlib doesn't like this at all, so we have to
  182267. * detect and deal with it. This code should not be needed in
  182268. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  182269. * been updated by Alexander Lehmann for version 0.89 to waste less
  182270. * memory.
  182271. *
  182272. * Note that we can't use png_size_t for the "size" declaration,
  182273. * since on some systems a png_size_t is a 16-bit quantity, and as a
  182274. * result, we would be truncating potentially larger memory requests
  182275. * (which should cause a fatal error) and introducing major problems.
  182276. */
  182277. png_voidp PNGAPI
  182278. png_malloc(png_structp png_ptr, png_uint_32 size)
  182279. {
  182280. png_voidp ret;
  182281. if (png_ptr == NULL || size == 0)
  182282. return (NULL);
  182283. #ifdef PNG_USER_MEM_SUPPORTED
  182284. if(png_ptr->malloc_fn != NULL)
  182285. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182286. else
  182287. ret = (png_malloc_default(png_ptr, size));
  182288. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182289. png_error(png_ptr, "Out of memory!");
  182290. return (ret);
  182291. }
  182292. png_voidp PNGAPI
  182293. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182294. {
  182295. png_voidp ret;
  182296. #endif /* PNG_USER_MEM_SUPPORTED */
  182297. if (png_ptr == NULL || size == 0)
  182298. return (NULL);
  182299. #ifdef PNG_MAX_MALLOC_64K
  182300. if (size > (png_uint_32)65536L)
  182301. {
  182302. png_warning(png_ptr, "Cannot Allocate > 64K");
  182303. ret = NULL;
  182304. }
  182305. else
  182306. #endif
  182307. if (size != (size_t)size)
  182308. ret = NULL;
  182309. else if (size == (png_uint_32)65536L)
  182310. {
  182311. if (png_ptr->offset_table == NULL)
  182312. {
  182313. /* try to see if we need to do any of this fancy stuff */
  182314. ret = farmalloc(size);
  182315. if (ret == NULL || ((png_size_t)ret & 0xffff))
  182316. {
  182317. int num_blocks;
  182318. png_uint_32 total_size;
  182319. png_bytep table;
  182320. int i;
  182321. png_byte huge * hptr;
  182322. if (ret != NULL)
  182323. {
  182324. farfree(ret);
  182325. ret = NULL;
  182326. }
  182327. if(png_ptr->zlib_window_bits > 14)
  182328. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  182329. else
  182330. num_blocks = 1;
  182331. if (png_ptr->zlib_mem_level >= 7)
  182332. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  182333. else
  182334. num_blocks++;
  182335. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  182336. table = farmalloc(total_size);
  182337. if (table == NULL)
  182338. {
  182339. #ifndef PNG_USER_MEM_SUPPORTED
  182340. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182341. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  182342. else
  182343. png_warning(png_ptr, "Out Of Memory.");
  182344. #endif
  182345. return (NULL);
  182346. }
  182347. if ((png_size_t)table & 0xfff0)
  182348. {
  182349. #ifndef PNG_USER_MEM_SUPPORTED
  182350. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182351. png_error(png_ptr,
  182352. "Farmalloc didn't return normalized pointer");
  182353. else
  182354. png_warning(png_ptr,
  182355. "Farmalloc didn't return normalized pointer");
  182356. #endif
  182357. return (NULL);
  182358. }
  182359. png_ptr->offset_table = table;
  182360. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  182361. png_sizeof (png_bytep));
  182362. if (png_ptr->offset_table_ptr == NULL)
  182363. {
  182364. #ifndef PNG_USER_MEM_SUPPORTED
  182365. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182366. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  182367. else
  182368. png_warning(png_ptr, "Out Of memory.");
  182369. #endif
  182370. return (NULL);
  182371. }
  182372. hptr = (png_byte huge *)table;
  182373. if ((png_size_t)hptr & 0xf)
  182374. {
  182375. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  182376. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  182377. }
  182378. for (i = 0; i < num_blocks; i++)
  182379. {
  182380. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  182381. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  182382. }
  182383. png_ptr->offset_table_number = num_blocks;
  182384. png_ptr->offset_table_count = 0;
  182385. png_ptr->offset_table_count_free = 0;
  182386. }
  182387. }
  182388. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  182389. {
  182390. #ifndef PNG_USER_MEM_SUPPORTED
  182391. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182392. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  182393. else
  182394. png_warning(png_ptr, "Out of Memory.");
  182395. #endif
  182396. return (NULL);
  182397. }
  182398. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  182399. }
  182400. else
  182401. ret = farmalloc(size);
  182402. #ifndef PNG_USER_MEM_SUPPORTED
  182403. if (ret == NULL)
  182404. {
  182405. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182406. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182407. else
  182408. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182409. }
  182410. #endif
  182411. return (ret);
  182412. }
  182413. /* free a pointer allocated by png_malloc(). In the default
  182414. configuration, png_ptr is not used, but is passed in case it
  182415. is needed. If ptr is NULL, return without taking any action. */
  182416. void PNGAPI
  182417. png_free(png_structp png_ptr, png_voidp ptr)
  182418. {
  182419. if (png_ptr == NULL || ptr == NULL)
  182420. return;
  182421. #ifdef PNG_USER_MEM_SUPPORTED
  182422. if (png_ptr->free_fn != NULL)
  182423. {
  182424. (*(png_ptr->free_fn))(png_ptr, ptr);
  182425. return;
  182426. }
  182427. else png_free_default(png_ptr, ptr);
  182428. }
  182429. void PNGAPI
  182430. png_free_default(png_structp png_ptr, png_voidp ptr)
  182431. {
  182432. #endif /* PNG_USER_MEM_SUPPORTED */
  182433. if(png_ptr == NULL) return;
  182434. if (png_ptr->offset_table != NULL)
  182435. {
  182436. int i;
  182437. for (i = 0; i < png_ptr->offset_table_count; i++)
  182438. {
  182439. if (ptr == png_ptr->offset_table_ptr[i])
  182440. {
  182441. ptr = NULL;
  182442. png_ptr->offset_table_count_free++;
  182443. break;
  182444. }
  182445. }
  182446. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  182447. {
  182448. farfree(png_ptr->offset_table);
  182449. farfree(png_ptr->offset_table_ptr);
  182450. png_ptr->offset_table = NULL;
  182451. png_ptr->offset_table_ptr = NULL;
  182452. }
  182453. }
  182454. if (ptr != NULL)
  182455. {
  182456. farfree(ptr);
  182457. }
  182458. }
  182459. #else /* Not the Borland DOS special memory handler */
  182460. /* Allocate memory for a png_struct or a png_info. The malloc and
  182461. memset can be replaced by a single call to calloc() if this is thought
  182462. to improve performance noticably. */
  182463. png_voidp /* PRIVATE */
  182464. png_create_struct(int type)
  182465. {
  182466. #ifdef PNG_USER_MEM_SUPPORTED
  182467. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182468. }
  182469. /* Allocate memory for a png_struct or a png_info. The malloc and
  182470. memset can be replaced by a single call to calloc() if this is thought
  182471. to improve performance noticably. */
  182472. png_voidp /* PRIVATE */
  182473. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182474. {
  182475. #endif /* PNG_USER_MEM_SUPPORTED */
  182476. png_size_t size;
  182477. png_voidp struct_ptr;
  182478. if (type == PNG_STRUCT_INFO)
  182479. size = png_sizeof(png_info);
  182480. else if (type == PNG_STRUCT_PNG)
  182481. size = png_sizeof(png_struct);
  182482. else
  182483. return (NULL);
  182484. #ifdef PNG_USER_MEM_SUPPORTED
  182485. if(malloc_fn != NULL)
  182486. {
  182487. png_struct dummy_struct;
  182488. png_structp png_ptr = &dummy_struct;
  182489. png_ptr->mem_ptr=mem_ptr;
  182490. struct_ptr = (*(malloc_fn))(png_ptr, size);
  182491. if (struct_ptr != NULL)
  182492. png_memset(struct_ptr, 0, size);
  182493. return (struct_ptr);
  182494. }
  182495. #endif /* PNG_USER_MEM_SUPPORTED */
  182496. #if defined(__TURBOC__) && !defined(__FLAT__)
  182497. struct_ptr = (png_voidp)farmalloc(size);
  182498. #else
  182499. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182500. struct_ptr = (png_voidp)halloc(size,1);
  182501. # else
  182502. struct_ptr = (png_voidp)malloc(size);
  182503. # endif
  182504. #endif
  182505. if (struct_ptr != NULL)
  182506. png_memset(struct_ptr, 0, size);
  182507. return (struct_ptr);
  182508. }
  182509. /* Free memory allocated by a png_create_struct() call */
  182510. void /* PRIVATE */
  182511. png_destroy_struct(png_voidp struct_ptr)
  182512. {
  182513. #ifdef PNG_USER_MEM_SUPPORTED
  182514. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182515. }
  182516. /* Free memory allocated by a png_create_struct() call */
  182517. void /* PRIVATE */
  182518. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182519. png_voidp mem_ptr)
  182520. {
  182521. #endif /* PNG_USER_MEM_SUPPORTED */
  182522. if (struct_ptr != NULL)
  182523. {
  182524. #ifdef PNG_USER_MEM_SUPPORTED
  182525. if(free_fn != NULL)
  182526. {
  182527. png_struct dummy_struct;
  182528. png_structp png_ptr = &dummy_struct;
  182529. png_ptr->mem_ptr=mem_ptr;
  182530. (*(free_fn))(png_ptr, struct_ptr);
  182531. return;
  182532. }
  182533. #endif /* PNG_USER_MEM_SUPPORTED */
  182534. #if defined(__TURBOC__) && !defined(__FLAT__)
  182535. farfree(struct_ptr);
  182536. #else
  182537. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182538. hfree(struct_ptr);
  182539. # else
  182540. free(struct_ptr);
  182541. # endif
  182542. #endif
  182543. }
  182544. }
  182545. /* Allocate memory. For reasonable files, size should never exceed
  182546. 64K. However, zlib may allocate more then 64K if you don't tell
  182547. it not to. See zconf.h and png.h for more information. zlib does
  182548. need to allocate exactly 64K, so whatever you call here must
  182549. have the ability to do that. */
  182550. png_voidp PNGAPI
  182551. png_malloc(png_structp png_ptr, png_uint_32 size)
  182552. {
  182553. png_voidp ret;
  182554. #ifdef PNG_USER_MEM_SUPPORTED
  182555. if (png_ptr == NULL || size == 0)
  182556. return (NULL);
  182557. if(png_ptr->malloc_fn != NULL)
  182558. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182559. else
  182560. ret = (png_malloc_default(png_ptr, size));
  182561. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182562. png_error(png_ptr, "Out of Memory!");
  182563. return (ret);
  182564. }
  182565. png_voidp PNGAPI
  182566. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182567. {
  182568. png_voidp ret;
  182569. #endif /* PNG_USER_MEM_SUPPORTED */
  182570. if (png_ptr == NULL || size == 0)
  182571. return (NULL);
  182572. #ifdef PNG_MAX_MALLOC_64K
  182573. if (size > (png_uint_32)65536L)
  182574. {
  182575. #ifndef PNG_USER_MEM_SUPPORTED
  182576. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182577. png_error(png_ptr, "Cannot Allocate > 64K");
  182578. else
  182579. #endif
  182580. return NULL;
  182581. }
  182582. #endif
  182583. /* Check for overflow */
  182584. #if defined(__TURBOC__) && !defined(__FLAT__)
  182585. if (size != (unsigned long)size)
  182586. ret = NULL;
  182587. else
  182588. ret = farmalloc(size);
  182589. #else
  182590. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182591. if (size != (unsigned long)size)
  182592. ret = NULL;
  182593. else
  182594. ret = halloc(size, 1);
  182595. # else
  182596. if (size != (size_t)size)
  182597. ret = NULL;
  182598. else
  182599. ret = malloc((size_t)size);
  182600. # endif
  182601. #endif
  182602. #ifndef PNG_USER_MEM_SUPPORTED
  182603. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182604. png_error(png_ptr, "Out of Memory");
  182605. #endif
  182606. return (ret);
  182607. }
  182608. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  182609. without taking any action. */
  182610. void PNGAPI
  182611. png_free(png_structp png_ptr, png_voidp ptr)
  182612. {
  182613. if (png_ptr == NULL || ptr == NULL)
  182614. return;
  182615. #ifdef PNG_USER_MEM_SUPPORTED
  182616. if (png_ptr->free_fn != NULL)
  182617. {
  182618. (*(png_ptr->free_fn))(png_ptr, ptr);
  182619. return;
  182620. }
  182621. else png_free_default(png_ptr, ptr);
  182622. }
  182623. void PNGAPI
  182624. png_free_default(png_structp png_ptr, png_voidp ptr)
  182625. {
  182626. if (png_ptr == NULL || ptr == NULL)
  182627. return;
  182628. #endif /* PNG_USER_MEM_SUPPORTED */
  182629. #if defined(__TURBOC__) && !defined(__FLAT__)
  182630. farfree(ptr);
  182631. #else
  182632. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182633. hfree(ptr);
  182634. # else
  182635. free(ptr);
  182636. # endif
  182637. #endif
  182638. }
  182639. #endif /* Not Borland DOS special memory handler */
  182640. #if defined(PNG_1_0_X)
  182641. # define png_malloc_warn png_malloc
  182642. #else
  182643. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  182644. * function will set up png_malloc() to issue a png_warning and return NULL
  182645. * instead of issuing a png_error, if it fails to allocate the requested
  182646. * memory.
  182647. */
  182648. png_voidp PNGAPI
  182649. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  182650. {
  182651. png_voidp ptr;
  182652. png_uint_32 save_flags;
  182653. if(png_ptr == NULL) return (NULL);
  182654. save_flags=png_ptr->flags;
  182655. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  182656. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  182657. png_ptr->flags=save_flags;
  182658. return(ptr);
  182659. }
  182660. #endif
  182661. png_voidp PNGAPI
  182662. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  182663. png_uint_32 length)
  182664. {
  182665. png_size_t size;
  182666. size = (png_size_t)length;
  182667. if ((png_uint_32)size != length)
  182668. png_error(png_ptr,"Overflow in png_memcpy_check.");
  182669. return(png_memcpy (s1, s2, size));
  182670. }
  182671. png_voidp PNGAPI
  182672. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  182673. png_uint_32 length)
  182674. {
  182675. png_size_t size;
  182676. size = (png_size_t)length;
  182677. if ((png_uint_32)size != length)
  182678. png_error(png_ptr,"Overflow in png_memset_check.");
  182679. return (png_memset (s1, value, size));
  182680. }
  182681. #ifdef PNG_USER_MEM_SUPPORTED
  182682. /* This function is called when the application wants to use another method
  182683. * of allocating and freeing memory.
  182684. */
  182685. void PNGAPI
  182686. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  182687. malloc_fn, png_free_ptr free_fn)
  182688. {
  182689. if(png_ptr != NULL) {
  182690. png_ptr->mem_ptr = mem_ptr;
  182691. png_ptr->malloc_fn = malloc_fn;
  182692. png_ptr->free_fn = free_fn;
  182693. }
  182694. }
  182695. /* This function returns a pointer to the mem_ptr associated with the user
  182696. * functions. The application should free any memory associated with this
  182697. * pointer before png_write_destroy and png_read_destroy are called.
  182698. */
  182699. png_voidp PNGAPI
  182700. png_get_mem_ptr(png_structp png_ptr)
  182701. {
  182702. if(png_ptr == NULL) return (NULL);
  182703. return ((png_voidp)png_ptr->mem_ptr);
  182704. }
  182705. #endif /* PNG_USER_MEM_SUPPORTED */
  182706. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182707. /********* End of inlined file: pngmem.c *********/
  182708. /********* Start of inlined file: pngread.c *********/
  182709. /* pngread.c - read a PNG file
  182710. *
  182711. * Last changed in libpng 1.2.20 September 7, 2007
  182712. * For conditions of distribution and use, see copyright notice in png.h
  182713. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182714. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182715. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182716. *
  182717. * This file contains routines that an application calls directly to
  182718. * read a PNG file or stream.
  182719. */
  182720. #define PNG_INTERNAL
  182721. #if defined(PNG_READ_SUPPORTED)
  182722. /* Create a PNG structure for reading, and allocate any memory needed. */
  182723. png_structp PNGAPI
  182724. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  182725. png_error_ptr error_fn, png_error_ptr warn_fn)
  182726. {
  182727. #ifdef PNG_USER_MEM_SUPPORTED
  182728. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  182729. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  182730. }
  182731. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  182732. png_structp PNGAPI
  182733. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  182734. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182735. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  182736. {
  182737. #endif /* PNG_USER_MEM_SUPPORTED */
  182738. png_structp png_ptr;
  182739. #ifdef PNG_SETJMP_SUPPORTED
  182740. #ifdef USE_FAR_KEYWORD
  182741. jmp_buf jmpbuf;
  182742. #endif
  182743. #endif
  182744. int i;
  182745. png_debug(1, "in png_create_read_struct\n");
  182746. #ifdef PNG_USER_MEM_SUPPORTED
  182747. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  182748. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  182749. #else
  182750. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182751. #endif
  182752. if (png_ptr == NULL)
  182753. return (NULL);
  182754. /* added at libpng-1.2.6 */
  182755. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182756. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182757. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182758. #endif
  182759. #ifdef PNG_SETJMP_SUPPORTED
  182760. #ifdef USE_FAR_KEYWORD
  182761. if (setjmp(jmpbuf))
  182762. #else
  182763. if (setjmp(png_ptr->jmpbuf))
  182764. #endif
  182765. {
  182766. png_free(png_ptr, png_ptr->zbuf);
  182767. png_ptr->zbuf=NULL;
  182768. #ifdef PNG_USER_MEM_SUPPORTED
  182769. png_destroy_struct_2((png_voidp)png_ptr,
  182770. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  182771. #else
  182772. png_destroy_struct((png_voidp)png_ptr);
  182773. #endif
  182774. return (NULL);
  182775. }
  182776. #ifdef USE_FAR_KEYWORD
  182777. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182778. #endif
  182779. #endif
  182780. #ifdef PNG_USER_MEM_SUPPORTED
  182781. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  182782. #endif
  182783. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  182784. i=0;
  182785. do
  182786. {
  182787. if(user_png_ver[i] != png_libpng_ver[i])
  182788. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182789. } while (png_libpng_ver[i++]);
  182790. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  182791. {
  182792. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  182793. * we must recompile any applications that use any older library version.
  182794. * For versions after libpng 1.0, we will be compatible, so we need
  182795. * only check the first digit.
  182796. */
  182797. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  182798. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  182799. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  182800. {
  182801. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182802. char msg[80];
  182803. if (user_png_ver)
  182804. {
  182805. png_snprintf(msg, 80,
  182806. "Application was compiled with png.h from libpng-%.20s",
  182807. user_png_ver);
  182808. png_warning(png_ptr, msg);
  182809. }
  182810. png_snprintf(msg, 80,
  182811. "Application is running with png.c from libpng-%.20s",
  182812. png_libpng_ver);
  182813. png_warning(png_ptr, msg);
  182814. #endif
  182815. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182816. png_ptr->flags=0;
  182817. #endif
  182818. png_error(png_ptr,
  182819. "Incompatible libpng version in application and library");
  182820. }
  182821. }
  182822. /* initialize zbuf - compression buffer */
  182823. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182824. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182825. (png_uint_32)png_ptr->zbuf_size);
  182826. png_ptr->zstream.zalloc = png_zalloc;
  182827. png_ptr->zstream.zfree = png_zfree;
  182828. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182829. switch (inflateInit(&png_ptr->zstream))
  182830. {
  182831. case Z_OK: /* Do nothing */ break;
  182832. case Z_MEM_ERROR:
  182833. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  182834. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  182835. default: png_error(png_ptr, "Unknown zlib error");
  182836. }
  182837. png_ptr->zstream.next_out = png_ptr->zbuf;
  182838. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182839. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182840. #ifdef PNG_SETJMP_SUPPORTED
  182841. /* Applications that neglect to set up their own setjmp() and then encounter
  182842. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  182843. abort instead of returning. */
  182844. #ifdef USE_FAR_KEYWORD
  182845. if (setjmp(jmpbuf))
  182846. PNG_ABORT();
  182847. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182848. #else
  182849. if (setjmp(png_ptr->jmpbuf))
  182850. PNG_ABORT();
  182851. #endif
  182852. #endif
  182853. return (png_ptr);
  182854. }
  182855. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182856. /* Initialize PNG structure for reading, and allocate any memory needed.
  182857. This interface is deprecated in favour of the png_create_read_struct(),
  182858. and it will disappear as of libpng-1.3.0. */
  182859. #undef png_read_init
  182860. void PNGAPI
  182861. png_read_init(png_structp png_ptr)
  182862. {
  182863. /* We only come here via pre-1.0.7-compiled applications */
  182864. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  182865. }
  182866. void PNGAPI
  182867. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  182868. png_size_t png_struct_size, png_size_t png_info_size)
  182869. {
  182870. /* We only come here via pre-1.0.12-compiled applications */
  182871. if(png_ptr == NULL) return;
  182872. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182873. if(png_sizeof(png_struct) > png_struct_size ||
  182874. png_sizeof(png_info) > png_info_size)
  182875. {
  182876. char msg[80];
  182877. png_ptr->warning_fn=NULL;
  182878. if (user_png_ver)
  182879. {
  182880. png_snprintf(msg, 80,
  182881. "Application was compiled with png.h from libpng-%.20s",
  182882. user_png_ver);
  182883. png_warning(png_ptr, msg);
  182884. }
  182885. png_snprintf(msg, 80,
  182886. "Application is running with png.c from libpng-%.20s",
  182887. png_libpng_ver);
  182888. png_warning(png_ptr, msg);
  182889. }
  182890. #endif
  182891. if(png_sizeof(png_struct) > png_struct_size)
  182892. {
  182893. png_ptr->error_fn=NULL;
  182894. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182895. png_ptr->flags=0;
  182896. #endif
  182897. png_error(png_ptr,
  182898. "The png struct allocated by the application for reading is too small.");
  182899. }
  182900. if(png_sizeof(png_info) > png_info_size)
  182901. {
  182902. png_ptr->error_fn=NULL;
  182903. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182904. png_ptr->flags=0;
  182905. #endif
  182906. png_error(png_ptr,
  182907. "The info struct allocated by application for reading is too small.");
  182908. }
  182909. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  182910. }
  182911. #endif /* PNG_1_0_X || PNG_1_2_X */
  182912. void PNGAPI
  182913. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  182914. png_size_t png_struct_size)
  182915. {
  182916. #ifdef PNG_SETJMP_SUPPORTED
  182917. jmp_buf tmp_jmp; /* to save current jump buffer */
  182918. #endif
  182919. int i=0;
  182920. png_structp png_ptr=*ptr_ptr;
  182921. if(png_ptr == NULL) return;
  182922. do
  182923. {
  182924. if(user_png_ver[i] != png_libpng_ver[i])
  182925. {
  182926. #ifdef PNG_LEGACY_SUPPORTED
  182927. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182928. #else
  182929. png_ptr->warning_fn=NULL;
  182930. png_warning(png_ptr,
  182931. "Application uses deprecated png_read_init() and should be recompiled.");
  182932. break;
  182933. #endif
  182934. }
  182935. } while (png_libpng_ver[i++]);
  182936. png_debug(1, "in png_read_init_3\n");
  182937. #ifdef PNG_SETJMP_SUPPORTED
  182938. /* save jump buffer and error functions */
  182939. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182940. #endif
  182941. if(png_sizeof(png_struct) > png_struct_size)
  182942. {
  182943. png_destroy_struct(png_ptr);
  182944. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182945. png_ptr = *ptr_ptr;
  182946. }
  182947. /* reset all variables to 0 */
  182948. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182949. #ifdef PNG_SETJMP_SUPPORTED
  182950. /* restore jump buffer */
  182951. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182952. #endif
  182953. /* added at libpng-1.2.6 */
  182954. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182955. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182956. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182957. #endif
  182958. /* initialize zbuf - compression buffer */
  182959. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182960. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182961. (png_uint_32)png_ptr->zbuf_size);
  182962. png_ptr->zstream.zalloc = png_zalloc;
  182963. png_ptr->zstream.zfree = png_zfree;
  182964. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182965. switch (inflateInit(&png_ptr->zstream))
  182966. {
  182967. case Z_OK: /* Do nothing */ break;
  182968. case Z_MEM_ERROR:
  182969. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  182970. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  182971. default: png_error(png_ptr, "Unknown zlib error");
  182972. }
  182973. png_ptr->zstream.next_out = png_ptr->zbuf;
  182974. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182975. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182976. }
  182977. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182978. /* Read the information before the actual image data. This has been
  182979. * changed in v0.90 to allow reading a file that already has the magic
  182980. * bytes read from the stream. You can tell libpng how many bytes have
  182981. * been read from the beginning of the stream (up to the maximum of 8)
  182982. * via png_set_sig_bytes(), and we will only check the remaining bytes
  182983. * here. The application can then have access to the signature bytes we
  182984. * read if it is determined that this isn't a valid PNG file.
  182985. */
  182986. void PNGAPI
  182987. png_read_info(png_structp png_ptr, png_infop info_ptr)
  182988. {
  182989. if(png_ptr == NULL) return;
  182990. png_debug(1, "in png_read_info\n");
  182991. /* If we haven't checked all of the PNG signature bytes, do so now. */
  182992. if (png_ptr->sig_bytes < 8)
  182993. {
  182994. png_size_t num_checked = png_ptr->sig_bytes,
  182995. num_to_check = 8 - num_checked;
  182996. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  182997. png_ptr->sig_bytes = 8;
  182998. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182999. {
  183000. if (num_checked < 4 &&
  183001. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  183002. png_error(png_ptr, "Not a PNG file");
  183003. else
  183004. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  183005. }
  183006. if (num_checked < 3)
  183007. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  183008. }
  183009. for(;;)
  183010. {
  183011. #ifdef PNG_USE_LOCAL_ARRAYS
  183012. PNG_CONST PNG_IHDR;
  183013. PNG_CONST PNG_IDAT;
  183014. PNG_CONST PNG_IEND;
  183015. PNG_CONST PNG_PLTE;
  183016. #if defined(PNG_READ_bKGD_SUPPORTED)
  183017. PNG_CONST PNG_bKGD;
  183018. #endif
  183019. #if defined(PNG_READ_cHRM_SUPPORTED)
  183020. PNG_CONST PNG_cHRM;
  183021. #endif
  183022. #if defined(PNG_READ_gAMA_SUPPORTED)
  183023. PNG_CONST PNG_gAMA;
  183024. #endif
  183025. #if defined(PNG_READ_hIST_SUPPORTED)
  183026. PNG_CONST PNG_hIST;
  183027. #endif
  183028. #if defined(PNG_READ_iCCP_SUPPORTED)
  183029. PNG_CONST PNG_iCCP;
  183030. #endif
  183031. #if defined(PNG_READ_iTXt_SUPPORTED)
  183032. PNG_CONST PNG_iTXt;
  183033. #endif
  183034. #if defined(PNG_READ_oFFs_SUPPORTED)
  183035. PNG_CONST PNG_oFFs;
  183036. #endif
  183037. #if defined(PNG_READ_pCAL_SUPPORTED)
  183038. PNG_CONST PNG_pCAL;
  183039. #endif
  183040. #if defined(PNG_READ_pHYs_SUPPORTED)
  183041. PNG_CONST PNG_pHYs;
  183042. #endif
  183043. #if defined(PNG_READ_sBIT_SUPPORTED)
  183044. PNG_CONST PNG_sBIT;
  183045. #endif
  183046. #if defined(PNG_READ_sCAL_SUPPORTED)
  183047. PNG_CONST PNG_sCAL;
  183048. #endif
  183049. #if defined(PNG_READ_sPLT_SUPPORTED)
  183050. PNG_CONST PNG_sPLT;
  183051. #endif
  183052. #if defined(PNG_READ_sRGB_SUPPORTED)
  183053. PNG_CONST PNG_sRGB;
  183054. #endif
  183055. #if defined(PNG_READ_tEXt_SUPPORTED)
  183056. PNG_CONST PNG_tEXt;
  183057. #endif
  183058. #if defined(PNG_READ_tIME_SUPPORTED)
  183059. PNG_CONST PNG_tIME;
  183060. #endif
  183061. #if defined(PNG_READ_tRNS_SUPPORTED)
  183062. PNG_CONST PNG_tRNS;
  183063. #endif
  183064. #if defined(PNG_READ_zTXt_SUPPORTED)
  183065. PNG_CONST PNG_zTXt;
  183066. #endif
  183067. #endif /* PNG_USE_LOCAL_ARRAYS */
  183068. png_byte chunk_length[4];
  183069. png_uint_32 length;
  183070. png_read_data(png_ptr, chunk_length, 4);
  183071. length = png_get_uint_31(png_ptr,chunk_length);
  183072. png_reset_crc(png_ptr);
  183073. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183074. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  183075. length);
  183076. /* This should be a binary subdivision search or a hash for
  183077. * matching the chunk name rather than a linear search.
  183078. */
  183079. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183080. if(png_ptr->mode & PNG_AFTER_IDAT)
  183081. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  183082. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183083. png_handle_IHDR(png_ptr, info_ptr, length);
  183084. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183085. png_handle_IEND(png_ptr, info_ptr, length);
  183086. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183087. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183088. {
  183089. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183090. png_ptr->mode |= PNG_HAVE_IDAT;
  183091. png_handle_unknown(png_ptr, info_ptr, length);
  183092. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183093. png_ptr->mode |= PNG_HAVE_PLTE;
  183094. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183095. {
  183096. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183097. png_error(png_ptr, "Missing IHDR before IDAT");
  183098. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183099. !(png_ptr->mode & PNG_HAVE_PLTE))
  183100. png_error(png_ptr, "Missing PLTE before IDAT");
  183101. break;
  183102. }
  183103. }
  183104. #endif
  183105. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183106. png_handle_PLTE(png_ptr, info_ptr, length);
  183107. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183108. {
  183109. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183110. png_error(png_ptr, "Missing IHDR before IDAT");
  183111. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183112. !(png_ptr->mode & PNG_HAVE_PLTE))
  183113. png_error(png_ptr, "Missing PLTE before IDAT");
  183114. png_ptr->idat_size = length;
  183115. png_ptr->mode |= PNG_HAVE_IDAT;
  183116. break;
  183117. }
  183118. #if defined(PNG_READ_bKGD_SUPPORTED)
  183119. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183120. png_handle_bKGD(png_ptr, info_ptr, length);
  183121. #endif
  183122. #if defined(PNG_READ_cHRM_SUPPORTED)
  183123. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183124. png_handle_cHRM(png_ptr, info_ptr, length);
  183125. #endif
  183126. #if defined(PNG_READ_gAMA_SUPPORTED)
  183127. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183128. png_handle_gAMA(png_ptr, info_ptr, length);
  183129. #endif
  183130. #if defined(PNG_READ_hIST_SUPPORTED)
  183131. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183132. png_handle_hIST(png_ptr, info_ptr, length);
  183133. #endif
  183134. #if defined(PNG_READ_oFFs_SUPPORTED)
  183135. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183136. png_handle_oFFs(png_ptr, info_ptr, length);
  183137. #endif
  183138. #if defined(PNG_READ_pCAL_SUPPORTED)
  183139. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183140. png_handle_pCAL(png_ptr, info_ptr, length);
  183141. #endif
  183142. #if defined(PNG_READ_sCAL_SUPPORTED)
  183143. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183144. png_handle_sCAL(png_ptr, info_ptr, length);
  183145. #endif
  183146. #if defined(PNG_READ_pHYs_SUPPORTED)
  183147. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183148. png_handle_pHYs(png_ptr, info_ptr, length);
  183149. #endif
  183150. #if defined(PNG_READ_sBIT_SUPPORTED)
  183151. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183152. png_handle_sBIT(png_ptr, info_ptr, length);
  183153. #endif
  183154. #if defined(PNG_READ_sRGB_SUPPORTED)
  183155. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183156. png_handle_sRGB(png_ptr, info_ptr, length);
  183157. #endif
  183158. #if defined(PNG_READ_iCCP_SUPPORTED)
  183159. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183160. png_handle_iCCP(png_ptr, info_ptr, length);
  183161. #endif
  183162. #if defined(PNG_READ_sPLT_SUPPORTED)
  183163. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183164. png_handle_sPLT(png_ptr, info_ptr, length);
  183165. #endif
  183166. #if defined(PNG_READ_tEXt_SUPPORTED)
  183167. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183168. png_handle_tEXt(png_ptr, info_ptr, length);
  183169. #endif
  183170. #if defined(PNG_READ_tIME_SUPPORTED)
  183171. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183172. png_handle_tIME(png_ptr, info_ptr, length);
  183173. #endif
  183174. #if defined(PNG_READ_tRNS_SUPPORTED)
  183175. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183176. png_handle_tRNS(png_ptr, info_ptr, length);
  183177. #endif
  183178. #if defined(PNG_READ_zTXt_SUPPORTED)
  183179. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183180. png_handle_zTXt(png_ptr, info_ptr, length);
  183181. #endif
  183182. #if defined(PNG_READ_iTXt_SUPPORTED)
  183183. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183184. png_handle_iTXt(png_ptr, info_ptr, length);
  183185. #endif
  183186. else
  183187. png_handle_unknown(png_ptr, info_ptr, length);
  183188. }
  183189. }
  183190. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183191. /* optional call to update the users info_ptr structure */
  183192. void PNGAPI
  183193. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  183194. {
  183195. png_debug(1, "in png_read_update_info\n");
  183196. if(png_ptr == NULL) return;
  183197. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183198. png_read_start_row(png_ptr);
  183199. else
  183200. png_warning(png_ptr,
  183201. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  183202. png_read_transform_info(png_ptr, info_ptr);
  183203. }
  183204. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183205. /* Initialize palette, background, etc, after transformations
  183206. * are set, but before any reading takes place. This allows
  183207. * the user to obtain a gamma-corrected palette, for example.
  183208. * If the user doesn't call this, we will do it ourselves.
  183209. */
  183210. void PNGAPI
  183211. png_start_read_image(png_structp png_ptr)
  183212. {
  183213. png_debug(1, "in png_start_read_image\n");
  183214. if(png_ptr == NULL) return;
  183215. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183216. png_read_start_row(png_ptr);
  183217. }
  183218. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183219. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183220. void PNGAPI
  183221. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  183222. {
  183223. #ifdef PNG_USE_LOCAL_ARRAYS
  183224. PNG_CONST PNG_IDAT;
  183225. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  183226. 0xff};
  183227. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183228. #endif
  183229. int ret;
  183230. if(png_ptr == NULL) return;
  183231. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  183232. png_ptr->row_number, png_ptr->pass);
  183233. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183234. png_read_start_row(png_ptr);
  183235. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  183236. {
  183237. /* check for transforms that have been set but were defined out */
  183238. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  183239. if (png_ptr->transformations & PNG_INVERT_MONO)
  183240. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  183241. #endif
  183242. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  183243. if (png_ptr->transformations & PNG_FILLER)
  183244. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  183245. #endif
  183246. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  183247. if (png_ptr->transformations & PNG_PACKSWAP)
  183248. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  183249. #endif
  183250. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  183251. if (png_ptr->transformations & PNG_PACK)
  183252. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  183253. #endif
  183254. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  183255. if (png_ptr->transformations & PNG_SHIFT)
  183256. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  183257. #endif
  183258. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  183259. if (png_ptr->transformations & PNG_BGR)
  183260. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  183261. #endif
  183262. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  183263. if (png_ptr->transformations & PNG_SWAP_BYTES)
  183264. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  183265. #endif
  183266. }
  183267. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183268. /* if interlaced and we do not need a new row, combine row and return */
  183269. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183270. {
  183271. switch (png_ptr->pass)
  183272. {
  183273. case 0:
  183274. if (png_ptr->row_number & 0x07)
  183275. {
  183276. if (dsp_row != NULL)
  183277. png_combine_row(png_ptr, dsp_row,
  183278. png_pass_dsp_mask[png_ptr->pass]);
  183279. png_read_finish_row(png_ptr);
  183280. return;
  183281. }
  183282. break;
  183283. case 1:
  183284. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  183285. {
  183286. if (dsp_row != NULL)
  183287. png_combine_row(png_ptr, dsp_row,
  183288. png_pass_dsp_mask[png_ptr->pass]);
  183289. png_read_finish_row(png_ptr);
  183290. return;
  183291. }
  183292. break;
  183293. case 2:
  183294. if ((png_ptr->row_number & 0x07) != 4)
  183295. {
  183296. if (dsp_row != NULL && (png_ptr->row_number & 4))
  183297. png_combine_row(png_ptr, dsp_row,
  183298. png_pass_dsp_mask[png_ptr->pass]);
  183299. png_read_finish_row(png_ptr);
  183300. return;
  183301. }
  183302. break;
  183303. case 3:
  183304. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  183305. {
  183306. if (dsp_row != NULL)
  183307. png_combine_row(png_ptr, dsp_row,
  183308. png_pass_dsp_mask[png_ptr->pass]);
  183309. png_read_finish_row(png_ptr);
  183310. return;
  183311. }
  183312. break;
  183313. case 4:
  183314. if ((png_ptr->row_number & 3) != 2)
  183315. {
  183316. if (dsp_row != NULL && (png_ptr->row_number & 2))
  183317. png_combine_row(png_ptr, dsp_row,
  183318. png_pass_dsp_mask[png_ptr->pass]);
  183319. png_read_finish_row(png_ptr);
  183320. return;
  183321. }
  183322. break;
  183323. case 5:
  183324. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  183325. {
  183326. if (dsp_row != NULL)
  183327. png_combine_row(png_ptr, dsp_row,
  183328. png_pass_dsp_mask[png_ptr->pass]);
  183329. png_read_finish_row(png_ptr);
  183330. return;
  183331. }
  183332. break;
  183333. case 6:
  183334. if (!(png_ptr->row_number & 1))
  183335. {
  183336. png_read_finish_row(png_ptr);
  183337. return;
  183338. }
  183339. break;
  183340. }
  183341. }
  183342. #endif
  183343. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  183344. png_error(png_ptr, "Invalid attempt to read row data");
  183345. png_ptr->zstream.next_out = png_ptr->row_buf;
  183346. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183347. do
  183348. {
  183349. if (!(png_ptr->zstream.avail_in))
  183350. {
  183351. while (!png_ptr->idat_size)
  183352. {
  183353. png_byte chunk_length[4];
  183354. png_crc_finish(png_ptr, 0);
  183355. png_read_data(png_ptr, chunk_length, 4);
  183356. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  183357. png_reset_crc(png_ptr);
  183358. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183359. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183360. png_error(png_ptr, "Not enough image data");
  183361. }
  183362. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  183363. png_ptr->zstream.next_in = png_ptr->zbuf;
  183364. if (png_ptr->zbuf_size > png_ptr->idat_size)
  183365. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  183366. png_crc_read(png_ptr, png_ptr->zbuf,
  183367. (png_size_t)png_ptr->zstream.avail_in);
  183368. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  183369. }
  183370. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183371. if (ret == Z_STREAM_END)
  183372. {
  183373. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  183374. png_ptr->idat_size)
  183375. png_error(png_ptr, "Extra compressed data");
  183376. png_ptr->mode |= PNG_AFTER_IDAT;
  183377. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183378. break;
  183379. }
  183380. if (ret != Z_OK)
  183381. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  183382. "Decompression error");
  183383. } while (png_ptr->zstream.avail_out);
  183384. png_ptr->row_info.color_type = png_ptr->color_type;
  183385. png_ptr->row_info.width = png_ptr->iwidth;
  183386. png_ptr->row_info.channels = png_ptr->channels;
  183387. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183388. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183389. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183390. png_ptr->row_info.width);
  183391. if(png_ptr->row_buf[0])
  183392. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183393. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183394. (int)(png_ptr->row_buf[0]));
  183395. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183396. png_ptr->rowbytes + 1);
  183397. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183398. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  183399. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  183400. {
  183401. /* Intrapixel differencing */
  183402. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  183403. }
  183404. #endif
  183405. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183406. png_do_read_transformations(png_ptr);
  183407. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183408. /* blow up interlaced rows to full size */
  183409. if (png_ptr->interlaced &&
  183410. (png_ptr->transformations & PNG_INTERLACE))
  183411. {
  183412. if (png_ptr->pass < 6)
  183413. /* old interface (pre-1.0.9):
  183414. png_do_read_interlace(&(png_ptr->row_info),
  183415. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183416. */
  183417. png_do_read_interlace(png_ptr);
  183418. if (dsp_row != NULL)
  183419. png_combine_row(png_ptr, dsp_row,
  183420. png_pass_dsp_mask[png_ptr->pass]);
  183421. if (row != NULL)
  183422. png_combine_row(png_ptr, row,
  183423. png_pass_mask[png_ptr->pass]);
  183424. }
  183425. else
  183426. #endif
  183427. {
  183428. if (row != NULL)
  183429. png_combine_row(png_ptr, row, 0xff);
  183430. if (dsp_row != NULL)
  183431. png_combine_row(png_ptr, dsp_row, 0xff);
  183432. }
  183433. png_read_finish_row(png_ptr);
  183434. if (png_ptr->read_row_fn != NULL)
  183435. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  183436. }
  183437. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183438. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183439. /* Read one or more rows of image data. If the image is interlaced,
  183440. * and png_set_interlace_handling() has been called, the rows need to
  183441. * contain the contents of the rows from the previous pass. If the
  183442. * image has alpha or transparency, and png_handle_alpha()[*] has been
  183443. * called, the rows contents must be initialized to the contents of the
  183444. * screen.
  183445. *
  183446. * "row" holds the actual image, and pixels are placed in it
  183447. * as they arrive. If the image is displayed after each pass, it will
  183448. * appear to "sparkle" in. "display_row" can be used to display a
  183449. * "chunky" progressive image, with finer detail added as it becomes
  183450. * available. If you do not want this "chunky" display, you may pass
  183451. * NULL for display_row. If you do not want the sparkle display, and
  183452. * you have not called png_handle_alpha(), you may pass NULL for rows.
  183453. * If you have called png_handle_alpha(), and the image has either an
  183454. * alpha channel or a transparency chunk, you must provide a buffer for
  183455. * rows. In this case, you do not have to provide a display_row buffer
  183456. * also, but you may. If the image is not interlaced, or if you have
  183457. * not called png_set_interlace_handling(), the display_row buffer will
  183458. * be ignored, so pass NULL to it.
  183459. *
  183460. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183461. */
  183462. void PNGAPI
  183463. png_read_rows(png_structp png_ptr, png_bytepp row,
  183464. png_bytepp display_row, png_uint_32 num_rows)
  183465. {
  183466. png_uint_32 i;
  183467. png_bytepp rp;
  183468. png_bytepp dp;
  183469. png_debug(1, "in png_read_rows\n");
  183470. if(png_ptr == NULL) return;
  183471. rp = row;
  183472. dp = display_row;
  183473. if (rp != NULL && dp != NULL)
  183474. for (i = 0; i < num_rows; i++)
  183475. {
  183476. png_bytep rptr = *rp++;
  183477. png_bytep dptr = *dp++;
  183478. png_read_row(png_ptr, rptr, dptr);
  183479. }
  183480. else if(rp != NULL)
  183481. for (i = 0; i < num_rows; i++)
  183482. {
  183483. png_bytep rptr = *rp;
  183484. png_read_row(png_ptr, rptr, png_bytep_NULL);
  183485. rp++;
  183486. }
  183487. else if(dp != NULL)
  183488. for (i = 0; i < num_rows; i++)
  183489. {
  183490. png_bytep dptr = *dp;
  183491. png_read_row(png_ptr, png_bytep_NULL, dptr);
  183492. dp++;
  183493. }
  183494. }
  183495. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183496. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183497. /* Read the entire image. If the image has an alpha channel or a tRNS
  183498. * chunk, and you have called png_handle_alpha()[*], you will need to
  183499. * initialize the image to the current image that PNG will be overlaying.
  183500. * We set the num_rows again here, in case it was incorrectly set in
  183501. * png_read_start_row() by a call to png_read_update_info() or
  183502. * png_start_read_image() if png_set_interlace_handling() wasn't called
  183503. * prior to either of these functions like it should have been. You can
  183504. * only call this function once. If you desire to have an image for
  183505. * each pass of a interlaced image, use png_read_rows() instead.
  183506. *
  183507. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183508. */
  183509. void PNGAPI
  183510. png_read_image(png_structp png_ptr, png_bytepp image)
  183511. {
  183512. png_uint_32 i,image_height;
  183513. int pass, j;
  183514. png_bytepp rp;
  183515. png_debug(1, "in png_read_image\n");
  183516. if(png_ptr == NULL) return;
  183517. #ifdef PNG_READ_INTERLACING_SUPPORTED
  183518. pass = png_set_interlace_handling(png_ptr);
  183519. #else
  183520. if (png_ptr->interlaced)
  183521. png_error(png_ptr,
  183522. "Cannot read interlaced image -- interlace handler disabled.");
  183523. pass = 1;
  183524. #endif
  183525. image_height=png_ptr->height;
  183526. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  183527. for (j = 0; j < pass; j++)
  183528. {
  183529. rp = image;
  183530. for (i = 0; i < image_height; i++)
  183531. {
  183532. png_read_row(png_ptr, *rp, png_bytep_NULL);
  183533. rp++;
  183534. }
  183535. }
  183536. }
  183537. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183538. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183539. /* Read the end of the PNG file. Will not read past the end of the
  183540. * file, will verify the end is accurate, and will read any comments
  183541. * or time information at the end of the file, if info is not NULL.
  183542. */
  183543. void PNGAPI
  183544. png_read_end(png_structp png_ptr, png_infop info_ptr)
  183545. {
  183546. png_byte chunk_length[4];
  183547. png_uint_32 length;
  183548. png_debug(1, "in png_read_end\n");
  183549. if(png_ptr == NULL) return;
  183550. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  183551. do
  183552. {
  183553. #ifdef PNG_USE_LOCAL_ARRAYS
  183554. PNG_CONST PNG_IHDR;
  183555. PNG_CONST PNG_IDAT;
  183556. PNG_CONST PNG_IEND;
  183557. PNG_CONST PNG_PLTE;
  183558. #if defined(PNG_READ_bKGD_SUPPORTED)
  183559. PNG_CONST PNG_bKGD;
  183560. #endif
  183561. #if defined(PNG_READ_cHRM_SUPPORTED)
  183562. PNG_CONST PNG_cHRM;
  183563. #endif
  183564. #if defined(PNG_READ_gAMA_SUPPORTED)
  183565. PNG_CONST PNG_gAMA;
  183566. #endif
  183567. #if defined(PNG_READ_hIST_SUPPORTED)
  183568. PNG_CONST PNG_hIST;
  183569. #endif
  183570. #if defined(PNG_READ_iCCP_SUPPORTED)
  183571. PNG_CONST PNG_iCCP;
  183572. #endif
  183573. #if defined(PNG_READ_iTXt_SUPPORTED)
  183574. PNG_CONST PNG_iTXt;
  183575. #endif
  183576. #if defined(PNG_READ_oFFs_SUPPORTED)
  183577. PNG_CONST PNG_oFFs;
  183578. #endif
  183579. #if defined(PNG_READ_pCAL_SUPPORTED)
  183580. PNG_CONST PNG_pCAL;
  183581. #endif
  183582. #if defined(PNG_READ_pHYs_SUPPORTED)
  183583. PNG_CONST PNG_pHYs;
  183584. #endif
  183585. #if defined(PNG_READ_sBIT_SUPPORTED)
  183586. PNG_CONST PNG_sBIT;
  183587. #endif
  183588. #if defined(PNG_READ_sCAL_SUPPORTED)
  183589. PNG_CONST PNG_sCAL;
  183590. #endif
  183591. #if defined(PNG_READ_sPLT_SUPPORTED)
  183592. PNG_CONST PNG_sPLT;
  183593. #endif
  183594. #if defined(PNG_READ_sRGB_SUPPORTED)
  183595. PNG_CONST PNG_sRGB;
  183596. #endif
  183597. #if defined(PNG_READ_tEXt_SUPPORTED)
  183598. PNG_CONST PNG_tEXt;
  183599. #endif
  183600. #if defined(PNG_READ_tIME_SUPPORTED)
  183601. PNG_CONST PNG_tIME;
  183602. #endif
  183603. #if defined(PNG_READ_tRNS_SUPPORTED)
  183604. PNG_CONST PNG_tRNS;
  183605. #endif
  183606. #if defined(PNG_READ_zTXt_SUPPORTED)
  183607. PNG_CONST PNG_zTXt;
  183608. #endif
  183609. #endif /* PNG_USE_LOCAL_ARRAYS */
  183610. png_read_data(png_ptr, chunk_length, 4);
  183611. length = png_get_uint_31(png_ptr,chunk_length);
  183612. png_reset_crc(png_ptr);
  183613. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183614. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  183615. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183616. png_handle_IHDR(png_ptr, info_ptr, length);
  183617. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183618. png_handle_IEND(png_ptr, info_ptr, length);
  183619. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183620. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183621. {
  183622. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183623. {
  183624. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183625. png_error(png_ptr, "Too many IDAT's found");
  183626. }
  183627. png_handle_unknown(png_ptr, info_ptr, length);
  183628. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183629. png_ptr->mode |= PNG_HAVE_PLTE;
  183630. }
  183631. #endif
  183632. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183633. {
  183634. /* Zero length IDATs are legal after the last IDAT has been
  183635. * read, but not after other chunks have been read.
  183636. */
  183637. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183638. png_error(png_ptr, "Too many IDAT's found");
  183639. png_crc_finish(png_ptr, length);
  183640. }
  183641. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183642. png_handle_PLTE(png_ptr, info_ptr, length);
  183643. #if defined(PNG_READ_bKGD_SUPPORTED)
  183644. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183645. png_handle_bKGD(png_ptr, info_ptr, length);
  183646. #endif
  183647. #if defined(PNG_READ_cHRM_SUPPORTED)
  183648. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183649. png_handle_cHRM(png_ptr, info_ptr, length);
  183650. #endif
  183651. #if defined(PNG_READ_gAMA_SUPPORTED)
  183652. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183653. png_handle_gAMA(png_ptr, info_ptr, length);
  183654. #endif
  183655. #if defined(PNG_READ_hIST_SUPPORTED)
  183656. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183657. png_handle_hIST(png_ptr, info_ptr, length);
  183658. #endif
  183659. #if defined(PNG_READ_oFFs_SUPPORTED)
  183660. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183661. png_handle_oFFs(png_ptr, info_ptr, length);
  183662. #endif
  183663. #if defined(PNG_READ_pCAL_SUPPORTED)
  183664. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183665. png_handle_pCAL(png_ptr, info_ptr, length);
  183666. #endif
  183667. #if defined(PNG_READ_sCAL_SUPPORTED)
  183668. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183669. png_handle_sCAL(png_ptr, info_ptr, length);
  183670. #endif
  183671. #if defined(PNG_READ_pHYs_SUPPORTED)
  183672. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183673. png_handle_pHYs(png_ptr, info_ptr, length);
  183674. #endif
  183675. #if defined(PNG_READ_sBIT_SUPPORTED)
  183676. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183677. png_handle_sBIT(png_ptr, info_ptr, length);
  183678. #endif
  183679. #if defined(PNG_READ_sRGB_SUPPORTED)
  183680. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183681. png_handle_sRGB(png_ptr, info_ptr, length);
  183682. #endif
  183683. #if defined(PNG_READ_iCCP_SUPPORTED)
  183684. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183685. png_handle_iCCP(png_ptr, info_ptr, length);
  183686. #endif
  183687. #if defined(PNG_READ_sPLT_SUPPORTED)
  183688. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183689. png_handle_sPLT(png_ptr, info_ptr, length);
  183690. #endif
  183691. #if defined(PNG_READ_tEXt_SUPPORTED)
  183692. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183693. png_handle_tEXt(png_ptr, info_ptr, length);
  183694. #endif
  183695. #if defined(PNG_READ_tIME_SUPPORTED)
  183696. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183697. png_handle_tIME(png_ptr, info_ptr, length);
  183698. #endif
  183699. #if defined(PNG_READ_tRNS_SUPPORTED)
  183700. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183701. png_handle_tRNS(png_ptr, info_ptr, length);
  183702. #endif
  183703. #if defined(PNG_READ_zTXt_SUPPORTED)
  183704. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183705. png_handle_zTXt(png_ptr, info_ptr, length);
  183706. #endif
  183707. #if defined(PNG_READ_iTXt_SUPPORTED)
  183708. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183709. png_handle_iTXt(png_ptr, info_ptr, length);
  183710. #endif
  183711. else
  183712. png_handle_unknown(png_ptr, info_ptr, length);
  183713. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  183714. }
  183715. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183716. /* free all memory used by the read */
  183717. void PNGAPI
  183718. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  183719. png_infopp end_info_ptr_ptr)
  183720. {
  183721. png_structp png_ptr = NULL;
  183722. png_infop info_ptr = NULL, end_info_ptr = NULL;
  183723. #ifdef PNG_USER_MEM_SUPPORTED
  183724. png_free_ptr free_fn;
  183725. png_voidp mem_ptr;
  183726. #endif
  183727. png_debug(1, "in png_destroy_read_struct\n");
  183728. if (png_ptr_ptr != NULL)
  183729. png_ptr = *png_ptr_ptr;
  183730. if (info_ptr_ptr != NULL)
  183731. info_ptr = *info_ptr_ptr;
  183732. if (end_info_ptr_ptr != NULL)
  183733. end_info_ptr = *end_info_ptr_ptr;
  183734. #ifdef PNG_USER_MEM_SUPPORTED
  183735. free_fn = png_ptr->free_fn;
  183736. mem_ptr = png_ptr->mem_ptr;
  183737. #endif
  183738. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  183739. if (info_ptr != NULL)
  183740. {
  183741. #if defined(PNG_TEXT_SUPPORTED)
  183742. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  183743. #endif
  183744. #ifdef PNG_USER_MEM_SUPPORTED
  183745. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  183746. (png_voidp)mem_ptr);
  183747. #else
  183748. png_destroy_struct((png_voidp)info_ptr);
  183749. #endif
  183750. *info_ptr_ptr = NULL;
  183751. }
  183752. if (end_info_ptr != NULL)
  183753. {
  183754. #if defined(PNG_READ_TEXT_SUPPORTED)
  183755. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  183756. #endif
  183757. #ifdef PNG_USER_MEM_SUPPORTED
  183758. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  183759. (png_voidp)mem_ptr);
  183760. #else
  183761. png_destroy_struct((png_voidp)end_info_ptr);
  183762. #endif
  183763. *end_info_ptr_ptr = NULL;
  183764. }
  183765. if (png_ptr != NULL)
  183766. {
  183767. #ifdef PNG_USER_MEM_SUPPORTED
  183768. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  183769. (png_voidp)mem_ptr);
  183770. #else
  183771. png_destroy_struct((png_voidp)png_ptr);
  183772. #endif
  183773. *png_ptr_ptr = NULL;
  183774. }
  183775. }
  183776. /* free all memory used by the read (old method) */
  183777. void /* PRIVATE */
  183778. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  183779. {
  183780. #ifdef PNG_SETJMP_SUPPORTED
  183781. jmp_buf tmp_jmp;
  183782. #endif
  183783. png_error_ptr error_fn;
  183784. png_error_ptr warning_fn;
  183785. png_voidp error_ptr;
  183786. #ifdef PNG_USER_MEM_SUPPORTED
  183787. png_free_ptr free_fn;
  183788. #endif
  183789. png_debug(1, "in png_read_destroy\n");
  183790. if (info_ptr != NULL)
  183791. png_info_destroy(png_ptr, info_ptr);
  183792. if (end_info_ptr != NULL)
  183793. png_info_destroy(png_ptr, end_info_ptr);
  183794. png_free(png_ptr, png_ptr->zbuf);
  183795. png_free(png_ptr, png_ptr->big_row_buf);
  183796. png_free(png_ptr, png_ptr->prev_row);
  183797. #if defined(PNG_READ_DITHER_SUPPORTED)
  183798. png_free(png_ptr, png_ptr->palette_lookup);
  183799. png_free(png_ptr, png_ptr->dither_index);
  183800. #endif
  183801. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183802. png_free(png_ptr, png_ptr->gamma_table);
  183803. #endif
  183804. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183805. png_free(png_ptr, png_ptr->gamma_from_1);
  183806. png_free(png_ptr, png_ptr->gamma_to_1);
  183807. #endif
  183808. #ifdef PNG_FREE_ME_SUPPORTED
  183809. if (png_ptr->free_me & PNG_FREE_PLTE)
  183810. png_zfree(png_ptr, png_ptr->palette);
  183811. png_ptr->free_me &= ~PNG_FREE_PLTE;
  183812. #else
  183813. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  183814. png_zfree(png_ptr, png_ptr->palette);
  183815. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  183816. #endif
  183817. #if defined(PNG_tRNS_SUPPORTED) || \
  183818. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183819. #ifdef PNG_FREE_ME_SUPPORTED
  183820. if (png_ptr->free_me & PNG_FREE_TRNS)
  183821. png_free(png_ptr, png_ptr->trans);
  183822. png_ptr->free_me &= ~PNG_FREE_TRNS;
  183823. #else
  183824. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  183825. png_free(png_ptr, png_ptr->trans);
  183826. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183827. #endif
  183828. #endif
  183829. #if defined(PNG_READ_hIST_SUPPORTED)
  183830. #ifdef PNG_FREE_ME_SUPPORTED
  183831. if (png_ptr->free_me & PNG_FREE_HIST)
  183832. png_free(png_ptr, png_ptr->hist);
  183833. png_ptr->free_me &= ~PNG_FREE_HIST;
  183834. #else
  183835. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  183836. png_free(png_ptr, png_ptr->hist);
  183837. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183838. #endif
  183839. #endif
  183840. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183841. if (png_ptr->gamma_16_table != NULL)
  183842. {
  183843. int i;
  183844. int istop = (1 << (8 - png_ptr->gamma_shift));
  183845. for (i = 0; i < istop; i++)
  183846. {
  183847. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  183848. }
  183849. png_free(png_ptr, png_ptr->gamma_16_table);
  183850. }
  183851. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183852. if (png_ptr->gamma_16_from_1 != NULL)
  183853. {
  183854. int i;
  183855. int istop = (1 << (8 - png_ptr->gamma_shift));
  183856. for (i = 0; i < istop; i++)
  183857. {
  183858. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  183859. }
  183860. png_free(png_ptr, png_ptr->gamma_16_from_1);
  183861. }
  183862. if (png_ptr->gamma_16_to_1 != NULL)
  183863. {
  183864. int i;
  183865. int istop = (1 << (8 - png_ptr->gamma_shift));
  183866. for (i = 0; i < istop; i++)
  183867. {
  183868. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  183869. }
  183870. png_free(png_ptr, png_ptr->gamma_16_to_1);
  183871. }
  183872. #endif
  183873. #endif
  183874. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183875. png_free(png_ptr, png_ptr->time_buffer);
  183876. #endif
  183877. inflateEnd(&png_ptr->zstream);
  183878. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183879. png_free(png_ptr, png_ptr->save_buffer);
  183880. #endif
  183881. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183882. #ifdef PNG_TEXT_SUPPORTED
  183883. png_free(png_ptr, png_ptr->current_text);
  183884. #endif /* PNG_TEXT_SUPPORTED */
  183885. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183886. /* Save the important info out of the png_struct, in case it is
  183887. * being used again.
  183888. */
  183889. #ifdef PNG_SETJMP_SUPPORTED
  183890. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183891. #endif
  183892. error_fn = png_ptr->error_fn;
  183893. warning_fn = png_ptr->warning_fn;
  183894. error_ptr = png_ptr->error_ptr;
  183895. #ifdef PNG_USER_MEM_SUPPORTED
  183896. free_fn = png_ptr->free_fn;
  183897. #endif
  183898. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183899. png_ptr->error_fn = error_fn;
  183900. png_ptr->warning_fn = warning_fn;
  183901. png_ptr->error_ptr = error_ptr;
  183902. #ifdef PNG_USER_MEM_SUPPORTED
  183903. png_ptr->free_fn = free_fn;
  183904. #endif
  183905. #ifdef PNG_SETJMP_SUPPORTED
  183906. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183907. #endif
  183908. }
  183909. void PNGAPI
  183910. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  183911. {
  183912. if(png_ptr == NULL) return;
  183913. png_ptr->read_row_fn = read_row_fn;
  183914. }
  183915. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183916. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183917. void PNGAPI
  183918. png_read_png(png_structp png_ptr, png_infop info_ptr,
  183919. int transforms,
  183920. voidp params)
  183921. {
  183922. int row;
  183923. if(png_ptr == NULL) return;
  183924. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183925. /* invert the alpha channel from opacity to transparency
  183926. */
  183927. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  183928. png_set_invert_alpha(png_ptr);
  183929. #endif
  183930. /* png_read_info() gives us all of the information from the
  183931. * PNG file before the first IDAT (image data chunk).
  183932. */
  183933. png_read_info(png_ptr, info_ptr);
  183934. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  183935. png_error(png_ptr,"Image is too high to process with png_read_png()");
  183936. /* -------------- image transformations start here ------------------- */
  183937. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183938. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  183939. */
  183940. if (transforms & PNG_TRANSFORM_STRIP_16)
  183941. png_set_strip_16(png_ptr);
  183942. #endif
  183943. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183944. /* Strip alpha bytes from the input data without combining with
  183945. * the background (not recommended).
  183946. */
  183947. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  183948. png_set_strip_alpha(png_ptr);
  183949. #endif
  183950. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  183951. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  183952. * byte into separate bytes (useful for paletted and grayscale images).
  183953. */
  183954. if (transforms & PNG_TRANSFORM_PACKING)
  183955. png_set_packing(png_ptr);
  183956. #endif
  183957. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  183958. /* Change the order of packed pixels to least significant bit first
  183959. * (not useful if you are using png_set_packing).
  183960. */
  183961. if (transforms & PNG_TRANSFORM_PACKSWAP)
  183962. png_set_packswap(png_ptr);
  183963. #endif
  183964. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183965. /* Expand paletted colors into true RGB triplets
  183966. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  183967. * Expand paletted or RGB images with transparency to full alpha
  183968. * channels so the data will be available as RGBA quartets.
  183969. */
  183970. if (transforms & PNG_TRANSFORM_EXPAND)
  183971. if ((png_ptr->bit_depth < 8) ||
  183972. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  183973. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  183974. png_set_expand(png_ptr);
  183975. #endif
  183976. /* We don't handle background color or gamma transformation or dithering.
  183977. */
  183978. #if defined(PNG_READ_INVERT_SUPPORTED)
  183979. /* invert monochrome files to have 0 as white and 1 as black
  183980. */
  183981. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  183982. png_set_invert_mono(png_ptr);
  183983. #endif
  183984. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183985. /* If you want to shift the pixel values from the range [0,255] or
  183986. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  183987. * colors were originally in:
  183988. */
  183989. if ((transforms & PNG_TRANSFORM_SHIFT)
  183990. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  183991. {
  183992. png_color_8p sig_bit;
  183993. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  183994. png_set_shift(png_ptr, sig_bit);
  183995. }
  183996. #endif
  183997. #if defined(PNG_READ_BGR_SUPPORTED)
  183998. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  183999. */
  184000. if (transforms & PNG_TRANSFORM_BGR)
  184001. png_set_bgr(png_ptr);
  184002. #endif
  184003. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184004. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  184005. */
  184006. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  184007. png_set_swap_alpha(png_ptr);
  184008. #endif
  184009. #if defined(PNG_READ_SWAP_SUPPORTED)
  184010. /* swap bytes of 16 bit files to least significant byte first
  184011. */
  184012. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  184013. png_set_swap(png_ptr);
  184014. #endif
  184015. /* We don't handle adding filler bytes */
  184016. /* Optional call to gamma correct and add the background to the palette
  184017. * and update info structure. REQUIRED if you are expecting libpng to
  184018. * update the palette for you (i.e., you selected such a transform above).
  184019. */
  184020. png_read_update_info(png_ptr, info_ptr);
  184021. /* -------------- image transformations end here ------------------- */
  184022. #ifdef PNG_FREE_ME_SUPPORTED
  184023. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  184024. #endif
  184025. if(info_ptr->row_pointers == NULL)
  184026. {
  184027. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  184028. info_ptr->height * png_sizeof(png_bytep));
  184029. #ifdef PNG_FREE_ME_SUPPORTED
  184030. info_ptr->free_me |= PNG_FREE_ROWS;
  184031. #endif
  184032. for (row = 0; row < (int)info_ptr->height; row++)
  184033. {
  184034. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  184035. png_get_rowbytes(png_ptr, info_ptr));
  184036. }
  184037. }
  184038. png_read_image(png_ptr, info_ptr->row_pointers);
  184039. info_ptr->valid |= PNG_INFO_IDAT;
  184040. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  184041. png_read_end(png_ptr, info_ptr);
  184042. transforms = transforms; /* quiet compiler warnings */
  184043. params = params;
  184044. }
  184045. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  184046. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184047. #endif /* PNG_READ_SUPPORTED */
  184048. /********* End of inlined file: pngread.c *********/
  184049. /********* Start of inlined file: pngpread.c *********/
  184050. /* pngpread.c - read a png file in push mode
  184051. *
  184052. * Last changed in libpng 1.2.21 October 4, 2007
  184053. * For conditions of distribution and use, see copyright notice in png.h
  184054. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184055. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184056. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184057. */
  184058. #define PNG_INTERNAL
  184059. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184060. /* push model modes */
  184061. #define PNG_READ_SIG_MODE 0
  184062. #define PNG_READ_CHUNK_MODE 1
  184063. #define PNG_READ_IDAT_MODE 2
  184064. #define PNG_SKIP_MODE 3
  184065. #define PNG_READ_tEXt_MODE 4
  184066. #define PNG_READ_zTXt_MODE 5
  184067. #define PNG_READ_DONE_MODE 6
  184068. #define PNG_READ_iTXt_MODE 7
  184069. #define PNG_ERROR_MODE 8
  184070. void PNGAPI
  184071. png_process_data(png_structp png_ptr, png_infop info_ptr,
  184072. png_bytep buffer, png_size_t buffer_size)
  184073. {
  184074. if(png_ptr == NULL) return;
  184075. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  184076. while (png_ptr->buffer_size)
  184077. {
  184078. png_process_some_data(png_ptr, info_ptr);
  184079. }
  184080. }
  184081. /* What we do with the incoming data depends on what we were previously
  184082. * doing before we ran out of data...
  184083. */
  184084. void /* PRIVATE */
  184085. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  184086. {
  184087. if(png_ptr == NULL) return;
  184088. switch (png_ptr->process_mode)
  184089. {
  184090. case PNG_READ_SIG_MODE:
  184091. {
  184092. png_push_read_sig(png_ptr, info_ptr);
  184093. break;
  184094. }
  184095. case PNG_READ_CHUNK_MODE:
  184096. {
  184097. png_push_read_chunk(png_ptr, info_ptr);
  184098. break;
  184099. }
  184100. case PNG_READ_IDAT_MODE:
  184101. {
  184102. png_push_read_IDAT(png_ptr);
  184103. break;
  184104. }
  184105. #if defined(PNG_READ_tEXt_SUPPORTED)
  184106. case PNG_READ_tEXt_MODE:
  184107. {
  184108. png_push_read_tEXt(png_ptr, info_ptr);
  184109. break;
  184110. }
  184111. #endif
  184112. #if defined(PNG_READ_zTXt_SUPPORTED)
  184113. case PNG_READ_zTXt_MODE:
  184114. {
  184115. png_push_read_zTXt(png_ptr, info_ptr);
  184116. break;
  184117. }
  184118. #endif
  184119. #if defined(PNG_READ_iTXt_SUPPORTED)
  184120. case PNG_READ_iTXt_MODE:
  184121. {
  184122. png_push_read_iTXt(png_ptr, info_ptr);
  184123. break;
  184124. }
  184125. #endif
  184126. case PNG_SKIP_MODE:
  184127. {
  184128. png_push_crc_finish(png_ptr);
  184129. break;
  184130. }
  184131. default:
  184132. {
  184133. png_ptr->buffer_size = 0;
  184134. break;
  184135. }
  184136. }
  184137. }
  184138. /* Read any remaining signature bytes from the stream and compare them with
  184139. * the correct PNG signature. It is possible that this routine is called
  184140. * with bytes already read from the signature, either because they have been
  184141. * checked by the calling application, or because of multiple calls to this
  184142. * routine.
  184143. */
  184144. void /* PRIVATE */
  184145. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  184146. {
  184147. png_size_t num_checked = png_ptr->sig_bytes,
  184148. num_to_check = 8 - num_checked;
  184149. if (png_ptr->buffer_size < num_to_check)
  184150. {
  184151. num_to_check = png_ptr->buffer_size;
  184152. }
  184153. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  184154. num_to_check);
  184155. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  184156. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184157. {
  184158. if (num_checked < 4 &&
  184159. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184160. png_error(png_ptr, "Not a PNG file");
  184161. else
  184162. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184163. }
  184164. else
  184165. {
  184166. if (png_ptr->sig_bytes >= 8)
  184167. {
  184168. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184169. }
  184170. }
  184171. }
  184172. void /* PRIVATE */
  184173. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  184174. {
  184175. #ifdef PNG_USE_LOCAL_ARRAYS
  184176. PNG_CONST PNG_IHDR;
  184177. PNG_CONST PNG_IDAT;
  184178. PNG_CONST PNG_IEND;
  184179. PNG_CONST PNG_PLTE;
  184180. #if defined(PNG_READ_bKGD_SUPPORTED)
  184181. PNG_CONST PNG_bKGD;
  184182. #endif
  184183. #if defined(PNG_READ_cHRM_SUPPORTED)
  184184. PNG_CONST PNG_cHRM;
  184185. #endif
  184186. #if defined(PNG_READ_gAMA_SUPPORTED)
  184187. PNG_CONST PNG_gAMA;
  184188. #endif
  184189. #if defined(PNG_READ_hIST_SUPPORTED)
  184190. PNG_CONST PNG_hIST;
  184191. #endif
  184192. #if defined(PNG_READ_iCCP_SUPPORTED)
  184193. PNG_CONST PNG_iCCP;
  184194. #endif
  184195. #if defined(PNG_READ_iTXt_SUPPORTED)
  184196. PNG_CONST PNG_iTXt;
  184197. #endif
  184198. #if defined(PNG_READ_oFFs_SUPPORTED)
  184199. PNG_CONST PNG_oFFs;
  184200. #endif
  184201. #if defined(PNG_READ_pCAL_SUPPORTED)
  184202. PNG_CONST PNG_pCAL;
  184203. #endif
  184204. #if defined(PNG_READ_pHYs_SUPPORTED)
  184205. PNG_CONST PNG_pHYs;
  184206. #endif
  184207. #if defined(PNG_READ_sBIT_SUPPORTED)
  184208. PNG_CONST PNG_sBIT;
  184209. #endif
  184210. #if defined(PNG_READ_sCAL_SUPPORTED)
  184211. PNG_CONST PNG_sCAL;
  184212. #endif
  184213. #if defined(PNG_READ_sRGB_SUPPORTED)
  184214. PNG_CONST PNG_sRGB;
  184215. #endif
  184216. #if defined(PNG_READ_sPLT_SUPPORTED)
  184217. PNG_CONST PNG_sPLT;
  184218. #endif
  184219. #if defined(PNG_READ_tEXt_SUPPORTED)
  184220. PNG_CONST PNG_tEXt;
  184221. #endif
  184222. #if defined(PNG_READ_tIME_SUPPORTED)
  184223. PNG_CONST PNG_tIME;
  184224. #endif
  184225. #if defined(PNG_READ_tRNS_SUPPORTED)
  184226. PNG_CONST PNG_tRNS;
  184227. #endif
  184228. #if defined(PNG_READ_zTXt_SUPPORTED)
  184229. PNG_CONST PNG_zTXt;
  184230. #endif
  184231. #endif /* PNG_USE_LOCAL_ARRAYS */
  184232. /* First we make sure we have enough data for the 4 byte chunk name
  184233. * and the 4 byte chunk length before proceeding with decoding the
  184234. * chunk data. To fully decode each of these chunks, we also make
  184235. * sure we have enough data in the buffer for the 4 byte CRC at the
  184236. * end of every chunk (except IDAT, which is handled separately).
  184237. */
  184238. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184239. {
  184240. png_byte chunk_length[4];
  184241. if (png_ptr->buffer_size < 8)
  184242. {
  184243. png_push_save_buffer(png_ptr);
  184244. return;
  184245. }
  184246. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184247. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184248. png_reset_crc(png_ptr);
  184249. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184250. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184251. }
  184252. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184253. if(png_ptr->mode & PNG_AFTER_IDAT)
  184254. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  184255. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184256. {
  184257. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184258. {
  184259. png_push_save_buffer(png_ptr);
  184260. return;
  184261. }
  184262. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  184263. }
  184264. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184265. {
  184266. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184267. {
  184268. png_push_save_buffer(png_ptr);
  184269. return;
  184270. }
  184271. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  184272. png_ptr->process_mode = PNG_READ_DONE_MODE;
  184273. png_push_have_end(png_ptr, info_ptr);
  184274. }
  184275. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184276. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184277. {
  184278. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184279. {
  184280. png_push_save_buffer(png_ptr);
  184281. return;
  184282. }
  184283. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184284. png_ptr->mode |= PNG_HAVE_IDAT;
  184285. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184286. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184287. png_ptr->mode |= PNG_HAVE_PLTE;
  184288. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184289. {
  184290. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184291. png_error(png_ptr, "Missing IHDR before IDAT");
  184292. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184293. !(png_ptr->mode & PNG_HAVE_PLTE))
  184294. png_error(png_ptr, "Missing PLTE before IDAT");
  184295. }
  184296. }
  184297. #endif
  184298. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184299. {
  184300. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184301. {
  184302. png_push_save_buffer(png_ptr);
  184303. return;
  184304. }
  184305. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  184306. }
  184307. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184308. {
  184309. /* If we reach an IDAT chunk, this means we have read all of the
  184310. * header chunks, and we can start reading the image (or if this
  184311. * is called after the image has been read - we have an error).
  184312. */
  184313. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184314. png_error(png_ptr, "Missing IHDR before IDAT");
  184315. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184316. !(png_ptr->mode & PNG_HAVE_PLTE))
  184317. png_error(png_ptr, "Missing PLTE before IDAT");
  184318. if (png_ptr->mode & PNG_HAVE_IDAT)
  184319. {
  184320. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184321. if (png_ptr->push_length == 0)
  184322. return;
  184323. if (png_ptr->mode & PNG_AFTER_IDAT)
  184324. png_error(png_ptr, "Too many IDAT's found");
  184325. }
  184326. png_ptr->idat_size = png_ptr->push_length;
  184327. png_ptr->mode |= PNG_HAVE_IDAT;
  184328. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  184329. png_push_have_info(png_ptr, info_ptr);
  184330. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184331. png_ptr->zstream.next_out = png_ptr->row_buf;
  184332. return;
  184333. }
  184334. #if defined(PNG_READ_gAMA_SUPPORTED)
  184335. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184336. {
  184337. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184338. {
  184339. png_push_save_buffer(png_ptr);
  184340. return;
  184341. }
  184342. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  184343. }
  184344. #endif
  184345. #if defined(PNG_READ_sBIT_SUPPORTED)
  184346. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184347. {
  184348. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184349. {
  184350. png_push_save_buffer(png_ptr);
  184351. return;
  184352. }
  184353. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  184354. }
  184355. #endif
  184356. #if defined(PNG_READ_cHRM_SUPPORTED)
  184357. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184358. {
  184359. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184360. {
  184361. png_push_save_buffer(png_ptr);
  184362. return;
  184363. }
  184364. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  184365. }
  184366. #endif
  184367. #if defined(PNG_READ_sRGB_SUPPORTED)
  184368. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184369. {
  184370. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184371. {
  184372. png_push_save_buffer(png_ptr);
  184373. return;
  184374. }
  184375. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  184376. }
  184377. #endif
  184378. #if defined(PNG_READ_iCCP_SUPPORTED)
  184379. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184380. {
  184381. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184382. {
  184383. png_push_save_buffer(png_ptr);
  184384. return;
  184385. }
  184386. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  184387. }
  184388. #endif
  184389. #if defined(PNG_READ_sPLT_SUPPORTED)
  184390. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184391. {
  184392. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184393. {
  184394. png_push_save_buffer(png_ptr);
  184395. return;
  184396. }
  184397. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  184398. }
  184399. #endif
  184400. #if defined(PNG_READ_tRNS_SUPPORTED)
  184401. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184402. {
  184403. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184404. {
  184405. png_push_save_buffer(png_ptr);
  184406. return;
  184407. }
  184408. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  184409. }
  184410. #endif
  184411. #if defined(PNG_READ_bKGD_SUPPORTED)
  184412. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184413. {
  184414. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184415. {
  184416. png_push_save_buffer(png_ptr);
  184417. return;
  184418. }
  184419. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  184420. }
  184421. #endif
  184422. #if defined(PNG_READ_hIST_SUPPORTED)
  184423. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184424. {
  184425. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184426. {
  184427. png_push_save_buffer(png_ptr);
  184428. return;
  184429. }
  184430. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  184431. }
  184432. #endif
  184433. #if defined(PNG_READ_pHYs_SUPPORTED)
  184434. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184435. {
  184436. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184437. {
  184438. png_push_save_buffer(png_ptr);
  184439. return;
  184440. }
  184441. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  184442. }
  184443. #endif
  184444. #if defined(PNG_READ_oFFs_SUPPORTED)
  184445. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184446. {
  184447. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184448. {
  184449. png_push_save_buffer(png_ptr);
  184450. return;
  184451. }
  184452. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  184453. }
  184454. #endif
  184455. #if defined(PNG_READ_pCAL_SUPPORTED)
  184456. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184457. {
  184458. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184459. {
  184460. png_push_save_buffer(png_ptr);
  184461. return;
  184462. }
  184463. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  184464. }
  184465. #endif
  184466. #if defined(PNG_READ_sCAL_SUPPORTED)
  184467. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184468. {
  184469. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184470. {
  184471. png_push_save_buffer(png_ptr);
  184472. return;
  184473. }
  184474. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  184475. }
  184476. #endif
  184477. #if defined(PNG_READ_tIME_SUPPORTED)
  184478. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184479. {
  184480. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184481. {
  184482. png_push_save_buffer(png_ptr);
  184483. return;
  184484. }
  184485. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  184486. }
  184487. #endif
  184488. #if defined(PNG_READ_tEXt_SUPPORTED)
  184489. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184490. {
  184491. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184492. {
  184493. png_push_save_buffer(png_ptr);
  184494. return;
  184495. }
  184496. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  184497. }
  184498. #endif
  184499. #if defined(PNG_READ_zTXt_SUPPORTED)
  184500. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184501. {
  184502. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184503. {
  184504. png_push_save_buffer(png_ptr);
  184505. return;
  184506. }
  184507. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  184508. }
  184509. #endif
  184510. #if defined(PNG_READ_iTXt_SUPPORTED)
  184511. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184512. {
  184513. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184514. {
  184515. png_push_save_buffer(png_ptr);
  184516. return;
  184517. }
  184518. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  184519. }
  184520. #endif
  184521. else
  184522. {
  184523. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184524. {
  184525. png_push_save_buffer(png_ptr);
  184526. return;
  184527. }
  184528. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184529. }
  184530. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184531. }
  184532. void /* PRIVATE */
  184533. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  184534. {
  184535. png_ptr->process_mode = PNG_SKIP_MODE;
  184536. png_ptr->skip_length = skip;
  184537. }
  184538. void /* PRIVATE */
  184539. png_push_crc_finish(png_structp png_ptr)
  184540. {
  184541. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  184542. {
  184543. png_size_t save_size;
  184544. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  184545. save_size = (png_size_t)png_ptr->skip_length;
  184546. else
  184547. save_size = png_ptr->save_buffer_size;
  184548. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184549. png_ptr->skip_length -= save_size;
  184550. png_ptr->buffer_size -= save_size;
  184551. png_ptr->save_buffer_size -= save_size;
  184552. png_ptr->save_buffer_ptr += save_size;
  184553. }
  184554. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  184555. {
  184556. png_size_t save_size;
  184557. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  184558. save_size = (png_size_t)png_ptr->skip_length;
  184559. else
  184560. save_size = png_ptr->current_buffer_size;
  184561. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184562. png_ptr->skip_length -= save_size;
  184563. png_ptr->buffer_size -= save_size;
  184564. png_ptr->current_buffer_size -= save_size;
  184565. png_ptr->current_buffer_ptr += save_size;
  184566. }
  184567. if (!png_ptr->skip_length)
  184568. {
  184569. if (png_ptr->buffer_size < 4)
  184570. {
  184571. png_push_save_buffer(png_ptr);
  184572. return;
  184573. }
  184574. png_crc_finish(png_ptr, 0);
  184575. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184576. }
  184577. }
  184578. void PNGAPI
  184579. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  184580. {
  184581. png_bytep ptr;
  184582. if(png_ptr == NULL) return;
  184583. ptr = buffer;
  184584. if (png_ptr->save_buffer_size)
  184585. {
  184586. png_size_t save_size;
  184587. if (length < png_ptr->save_buffer_size)
  184588. save_size = length;
  184589. else
  184590. save_size = png_ptr->save_buffer_size;
  184591. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  184592. length -= save_size;
  184593. ptr += save_size;
  184594. png_ptr->buffer_size -= save_size;
  184595. png_ptr->save_buffer_size -= save_size;
  184596. png_ptr->save_buffer_ptr += save_size;
  184597. }
  184598. if (length && png_ptr->current_buffer_size)
  184599. {
  184600. png_size_t save_size;
  184601. if (length < png_ptr->current_buffer_size)
  184602. save_size = length;
  184603. else
  184604. save_size = png_ptr->current_buffer_size;
  184605. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  184606. png_ptr->buffer_size -= save_size;
  184607. png_ptr->current_buffer_size -= save_size;
  184608. png_ptr->current_buffer_ptr += save_size;
  184609. }
  184610. }
  184611. void /* PRIVATE */
  184612. png_push_save_buffer(png_structp png_ptr)
  184613. {
  184614. if (png_ptr->save_buffer_size)
  184615. {
  184616. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  184617. {
  184618. png_size_t i,istop;
  184619. png_bytep sp;
  184620. png_bytep dp;
  184621. istop = png_ptr->save_buffer_size;
  184622. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  184623. i < istop; i++, sp++, dp++)
  184624. {
  184625. *dp = *sp;
  184626. }
  184627. }
  184628. }
  184629. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  184630. png_ptr->save_buffer_max)
  184631. {
  184632. png_size_t new_max;
  184633. png_bytep old_buffer;
  184634. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  184635. (png_ptr->current_buffer_size + 256))
  184636. {
  184637. png_error(png_ptr, "Potential overflow of save_buffer");
  184638. }
  184639. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  184640. old_buffer = png_ptr->save_buffer;
  184641. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  184642. (png_uint_32)new_max);
  184643. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  184644. png_free(png_ptr, old_buffer);
  184645. png_ptr->save_buffer_max = new_max;
  184646. }
  184647. if (png_ptr->current_buffer_size)
  184648. {
  184649. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  184650. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  184651. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  184652. png_ptr->current_buffer_size = 0;
  184653. }
  184654. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  184655. png_ptr->buffer_size = 0;
  184656. }
  184657. void /* PRIVATE */
  184658. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  184659. png_size_t buffer_length)
  184660. {
  184661. png_ptr->current_buffer = buffer;
  184662. png_ptr->current_buffer_size = buffer_length;
  184663. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  184664. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  184665. }
  184666. void /* PRIVATE */
  184667. png_push_read_IDAT(png_structp png_ptr)
  184668. {
  184669. #ifdef PNG_USE_LOCAL_ARRAYS
  184670. PNG_CONST PNG_IDAT;
  184671. #endif
  184672. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184673. {
  184674. png_byte chunk_length[4];
  184675. if (png_ptr->buffer_size < 8)
  184676. {
  184677. png_push_save_buffer(png_ptr);
  184678. return;
  184679. }
  184680. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184681. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184682. png_reset_crc(png_ptr);
  184683. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184684. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184685. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184686. {
  184687. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184688. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184689. png_error(png_ptr, "Not enough compressed data");
  184690. return;
  184691. }
  184692. png_ptr->idat_size = png_ptr->push_length;
  184693. }
  184694. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  184695. {
  184696. png_size_t save_size;
  184697. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  184698. {
  184699. save_size = (png_size_t)png_ptr->idat_size;
  184700. /* check for overflow */
  184701. if((png_uint_32)save_size != png_ptr->idat_size)
  184702. png_error(png_ptr, "save_size overflowed in pngpread");
  184703. }
  184704. else
  184705. save_size = png_ptr->save_buffer_size;
  184706. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184707. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184708. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184709. png_ptr->idat_size -= save_size;
  184710. png_ptr->buffer_size -= save_size;
  184711. png_ptr->save_buffer_size -= save_size;
  184712. png_ptr->save_buffer_ptr += save_size;
  184713. }
  184714. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  184715. {
  184716. png_size_t save_size;
  184717. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  184718. {
  184719. save_size = (png_size_t)png_ptr->idat_size;
  184720. /* check for overflow */
  184721. if((png_uint_32)save_size != png_ptr->idat_size)
  184722. png_error(png_ptr, "save_size overflowed in pngpread");
  184723. }
  184724. else
  184725. save_size = png_ptr->current_buffer_size;
  184726. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184727. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184728. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184729. png_ptr->idat_size -= save_size;
  184730. png_ptr->buffer_size -= save_size;
  184731. png_ptr->current_buffer_size -= save_size;
  184732. png_ptr->current_buffer_ptr += save_size;
  184733. }
  184734. if (!png_ptr->idat_size)
  184735. {
  184736. if (png_ptr->buffer_size < 4)
  184737. {
  184738. png_push_save_buffer(png_ptr);
  184739. return;
  184740. }
  184741. png_crc_finish(png_ptr, 0);
  184742. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184743. png_ptr->mode |= PNG_AFTER_IDAT;
  184744. }
  184745. }
  184746. void /* PRIVATE */
  184747. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  184748. png_size_t buffer_length)
  184749. {
  184750. int ret;
  184751. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  184752. png_error(png_ptr, "Extra compression data");
  184753. png_ptr->zstream.next_in = buffer;
  184754. png_ptr->zstream.avail_in = (uInt)buffer_length;
  184755. for(;;)
  184756. {
  184757. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184758. if (ret != Z_OK)
  184759. {
  184760. if (ret == Z_STREAM_END)
  184761. {
  184762. if (png_ptr->zstream.avail_in)
  184763. png_error(png_ptr, "Extra compressed data");
  184764. if (!(png_ptr->zstream.avail_out))
  184765. {
  184766. png_push_process_row(png_ptr);
  184767. }
  184768. png_ptr->mode |= PNG_AFTER_IDAT;
  184769. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184770. break;
  184771. }
  184772. else if (ret == Z_BUF_ERROR)
  184773. break;
  184774. else
  184775. png_error(png_ptr, "Decompression Error");
  184776. }
  184777. if (!(png_ptr->zstream.avail_out))
  184778. {
  184779. if ((
  184780. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184781. png_ptr->interlaced && png_ptr->pass > 6) ||
  184782. (!png_ptr->interlaced &&
  184783. #endif
  184784. png_ptr->row_number == png_ptr->num_rows))
  184785. {
  184786. if (png_ptr->zstream.avail_in)
  184787. {
  184788. png_warning(png_ptr, "Too much data in IDAT chunks");
  184789. }
  184790. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184791. break;
  184792. }
  184793. png_push_process_row(png_ptr);
  184794. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184795. png_ptr->zstream.next_out = png_ptr->row_buf;
  184796. }
  184797. else
  184798. break;
  184799. }
  184800. }
  184801. void /* PRIVATE */
  184802. png_push_process_row(png_structp png_ptr)
  184803. {
  184804. png_ptr->row_info.color_type = png_ptr->color_type;
  184805. png_ptr->row_info.width = png_ptr->iwidth;
  184806. png_ptr->row_info.channels = png_ptr->channels;
  184807. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184808. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184809. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184810. png_ptr->row_info.width);
  184811. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184812. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184813. (int)(png_ptr->row_buf[0]));
  184814. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184815. png_ptr->rowbytes + 1);
  184816. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184817. png_do_read_transformations(png_ptr);
  184818. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184819. /* blow up interlaced rows to full size */
  184820. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184821. {
  184822. if (png_ptr->pass < 6)
  184823. /* old interface (pre-1.0.9):
  184824. png_do_read_interlace(&(png_ptr->row_info),
  184825. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184826. */
  184827. png_do_read_interlace(png_ptr);
  184828. switch (png_ptr->pass)
  184829. {
  184830. case 0:
  184831. {
  184832. int i;
  184833. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  184834. {
  184835. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184836. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  184837. }
  184838. if (png_ptr->pass == 2) /* pass 1 might be empty */
  184839. {
  184840. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184841. {
  184842. png_push_have_row(png_ptr, png_bytep_NULL);
  184843. png_read_push_finish_row(png_ptr);
  184844. }
  184845. }
  184846. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  184847. {
  184848. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184849. {
  184850. png_push_have_row(png_ptr, png_bytep_NULL);
  184851. png_read_push_finish_row(png_ptr);
  184852. }
  184853. }
  184854. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  184855. {
  184856. png_push_have_row(png_ptr, png_bytep_NULL);
  184857. png_read_push_finish_row(png_ptr);
  184858. }
  184859. break;
  184860. }
  184861. case 1:
  184862. {
  184863. int i;
  184864. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  184865. {
  184866. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184867. png_read_push_finish_row(png_ptr);
  184868. }
  184869. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  184870. {
  184871. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184872. {
  184873. png_push_have_row(png_ptr, png_bytep_NULL);
  184874. png_read_push_finish_row(png_ptr);
  184875. }
  184876. }
  184877. break;
  184878. }
  184879. case 2:
  184880. {
  184881. int i;
  184882. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184883. {
  184884. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184885. png_read_push_finish_row(png_ptr);
  184886. }
  184887. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184888. {
  184889. png_push_have_row(png_ptr, png_bytep_NULL);
  184890. png_read_push_finish_row(png_ptr);
  184891. }
  184892. if (png_ptr->pass == 4) /* pass 3 might be empty */
  184893. {
  184894. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184895. {
  184896. png_push_have_row(png_ptr, png_bytep_NULL);
  184897. png_read_push_finish_row(png_ptr);
  184898. }
  184899. }
  184900. break;
  184901. }
  184902. case 3:
  184903. {
  184904. int i;
  184905. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  184906. {
  184907. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184908. png_read_push_finish_row(png_ptr);
  184909. }
  184910. if (png_ptr->pass == 4) /* skip top two generated rows */
  184911. {
  184912. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184913. {
  184914. png_push_have_row(png_ptr, png_bytep_NULL);
  184915. png_read_push_finish_row(png_ptr);
  184916. }
  184917. }
  184918. break;
  184919. }
  184920. case 4:
  184921. {
  184922. int i;
  184923. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184924. {
  184925. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184926. png_read_push_finish_row(png_ptr);
  184927. }
  184928. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184929. {
  184930. png_push_have_row(png_ptr, png_bytep_NULL);
  184931. png_read_push_finish_row(png_ptr);
  184932. }
  184933. if (png_ptr->pass == 6) /* pass 5 might be empty */
  184934. {
  184935. png_push_have_row(png_ptr, png_bytep_NULL);
  184936. png_read_push_finish_row(png_ptr);
  184937. }
  184938. break;
  184939. }
  184940. case 5:
  184941. {
  184942. int i;
  184943. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  184944. {
  184945. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184946. png_read_push_finish_row(png_ptr);
  184947. }
  184948. if (png_ptr->pass == 6) /* skip top generated row */
  184949. {
  184950. png_push_have_row(png_ptr, png_bytep_NULL);
  184951. png_read_push_finish_row(png_ptr);
  184952. }
  184953. break;
  184954. }
  184955. case 6:
  184956. {
  184957. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184958. png_read_push_finish_row(png_ptr);
  184959. if (png_ptr->pass != 6)
  184960. break;
  184961. png_push_have_row(png_ptr, png_bytep_NULL);
  184962. png_read_push_finish_row(png_ptr);
  184963. }
  184964. }
  184965. }
  184966. else
  184967. #endif
  184968. {
  184969. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184970. png_read_push_finish_row(png_ptr);
  184971. }
  184972. }
  184973. void /* PRIVATE */
  184974. png_read_push_finish_row(png_structp png_ptr)
  184975. {
  184976. #ifdef PNG_USE_LOCAL_ARRAYS
  184977. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184978. /* start of interlace block */
  184979. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184980. /* offset to next interlace block */
  184981. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184982. /* start of interlace block in the y direction */
  184983. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184984. /* offset to next interlace block in the y direction */
  184985. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184986. /* Height of interlace block. This is not currently used - if you need
  184987. * it, uncomment it here and in png.h
  184988. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184989. */
  184990. #endif
  184991. png_ptr->row_number++;
  184992. if (png_ptr->row_number < png_ptr->num_rows)
  184993. return;
  184994. if (png_ptr->interlaced)
  184995. {
  184996. png_ptr->row_number = 0;
  184997. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  184998. png_ptr->rowbytes + 1);
  184999. do
  185000. {
  185001. png_ptr->pass++;
  185002. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  185003. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  185004. (png_ptr->pass == 5 && png_ptr->width < 2))
  185005. png_ptr->pass++;
  185006. if (png_ptr->pass > 7)
  185007. png_ptr->pass--;
  185008. if (png_ptr->pass >= 7)
  185009. break;
  185010. png_ptr->iwidth = (png_ptr->width +
  185011. png_pass_inc[png_ptr->pass] - 1 -
  185012. png_pass_start[png_ptr->pass]) /
  185013. png_pass_inc[png_ptr->pass];
  185014. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  185015. png_ptr->iwidth) + 1;
  185016. if (png_ptr->transformations & PNG_INTERLACE)
  185017. break;
  185018. png_ptr->num_rows = (png_ptr->height +
  185019. png_pass_yinc[png_ptr->pass] - 1 -
  185020. png_pass_ystart[png_ptr->pass]) /
  185021. png_pass_yinc[png_ptr->pass];
  185022. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  185023. }
  185024. }
  185025. #if defined(PNG_READ_tEXt_SUPPORTED)
  185026. void /* PRIVATE */
  185027. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185028. length)
  185029. {
  185030. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185031. {
  185032. png_error(png_ptr, "Out of place tEXt");
  185033. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185034. }
  185035. #ifdef PNG_MAX_MALLOC_64K
  185036. png_ptr->skip_length = 0; /* This may not be necessary */
  185037. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185038. {
  185039. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  185040. png_ptr->skip_length = length - (png_uint_32)65535L;
  185041. length = (png_uint_32)65535L;
  185042. }
  185043. #endif
  185044. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185045. (png_uint_32)(length+1));
  185046. png_ptr->current_text[length] = '\0';
  185047. png_ptr->current_text_ptr = png_ptr->current_text;
  185048. png_ptr->current_text_size = (png_size_t)length;
  185049. png_ptr->current_text_left = (png_size_t)length;
  185050. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  185051. }
  185052. void /* PRIVATE */
  185053. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  185054. {
  185055. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185056. {
  185057. png_size_t text_size;
  185058. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185059. text_size = png_ptr->buffer_size;
  185060. else
  185061. text_size = png_ptr->current_text_left;
  185062. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185063. png_ptr->current_text_left -= text_size;
  185064. png_ptr->current_text_ptr += text_size;
  185065. }
  185066. if (!(png_ptr->current_text_left))
  185067. {
  185068. png_textp text_ptr;
  185069. png_charp text;
  185070. png_charp key;
  185071. int ret;
  185072. if (png_ptr->buffer_size < 4)
  185073. {
  185074. png_push_save_buffer(png_ptr);
  185075. return;
  185076. }
  185077. png_push_crc_finish(png_ptr);
  185078. #if defined(PNG_MAX_MALLOC_64K)
  185079. if (png_ptr->skip_length)
  185080. return;
  185081. #endif
  185082. key = png_ptr->current_text;
  185083. for (text = key; *text; text++)
  185084. /* empty loop */ ;
  185085. if (text < key + png_ptr->current_text_size)
  185086. text++;
  185087. text_ptr = (png_textp)png_malloc(png_ptr,
  185088. (png_uint_32)png_sizeof(png_text));
  185089. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  185090. text_ptr->key = key;
  185091. #ifdef PNG_iTXt_SUPPORTED
  185092. text_ptr->lang = NULL;
  185093. text_ptr->lang_key = NULL;
  185094. #endif
  185095. text_ptr->text = text;
  185096. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185097. png_free(png_ptr, key);
  185098. png_free(png_ptr, text_ptr);
  185099. png_ptr->current_text = NULL;
  185100. if (ret)
  185101. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185102. }
  185103. }
  185104. #endif
  185105. #if defined(PNG_READ_zTXt_SUPPORTED)
  185106. void /* PRIVATE */
  185107. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185108. length)
  185109. {
  185110. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185111. {
  185112. png_error(png_ptr, "Out of place zTXt");
  185113. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185114. }
  185115. #ifdef PNG_MAX_MALLOC_64K
  185116. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  185117. * to be able to store the uncompressed data. Actually, the threshold
  185118. * is probably around 32K, but it isn't as definite as 64K is.
  185119. */
  185120. if (length > (png_uint_32)65535L)
  185121. {
  185122. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  185123. png_push_crc_skip(png_ptr, length);
  185124. return;
  185125. }
  185126. #endif
  185127. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185128. (png_uint_32)(length+1));
  185129. png_ptr->current_text[length] = '\0';
  185130. png_ptr->current_text_ptr = png_ptr->current_text;
  185131. png_ptr->current_text_size = (png_size_t)length;
  185132. png_ptr->current_text_left = (png_size_t)length;
  185133. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  185134. }
  185135. void /* PRIVATE */
  185136. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  185137. {
  185138. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185139. {
  185140. png_size_t text_size;
  185141. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  185142. text_size = png_ptr->buffer_size;
  185143. else
  185144. text_size = png_ptr->current_text_left;
  185145. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185146. png_ptr->current_text_left -= text_size;
  185147. png_ptr->current_text_ptr += text_size;
  185148. }
  185149. if (!(png_ptr->current_text_left))
  185150. {
  185151. png_textp text_ptr;
  185152. png_charp text;
  185153. png_charp key;
  185154. int ret;
  185155. png_size_t text_size, key_size;
  185156. if (png_ptr->buffer_size < 4)
  185157. {
  185158. png_push_save_buffer(png_ptr);
  185159. return;
  185160. }
  185161. png_push_crc_finish(png_ptr);
  185162. key = png_ptr->current_text;
  185163. for (text = key; *text; text++)
  185164. /* empty loop */ ;
  185165. /* zTXt can't have zero text */
  185166. if (text >= key + png_ptr->current_text_size)
  185167. {
  185168. png_ptr->current_text = NULL;
  185169. png_free(png_ptr, key);
  185170. return;
  185171. }
  185172. text++;
  185173. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  185174. {
  185175. png_ptr->current_text = NULL;
  185176. png_free(png_ptr, key);
  185177. return;
  185178. }
  185179. text++;
  185180. png_ptr->zstream.next_in = (png_bytep )text;
  185181. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  185182. (text - key));
  185183. png_ptr->zstream.next_out = png_ptr->zbuf;
  185184. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185185. key_size = text - key;
  185186. text_size = 0;
  185187. text = NULL;
  185188. ret = Z_STREAM_END;
  185189. while (png_ptr->zstream.avail_in)
  185190. {
  185191. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185192. if (ret != Z_OK && ret != Z_STREAM_END)
  185193. {
  185194. inflateReset(&png_ptr->zstream);
  185195. png_ptr->zstream.avail_in = 0;
  185196. png_ptr->current_text = NULL;
  185197. png_free(png_ptr, key);
  185198. png_free(png_ptr, text);
  185199. return;
  185200. }
  185201. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  185202. {
  185203. if (text == NULL)
  185204. {
  185205. text = (png_charp)png_malloc(png_ptr,
  185206. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185207. + key_size + 1));
  185208. png_memcpy(text + key_size, png_ptr->zbuf,
  185209. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185210. png_memcpy(text, key, key_size);
  185211. text_size = key_size + png_ptr->zbuf_size -
  185212. png_ptr->zstream.avail_out;
  185213. *(text + text_size) = '\0';
  185214. }
  185215. else
  185216. {
  185217. png_charp tmp;
  185218. tmp = text;
  185219. text = (png_charp)png_malloc(png_ptr, text_size +
  185220. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185221. + 1));
  185222. png_memcpy(text, tmp, text_size);
  185223. png_free(png_ptr, tmp);
  185224. png_memcpy(text + text_size, png_ptr->zbuf,
  185225. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185226. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  185227. *(text + text_size) = '\0';
  185228. }
  185229. if (ret != Z_STREAM_END)
  185230. {
  185231. png_ptr->zstream.next_out = png_ptr->zbuf;
  185232. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185233. }
  185234. }
  185235. else
  185236. {
  185237. break;
  185238. }
  185239. if (ret == Z_STREAM_END)
  185240. break;
  185241. }
  185242. inflateReset(&png_ptr->zstream);
  185243. png_ptr->zstream.avail_in = 0;
  185244. if (ret != Z_STREAM_END)
  185245. {
  185246. png_ptr->current_text = NULL;
  185247. png_free(png_ptr, key);
  185248. png_free(png_ptr, text);
  185249. return;
  185250. }
  185251. png_ptr->current_text = NULL;
  185252. png_free(png_ptr, key);
  185253. key = text;
  185254. text += key_size;
  185255. text_ptr = (png_textp)png_malloc(png_ptr,
  185256. (png_uint_32)png_sizeof(png_text));
  185257. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  185258. text_ptr->key = key;
  185259. #ifdef PNG_iTXt_SUPPORTED
  185260. text_ptr->lang = NULL;
  185261. text_ptr->lang_key = NULL;
  185262. #endif
  185263. text_ptr->text = text;
  185264. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185265. png_free(png_ptr, key);
  185266. png_free(png_ptr, text_ptr);
  185267. if (ret)
  185268. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185269. }
  185270. }
  185271. #endif
  185272. #if defined(PNG_READ_iTXt_SUPPORTED)
  185273. void /* PRIVATE */
  185274. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185275. length)
  185276. {
  185277. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185278. {
  185279. png_error(png_ptr, "Out of place iTXt");
  185280. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185281. }
  185282. #ifdef PNG_MAX_MALLOC_64K
  185283. png_ptr->skip_length = 0; /* This may not be necessary */
  185284. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185285. {
  185286. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  185287. png_ptr->skip_length = length - (png_uint_32)65535L;
  185288. length = (png_uint_32)65535L;
  185289. }
  185290. #endif
  185291. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185292. (png_uint_32)(length+1));
  185293. png_ptr->current_text[length] = '\0';
  185294. png_ptr->current_text_ptr = png_ptr->current_text;
  185295. png_ptr->current_text_size = (png_size_t)length;
  185296. png_ptr->current_text_left = (png_size_t)length;
  185297. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  185298. }
  185299. void /* PRIVATE */
  185300. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  185301. {
  185302. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185303. {
  185304. png_size_t text_size;
  185305. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185306. text_size = png_ptr->buffer_size;
  185307. else
  185308. text_size = png_ptr->current_text_left;
  185309. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185310. png_ptr->current_text_left -= text_size;
  185311. png_ptr->current_text_ptr += text_size;
  185312. }
  185313. if (!(png_ptr->current_text_left))
  185314. {
  185315. png_textp text_ptr;
  185316. png_charp key;
  185317. int comp_flag;
  185318. png_charp lang;
  185319. png_charp lang_key;
  185320. png_charp text;
  185321. int ret;
  185322. if (png_ptr->buffer_size < 4)
  185323. {
  185324. png_push_save_buffer(png_ptr);
  185325. return;
  185326. }
  185327. png_push_crc_finish(png_ptr);
  185328. #if defined(PNG_MAX_MALLOC_64K)
  185329. if (png_ptr->skip_length)
  185330. return;
  185331. #endif
  185332. key = png_ptr->current_text;
  185333. for (lang = key; *lang; lang++)
  185334. /* empty loop */ ;
  185335. if (lang < key + png_ptr->current_text_size - 3)
  185336. lang++;
  185337. comp_flag = *lang++;
  185338. lang++; /* skip comp_type, always zero */
  185339. for (lang_key = lang; *lang_key; lang_key++)
  185340. /* empty loop */ ;
  185341. lang_key++; /* skip NUL separator */
  185342. text=lang_key;
  185343. if (lang_key < key + png_ptr->current_text_size - 1)
  185344. {
  185345. for (; *text; text++)
  185346. /* empty loop */ ;
  185347. }
  185348. if (text < key + png_ptr->current_text_size)
  185349. text++;
  185350. text_ptr = (png_textp)png_malloc(png_ptr,
  185351. (png_uint_32)png_sizeof(png_text));
  185352. text_ptr->compression = comp_flag + 2;
  185353. text_ptr->key = key;
  185354. text_ptr->lang = lang;
  185355. text_ptr->lang_key = lang_key;
  185356. text_ptr->text = text;
  185357. text_ptr->text_length = 0;
  185358. text_ptr->itxt_length = png_strlen(text);
  185359. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185360. png_ptr->current_text = NULL;
  185361. png_free(png_ptr, text_ptr);
  185362. if (ret)
  185363. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  185364. }
  185365. }
  185366. #endif
  185367. /* This function is called when we haven't found a handler for this
  185368. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  185369. * name or a critical chunk), the chunk is (currently) silently ignored.
  185370. */
  185371. void /* PRIVATE */
  185372. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185373. length)
  185374. {
  185375. png_uint_32 skip=0;
  185376. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  185377. if (!(png_ptr->chunk_name[0] & 0x20))
  185378. {
  185379. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185380. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185381. PNG_HANDLE_CHUNK_ALWAYS
  185382. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185383. && png_ptr->read_user_chunk_fn == NULL
  185384. #endif
  185385. )
  185386. #endif
  185387. png_chunk_error(png_ptr, "unknown critical chunk");
  185388. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185389. }
  185390. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185391. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  185392. {
  185393. #ifdef PNG_MAX_MALLOC_64K
  185394. if (length > (png_uint_32)65535L)
  185395. {
  185396. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  185397. skip = length - (png_uint_32)65535L;
  185398. length = (png_uint_32)65535L;
  185399. }
  185400. #endif
  185401. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  185402. (png_charp)png_ptr->chunk_name, 5);
  185403. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  185404. png_ptr->unknown_chunk.size = (png_size_t)length;
  185405. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  185406. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185407. if(png_ptr->read_user_chunk_fn != NULL)
  185408. {
  185409. /* callback to user unknown chunk handler */
  185410. int ret;
  185411. ret = (*(png_ptr->read_user_chunk_fn))
  185412. (png_ptr, &png_ptr->unknown_chunk);
  185413. if (ret < 0)
  185414. png_chunk_error(png_ptr, "error in user chunk");
  185415. if (ret == 0)
  185416. {
  185417. if (!(png_ptr->chunk_name[0] & 0x20))
  185418. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185419. PNG_HANDLE_CHUNK_ALWAYS)
  185420. png_chunk_error(png_ptr, "unknown critical chunk");
  185421. png_set_unknown_chunks(png_ptr, info_ptr,
  185422. &png_ptr->unknown_chunk, 1);
  185423. }
  185424. }
  185425. #else
  185426. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  185427. #endif
  185428. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185429. png_ptr->unknown_chunk.data = NULL;
  185430. }
  185431. else
  185432. #endif
  185433. skip=length;
  185434. png_push_crc_skip(png_ptr, skip);
  185435. }
  185436. void /* PRIVATE */
  185437. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  185438. {
  185439. if (png_ptr->info_fn != NULL)
  185440. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  185441. }
  185442. void /* PRIVATE */
  185443. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  185444. {
  185445. if (png_ptr->end_fn != NULL)
  185446. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  185447. }
  185448. void /* PRIVATE */
  185449. png_push_have_row(png_structp png_ptr, png_bytep row)
  185450. {
  185451. if (png_ptr->row_fn != NULL)
  185452. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  185453. (int)png_ptr->pass);
  185454. }
  185455. void PNGAPI
  185456. png_progressive_combine_row (png_structp png_ptr,
  185457. png_bytep old_row, png_bytep new_row)
  185458. {
  185459. #ifdef PNG_USE_LOCAL_ARRAYS
  185460. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  185461. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  185462. #endif
  185463. if(png_ptr == NULL) return;
  185464. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  185465. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  185466. }
  185467. void PNGAPI
  185468. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  185469. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  185470. png_progressive_end_ptr end_fn)
  185471. {
  185472. if(png_ptr == NULL) return;
  185473. png_ptr->info_fn = info_fn;
  185474. png_ptr->row_fn = row_fn;
  185475. png_ptr->end_fn = end_fn;
  185476. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  185477. }
  185478. png_voidp PNGAPI
  185479. png_get_progressive_ptr(png_structp png_ptr)
  185480. {
  185481. if(png_ptr == NULL) return (NULL);
  185482. return png_ptr->io_ptr;
  185483. }
  185484. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185485. /********* End of inlined file: pngpread.c *********/
  185486. /********* Start of inlined file: pngrio.c *********/
  185487. /* pngrio.c - functions for data input
  185488. *
  185489. * Last changed in libpng 1.2.13 November 13, 2006
  185490. * For conditions of distribution and use, see copyright notice in png.h
  185491. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185492. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185493. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185494. *
  185495. * This file provides a location for all input. Users who need
  185496. * special handling are expected to write a function that has the same
  185497. * arguments as this and performs a similar function, but that possibly
  185498. * has a different input method. Note that you shouldn't change this
  185499. * function, but rather write a replacement function and then make
  185500. * libpng use it at run time with png_set_read_fn(...).
  185501. */
  185502. #define PNG_INTERNAL
  185503. #if defined(PNG_READ_SUPPORTED)
  185504. /* Read the data from whatever input you are using. The default routine
  185505. reads from a file pointer. Note that this routine sometimes gets called
  185506. with very small lengths, so you should implement some kind of simple
  185507. buffering if you are using unbuffered reads. This should never be asked
  185508. to read more then 64K on a 16 bit machine. */
  185509. void /* PRIVATE */
  185510. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185511. {
  185512. png_debug1(4,"reading %d bytes\n", (int)length);
  185513. if (png_ptr->read_data_fn != NULL)
  185514. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  185515. else
  185516. png_error(png_ptr, "Call to NULL read function");
  185517. }
  185518. #if !defined(PNG_NO_STDIO)
  185519. /* This is the function that does the actual reading of data. If you are
  185520. not reading from a standard C stream, you should create a replacement
  185521. read_data function and use it at run time with png_set_read_fn(), rather
  185522. than changing the library. */
  185523. #ifndef USE_FAR_KEYWORD
  185524. void PNGAPI
  185525. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185526. {
  185527. png_size_t check;
  185528. if(png_ptr == NULL) return;
  185529. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  185530. * instead of an int, which is what fread() actually returns.
  185531. */
  185532. #if defined(_WIN32_WCE)
  185533. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185534. check = 0;
  185535. #else
  185536. check = (png_size_t)fread(data, (png_size_t)1, length,
  185537. (png_FILE_p)png_ptr->io_ptr);
  185538. #endif
  185539. if (check != length)
  185540. png_error(png_ptr, "Read Error");
  185541. }
  185542. #else
  185543. /* this is the model-independent version. Since the standard I/O library
  185544. can't handle far buffers in the medium and small models, we have to copy
  185545. the data.
  185546. */
  185547. #define NEAR_BUF_SIZE 1024
  185548. #define MIN(a,b) (a <= b ? a : b)
  185549. static void PNGAPI
  185550. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185551. {
  185552. int check;
  185553. png_byte *n_data;
  185554. png_FILE_p io_ptr;
  185555. if(png_ptr == NULL) return;
  185556. /* Check if data really is near. If so, use usual code. */
  185557. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  185558. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  185559. if ((png_bytep)n_data == data)
  185560. {
  185561. #if defined(_WIN32_WCE)
  185562. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185563. check = 0;
  185564. #else
  185565. check = fread(n_data, 1, length, io_ptr);
  185566. #endif
  185567. }
  185568. else
  185569. {
  185570. png_byte buf[NEAR_BUF_SIZE];
  185571. png_size_t read, remaining, err;
  185572. check = 0;
  185573. remaining = length;
  185574. do
  185575. {
  185576. read = MIN(NEAR_BUF_SIZE, remaining);
  185577. #if defined(_WIN32_WCE)
  185578. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  185579. err = 0;
  185580. #else
  185581. err = fread(buf, (png_size_t)1, read, io_ptr);
  185582. #endif
  185583. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  185584. if(err != read)
  185585. break;
  185586. else
  185587. check += err;
  185588. data += read;
  185589. remaining -= read;
  185590. }
  185591. while (remaining != 0);
  185592. }
  185593. if ((png_uint_32)check != (png_uint_32)length)
  185594. png_error(png_ptr, "read Error");
  185595. }
  185596. #endif
  185597. #endif
  185598. /* This function allows the application to supply a new input function
  185599. for libpng if standard C streams aren't being used.
  185600. This function takes as its arguments:
  185601. png_ptr - pointer to a png input data structure
  185602. io_ptr - pointer to user supplied structure containing info about
  185603. the input functions. May be NULL.
  185604. read_data_fn - pointer to a new input function that takes as its
  185605. arguments a pointer to a png_struct, a pointer to
  185606. a location where input data can be stored, and a 32-bit
  185607. unsigned int that is the number of bytes to be read.
  185608. To exit and output any fatal error messages the new write
  185609. function should call png_error(png_ptr, "Error msg"). */
  185610. void PNGAPI
  185611. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  185612. png_rw_ptr read_data_fn)
  185613. {
  185614. if(png_ptr == NULL) return;
  185615. png_ptr->io_ptr = io_ptr;
  185616. #if !defined(PNG_NO_STDIO)
  185617. if (read_data_fn != NULL)
  185618. png_ptr->read_data_fn = read_data_fn;
  185619. else
  185620. png_ptr->read_data_fn = png_default_read_data;
  185621. #else
  185622. png_ptr->read_data_fn = read_data_fn;
  185623. #endif
  185624. /* It is an error to write to a read device */
  185625. if (png_ptr->write_data_fn != NULL)
  185626. {
  185627. png_ptr->write_data_fn = NULL;
  185628. png_warning(png_ptr,
  185629. "It's an error to set both read_data_fn and write_data_fn in the ");
  185630. png_warning(png_ptr,
  185631. "same structure. Resetting write_data_fn to NULL.");
  185632. }
  185633. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  185634. png_ptr->output_flush_fn = NULL;
  185635. #endif
  185636. }
  185637. #endif /* PNG_READ_SUPPORTED */
  185638. /********* End of inlined file: pngrio.c *********/
  185639. /********* Start of inlined file: pngrtran.c *********/
  185640. /* pngrtran.c - transforms the data in a row for PNG readers
  185641. *
  185642. * Last changed in libpng 1.2.21 [October 4, 2007]
  185643. * For conditions of distribution and use, see copyright notice in png.h
  185644. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185645. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185646. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185647. *
  185648. * This file contains functions optionally called by an application
  185649. * in order to tell libpng how to handle data when reading a PNG.
  185650. * Transformations that are used in both reading and writing are
  185651. * in pngtrans.c.
  185652. */
  185653. #define PNG_INTERNAL
  185654. #if defined(PNG_READ_SUPPORTED)
  185655. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  185656. void PNGAPI
  185657. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  185658. {
  185659. png_debug(1, "in png_set_crc_action\n");
  185660. /* Tell libpng how we react to CRC errors in critical chunks */
  185661. if(png_ptr == NULL) return;
  185662. switch (crit_action)
  185663. {
  185664. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185665. break;
  185666. case PNG_CRC_WARN_USE: /* warn/use data */
  185667. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185668. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  185669. break;
  185670. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185671. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185672. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  185673. PNG_FLAG_CRC_CRITICAL_IGNORE;
  185674. break;
  185675. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  185676. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  185677. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185678. case PNG_CRC_DEFAULT:
  185679. default:
  185680. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185681. break;
  185682. }
  185683. switch (ancil_action)
  185684. {
  185685. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185686. break;
  185687. case PNG_CRC_WARN_USE: /* warn/use data */
  185688. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185689. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  185690. break;
  185691. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185692. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185693. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  185694. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185695. break;
  185696. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185697. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185698. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185699. break;
  185700. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  185701. case PNG_CRC_DEFAULT:
  185702. default:
  185703. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185704. break;
  185705. }
  185706. }
  185707. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185708. defined(PNG_FLOATING_POINT_SUPPORTED)
  185709. /* handle alpha and tRNS via a background color */
  185710. void PNGAPI
  185711. png_set_background(png_structp png_ptr,
  185712. png_color_16p background_color, int background_gamma_code,
  185713. int need_expand, double background_gamma)
  185714. {
  185715. png_debug(1, "in png_set_background\n");
  185716. if(png_ptr == NULL) return;
  185717. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  185718. {
  185719. png_warning(png_ptr, "Application must supply a known background gamma");
  185720. return;
  185721. }
  185722. png_ptr->transformations |= PNG_BACKGROUND;
  185723. png_memcpy(&(png_ptr->background), background_color,
  185724. png_sizeof(png_color_16));
  185725. png_ptr->background_gamma = (float)background_gamma;
  185726. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  185727. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  185728. }
  185729. #endif
  185730. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185731. /* strip 16 bit depth files to 8 bit depth */
  185732. void PNGAPI
  185733. png_set_strip_16(png_structp png_ptr)
  185734. {
  185735. png_debug(1, "in png_set_strip_16\n");
  185736. if(png_ptr == NULL) return;
  185737. png_ptr->transformations |= PNG_16_TO_8;
  185738. }
  185739. #endif
  185740. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185741. void PNGAPI
  185742. png_set_strip_alpha(png_structp png_ptr)
  185743. {
  185744. png_debug(1, "in png_set_strip_alpha\n");
  185745. if(png_ptr == NULL) return;
  185746. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  185747. }
  185748. #endif
  185749. #if defined(PNG_READ_DITHER_SUPPORTED)
  185750. /* Dither file to 8 bit. Supply a palette, the current number
  185751. * of elements in the palette, the maximum number of elements
  185752. * allowed, and a histogram if possible. If the current number
  185753. * of colors is greater then the maximum number, the palette will be
  185754. * modified to fit in the maximum number. "full_dither" indicates
  185755. * whether we need a dithering cube set up for RGB images, or if we
  185756. * simply are reducing the number of colors in a paletted image.
  185757. */
  185758. typedef struct png_dsort_struct
  185759. {
  185760. struct png_dsort_struct FAR * next;
  185761. png_byte left;
  185762. png_byte right;
  185763. } png_dsort;
  185764. typedef png_dsort FAR * png_dsortp;
  185765. typedef png_dsort FAR * FAR * png_dsortpp;
  185766. void PNGAPI
  185767. png_set_dither(png_structp png_ptr, png_colorp palette,
  185768. int num_palette, int maximum_colors, png_uint_16p histogram,
  185769. int full_dither)
  185770. {
  185771. png_debug(1, "in png_set_dither\n");
  185772. if(png_ptr == NULL) return;
  185773. png_ptr->transformations |= PNG_DITHER;
  185774. if (!full_dither)
  185775. {
  185776. int i;
  185777. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  185778. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185779. for (i = 0; i < num_palette; i++)
  185780. png_ptr->dither_index[i] = (png_byte)i;
  185781. }
  185782. if (num_palette > maximum_colors)
  185783. {
  185784. if (histogram != NULL)
  185785. {
  185786. /* This is easy enough, just throw out the least used colors.
  185787. Perhaps not the best solution, but good enough. */
  185788. int i;
  185789. /* initialize an array to sort colors */
  185790. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  185791. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185792. /* initialize the dither_sort array */
  185793. for (i = 0; i < num_palette; i++)
  185794. png_ptr->dither_sort[i] = (png_byte)i;
  185795. /* Find the least used palette entries by starting a
  185796. bubble sort, and running it until we have sorted
  185797. out enough colors. Note that we don't care about
  185798. sorting all the colors, just finding which are
  185799. least used. */
  185800. for (i = num_palette - 1; i >= maximum_colors; i--)
  185801. {
  185802. int done; /* to stop early if the list is pre-sorted */
  185803. int j;
  185804. done = 1;
  185805. for (j = 0; j < i; j++)
  185806. {
  185807. if (histogram[png_ptr->dither_sort[j]]
  185808. < histogram[png_ptr->dither_sort[j + 1]])
  185809. {
  185810. png_byte t;
  185811. t = png_ptr->dither_sort[j];
  185812. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  185813. png_ptr->dither_sort[j + 1] = t;
  185814. done = 0;
  185815. }
  185816. }
  185817. if (done)
  185818. break;
  185819. }
  185820. /* swap the palette around, and set up a table, if necessary */
  185821. if (full_dither)
  185822. {
  185823. int j = num_palette;
  185824. /* put all the useful colors within the max, but don't
  185825. move the others */
  185826. for (i = 0; i < maximum_colors; i++)
  185827. {
  185828. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185829. {
  185830. do
  185831. j--;
  185832. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185833. palette[i] = palette[j];
  185834. }
  185835. }
  185836. }
  185837. else
  185838. {
  185839. int j = num_palette;
  185840. /* move all the used colors inside the max limit, and
  185841. develop a translation table */
  185842. for (i = 0; i < maximum_colors; i++)
  185843. {
  185844. /* only move the colors we need to */
  185845. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185846. {
  185847. png_color tmp_color;
  185848. do
  185849. j--;
  185850. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185851. tmp_color = palette[j];
  185852. palette[j] = palette[i];
  185853. palette[i] = tmp_color;
  185854. /* indicate where the color went */
  185855. png_ptr->dither_index[j] = (png_byte)i;
  185856. png_ptr->dither_index[i] = (png_byte)j;
  185857. }
  185858. }
  185859. /* find closest color for those colors we are not using */
  185860. for (i = 0; i < num_palette; i++)
  185861. {
  185862. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  185863. {
  185864. int min_d, k, min_k, d_index;
  185865. /* find the closest color to one we threw out */
  185866. d_index = png_ptr->dither_index[i];
  185867. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  185868. for (k = 1, min_k = 0; k < maximum_colors; k++)
  185869. {
  185870. int d;
  185871. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  185872. if (d < min_d)
  185873. {
  185874. min_d = d;
  185875. min_k = k;
  185876. }
  185877. }
  185878. /* point to closest color */
  185879. png_ptr->dither_index[i] = (png_byte)min_k;
  185880. }
  185881. }
  185882. }
  185883. png_free(png_ptr, png_ptr->dither_sort);
  185884. png_ptr->dither_sort=NULL;
  185885. }
  185886. else
  185887. {
  185888. /* This is much harder to do simply (and quickly). Perhaps
  185889. we need to go through a median cut routine, but those
  185890. don't always behave themselves with only a few colors
  185891. as input. So we will just find the closest two colors,
  185892. and throw out one of them (chosen somewhat randomly).
  185893. [We don't understand this at all, so if someone wants to
  185894. work on improving it, be our guest - AED, GRP]
  185895. */
  185896. int i;
  185897. int max_d;
  185898. int num_new_palette;
  185899. png_dsortp t;
  185900. png_dsortpp hash;
  185901. t=NULL;
  185902. /* initialize palette index arrays */
  185903. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  185904. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185905. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  185906. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185907. /* initialize the sort array */
  185908. for (i = 0; i < num_palette; i++)
  185909. {
  185910. png_ptr->index_to_palette[i] = (png_byte)i;
  185911. png_ptr->palette_to_index[i] = (png_byte)i;
  185912. }
  185913. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  185914. png_sizeof (png_dsortp)));
  185915. for (i = 0; i < 769; i++)
  185916. hash[i] = NULL;
  185917. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  185918. num_new_palette = num_palette;
  185919. /* initial wild guess at how far apart the farthest pixel
  185920. pair we will be eliminating will be. Larger
  185921. numbers mean more areas will be allocated, Smaller
  185922. numbers run the risk of not saving enough data, and
  185923. having to do this all over again.
  185924. I have not done extensive checking on this number.
  185925. */
  185926. max_d = 96;
  185927. while (num_new_palette > maximum_colors)
  185928. {
  185929. for (i = 0; i < num_new_palette - 1; i++)
  185930. {
  185931. int j;
  185932. for (j = i + 1; j < num_new_palette; j++)
  185933. {
  185934. int d;
  185935. d = PNG_COLOR_DIST(palette[i], palette[j]);
  185936. if (d <= max_d)
  185937. {
  185938. t = (png_dsortp)png_malloc_warn(png_ptr,
  185939. (png_uint_32)(png_sizeof(png_dsort)));
  185940. if (t == NULL)
  185941. break;
  185942. t->next = hash[d];
  185943. t->left = (png_byte)i;
  185944. t->right = (png_byte)j;
  185945. hash[d] = t;
  185946. }
  185947. }
  185948. if (t == NULL)
  185949. break;
  185950. }
  185951. if (t != NULL)
  185952. for (i = 0; i <= max_d; i++)
  185953. {
  185954. if (hash[i] != NULL)
  185955. {
  185956. png_dsortp p;
  185957. for (p = hash[i]; p; p = p->next)
  185958. {
  185959. if ((int)png_ptr->index_to_palette[p->left]
  185960. < num_new_palette &&
  185961. (int)png_ptr->index_to_palette[p->right]
  185962. < num_new_palette)
  185963. {
  185964. int j, next_j;
  185965. if (num_new_palette & 0x01)
  185966. {
  185967. j = p->left;
  185968. next_j = p->right;
  185969. }
  185970. else
  185971. {
  185972. j = p->right;
  185973. next_j = p->left;
  185974. }
  185975. num_new_palette--;
  185976. palette[png_ptr->index_to_palette[j]]
  185977. = palette[num_new_palette];
  185978. if (!full_dither)
  185979. {
  185980. int k;
  185981. for (k = 0; k < num_palette; k++)
  185982. {
  185983. if (png_ptr->dither_index[k] ==
  185984. png_ptr->index_to_palette[j])
  185985. png_ptr->dither_index[k] =
  185986. png_ptr->index_to_palette[next_j];
  185987. if ((int)png_ptr->dither_index[k] ==
  185988. num_new_palette)
  185989. png_ptr->dither_index[k] =
  185990. png_ptr->index_to_palette[j];
  185991. }
  185992. }
  185993. png_ptr->index_to_palette[png_ptr->palette_to_index
  185994. [num_new_palette]] = png_ptr->index_to_palette[j];
  185995. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  185996. = png_ptr->palette_to_index[num_new_palette];
  185997. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  185998. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  185999. }
  186000. if (num_new_palette <= maximum_colors)
  186001. break;
  186002. }
  186003. if (num_new_palette <= maximum_colors)
  186004. break;
  186005. }
  186006. }
  186007. for (i = 0; i < 769; i++)
  186008. {
  186009. if (hash[i] != NULL)
  186010. {
  186011. png_dsortp p = hash[i];
  186012. while (p)
  186013. {
  186014. t = p->next;
  186015. png_free(png_ptr, p);
  186016. p = t;
  186017. }
  186018. }
  186019. hash[i] = 0;
  186020. }
  186021. max_d += 96;
  186022. }
  186023. png_free(png_ptr, hash);
  186024. png_free(png_ptr, png_ptr->palette_to_index);
  186025. png_free(png_ptr, png_ptr->index_to_palette);
  186026. png_ptr->palette_to_index=NULL;
  186027. png_ptr->index_to_palette=NULL;
  186028. }
  186029. num_palette = maximum_colors;
  186030. }
  186031. if (png_ptr->palette == NULL)
  186032. {
  186033. png_ptr->palette = palette;
  186034. }
  186035. png_ptr->num_palette = (png_uint_16)num_palette;
  186036. if (full_dither)
  186037. {
  186038. int i;
  186039. png_bytep distance;
  186040. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  186041. PNG_DITHER_BLUE_BITS;
  186042. int num_red = (1 << PNG_DITHER_RED_BITS);
  186043. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  186044. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  186045. png_size_t num_entries = ((png_size_t)1 << total_bits);
  186046. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  186047. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  186048. png_memset(png_ptr->palette_lookup, 0, num_entries *
  186049. png_sizeof (png_byte));
  186050. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  186051. png_sizeof(png_byte)));
  186052. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  186053. for (i = 0; i < num_palette; i++)
  186054. {
  186055. int ir, ig, ib;
  186056. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  186057. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  186058. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  186059. for (ir = 0; ir < num_red; ir++)
  186060. {
  186061. /* int dr = abs(ir - r); */
  186062. int dr = ((ir > r) ? ir - r : r - ir);
  186063. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  186064. for (ig = 0; ig < num_green; ig++)
  186065. {
  186066. /* int dg = abs(ig - g); */
  186067. int dg = ((ig > g) ? ig - g : g - ig);
  186068. int dt = dr + dg;
  186069. int dm = ((dr > dg) ? dr : dg);
  186070. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  186071. for (ib = 0; ib < num_blue; ib++)
  186072. {
  186073. int d_index = index_g | ib;
  186074. /* int db = abs(ib - b); */
  186075. int db = ((ib > b) ? ib - b : b - ib);
  186076. int dmax = ((dm > db) ? dm : db);
  186077. int d = dmax + dt + db;
  186078. if (d < (int)distance[d_index])
  186079. {
  186080. distance[d_index] = (png_byte)d;
  186081. png_ptr->palette_lookup[d_index] = (png_byte)i;
  186082. }
  186083. }
  186084. }
  186085. }
  186086. }
  186087. png_free(png_ptr, distance);
  186088. }
  186089. }
  186090. #endif
  186091. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186092. /* Transform the image from the file_gamma to the screen_gamma. We
  186093. * only do transformations on images where the file_gamma and screen_gamma
  186094. * are not close reciprocals, otherwise it slows things down slightly, and
  186095. * also needlessly introduces small errors.
  186096. *
  186097. * We will turn off gamma transformation later if no semitransparent entries
  186098. * are present in the tRNS array for palette images. We can't do it here
  186099. * because we don't necessarily have the tRNS chunk yet.
  186100. */
  186101. void PNGAPI
  186102. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  186103. {
  186104. png_debug(1, "in png_set_gamma\n");
  186105. if(png_ptr == NULL) return;
  186106. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  186107. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  186108. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  186109. png_ptr->transformations |= PNG_GAMMA;
  186110. png_ptr->gamma = (float)file_gamma;
  186111. png_ptr->screen_gamma = (float)scrn_gamma;
  186112. }
  186113. #endif
  186114. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186115. /* Expand paletted images to RGB, expand grayscale images of
  186116. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  186117. * to alpha channels.
  186118. */
  186119. void PNGAPI
  186120. png_set_expand(png_structp png_ptr)
  186121. {
  186122. png_debug(1, "in png_set_expand\n");
  186123. if(png_ptr == NULL) return;
  186124. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186125. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186126. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186127. #endif
  186128. }
  186129. /* GRR 19990627: the following three functions currently are identical
  186130. * to png_set_expand(). However, it is entirely reasonable that someone
  186131. * might wish to expand an indexed image to RGB but *not* expand a single,
  186132. * fully transparent palette entry to a full alpha channel--perhaps instead
  186133. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  186134. * the transparent color with a particular RGB value, or drop tRNS entirely.
  186135. * IOW, a future version of the library may make the transformations flag
  186136. * a bit more fine-grained, with separate bits for each of these three
  186137. * functions.
  186138. *
  186139. * More to the point, these functions make it obvious what libpng will be
  186140. * doing, whereas "expand" can (and does) mean any number of things.
  186141. *
  186142. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  186143. * to expand only the sample depth but not to expand the tRNS to alpha.
  186144. */
  186145. /* Expand paletted images to RGB. */
  186146. void PNGAPI
  186147. png_set_palette_to_rgb(png_structp png_ptr)
  186148. {
  186149. png_debug(1, "in png_set_palette_to_rgb\n");
  186150. if(png_ptr == NULL) return;
  186151. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186152. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186153. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  186154. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186155. #endif
  186156. }
  186157. #if !defined(PNG_1_0_X)
  186158. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186159. void PNGAPI
  186160. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  186161. {
  186162. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  186163. if(png_ptr == NULL) return;
  186164. png_ptr->transformations |= PNG_EXPAND;
  186165. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186166. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186167. #endif
  186168. }
  186169. #endif
  186170. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186171. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186172. /* Deprecated as of libpng-1.2.9 */
  186173. void PNGAPI
  186174. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  186175. {
  186176. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  186177. if(png_ptr == NULL) return;
  186178. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186179. }
  186180. #endif
  186181. /* Expand tRNS chunks to alpha channels. */
  186182. void PNGAPI
  186183. png_set_tRNS_to_alpha(png_structp png_ptr)
  186184. {
  186185. png_debug(1, "in png_set_tRNS_to_alpha\n");
  186186. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186187. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186188. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186189. #endif
  186190. }
  186191. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  186192. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186193. void PNGAPI
  186194. png_set_gray_to_rgb(png_structp png_ptr)
  186195. {
  186196. png_debug(1, "in png_set_gray_to_rgb\n");
  186197. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  186198. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186199. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186200. #endif
  186201. }
  186202. #endif
  186203. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186204. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  186205. /* Convert a RGB image to a grayscale of the same width. This allows us,
  186206. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  186207. */
  186208. void PNGAPI
  186209. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  186210. double green)
  186211. {
  186212. int red_fixed = (int)((float)red*100000.0 + 0.5);
  186213. int green_fixed = (int)((float)green*100000.0 + 0.5);
  186214. if(png_ptr == NULL) return;
  186215. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  186216. }
  186217. #endif
  186218. void PNGAPI
  186219. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  186220. png_fixed_point red, png_fixed_point green)
  186221. {
  186222. png_debug(1, "in png_set_rgb_to_gray\n");
  186223. if(png_ptr == NULL) return;
  186224. switch(error_action)
  186225. {
  186226. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  186227. break;
  186228. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  186229. break;
  186230. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  186231. }
  186232. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186233. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186234. png_ptr->transformations |= PNG_EXPAND;
  186235. #else
  186236. {
  186237. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  186238. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  186239. }
  186240. #endif
  186241. {
  186242. png_uint_16 red_int, green_int;
  186243. if(red < 0 || green < 0)
  186244. {
  186245. red_int = 6968; /* .212671 * 32768 + .5 */
  186246. green_int = 23434; /* .715160 * 32768 + .5 */
  186247. }
  186248. else if(red + green < 100000L)
  186249. {
  186250. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  186251. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  186252. }
  186253. else
  186254. {
  186255. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  186256. red_int = 6968;
  186257. green_int = 23434;
  186258. }
  186259. png_ptr->rgb_to_gray_red_coeff = red_int;
  186260. png_ptr->rgb_to_gray_green_coeff = green_int;
  186261. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  186262. }
  186263. }
  186264. #endif
  186265. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  186266. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  186267. defined(PNG_LEGACY_SUPPORTED)
  186268. void PNGAPI
  186269. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  186270. read_user_transform_fn)
  186271. {
  186272. png_debug(1, "in png_set_read_user_transform_fn\n");
  186273. if(png_ptr == NULL) return;
  186274. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186275. png_ptr->transformations |= PNG_USER_TRANSFORM;
  186276. png_ptr->read_user_transform_fn = read_user_transform_fn;
  186277. #endif
  186278. #ifdef PNG_LEGACY_SUPPORTED
  186279. if(read_user_transform_fn)
  186280. png_warning(png_ptr,
  186281. "This version of libpng does not support user transforms");
  186282. #endif
  186283. }
  186284. #endif
  186285. /* Initialize everything needed for the read. This includes modifying
  186286. * the palette.
  186287. */
  186288. void /* PRIVATE */
  186289. png_init_read_transformations(png_structp png_ptr)
  186290. {
  186291. png_debug(1, "in png_init_read_transformations\n");
  186292. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186293. if(png_ptr != NULL)
  186294. #endif
  186295. {
  186296. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  186297. || defined(PNG_READ_GAMMA_SUPPORTED)
  186298. int color_type = png_ptr->color_type;
  186299. #endif
  186300. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  186301. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186302. /* Detect gray background and attempt to enable optimization
  186303. * for gray --> RGB case */
  186304. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  186305. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  186306. * background color might actually be gray yet not be flagged as such.
  186307. * This is not a problem for the current code, which uses
  186308. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  186309. * png_do_gray_to_rgb() transformation.
  186310. */
  186311. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186312. !(color_type & PNG_COLOR_MASK_COLOR))
  186313. {
  186314. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186315. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186316. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186317. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186318. png_ptr->background.red == png_ptr->background.green &&
  186319. png_ptr->background.red == png_ptr->background.blue)
  186320. {
  186321. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186322. png_ptr->background.gray = png_ptr->background.red;
  186323. }
  186324. #endif
  186325. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186326. (png_ptr->transformations & PNG_EXPAND))
  186327. {
  186328. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  186329. {
  186330. /* expand background and tRNS chunks */
  186331. switch (png_ptr->bit_depth)
  186332. {
  186333. case 1:
  186334. png_ptr->background.gray *= (png_uint_16)0xff;
  186335. png_ptr->background.red = png_ptr->background.green
  186336. = png_ptr->background.blue = png_ptr->background.gray;
  186337. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186338. {
  186339. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  186340. png_ptr->trans_values.red = png_ptr->trans_values.green
  186341. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186342. }
  186343. break;
  186344. case 2:
  186345. png_ptr->background.gray *= (png_uint_16)0x55;
  186346. png_ptr->background.red = png_ptr->background.green
  186347. = png_ptr->background.blue = png_ptr->background.gray;
  186348. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186349. {
  186350. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  186351. png_ptr->trans_values.red = png_ptr->trans_values.green
  186352. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186353. }
  186354. break;
  186355. case 4:
  186356. png_ptr->background.gray *= (png_uint_16)0x11;
  186357. png_ptr->background.red = png_ptr->background.green
  186358. = png_ptr->background.blue = png_ptr->background.gray;
  186359. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186360. {
  186361. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  186362. png_ptr->trans_values.red = png_ptr->trans_values.green
  186363. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186364. }
  186365. break;
  186366. case 8:
  186367. case 16:
  186368. png_ptr->background.red = png_ptr->background.green
  186369. = png_ptr->background.blue = png_ptr->background.gray;
  186370. break;
  186371. }
  186372. }
  186373. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  186374. {
  186375. png_ptr->background.red =
  186376. png_ptr->palette[png_ptr->background.index].red;
  186377. png_ptr->background.green =
  186378. png_ptr->palette[png_ptr->background.index].green;
  186379. png_ptr->background.blue =
  186380. png_ptr->palette[png_ptr->background.index].blue;
  186381. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186382. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186383. {
  186384. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186385. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186386. #endif
  186387. {
  186388. /* invert the alpha channel (in tRNS) unless the pixels are
  186389. going to be expanded, in which case leave it for later */
  186390. int i,istop;
  186391. istop=(int)png_ptr->num_trans;
  186392. for (i=0; i<istop; i++)
  186393. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  186394. }
  186395. }
  186396. #endif
  186397. }
  186398. }
  186399. #endif
  186400. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  186401. png_ptr->background_1 = png_ptr->background;
  186402. #endif
  186403. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186404. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  186405. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  186406. < PNG_GAMMA_THRESHOLD))
  186407. {
  186408. int i,k;
  186409. k=0;
  186410. for (i=0; i<png_ptr->num_trans; i++)
  186411. {
  186412. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  186413. k=1; /* partial transparency is present */
  186414. }
  186415. if (k == 0)
  186416. png_ptr->transformations &= (~PNG_GAMMA);
  186417. }
  186418. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  186419. png_ptr->gamma != 0.0)
  186420. {
  186421. png_build_gamma_table(png_ptr);
  186422. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186423. if (png_ptr->transformations & PNG_BACKGROUND)
  186424. {
  186425. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186426. {
  186427. /* could skip if no transparency and
  186428. */
  186429. png_color back, back_1;
  186430. png_colorp palette = png_ptr->palette;
  186431. int num_palette = png_ptr->num_palette;
  186432. int i;
  186433. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186434. {
  186435. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186436. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186437. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186438. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186439. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186440. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186441. }
  186442. else
  186443. {
  186444. double g, gs;
  186445. switch (png_ptr->background_gamma_type)
  186446. {
  186447. case PNG_BACKGROUND_GAMMA_SCREEN:
  186448. g = (png_ptr->screen_gamma);
  186449. gs = 1.0;
  186450. break;
  186451. case PNG_BACKGROUND_GAMMA_FILE:
  186452. g = 1.0 / (png_ptr->gamma);
  186453. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186454. break;
  186455. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186456. g = 1.0 / (png_ptr->background_gamma);
  186457. gs = 1.0 / (png_ptr->background_gamma *
  186458. png_ptr->screen_gamma);
  186459. break;
  186460. default:
  186461. g = 1.0; /* back_1 */
  186462. gs = 1.0; /* back */
  186463. }
  186464. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  186465. {
  186466. back.red = (png_byte)png_ptr->background.red;
  186467. back.green = (png_byte)png_ptr->background.green;
  186468. back.blue = (png_byte)png_ptr->background.blue;
  186469. }
  186470. else
  186471. {
  186472. back.red = (png_byte)(pow(
  186473. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  186474. back.green = (png_byte)(pow(
  186475. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  186476. back.blue = (png_byte)(pow(
  186477. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  186478. }
  186479. back_1.red = (png_byte)(pow(
  186480. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  186481. back_1.green = (png_byte)(pow(
  186482. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  186483. back_1.blue = (png_byte)(pow(
  186484. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  186485. }
  186486. for (i = 0; i < num_palette; i++)
  186487. {
  186488. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186489. {
  186490. if (png_ptr->trans[i] == 0)
  186491. {
  186492. palette[i] = back;
  186493. }
  186494. else /* if (png_ptr->trans[i] != 0xff) */
  186495. {
  186496. png_byte v, w;
  186497. v = png_ptr->gamma_to_1[palette[i].red];
  186498. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186499. palette[i].red = png_ptr->gamma_from_1[w];
  186500. v = png_ptr->gamma_to_1[palette[i].green];
  186501. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186502. palette[i].green = png_ptr->gamma_from_1[w];
  186503. v = png_ptr->gamma_to_1[palette[i].blue];
  186504. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186505. palette[i].blue = png_ptr->gamma_from_1[w];
  186506. }
  186507. }
  186508. else
  186509. {
  186510. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186511. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186512. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186513. }
  186514. }
  186515. }
  186516. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  186517. else
  186518. /* color_type != PNG_COLOR_TYPE_PALETTE */
  186519. {
  186520. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  186521. double g = 1.0;
  186522. double gs = 1.0;
  186523. switch (png_ptr->background_gamma_type)
  186524. {
  186525. case PNG_BACKGROUND_GAMMA_SCREEN:
  186526. g = (png_ptr->screen_gamma);
  186527. gs = 1.0;
  186528. break;
  186529. case PNG_BACKGROUND_GAMMA_FILE:
  186530. g = 1.0 / (png_ptr->gamma);
  186531. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186532. break;
  186533. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186534. g = 1.0 / (png_ptr->background_gamma);
  186535. gs = 1.0 / (png_ptr->background_gamma *
  186536. png_ptr->screen_gamma);
  186537. break;
  186538. }
  186539. png_ptr->background_1.gray = (png_uint_16)(pow(
  186540. (double)png_ptr->background.gray / m, g) * m + .5);
  186541. png_ptr->background.gray = (png_uint_16)(pow(
  186542. (double)png_ptr->background.gray / m, gs) * m + .5);
  186543. if ((png_ptr->background.red != png_ptr->background.green) ||
  186544. (png_ptr->background.red != png_ptr->background.blue) ||
  186545. (png_ptr->background.red != png_ptr->background.gray))
  186546. {
  186547. /* RGB or RGBA with color background */
  186548. png_ptr->background_1.red = (png_uint_16)(pow(
  186549. (double)png_ptr->background.red / m, g) * m + .5);
  186550. png_ptr->background_1.green = (png_uint_16)(pow(
  186551. (double)png_ptr->background.green / m, g) * m + .5);
  186552. png_ptr->background_1.blue = (png_uint_16)(pow(
  186553. (double)png_ptr->background.blue / m, g) * m + .5);
  186554. png_ptr->background.red = (png_uint_16)(pow(
  186555. (double)png_ptr->background.red / m, gs) * m + .5);
  186556. png_ptr->background.green = (png_uint_16)(pow(
  186557. (double)png_ptr->background.green / m, gs) * m + .5);
  186558. png_ptr->background.blue = (png_uint_16)(pow(
  186559. (double)png_ptr->background.blue / m, gs) * m + .5);
  186560. }
  186561. else
  186562. {
  186563. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  186564. png_ptr->background_1.red = png_ptr->background_1.green
  186565. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  186566. png_ptr->background.red = png_ptr->background.green
  186567. = png_ptr->background.blue = png_ptr->background.gray;
  186568. }
  186569. }
  186570. }
  186571. else
  186572. /* transformation does not include PNG_BACKGROUND */
  186573. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186574. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186575. {
  186576. png_colorp palette = png_ptr->palette;
  186577. int num_palette = png_ptr->num_palette;
  186578. int i;
  186579. for (i = 0; i < num_palette; i++)
  186580. {
  186581. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186582. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186583. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186584. }
  186585. }
  186586. }
  186587. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186588. else
  186589. #endif
  186590. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  186591. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186592. /* No GAMMA transformation */
  186593. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186594. (color_type == PNG_COLOR_TYPE_PALETTE))
  186595. {
  186596. int i;
  186597. int istop = (int)png_ptr->num_trans;
  186598. png_color back;
  186599. png_colorp palette = png_ptr->palette;
  186600. back.red = (png_byte)png_ptr->background.red;
  186601. back.green = (png_byte)png_ptr->background.green;
  186602. back.blue = (png_byte)png_ptr->background.blue;
  186603. for (i = 0; i < istop; i++)
  186604. {
  186605. if (png_ptr->trans[i] == 0)
  186606. {
  186607. palette[i] = back;
  186608. }
  186609. else if (png_ptr->trans[i] != 0xff)
  186610. {
  186611. /* The png_composite() macro is defined in png.h */
  186612. png_composite(palette[i].red, palette[i].red,
  186613. png_ptr->trans[i], back.red);
  186614. png_composite(palette[i].green, palette[i].green,
  186615. png_ptr->trans[i], back.green);
  186616. png_composite(palette[i].blue, palette[i].blue,
  186617. png_ptr->trans[i], back.blue);
  186618. }
  186619. }
  186620. }
  186621. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186622. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186623. if ((png_ptr->transformations & PNG_SHIFT) &&
  186624. (color_type == PNG_COLOR_TYPE_PALETTE))
  186625. {
  186626. png_uint_16 i;
  186627. png_uint_16 istop = png_ptr->num_palette;
  186628. int sr = 8 - png_ptr->sig_bit.red;
  186629. int sg = 8 - png_ptr->sig_bit.green;
  186630. int sb = 8 - png_ptr->sig_bit.blue;
  186631. if (sr < 0 || sr > 8)
  186632. sr = 0;
  186633. if (sg < 0 || sg > 8)
  186634. sg = 0;
  186635. if (sb < 0 || sb > 8)
  186636. sb = 0;
  186637. for (i = 0; i < istop; i++)
  186638. {
  186639. png_ptr->palette[i].red >>= sr;
  186640. png_ptr->palette[i].green >>= sg;
  186641. png_ptr->palette[i].blue >>= sb;
  186642. }
  186643. }
  186644. #endif /* PNG_READ_SHIFT_SUPPORTED */
  186645. }
  186646. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  186647. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  186648. if(png_ptr)
  186649. return;
  186650. #endif
  186651. }
  186652. /* Modify the info structure to reflect the transformations. The
  186653. * info should be updated so a PNG file could be written with it,
  186654. * assuming the transformations result in valid PNG data.
  186655. */
  186656. void /* PRIVATE */
  186657. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  186658. {
  186659. png_debug(1, "in png_read_transform_info\n");
  186660. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186661. if (png_ptr->transformations & PNG_EXPAND)
  186662. {
  186663. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186664. {
  186665. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  186666. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186667. else
  186668. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  186669. info_ptr->bit_depth = 8;
  186670. info_ptr->num_trans = 0;
  186671. }
  186672. else
  186673. {
  186674. if (png_ptr->num_trans)
  186675. {
  186676. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  186677. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186678. else
  186679. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186680. }
  186681. if (info_ptr->bit_depth < 8)
  186682. info_ptr->bit_depth = 8;
  186683. info_ptr->num_trans = 0;
  186684. }
  186685. }
  186686. #endif
  186687. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186688. if (png_ptr->transformations & PNG_BACKGROUND)
  186689. {
  186690. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186691. info_ptr->num_trans = 0;
  186692. info_ptr->background = png_ptr->background;
  186693. }
  186694. #endif
  186695. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186696. if (png_ptr->transformations & PNG_GAMMA)
  186697. {
  186698. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186699. info_ptr->gamma = png_ptr->gamma;
  186700. #endif
  186701. #ifdef PNG_FIXED_POINT_SUPPORTED
  186702. info_ptr->int_gamma = png_ptr->int_gamma;
  186703. #endif
  186704. }
  186705. #endif
  186706. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186707. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  186708. info_ptr->bit_depth = 8;
  186709. #endif
  186710. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186711. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  186712. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186713. #endif
  186714. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186715. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186716. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  186717. #endif
  186718. #if defined(PNG_READ_DITHER_SUPPORTED)
  186719. if (png_ptr->transformations & PNG_DITHER)
  186720. {
  186721. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186722. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  186723. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  186724. {
  186725. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  186726. }
  186727. }
  186728. #endif
  186729. #if defined(PNG_READ_PACK_SUPPORTED)
  186730. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  186731. info_ptr->bit_depth = 8;
  186732. #endif
  186733. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186734. info_ptr->channels = 1;
  186735. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  186736. info_ptr->channels = 3;
  186737. else
  186738. info_ptr->channels = 1;
  186739. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186740. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186741. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186742. #endif
  186743. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  186744. info_ptr->channels++;
  186745. #if defined(PNG_READ_FILLER_SUPPORTED)
  186746. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  186747. if ((png_ptr->transformations & PNG_FILLER) &&
  186748. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186749. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  186750. {
  186751. info_ptr->channels++;
  186752. /* if adding a true alpha channel not just filler */
  186753. #if !defined(PNG_1_0_X)
  186754. if (png_ptr->transformations & PNG_ADD_ALPHA)
  186755. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186756. #endif
  186757. }
  186758. #endif
  186759. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  186760. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186761. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  186762. {
  186763. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  186764. info_ptr->bit_depth = png_ptr->user_transform_depth;
  186765. if(info_ptr->channels < png_ptr->user_transform_channels)
  186766. info_ptr->channels = png_ptr->user_transform_channels;
  186767. }
  186768. #endif
  186769. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  186770. info_ptr->bit_depth);
  186771. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  186772. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  186773. if(png_ptr)
  186774. return;
  186775. #endif
  186776. }
  186777. /* Transform the row. The order of transformations is significant,
  186778. * and is very touchy. If you add a transformation, take care to
  186779. * decide how it fits in with the other transformations here.
  186780. */
  186781. void /* PRIVATE */
  186782. png_do_read_transformations(png_structp png_ptr)
  186783. {
  186784. png_debug(1, "in png_do_read_transformations\n");
  186785. if (png_ptr->row_buf == NULL)
  186786. {
  186787. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186788. char msg[50];
  186789. png_snprintf2(msg, 50,
  186790. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  186791. png_ptr->pass);
  186792. png_error(png_ptr, msg);
  186793. #else
  186794. png_error(png_ptr, "NULL row buffer");
  186795. #endif
  186796. }
  186797. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186798. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186799. /* Application has failed to call either png_read_start_image()
  186800. * or png_read_update_info() after setting transforms that expand
  186801. * pixels. This check added to libpng-1.2.19 */
  186802. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  186803. png_error(png_ptr, "Uninitialized row");
  186804. #else
  186805. png_warning(png_ptr, "Uninitialized row");
  186806. #endif
  186807. #endif
  186808. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186809. if (png_ptr->transformations & PNG_EXPAND)
  186810. {
  186811. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  186812. {
  186813. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186814. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  186815. }
  186816. else
  186817. {
  186818. if (png_ptr->num_trans &&
  186819. (png_ptr->transformations & PNG_EXPAND_tRNS))
  186820. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186821. &(png_ptr->trans_values));
  186822. else
  186823. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186824. NULL);
  186825. }
  186826. }
  186827. #endif
  186828. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186829. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186830. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186831. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  186832. #endif
  186833. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186834. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186835. {
  186836. int rgb_error =
  186837. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  186838. if(rgb_error)
  186839. {
  186840. png_ptr->rgb_to_gray_status=1;
  186841. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186842. PNG_RGB_TO_GRAY_WARN)
  186843. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186844. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186845. PNG_RGB_TO_GRAY_ERR)
  186846. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186847. }
  186848. }
  186849. #endif
  186850. /*
  186851. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  186852. In most cases, the "simple transparency" should be done prior to doing
  186853. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  186854. pixel is transparent. You would also need to make sure that the
  186855. transparency information is upgraded to RGB.
  186856. To summarize, the current flow is:
  186857. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  186858. with background "in place" if transparent,
  186859. convert to RGB if necessary
  186860. - Gray + alpha -> composite with gray background and remove alpha bytes,
  186861. convert to RGB if necessary
  186862. To support RGB backgrounds for gray images we need:
  186863. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  186864. 3 or 6 bytes and composite with background
  186865. "in place" if transparent (3x compare/pixel
  186866. compared to doing composite with gray bkgrnd)
  186867. - Gray + alpha -> convert to RGB + alpha, composite with background and
  186868. remove alpha bytes (3x float operations/pixel
  186869. compared with composite on gray background)
  186870. Greg's change will do this. The reason it wasn't done before is for
  186871. performance, as this increases the per-pixel operations. If we would check
  186872. in advance if the background was gray or RGB, and position the gray-to-RGB
  186873. transform appropriately, then it would save a lot of work/time.
  186874. */
  186875. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186876. /* if gray -> RGB, do so now only if background is non-gray; else do later
  186877. * for performance reasons */
  186878. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186879. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186880. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186881. #endif
  186882. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186883. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186884. ((png_ptr->num_trans != 0 ) ||
  186885. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  186886. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186887. &(png_ptr->trans_values), &(png_ptr->background)
  186888. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186889. , &(png_ptr->background_1),
  186890. png_ptr->gamma_table, png_ptr->gamma_from_1,
  186891. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  186892. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  186893. png_ptr->gamma_shift
  186894. #endif
  186895. );
  186896. #endif
  186897. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186898. if ((png_ptr->transformations & PNG_GAMMA) &&
  186899. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186900. !((png_ptr->transformations & PNG_BACKGROUND) &&
  186901. ((png_ptr->num_trans != 0) ||
  186902. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  186903. #endif
  186904. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  186905. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186906. png_ptr->gamma_table, png_ptr->gamma_16_table,
  186907. png_ptr->gamma_shift);
  186908. #endif
  186909. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186910. if (png_ptr->transformations & PNG_16_TO_8)
  186911. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186912. #endif
  186913. #if defined(PNG_READ_DITHER_SUPPORTED)
  186914. if (png_ptr->transformations & PNG_DITHER)
  186915. {
  186916. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  186917. png_ptr->palette_lookup, png_ptr->dither_index);
  186918. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  186919. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  186920. }
  186921. #endif
  186922. #if defined(PNG_READ_INVERT_SUPPORTED)
  186923. if (png_ptr->transformations & PNG_INVERT_MONO)
  186924. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186925. #endif
  186926. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186927. if (png_ptr->transformations & PNG_SHIFT)
  186928. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186929. &(png_ptr->shift));
  186930. #endif
  186931. #if defined(PNG_READ_PACK_SUPPORTED)
  186932. if (png_ptr->transformations & PNG_PACK)
  186933. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186934. #endif
  186935. #if defined(PNG_READ_BGR_SUPPORTED)
  186936. if (png_ptr->transformations & PNG_BGR)
  186937. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186938. #endif
  186939. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  186940. if (png_ptr->transformations & PNG_PACKSWAP)
  186941. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186942. #endif
  186943. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186944. /* if gray -> RGB, do so now only if we did not do so above */
  186945. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186946. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186947. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186948. #endif
  186949. #if defined(PNG_READ_FILLER_SUPPORTED)
  186950. if (png_ptr->transformations & PNG_FILLER)
  186951. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186952. (png_uint_32)png_ptr->filler, png_ptr->flags);
  186953. #endif
  186954. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186955. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186956. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186957. #endif
  186958. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186959. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  186960. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186961. #endif
  186962. #if defined(PNG_READ_SWAP_SUPPORTED)
  186963. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186964. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186965. #endif
  186966. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186967. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  186968. {
  186969. if(png_ptr->read_user_transform_fn != NULL)
  186970. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  186971. (png_ptr, /* png_ptr */
  186972. &(png_ptr->row_info), /* row_info: */
  186973. /* png_uint_32 width; width of row */
  186974. /* png_uint_32 rowbytes; number of bytes in row */
  186975. /* png_byte color_type; color type of pixels */
  186976. /* png_byte bit_depth; bit depth of samples */
  186977. /* png_byte channels; number of channels (1-4) */
  186978. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  186979. png_ptr->row_buf + 1); /* start of pixel data for row */
  186980. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  186981. if(png_ptr->user_transform_depth)
  186982. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  186983. if(png_ptr->user_transform_channels)
  186984. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  186985. #endif
  186986. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  186987. png_ptr->row_info.channels);
  186988. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186989. png_ptr->row_info.width);
  186990. }
  186991. #endif
  186992. }
  186993. #if defined(PNG_READ_PACK_SUPPORTED)
  186994. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  186995. * without changing the actual values. Thus, if you had a row with
  186996. * a bit depth of 1, you would end up with bytes that only contained
  186997. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  186998. * png_do_shift() after this.
  186999. */
  187000. void /* PRIVATE */
  187001. png_do_unpack(png_row_infop row_info, png_bytep row)
  187002. {
  187003. png_debug(1, "in png_do_unpack\n");
  187004. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187005. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  187006. #else
  187007. if (row_info->bit_depth < 8)
  187008. #endif
  187009. {
  187010. png_uint_32 i;
  187011. png_uint_32 row_width=row_info->width;
  187012. switch (row_info->bit_depth)
  187013. {
  187014. case 1:
  187015. {
  187016. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  187017. png_bytep dp = row + (png_size_t)row_width - 1;
  187018. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  187019. for (i = 0; i < row_width; i++)
  187020. {
  187021. *dp = (png_byte)((*sp >> shift) & 0x01);
  187022. if (shift == 7)
  187023. {
  187024. shift = 0;
  187025. sp--;
  187026. }
  187027. else
  187028. shift++;
  187029. dp--;
  187030. }
  187031. break;
  187032. }
  187033. case 2:
  187034. {
  187035. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  187036. png_bytep dp = row + (png_size_t)row_width - 1;
  187037. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187038. for (i = 0; i < row_width; i++)
  187039. {
  187040. *dp = (png_byte)((*sp >> shift) & 0x03);
  187041. if (shift == 6)
  187042. {
  187043. shift = 0;
  187044. sp--;
  187045. }
  187046. else
  187047. shift += 2;
  187048. dp--;
  187049. }
  187050. break;
  187051. }
  187052. case 4:
  187053. {
  187054. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  187055. png_bytep dp = row + (png_size_t)row_width - 1;
  187056. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187057. for (i = 0; i < row_width; i++)
  187058. {
  187059. *dp = (png_byte)((*sp >> shift) & 0x0f);
  187060. if (shift == 4)
  187061. {
  187062. shift = 0;
  187063. sp--;
  187064. }
  187065. else
  187066. shift = 4;
  187067. dp--;
  187068. }
  187069. break;
  187070. }
  187071. }
  187072. row_info->bit_depth = 8;
  187073. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187074. row_info->rowbytes = row_width * row_info->channels;
  187075. }
  187076. }
  187077. #endif
  187078. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187079. /* Reverse the effects of png_do_shift. This routine merely shifts the
  187080. * pixels back to their significant bits values. Thus, if you have
  187081. * a row of bit depth 8, but only 5 are significant, this will shift
  187082. * the values back to 0 through 31.
  187083. */
  187084. void /* PRIVATE */
  187085. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  187086. {
  187087. png_debug(1, "in png_do_unshift\n");
  187088. if (
  187089. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187090. row != NULL && row_info != NULL && sig_bits != NULL &&
  187091. #endif
  187092. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  187093. {
  187094. int shift[4];
  187095. int channels = 0;
  187096. int c;
  187097. png_uint_16 value = 0;
  187098. png_uint_32 row_width = row_info->width;
  187099. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  187100. {
  187101. shift[channels++] = row_info->bit_depth - sig_bits->red;
  187102. shift[channels++] = row_info->bit_depth - sig_bits->green;
  187103. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  187104. }
  187105. else
  187106. {
  187107. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  187108. }
  187109. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187110. {
  187111. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  187112. }
  187113. for (c = 0; c < channels; c++)
  187114. {
  187115. if (shift[c] <= 0)
  187116. shift[c] = 0;
  187117. else
  187118. value = 1;
  187119. }
  187120. if (!value)
  187121. return;
  187122. switch (row_info->bit_depth)
  187123. {
  187124. case 2:
  187125. {
  187126. png_bytep bp;
  187127. png_uint_32 i;
  187128. png_uint_32 istop = row_info->rowbytes;
  187129. for (bp = row, i = 0; i < istop; i++)
  187130. {
  187131. *bp >>= 1;
  187132. *bp++ &= 0x55;
  187133. }
  187134. break;
  187135. }
  187136. case 4:
  187137. {
  187138. png_bytep bp = row;
  187139. png_uint_32 i;
  187140. png_uint_32 istop = row_info->rowbytes;
  187141. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  187142. (png_byte)((int)0xf >> shift[0]));
  187143. for (i = 0; i < istop; i++)
  187144. {
  187145. *bp >>= shift[0];
  187146. *bp++ &= mask;
  187147. }
  187148. break;
  187149. }
  187150. case 8:
  187151. {
  187152. png_bytep bp = row;
  187153. png_uint_32 i;
  187154. png_uint_32 istop = row_width * channels;
  187155. for (i = 0; i < istop; i++)
  187156. {
  187157. *bp++ >>= shift[i%channels];
  187158. }
  187159. break;
  187160. }
  187161. case 16:
  187162. {
  187163. png_bytep bp = row;
  187164. png_uint_32 i;
  187165. png_uint_32 istop = channels * row_width;
  187166. for (i = 0; i < istop; i++)
  187167. {
  187168. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  187169. value >>= shift[i%channels];
  187170. *bp++ = (png_byte)(value >> 8);
  187171. *bp++ = (png_byte)(value & 0xff);
  187172. }
  187173. break;
  187174. }
  187175. }
  187176. }
  187177. }
  187178. #endif
  187179. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187180. /* chop rows of bit depth 16 down to 8 */
  187181. void /* PRIVATE */
  187182. png_do_chop(png_row_infop row_info, png_bytep row)
  187183. {
  187184. png_debug(1, "in png_do_chop\n");
  187185. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187186. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  187187. #else
  187188. if (row_info->bit_depth == 16)
  187189. #endif
  187190. {
  187191. png_bytep sp = row;
  187192. png_bytep dp = row;
  187193. png_uint_32 i;
  187194. png_uint_32 istop = row_info->width * row_info->channels;
  187195. for (i = 0; i<istop; i++, sp += 2, dp++)
  187196. {
  187197. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  187198. /* This does a more accurate scaling of the 16-bit color
  187199. * value, rather than a simple low-byte truncation.
  187200. *
  187201. * What the ideal calculation should be:
  187202. * *dp = (((((png_uint_32)(*sp) << 8) |
  187203. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  187204. *
  187205. * GRR: no, I think this is what it really should be:
  187206. * *dp = (((((png_uint_32)(*sp) << 8) |
  187207. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  187208. *
  187209. * GRR: here's the exact calculation with shifts:
  187210. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  187211. * *dp = (temp - (temp >> 8)) >> 8;
  187212. *
  187213. * Approximate calculation with shift/add instead of multiply/divide:
  187214. * *dp = ((((png_uint_32)(*sp) << 8) |
  187215. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  187216. *
  187217. * What we actually do to avoid extra shifting and conversion:
  187218. */
  187219. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  187220. #else
  187221. /* Simply discard the low order byte */
  187222. *dp = *sp;
  187223. #endif
  187224. }
  187225. row_info->bit_depth = 8;
  187226. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187227. row_info->rowbytes = row_info->width * row_info->channels;
  187228. }
  187229. }
  187230. #endif
  187231. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187232. void /* PRIVATE */
  187233. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  187234. {
  187235. png_debug(1, "in png_do_read_swap_alpha\n");
  187236. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187237. if (row != NULL && row_info != NULL)
  187238. #endif
  187239. {
  187240. png_uint_32 row_width = row_info->width;
  187241. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187242. {
  187243. /* This converts from RGBA to ARGB */
  187244. if (row_info->bit_depth == 8)
  187245. {
  187246. png_bytep sp = row + row_info->rowbytes;
  187247. png_bytep dp = sp;
  187248. png_byte save;
  187249. png_uint_32 i;
  187250. for (i = 0; i < row_width; i++)
  187251. {
  187252. save = *(--sp);
  187253. *(--dp) = *(--sp);
  187254. *(--dp) = *(--sp);
  187255. *(--dp) = *(--sp);
  187256. *(--dp) = save;
  187257. }
  187258. }
  187259. /* This converts from RRGGBBAA to AARRGGBB */
  187260. else
  187261. {
  187262. png_bytep sp = row + row_info->rowbytes;
  187263. png_bytep dp = sp;
  187264. png_byte save[2];
  187265. png_uint_32 i;
  187266. for (i = 0; i < row_width; i++)
  187267. {
  187268. save[0] = *(--sp);
  187269. save[1] = *(--sp);
  187270. *(--dp) = *(--sp);
  187271. *(--dp) = *(--sp);
  187272. *(--dp) = *(--sp);
  187273. *(--dp) = *(--sp);
  187274. *(--dp) = *(--sp);
  187275. *(--dp) = *(--sp);
  187276. *(--dp) = save[0];
  187277. *(--dp) = save[1];
  187278. }
  187279. }
  187280. }
  187281. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187282. {
  187283. /* This converts from GA to AG */
  187284. if (row_info->bit_depth == 8)
  187285. {
  187286. png_bytep sp = row + row_info->rowbytes;
  187287. png_bytep dp = sp;
  187288. png_byte save;
  187289. png_uint_32 i;
  187290. for (i = 0; i < row_width; i++)
  187291. {
  187292. save = *(--sp);
  187293. *(--dp) = *(--sp);
  187294. *(--dp) = save;
  187295. }
  187296. }
  187297. /* This converts from GGAA to AAGG */
  187298. else
  187299. {
  187300. png_bytep sp = row + row_info->rowbytes;
  187301. png_bytep dp = sp;
  187302. png_byte save[2];
  187303. png_uint_32 i;
  187304. for (i = 0; i < row_width; i++)
  187305. {
  187306. save[0] = *(--sp);
  187307. save[1] = *(--sp);
  187308. *(--dp) = *(--sp);
  187309. *(--dp) = *(--sp);
  187310. *(--dp) = save[0];
  187311. *(--dp) = save[1];
  187312. }
  187313. }
  187314. }
  187315. }
  187316. }
  187317. #endif
  187318. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187319. void /* PRIVATE */
  187320. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  187321. {
  187322. png_debug(1, "in png_do_read_invert_alpha\n");
  187323. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187324. if (row != NULL && row_info != NULL)
  187325. #endif
  187326. {
  187327. png_uint_32 row_width = row_info->width;
  187328. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187329. {
  187330. /* This inverts the alpha channel in RGBA */
  187331. if (row_info->bit_depth == 8)
  187332. {
  187333. png_bytep sp = row + row_info->rowbytes;
  187334. png_bytep dp = sp;
  187335. png_uint_32 i;
  187336. for (i = 0; i < row_width; i++)
  187337. {
  187338. *(--dp) = (png_byte)(255 - *(--sp));
  187339. /* This does nothing:
  187340. *(--dp) = *(--sp);
  187341. *(--dp) = *(--sp);
  187342. *(--dp) = *(--sp);
  187343. We can replace it with:
  187344. */
  187345. sp-=3;
  187346. dp=sp;
  187347. }
  187348. }
  187349. /* This inverts the alpha channel in RRGGBBAA */
  187350. else
  187351. {
  187352. png_bytep sp = row + row_info->rowbytes;
  187353. png_bytep dp = sp;
  187354. png_uint_32 i;
  187355. for (i = 0; i < row_width; i++)
  187356. {
  187357. *(--dp) = (png_byte)(255 - *(--sp));
  187358. *(--dp) = (png_byte)(255 - *(--sp));
  187359. /* This does nothing:
  187360. *(--dp) = *(--sp);
  187361. *(--dp) = *(--sp);
  187362. *(--dp) = *(--sp);
  187363. *(--dp) = *(--sp);
  187364. *(--dp) = *(--sp);
  187365. *(--dp) = *(--sp);
  187366. We can replace it with:
  187367. */
  187368. sp-=6;
  187369. dp=sp;
  187370. }
  187371. }
  187372. }
  187373. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187374. {
  187375. /* This inverts the alpha channel in GA */
  187376. if (row_info->bit_depth == 8)
  187377. {
  187378. png_bytep sp = row + row_info->rowbytes;
  187379. png_bytep dp = sp;
  187380. png_uint_32 i;
  187381. for (i = 0; i < row_width; i++)
  187382. {
  187383. *(--dp) = (png_byte)(255 - *(--sp));
  187384. *(--dp) = *(--sp);
  187385. }
  187386. }
  187387. /* This inverts the alpha channel in GGAA */
  187388. else
  187389. {
  187390. png_bytep sp = row + row_info->rowbytes;
  187391. png_bytep dp = sp;
  187392. png_uint_32 i;
  187393. for (i = 0; i < row_width; i++)
  187394. {
  187395. *(--dp) = (png_byte)(255 - *(--sp));
  187396. *(--dp) = (png_byte)(255 - *(--sp));
  187397. /*
  187398. *(--dp) = *(--sp);
  187399. *(--dp) = *(--sp);
  187400. */
  187401. sp-=2;
  187402. dp=sp;
  187403. }
  187404. }
  187405. }
  187406. }
  187407. }
  187408. #endif
  187409. #if defined(PNG_READ_FILLER_SUPPORTED)
  187410. /* Add filler channel if we have RGB color */
  187411. void /* PRIVATE */
  187412. png_do_read_filler(png_row_infop row_info, png_bytep row,
  187413. png_uint_32 filler, png_uint_32 flags)
  187414. {
  187415. png_uint_32 i;
  187416. png_uint_32 row_width = row_info->width;
  187417. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  187418. png_byte lo_filler = (png_byte)(filler & 0xff);
  187419. png_debug(1, "in png_do_read_filler\n");
  187420. if (
  187421. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187422. row != NULL && row_info != NULL &&
  187423. #endif
  187424. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187425. {
  187426. if(row_info->bit_depth == 8)
  187427. {
  187428. /* This changes the data from G to GX */
  187429. if (flags & PNG_FLAG_FILLER_AFTER)
  187430. {
  187431. png_bytep sp = row + (png_size_t)row_width;
  187432. png_bytep dp = sp + (png_size_t)row_width;
  187433. for (i = 1; i < row_width; i++)
  187434. {
  187435. *(--dp) = lo_filler;
  187436. *(--dp) = *(--sp);
  187437. }
  187438. *(--dp) = lo_filler;
  187439. row_info->channels = 2;
  187440. row_info->pixel_depth = 16;
  187441. row_info->rowbytes = row_width * 2;
  187442. }
  187443. /* This changes the data from G to XG */
  187444. else
  187445. {
  187446. png_bytep sp = row + (png_size_t)row_width;
  187447. png_bytep dp = sp + (png_size_t)row_width;
  187448. for (i = 0; i < row_width; i++)
  187449. {
  187450. *(--dp) = *(--sp);
  187451. *(--dp) = lo_filler;
  187452. }
  187453. row_info->channels = 2;
  187454. row_info->pixel_depth = 16;
  187455. row_info->rowbytes = row_width * 2;
  187456. }
  187457. }
  187458. else if(row_info->bit_depth == 16)
  187459. {
  187460. /* This changes the data from GG to GGXX */
  187461. if (flags & PNG_FLAG_FILLER_AFTER)
  187462. {
  187463. png_bytep sp = row + (png_size_t)row_width * 2;
  187464. png_bytep dp = sp + (png_size_t)row_width * 2;
  187465. for (i = 1; i < row_width; i++)
  187466. {
  187467. *(--dp) = hi_filler;
  187468. *(--dp) = lo_filler;
  187469. *(--dp) = *(--sp);
  187470. *(--dp) = *(--sp);
  187471. }
  187472. *(--dp) = hi_filler;
  187473. *(--dp) = lo_filler;
  187474. row_info->channels = 2;
  187475. row_info->pixel_depth = 32;
  187476. row_info->rowbytes = row_width * 4;
  187477. }
  187478. /* This changes the data from GG to XXGG */
  187479. else
  187480. {
  187481. png_bytep sp = row + (png_size_t)row_width * 2;
  187482. png_bytep dp = sp + (png_size_t)row_width * 2;
  187483. for (i = 0; i < row_width; i++)
  187484. {
  187485. *(--dp) = *(--sp);
  187486. *(--dp) = *(--sp);
  187487. *(--dp) = hi_filler;
  187488. *(--dp) = lo_filler;
  187489. }
  187490. row_info->channels = 2;
  187491. row_info->pixel_depth = 32;
  187492. row_info->rowbytes = row_width * 4;
  187493. }
  187494. }
  187495. } /* COLOR_TYPE == GRAY */
  187496. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187497. {
  187498. if(row_info->bit_depth == 8)
  187499. {
  187500. /* This changes the data from RGB to RGBX */
  187501. if (flags & PNG_FLAG_FILLER_AFTER)
  187502. {
  187503. png_bytep sp = row + (png_size_t)row_width * 3;
  187504. png_bytep dp = sp + (png_size_t)row_width;
  187505. for (i = 1; i < row_width; i++)
  187506. {
  187507. *(--dp) = lo_filler;
  187508. *(--dp) = *(--sp);
  187509. *(--dp) = *(--sp);
  187510. *(--dp) = *(--sp);
  187511. }
  187512. *(--dp) = lo_filler;
  187513. row_info->channels = 4;
  187514. row_info->pixel_depth = 32;
  187515. row_info->rowbytes = row_width * 4;
  187516. }
  187517. /* This changes the data from RGB to XRGB */
  187518. else
  187519. {
  187520. png_bytep sp = row + (png_size_t)row_width * 3;
  187521. png_bytep dp = sp + (png_size_t)row_width;
  187522. for (i = 0; i < row_width; i++)
  187523. {
  187524. *(--dp) = *(--sp);
  187525. *(--dp) = *(--sp);
  187526. *(--dp) = *(--sp);
  187527. *(--dp) = lo_filler;
  187528. }
  187529. row_info->channels = 4;
  187530. row_info->pixel_depth = 32;
  187531. row_info->rowbytes = row_width * 4;
  187532. }
  187533. }
  187534. else if(row_info->bit_depth == 16)
  187535. {
  187536. /* This changes the data from RRGGBB to RRGGBBXX */
  187537. if (flags & PNG_FLAG_FILLER_AFTER)
  187538. {
  187539. png_bytep sp = row + (png_size_t)row_width * 6;
  187540. png_bytep dp = sp + (png_size_t)row_width * 2;
  187541. for (i = 1; i < row_width; i++)
  187542. {
  187543. *(--dp) = hi_filler;
  187544. *(--dp) = lo_filler;
  187545. *(--dp) = *(--sp);
  187546. *(--dp) = *(--sp);
  187547. *(--dp) = *(--sp);
  187548. *(--dp) = *(--sp);
  187549. *(--dp) = *(--sp);
  187550. *(--dp) = *(--sp);
  187551. }
  187552. *(--dp) = hi_filler;
  187553. *(--dp) = lo_filler;
  187554. row_info->channels = 4;
  187555. row_info->pixel_depth = 64;
  187556. row_info->rowbytes = row_width * 8;
  187557. }
  187558. /* This changes the data from RRGGBB to XXRRGGBB */
  187559. else
  187560. {
  187561. png_bytep sp = row + (png_size_t)row_width * 6;
  187562. png_bytep dp = sp + (png_size_t)row_width * 2;
  187563. for (i = 0; i < row_width; i++)
  187564. {
  187565. *(--dp) = *(--sp);
  187566. *(--dp) = *(--sp);
  187567. *(--dp) = *(--sp);
  187568. *(--dp) = *(--sp);
  187569. *(--dp) = *(--sp);
  187570. *(--dp) = *(--sp);
  187571. *(--dp) = hi_filler;
  187572. *(--dp) = lo_filler;
  187573. }
  187574. row_info->channels = 4;
  187575. row_info->pixel_depth = 64;
  187576. row_info->rowbytes = row_width * 8;
  187577. }
  187578. }
  187579. } /* COLOR_TYPE == RGB */
  187580. }
  187581. #endif
  187582. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187583. /* expand grayscale files to RGB, with or without alpha */
  187584. void /* PRIVATE */
  187585. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  187586. {
  187587. png_uint_32 i;
  187588. png_uint_32 row_width = row_info->width;
  187589. png_debug(1, "in png_do_gray_to_rgb\n");
  187590. if (row_info->bit_depth >= 8 &&
  187591. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187592. row != NULL && row_info != NULL &&
  187593. #endif
  187594. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  187595. {
  187596. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187597. {
  187598. if (row_info->bit_depth == 8)
  187599. {
  187600. png_bytep sp = row + (png_size_t)row_width - 1;
  187601. png_bytep dp = sp + (png_size_t)row_width * 2;
  187602. for (i = 0; i < row_width; i++)
  187603. {
  187604. *(dp--) = *sp;
  187605. *(dp--) = *sp;
  187606. *(dp--) = *(sp--);
  187607. }
  187608. }
  187609. else
  187610. {
  187611. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187612. png_bytep dp = sp + (png_size_t)row_width * 4;
  187613. for (i = 0; i < row_width; i++)
  187614. {
  187615. *(dp--) = *sp;
  187616. *(dp--) = *(sp - 1);
  187617. *(dp--) = *sp;
  187618. *(dp--) = *(sp - 1);
  187619. *(dp--) = *(sp--);
  187620. *(dp--) = *(sp--);
  187621. }
  187622. }
  187623. }
  187624. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187625. {
  187626. if (row_info->bit_depth == 8)
  187627. {
  187628. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187629. png_bytep dp = sp + (png_size_t)row_width * 2;
  187630. for (i = 0; i < row_width; i++)
  187631. {
  187632. *(dp--) = *(sp--);
  187633. *(dp--) = *sp;
  187634. *(dp--) = *sp;
  187635. *(dp--) = *(sp--);
  187636. }
  187637. }
  187638. else
  187639. {
  187640. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  187641. png_bytep dp = sp + (png_size_t)row_width * 4;
  187642. for (i = 0; i < row_width; i++)
  187643. {
  187644. *(dp--) = *(sp--);
  187645. *(dp--) = *(sp--);
  187646. *(dp--) = *sp;
  187647. *(dp--) = *(sp - 1);
  187648. *(dp--) = *sp;
  187649. *(dp--) = *(sp - 1);
  187650. *(dp--) = *(sp--);
  187651. *(dp--) = *(sp--);
  187652. }
  187653. }
  187654. }
  187655. row_info->channels += (png_byte)2;
  187656. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  187657. row_info->pixel_depth = (png_byte)(row_info->channels *
  187658. row_info->bit_depth);
  187659. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187660. }
  187661. }
  187662. #endif
  187663. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187664. /* reduce RGB files to grayscale, with or without alpha
  187665. * using the equation given in Poynton's ColorFAQ at
  187666. * <http://www.inforamp.net/~poynton/>
  187667. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  187668. *
  187669. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  187670. *
  187671. * We approximate this with
  187672. *
  187673. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  187674. *
  187675. * which can be expressed with integers as
  187676. *
  187677. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  187678. *
  187679. * The calculation is to be done in a linear colorspace.
  187680. *
  187681. * Other integer coefficents can be used via png_set_rgb_to_gray().
  187682. */
  187683. int /* PRIVATE */
  187684. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  187685. {
  187686. png_uint_32 i;
  187687. png_uint_32 row_width = row_info->width;
  187688. int rgb_error = 0;
  187689. png_debug(1, "in png_do_rgb_to_gray\n");
  187690. if (
  187691. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187692. row != NULL && row_info != NULL &&
  187693. #endif
  187694. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187695. {
  187696. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  187697. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  187698. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  187699. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187700. {
  187701. if (row_info->bit_depth == 8)
  187702. {
  187703. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187704. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187705. {
  187706. png_bytep sp = row;
  187707. png_bytep dp = row;
  187708. for (i = 0; i < row_width; i++)
  187709. {
  187710. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187711. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187712. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187713. if(red != green || red != blue)
  187714. {
  187715. rgb_error |= 1;
  187716. *(dp++) = png_ptr->gamma_from_1[
  187717. (rc*red+gc*green+bc*blue)>>15];
  187718. }
  187719. else
  187720. *(dp++) = *(sp-1);
  187721. }
  187722. }
  187723. else
  187724. #endif
  187725. {
  187726. png_bytep sp = row;
  187727. png_bytep dp = row;
  187728. for (i = 0; i < row_width; i++)
  187729. {
  187730. png_byte red = *(sp++);
  187731. png_byte green = *(sp++);
  187732. png_byte blue = *(sp++);
  187733. if(red != green || red != blue)
  187734. {
  187735. rgb_error |= 1;
  187736. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  187737. }
  187738. else
  187739. *(dp++) = *(sp-1);
  187740. }
  187741. }
  187742. }
  187743. else /* RGB bit_depth == 16 */
  187744. {
  187745. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187746. if (png_ptr->gamma_16_to_1 != NULL &&
  187747. png_ptr->gamma_16_from_1 != NULL)
  187748. {
  187749. png_bytep sp = row;
  187750. png_bytep dp = row;
  187751. for (i = 0; i < row_width; i++)
  187752. {
  187753. png_uint_16 red, green, blue, w;
  187754. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187755. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187756. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187757. if(red == green && red == blue)
  187758. w = red;
  187759. else
  187760. {
  187761. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187762. png_ptr->gamma_shift][red>>8];
  187763. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187764. png_ptr->gamma_shift][green>>8];
  187765. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187766. png_ptr->gamma_shift][blue>>8];
  187767. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  187768. + bc*blue_1)>>15);
  187769. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187770. png_ptr->gamma_shift][gray16 >> 8];
  187771. rgb_error |= 1;
  187772. }
  187773. *(dp++) = (png_byte)((w>>8) & 0xff);
  187774. *(dp++) = (png_byte)(w & 0xff);
  187775. }
  187776. }
  187777. else
  187778. #endif
  187779. {
  187780. png_bytep sp = row;
  187781. png_bytep dp = row;
  187782. for (i = 0; i < row_width; i++)
  187783. {
  187784. png_uint_16 red, green, blue, gray16;
  187785. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187786. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187787. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187788. if(red != green || red != blue)
  187789. rgb_error |= 1;
  187790. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187791. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187792. *(dp++) = (png_byte)(gray16 & 0xff);
  187793. }
  187794. }
  187795. }
  187796. }
  187797. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187798. {
  187799. if (row_info->bit_depth == 8)
  187800. {
  187801. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187802. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187803. {
  187804. png_bytep sp = row;
  187805. png_bytep dp = row;
  187806. for (i = 0; i < row_width; i++)
  187807. {
  187808. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187809. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187810. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187811. if(red != green || red != blue)
  187812. rgb_error |= 1;
  187813. *(dp++) = png_ptr->gamma_from_1
  187814. [(rc*red + gc*green + bc*blue)>>15];
  187815. *(dp++) = *(sp++); /* alpha */
  187816. }
  187817. }
  187818. else
  187819. #endif
  187820. {
  187821. png_bytep sp = row;
  187822. png_bytep dp = row;
  187823. for (i = 0; i < row_width; i++)
  187824. {
  187825. png_byte red = *(sp++);
  187826. png_byte green = *(sp++);
  187827. png_byte blue = *(sp++);
  187828. if(red != green || red != blue)
  187829. rgb_error |= 1;
  187830. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  187831. *(dp++) = *(sp++); /* alpha */
  187832. }
  187833. }
  187834. }
  187835. else /* RGBA bit_depth == 16 */
  187836. {
  187837. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187838. if (png_ptr->gamma_16_to_1 != NULL &&
  187839. png_ptr->gamma_16_from_1 != NULL)
  187840. {
  187841. png_bytep sp = row;
  187842. png_bytep dp = row;
  187843. for (i = 0; i < row_width; i++)
  187844. {
  187845. png_uint_16 red, green, blue, w;
  187846. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187847. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187848. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187849. if(red == green && red == blue)
  187850. w = red;
  187851. else
  187852. {
  187853. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187854. png_ptr->gamma_shift][red>>8];
  187855. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187856. png_ptr->gamma_shift][green>>8];
  187857. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187858. png_ptr->gamma_shift][blue>>8];
  187859. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  187860. + gc * green_1 + bc * blue_1)>>15);
  187861. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187862. png_ptr->gamma_shift][gray16 >> 8];
  187863. rgb_error |= 1;
  187864. }
  187865. *(dp++) = (png_byte)((w>>8) & 0xff);
  187866. *(dp++) = (png_byte)(w & 0xff);
  187867. *(dp++) = *(sp++); /* alpha */
  187868. *(dp++) = *(sp++);
  187869. }
  187870. }
  187871. else
  187872. #endif
  187873. {
  187874. png_bytep sp = row;
  187875. png_bytep dp = row;
  187876. for (i = 0; i < row_width; i++)
  187877. {
  187878. png_uint_16 red, green, blue, gray16;
  187879. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187880. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187881. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187882. if(red != green || red != blue)
  187883. rgb_error |= 1;
  187884. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187885. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187886. *(dp++) = (png_byte)(gray16 & 0xff);
  187887. *(dp++) = *(sp++); /* alpha */
  187888. *(dp++) = *(sp++);
  187889. }
  187890. }
  187891. }
  187892. }
  187893. row_info->channels -= (png_byte)2;
  187894. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  187895. row_info->pixel_depth = (png_byte)(row_info->channels *
  187896. row_info->bit_depth);
  187897. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187898. }
  187899. return rgb_error;
  187900. }
  187901. #endif
  187902. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  187903. * large of png_color. This lets grayscale images be treated as
  187904. * paletted. Most useful for gamma correction and simplification
  187905. * of code.
  187906. */
  187907. void PNGAPI
  187908. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  187909. {
  187910. int num_palette;
  187911. int color_inc;
  187912. int i;
  187913. int v;
  187914. png_debug(1, "in png_do_build_grayscale_palette\n");
  187915. if (palette == NULL)
  187916. return;
  187917. switch (bit_depth)
  187918. {
  187919. case 1:
  187920. num_palette = 2;
  187921. color_inc = 0xff;
  187922. break;
  187923. case 2:
  187924. num_palette = 4;
  187925. color_inc = 0x55;
  187926. break;
  187927. case 4:
  187928. num_palette = 16;
  187929. color_inc = 0x11;
  187930. break;
  187931. case 8:
  187932. num_palette = 256;
  187933. color_inc = 1;
  187934. break;
  187935. default:
  187936. num_palette = 0;
  187937. color_inc = 0;
  187938. break;
  187939. }
  187940. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  187941. {
  187942. palette[i].red = (png_byte)v;
  187943. palette[i].green = (png_byte)v;
  187944. palette[i].blue = (png_byte)v;
  187945. }
  187946. }
  187947. /* This function is currently unused. Do we really need it? */
  187948. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  187949. void /* PRIVATE */
  187950. png_correct_palette(png_structp png_ptr, png_colorp palette,
  187951. int num_palette)
  187952. {
  187953. png_debug(1, "in png_correct_palette\n");
  187954. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187955. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187956. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  187957. {
  187958. png_color back, back_1;
  187959. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187960. {
  187961. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187962. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187963. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187964. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187965. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187966. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187967. }
  187968. else
  187969. {
  187970. double g;
  187971. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  187972. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  187973. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  187974. {
  187975. back.red = png_ptr->background.red;
  187976. back.green = png_ptr->background.green;
  187977. back.blue = png_ptr->background.blue;
  187978. }
  187979. else
  187980. {
  187981. back.red =
  187982. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187983. 255.0 + 0.5);
  187984. back.green =
  187985. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187986. 255.0 + 0.5);
  187987. back.blue =
  187988. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187989. 255.0 + 0.5);
  187990. }
  187991. g = 1.0 / png_ptr->background_gamma;
  187992. back_1.red =
  187993. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187994. 255.0 + 0.5);
  187995. back_1.green =
  187996. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187997. 255.0 + 0.5);
  187998. back_1.blue =
  187999. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188000. 255.0 + 0.5);
  188001. }
  188002. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188003. {
  188004. png_uint_32 i;
  188005. for (i = 0; i < (png_uint_32)num_palette; i++)
  188006. {
  188007. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  188008. {
  188009. palette[i] = back;
  188010. }
  188011. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  188012. {
  188013. png_byte v, w;
  188014. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  188015. png_composite(w, v, png_ptr->trans[i], back_1.red);
  188016. palette[i].red = png_ptr->gamma_from_1[w];
  188017. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  188018. png_composite(w, v, png_ptr->trans[i], back_1.green);
  188019. palette[i].green = png_ptr->gamma_from_1[w];
  188020. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  188021. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  188022. palette[i].blue = png_ptr->gamma_from_1[w];
  188023. }
  188024. else
  188025. {
  188026. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188027. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188028. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188029. }
  188030. }
  188031. }
  188032. else
  188033. {
  188034. int i;
  188035. for (i = 0; i < num_palette; i++)
  188036. {
  188037. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  188038. {
  188039. palette[i] = back;
  188040. }
  188041. else
  188042. {
  188043. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188044. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188045. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188046. }
  188047. }
  188048. }
  188049. }
  188050. else
  188051. #endif
  188052. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188053. if (png_ptr->transformations & PNG_GAMMA)
  188054. {
  188055. int i;
  188056. for (i = 0; i < num_palette; i++)
  188057. {
  188058. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188059. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188060. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188061. }
  188062. }
  188063. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188064. else
  188065. #endif
  188066. #endif
  188067. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188068. if (png_ptr->transformations & PNG_BACKGROUND)
  188069. {
  188070. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188071. {
  188072. png_color back;
  188073. back.red = (png_byte)png_ptr->background.red;
  188074. back.green = (png_byte)png_ptr->background.green;
  188075. back.blue = (png_byte)png_ptr->background.blue;
  188076. for (i = 0; i < (int)png_ptr->num_trans; i++)
  188077. {
  188078. if (png_ptr->trans[i] == 0)
  188079. {
  188080. palette[i].red = back.red;
  188081. palette[i].green = back.green;
  188082. palette[i].blue = back.blue;
  188083. }
  188084. else if (png_ptr->trans[i] != 0xff)
  188085. {
  188086. png_composite(palette[i].red, png_ptr->palette[i].red,
  188087. png_ptr->trans[i], back.red);
  188088. png_composite(palette[i].green, png_ptr->palette[i].green,
  188089. png_ptr->trans[i], back.green);
  188090. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  188091. png_ptr->trans[i], back.blue);
  188092. }
  188093. }
  188094. }
  188095. else /* assume grayscale palette (what else could it be?) */
  188096. {
  188097. int i;
  188098. for (i = 0; i < num_palette; i++)
  188099. {
  188100. if (i == (png_byte)png_ptr->trans_values.gray)
  188101. {
  188102. palette[i].red = (png_byte)png_ptr->background.red;
  188103. palette[i].green = (png_byte)png_ptr->background.green;
  188104. palette[i].blue = (png_byte)png_ptr->background.blue;
  188105. }
  188106. }
  188107. }
  188108. }
  188109. #endif
  188110. }
  188111. #endif
  188112. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188113. /* Replace any alpha or transparency with the supplied background color.
  188114. * "background" is already in the screen gamma, while "background_1" is
  188115. * at a gamma of 1.0. Paletted files have already been taken care of.
  188116. */
  188117. void /* PRIVATE */
  188118. png_do_background(png_row_infop row_info, png_bytep row,
  188119. png_color_16p trans_values, png_color_16p background
  188120. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188121. , png_color_16p background_1,
  188122. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  188123. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  188124. png_uint_16pp gamma_16_to_1, int gamma_shift
  188125. #endif
  188126. )
  188127. {
  188128. png_bytep sp, dp;
  188129. png_uint_32 i;
  188130. png_uint_32 row_width=row_info->width;
  188131. int shift;
  188132. png_debug(1, "in png_do_background\n");
  188133. if (background != NULL &&
  188134. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188135. row != NULL && row_info != NULL &&
  188136. #endif
  188137. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  188138. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  188139. {
  188140. switch (row_info->color_type)
  188141. {
  188142. case PNG_COLOR_TYPE_GRAY:
  188143. {
  188144. switch (row_info->bit_depth)
  188145. {
  188146. case 1:
  188147. {
  188148. sp = row;
  188149. shift = 7;
  188150. for (i = 0; i < row_width; i++)
  188151. {
  188152. if ((png_uint_16)((*sp >> shift) & 0x01)
  188153. == trans_values->gray)
  188154. {
  188155. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  188156. *sp |= (png_byte)(background->gray << shift);
  188157. }
  188158. if (!shift)
  188159. {
  188160. shift = 7;
  188161. sp++;
  188162. }
  188163. else
  188164. shift--;
  188165. }
  188166. break;
  188167. }
  188168. case 2:
  188169. {
  188170. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188171. if (gamma_table != NULL)
  188172. {
  188173. sp = row;
  188174. shift = 6;
  188175. for (i = 0; i < row_width; i++)
  188176. {
  188177. if ((png_uint_16)((*sp >> shift) & 0x03)
  188178. == trans_values->gray)
  188179. {
  188180. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188181. *sp |= (png_byte)(background->gray << shift);
  188182. }
  188183. else
  188184. {
  188185. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  188186. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  188187. (p << 4) | (p << 6)] >> 6) & 0x03);
  188188. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188189. *sp |= (png_byte)(g << shift);
  188190. }
  188191. if (!shift)
  188192. {
  188193. shift = 6;
  188194. sp++;
  188195. }
  188196. else
  188197. shift -= 2;
  188198. }
  188199. }
  188200. else
  188201. #endif
  188202. {
  188203. sp = row;
  188204. shift = 6;
  188205. for (i = 0; i < row_width; i++)
  188206. {
  188207. if ((png_uint_16)((*sp >> shift) & 0x03)
  188208. == trans_values->gray)
  188209. {
  188210. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188211. *sp |= (png_byte)(background->gray << shift);
  188212. }
  188213. if (!shift)
  188214. {
  188215. shift = 6;
  188216. sp++;
  188217. }
  188218. else
  188219. shift -= 2;
  188220. }
  188221. }
  188222. break;
  188223. }
  188224. case 4:
  188225. {
  188226. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188227. if (gamma_table != NULL)
  188228. {
  188229. sp = row;
  188230. shift = 4;
  188231. for (i = 0; i < row_width; i++)
  188232. {
  188233. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188234. == trans_values->gray)
  188235. {
  188236. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188237. *sp |= (png_byte)(background->gray << shift);
  188238. }
  188239. else
  188240. {
  188241. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  188242. png_byte g = (png_byte)((gamma_table[p |
  188243. (p << 4)] >> 4) & 0x0f);
  188244. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188245. *sp |= (png_byte)(g << shift);
  188246. }
  188247. if (!shift)
  188248. {
  188249. shift = 4;
  188250. sp++;
  188251. }
  188252. else
  188253. shift -= 4;
  188254. }
  188255. }
  188256. else
  188257. #endif
  188258. {
  188259. sp = row;
  188260. shift = 4;
  188261. for (i = 0; i < row_width; i++)
  188262. {
  188263. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188264. == trans_values->gray)
  188265. {
  188266. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188267. *sp |= (png_byte)(background->gray << shift);
  188268. }
  188269. if (!shift)
  188270. {
  188271. shift = 4;
  188272. sp++;
  188273. }
  188274. else
  188275. shift -= 4;
  188276. }
  188277. }
  188278. break;
  188279. }
  188280. case 8:
  188281. {
  188282. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188283. if (gamma_table != NULL)
  188284. {
  188285. sp = row;
  188286. for (i = 0; i < row_width; i++, sp++)
  188287. {
  188288. if (*sp == trans_values->gray)
  188289. {
  188290. *sp = (png_byte)background->gray;
  188291. }
  188292. else
  188293. {
  188294. *sp = gamma_table[*sp];
  188295. }
  188296. }
  188297. }
  188298. else
  188299. #endif
  188300. {
  188301. sp = row;
  188302. for (i = 0; i < row_width; i++, sp++)
  188303. {
  188304. if (*sp == trans_values->gray)
  188305. {
  188306. *sp = (png_byte)background->gray;
  188307. }
  188308. }
  188309. }
  188310. break;
  188311. }
  188312. case 16:
  188313. {
  188314. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188315. if (gamma_16 != NULL)
  188316. {
  188317. sp = row;
  188318. for (i = 0; i < row_width; i++, sp += 2)
  188319. {
  188320. png_uint_16 v;
  188321. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188322. if (v == trans_values->gray)
  188323. {
  188324. /* background is already in screen gamma */
  188325. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188326. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188327. }
  188328. else
  188329. {
  188330. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188331. *sp = (png_byte)((v >> 8) & 0xff);
  188332. *(sp + 1) = (png_byte)(v & 0xff);
  188333. }
  188334. }
  188335. }
  188336. else
  188337. #endif
  188338. {
  188339. sp = row;
  188340. for (i = 0; i < row_width; i++, sp += 2)
  188341. {
  188342. png_uint_16 v;
  188343. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188344. if (v == trans_values->gray)
  188345. {
  188346. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188347. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188348. }
  188349. }
  188350. }
  188351. break;
  188352. }
  188353. }
  188354. break;
  188355. }
  188356. case PNG_COLOR_TYPE_RGB:
  188357. {
  188358. if (row_info->bit_depth == 8)
  188359. {
  188360. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188361. if (gamma_table != NULL)
  188362. {
  188363. sp = row;
  188364. for (i = 0; i < row_width; i++, sp += 3)
  188365. {
  188366. if (*sp == trans_values->red &&
  188367. *(sp + 1) == trans_values->green &&
  188368. *(sp + 2) == trans_values->blue)
  188369. {
  188370. *sp = (png_byte)background->red;
  188371. *(sp + 1) = (png_byte)background->green;
  188372. *(sp + 2) = (png_byte)background->blue;
  188373. }
  188374. else
  188375. {
  188376. *sp = gamma_table[*sp];
  188377. *(sp + 1) = gamma_table[*(sp + 1)];
  188378. *(sp + 2) = gamma_table[*(sp + 2)];
  188379. }
  188380. }
  188381. }
  188382. else
  188383. #endif
  188384. {
  188385. sp = row;
  188386. for (i = 0; i < row_width; i++, sp += 3)
  188387. {
  188388. if (*sp == trans_values->red &&
  188389. *(sp + 1) == trans_values->green &&
  188390. *(sp + 2) == trans_values->blue)
  188391. {
  188392. *sp = (png_byte)background->red;
  188393. *(sp + 1) = (png_byte)background->green;
  188394. *(sp + 2) = (png_byte)background->blue;
  188395. }
  188396. }
  188397. }
  188398. }
  188399. else /* if (row_info->bit_depth == 16) */
  188400. {
  188401. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188402. if (gamma_16 != NULL)
  188403. {
  188404. sp = row;
  188405. for (i = 0; i < row_width; i++, sp += 6)
  188406. {
  188407. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188408. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188409. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188410. if (r == trans_values->red && g == trans_values->green &&
  188411. b == trans_values->blue)
  188412. {
  188413. /* background is already in screen gamma */
  188414. *sp = (png_byte)((background->red >> 8) & 0xff);
  188415. *(sp + 1) = (png_byte)(background->red & 0xff);
  188416. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188417. *(sp + 3) = (png_byte)(background->green & 0xff);
  188418. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188419. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188420. }
  188421. else
  188422. {
  188423. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188424. *sp = (png_byte)((v >> 8) & 0xff);
  188425. *(sp + 1) = (png_byte)(v & 0xff);
  188426. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188427. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  188428. *(sp + 3) = (png_byte)(v & 0xff);
  188429. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188430. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  188431. *(sp + 5) = (png_byte)(v & 0xff);
  188432. }
  188433. }
  188434. }
  188435. else
  188436. #endif
  188437. {
  188438. sp = row;
  188439. for (i = 0; i < row_width; i++, sp += 6)
  188440. {
  188441. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  188442. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188443. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188444. if (r == trans_values->red && g == trans_values->green &&
  188445. b == trans_values->blue)
  188446. {
  188447. *sp = (png_byte)((background->red >> 8) & 0xff);
  188448. *(sp + 1) = (png_byte)(background->red & 0xff);
  188449. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188450. *(sp + 3) = (png_byte)(background->green & 0xff);
  188451. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188452. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188453. }
  188454. }
  188455. }
  188456. }
  188457. break;
  188458. }
  188459. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188460. {
  188461. if (row_info->bit_depth == 8)
  188462. {
  188463. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188464. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188465. gamma_table != NULL)
  188466. {
  188467. sp = row;
  188468. dp = row;
  188469. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188470. {
  188471. png_uint_16 a = *(sp + 1);
  188472. if (a == 0xff)
  188473. {
  188474. *dp = gamma_table[*sp];
  188475. }
  188476. else if (a == 0)
  188477. {
  188478. /* background is already in screen gamma */
  188479. *dp = (png_byte)background->gray;
  188480. }
  188481. else
  188482. {
  188483. png_byte v, w;
  188484. v = gamma_to_1[*sp];
  188485. png_composite(w, v, a, background_1->gray);
  188486. *dp = gamma_from_1[w];
  188487. }
  188488. }
  188489. }
  188490. else
  188491. #endif
  188492. {
  188493. sp = row;
  188494. dp = row;
  188495. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188496. {
  188497. png_byte a = *(sp + 1);
  188498. if (a == 0xff)
  188499. {
  188500. *dp = *sp;
  188501. }
  188502. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188503. else if (a == 0)
  188504. {
  188505. *dp = (png_byte)background->gray;
  188506. }
  188507. else
  188508. {
  188509. png_composite(*dp, *sp, a, background_1->gray);
  188510. }
  188511. #else
  188512. *dp = (png_byte)background->gray;
  188513. #endif
  188514. }
  188515. }
  188516. }
  188517. else /* if (png_ptr->bit_depth == 16) */
  188518. {
  188519. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188520. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188521. gamma_16_to_1 != NULL)
  188522. {
  188523. sp = row;
  188524. dp = row;
  188525. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188526. {
  188527. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188528. if (a == (png_uint_16)0xffff)
  188529. {
  188530. png_uint_16 v;
  188531. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188532. *dp = (png_byte)((v >> 8) & 0xff);
  188533. *(dp + 1) = (png_byte)(v & 0xff);
  188534. }
  188535. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188536. else if (a == 0)
  188537. #else
  188538. else
  188539. #endif
  188540. {
  188541. /* background is already in screen gamma */
  188542. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188543. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188544. }
  188545. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188546. else
  188547. {
  188548. png_uint_16 g, v, w;
  188549. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188550. png_composite_16(v, g, a, background_1->gray);
  188551. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  188552. *dp = (png_byte)((w >> 8) & 0xff);
  188553. *(dp + 1) = (png_byte)(w & 0xff);
  188554. }
  188555. #endif
  188556. }
  188557. }
  188558. else
  188559. #endif
  188560. {
  188561. sp = row;
  188562. dp = row;
  188563. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188564. {
  188565. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188566. if (a == (png_uint_16)0xffff)
  188567. {
  188568. png_memcpy(dp, sp, 2);
  188569. }
  188570. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188571. else if (a == 0)
  188572. #else
  188573. else
  188574. #endif
  188575. {
  188576. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188577. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188578. }
  188579. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188580. else
  188581. {
  188582. png_uint_16 g, v;
  188583. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188584. png_composite_16(v, g, a, background_1->gray);
  188585. *dp = (png_byte)((v >> 8) & 0xff);
  188586. *(dp + 1) = (png_byte)(v & 0xff);
  188587. }
  188588. #endif
  188589. }
  188590. }
  188591. }
  188592. break;
  188593. }
  188594. case PNG_COLOR_TYPE_RGB_ALPHA:
  188595. {
  188596. if (row_info->bit_depth == 8)
  188597. {
  188598. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188599. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188600. gamma_table != NULL)
  188601. {
  188602. sp = row;
  188603. dp = row;
  188604. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188605. {
  188606. png_byte a = *(sp + 3);
  188607. if (a == 0xff)
  188608. {
  188609. *dp = gamma_table[*sp];
  188610. *(dp + 1) = gamma_table[*(sp + 1)];
  188611. *(dp + 2) = gamma_table[*(sp + 2)];
  188612. }
  188613. else if (a == 0)
  188614. {
  188615. /* background is already in screen gamma */
  188616. *dp = (png_byte)background->red;
  188617. *(dp + 1) = (png_byte)background->green;
  188618. *(dp + 2) = (png_byte)background->blue;
  188619. }
  188620. else
  188621. {
  188622. png_byte v, w;
  188623. v = gamma_to_1[*sp];
  188624. png_composite(w, v, a, background_1->red);
  188625. *dp = gamma_from_1[w];
  188626. v = gamma_to_1[*(sp + 1)];
  188627. png_composite(w, v, a, background_1->green);
  188628. *(dp + 1) = gamma_from_1[w];
  188629. v = gamma_to_1[*(sp + 2)];
  188630. png_composite(w, v, a, background_1->blue);
  188631. *(dp + 2) = gamma_from_1[w];
  188632. }
  188633. }
  188634. }
  188635. else
  188636. #endif
  188637. {
  188638. sp = row;
  188639. dp = row;
  188640. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188641. {
  188642. png_byte a = *(sp + 3);
  188643. if (a == 0xff)
  188644. {
  188645. *dp = *sp;
  188646. *(dp + 1) = *(sp + 1);
  188647. *(dp + 2) = *(sp + 2);
  188648. }
  188649. else if (a == 0)
  188650. {
  188651. *dp = (png_byte)background->red;
  188652. *(dp + 1) = (png_byte)background->green;
  188653. *(dp + 2) = (png_byte)background->blue;
  188654. }
  188655. else
  188656. {
  188657. png_composite(*dp, *sp, a, background->red);
  188658. png_composite(*(dp + 1), *(sp + 1), a,
  188659. background->green);
  188660. png_composite(*(dp + 2), *(sp + 2), a,
  188661. background->blue);
  188662. }
  188663. }
  188664. }
  188665. }
  188666. else /* if (row_info->bit_depth == 16) */
  188667. {
  188668. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188669. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188670. gamma_16_to_1 != NULL)
  188671. {
  188672. sp = row;
  188673. dp = row;
  188674. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188675. {
  188676. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188677. << 8) + (png_uint_16)(*(sp + 7)));
  188678. if (a == (png_uint_16)0xffff)
  188679. {
  188680. png_uint_16 v;
  188681. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188682. *dp = (png_byte)((v >> 8) & 0xff);
  188683. *(dp + 1) = (png_byte)(v & 0xff);
  188684. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188685. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188686. *(dp + 3) = (png_byte)(v & 0xff);
  188687. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188688. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188689. *(dp + 5) = (png_byte)(v & 0xff);
  188690. }
  188691. else if (a == 0)
  188692. {
  188693. /* background is already in screen gamma */
  188694. *dp = (png_byte)((background->red >> 8) & 0xff);
  188695. *(dp + 1) = (png_byte)(background->red & 0xff);
  188696. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188697. *(dp + 3) = (png_byte)(background->green & 0xff);
  188698. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188699. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188700. }
  188701. else
  188702. {
  188703. png_uint_16 v, w, x;
  188704. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188705. png_composite_16(w, v, a, background_1->red);
  188706. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188707. *dp = (png_byte)((x >> 8) & 0xff);
  188708. *(dp + 1) = (png_byte)(x & 0xff);
  188709. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188710. png_composite_16(w, v, a, background_1->green);
  188711. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188712. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  188713. *(dp + 3) = (png_byte)(x & 0xff);
  188714. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188715. png_composite_16(w, v, a, background_1->blue);
  188716. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  188717. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  188718. *(dp + 5) = (png_byte)(x & 0xff);
  188719. }
  188720. }
  188721. }
  188722. else
  188723. #endif
  188724. {
  188725. sp = row;
  188726. dp = row;
  188727. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188728. {
  188729. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188730. << 8) + (png_uint_16)(*(sp + 7)));
  188731. if (a == (png_uint_16)0xffff)
  188732. {
  188733. png_memcpy(dp, sp, 6);
  188734. }
  188735. else if (a == 0)
  188736. {
  188737. *dp = (png_byte)((background->red >> 8) & 0xff);
  188738. *(dp + 1) = (png_byte)(background->red & 0xff);
  188739. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188740. *(dp + 3) = (png_byte)(background->green & 0xff);
  188741. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188742. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188743. }
  188744. else
  188745. {
  188746. png_uint_16 v;
  188747. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188748. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  188749. + *(sp + 3));
  188750. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  188751. + *(sp + 5));
  188752. png_composite_16(v, r, a, background->red);
  188753. *dp = (png_byte)((v >> 8) & 0xff);
  188754. *(dp + 1) = (png_byte)(v & 0xff);
  188755. png_composite_16(v, g, a, background->green);
  188756. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188757. *(dp + 3) = (png_byte)(v & 0xff);
  188758. png_composite_16(v, b, a, background->blue);
  188759. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188760. *(dp + 5) = (png_byte)(v & 0xff);
  188761. }
  188762. }
  188763. }
  188764. }
  188765. break;
  188766. }
  188767. }
  188768. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188769. {
  188770. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188771. row_info->channels--;
  188772. row_info->pixel_depth = (png_byte)(row_info->channels *
  188773. row_info->bit_depth);
  188774. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188775. }
  188776. }
  188777. }
  188778. #endif
  188779. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188780. /* Gamma correct the image, avoiding the alpha channel. Make sure
  188781. * you do this after you deal with the transparency issue on grayscale
  188782. * or RGB images. If your bit depth is 8, use gamma_table, if it
  188783. * is 16, use gamma_16_table and gamma_shift. Build these with
  188784. * build_gamma_table().
  188785. */
  188786. void /* PRIVATE */
  188787. png_do_gamma(png_row_infop row_info, png_bytep row,
  188788. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  188789. int gamma_shift)
  188790. {
  188791. png_bytep sp;
  188792. png_uint_32 i;
  188793. png_uint_32 row_width=row_info->width;
  188794. png_debug(1, "in png_do_gamma\n");
  188795. if (
  188796. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188797. row != NULL && row_info != NULL &&
  188798. #endif
  188799. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  188800. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  188801. {
  188802. switch (row_info->color_type)
  188803. {
  188804. case PNG_COLOR_TYPE_RGB:
  188805. {
  188806. if (row_info->bit_depth == 8)
  188807. {
  188808. sp = row;
  188809. for (i = 0; i < row_width; i++)
  188810. {
  188811. *sp = gamma_table[*sp];
  188812. sp++;
  188813. *sp = gamma_table[*sp];
  188814. sp++;
  188815. *sp = gamma_table[*sp];
  188816. sp++;
  188817. }
  188818. }
  188819. else /* if (row_info->bit_depth == 16) */
  188820. {
  188821. sp = row;
  188822. for (i = 0; i < row_width; i++)
  188823. {
  188824. png_uint_16 v;
  188825. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188826. *sp = (png_byte)((v >> 8) & 0xff);
  188827. *(sp + 1) = (png_byte)(v & 0xff);
  188828. sp += 2;
  188829. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188830. *sp = (png_byte)((v >> 8) & 0xff);
  188831. *(sp + 1) = (png_byte)(v & 0xff);
  188832. sp += 2;
  188833. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188834. *sp = (png_byte)((v >> 8) & 0xff);
  188835. *(sp + 1) = (png_byte)(v & 0xff);
  188836. sp += 2;
  188837. }
  188838. }
  188839. break;
  188840. }
  188841. case PNG_COLOR_TYPE_RGB_ALPHA:
  188842. {
  188843. if (row_info->bit_depth == 8)
  188844. {
  188845. sp = row;
  188846. for (i = 0; i < row_width; i++)
  188847. {
  188848. *sp = gamma_table[*sp];
  188849. sp++;
  188850. *sp = gamma_table[*sp];
  188851. sp++;
  188852. *sp = gamma_table[*sp];
  188853. sp++;
  188854. sp++;
  188855. }
  188856. }
  188857. else /* if (row_info->bit_depth == 16) */
  188858. {
  188859. sp = row;
  188860. for (i = 0; i < row_width; i++)
  188861. {
  188862. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188863. *sp = (png_byte)((v >> 8) & 0xff);
  188864. *(sp + 1) = (png_byte)(v & 0xff);
  188865. sp += 2;
  188866. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188867. *sp = (png_byte)((v >> 8) & 0xff);
  188868. *(sp + 1) = (png_byte)(v & 0xff);
  188869. sp += 2;
  188870. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188871. *sp = (png_byte)((v >> 8) & 0xff);
  188872. *(sp + 1) = (png_byte)(v & 0xff);
  188873. sp += 4;
  188874. }
  188875. }
  188876. break;
  188877. }
  188878. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188879. {
  188880. if (row_info->bit_depth == 8)
  188881. {
  188882. sp = row;
  188883. for (i = 0; i < row_width; i++)
  188884. {
  188885. *sp = gamma_table[*sp];
  188886. sp += 2;
  188887. }
  188888. }
  188889. else /* if (row_info->bit_depth == 16) */
  188890. {
  188891. sp = row;
  188892. for (i = 0; i < row_width; i++)
  188893. {
  188894. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188895. *sp = (png_byte)((v >> 8) & 0xff);
  188896. *(sp + 1) = (png_byte)(v & 0xff);
  188897. sp += 4;
  188898. }
  188899. }
  188900. break;
  188901. }
  188902. case PNG_COLOR_TYPE_GRAY:
  188903. {
  188904. if (row_info->bit_depth == 2)
  188905. {
  188906. sp = row;
  188907. for (i = 0; i < row_width; i += 4)
  188908. {
  188909. int a = *sp & 0xc0;
  188910. int b = *sp & 0x30;
  188911. int c = *sp & 0x0c;
  188912. int d = *sp & 0x03;
  188913. *sp = (png_byte)(
  188914. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  188915. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  188916. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  188917. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  188918. sp++;
  188919. }
  188920. }
  188921. if (row_info->bit_depth == 4)
  188922. {
  188923. sp = row;
  188924. for (i = 0; i < row_width; i += 2)
  188925. {
  188926. int msb = *sp & 0xf0;
  188927. int lsb = *sp & 0x0f;
  188928. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  188929. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  188930. sp++;
  188931. }
  188932. }
  188933. else if (row_info->bit_depth == 8)
  188934. {
  188935. sp = row;
  188936. for (i = 0; i < row_width; i++)
  188937. {
  188938. *sp = gamma_table[*sp];
  188939. sp++;
  188940. }
  188941. }
  188942. else if (row_info->bit_depth == 16)
  188943. {
  188944. sp = row;
  188945. for (i = 0; i < row_width; i++)
  188946. {
  188947. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188948. *sp = (png_byte)((v >> 8) & 0xff);
  188949. *(sp + 1) = (png_byte)(v & 0xff);
  188950. sp += 2;
  188951. }
  188952. }
  188953. break;
  188954. }
  188955. }
  188956. }
  188957. }
  188958. #endif
  188959. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188960. /* Expands a palette row to an RGB or RGBA row depending
  188961. * upon whether you supply trans and num_trans.
  188962. */
  188963. void /* PRIVATE */
  188964. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  188965. png_colorp palette, png_bytep trans, int num_trans)
  188966. {
  188967. int shift, value;
  188968. png_bytep sp, dp;
  188969. png_uint_32 i;
  188970. png_uint_32 row_width=row_info->width;
  188971. png_debug(1, "in png_do_expand_palette\n");
  188972. if (
  188973. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188974. row != NULL && row_info != NULL &&
  188975. #endif
  188976. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  188977. {
  188978. if (row_info->bit_depth < 8)
  188979. {
  188980. switch (row_info->bit_depth)
  188981. {
  188982. case 1:
  188983. {
  188984. sp = row + (png_size_t)((row_width - 1) >> 3);
  188985. dp = row + (png_size_t)row_width - 1;
  188986. shift = 7 - (int)((row_width + 7) & 0x07);
  188987. for (i = 0; i < row_width; i++)
  188988. {
  188989. if ((*sp >> shift) & 0x01)
  188990. *dp = 1;
  188991. else
  188992. *dp = 0;
  188993. if (shift == 7)
  188994. {
  188995. shift = 0;
  188996. sp--;
  188997. }
  188998. else
  188999. shift++;
  189000. dp--;
  189001. }
  189002. break;
  189003. }
  189004. case 2:
  189005. {
  189006. sp = row + (png_size_t)((row_width - 1) >> 2);
  189007. dp = row + (png_size_t)row_width - 1;
  189008. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189009. for (i = 0; i < row_width; i++)
  189010. {
  189011. value = (*sp >> shift) & 0x03;
  189012. *dp = (png_byte)value;
  189013. if (shift == 6)
  189014. {
  189015. shift = 0;
  189016. sp--;
  189017. }
  189018. else
  189019. shift += 2;
  189020. dp--;
  189021. }
  189022. break;
  189023. }
  189024. case 4:
  189025. {
  189026. sp = row + (png_size_t)((row_width - 1) >> 1);
  189027. dp = row + (png_size_t)row_width - 1;
  189028. shift = (int)((row_width & 0x01) << 2);
  189029. for (i = 0; i < row_width; i++)
  189030. {
  189031. value = (*sp >> shift) & 0x0f;
  189032. *dp = (png_byte)value;
  189033. if (shift == 4)
  189034. {
  189035. shift = 0;
  189036. sp--;
  189037. }
  189038. else
  189039. shift += 4;
  189040. dp--;
  189041. }
  189042. break;
  189043. }
  189044. }
  189045. row_info->bit_depth = 8;
  189046. row_info->pixel_depth = 8;
  189047. row_info->rowbytes = row_width;
  189048. }
  189049. switch (row_info->bit_depth)
  189050. {
  189051. case 8:
  189052. {
  189053. if (trans != NULL)
  189054. {
  189055. sp = row + (png_size_t)row_width - 1;
  189056. dp = row + (png_size_t)(row_width << 2) - 1;
  189057. for (i = 0; i < row_width; i++)
  189058. {
  189059. if ((int)(*sp) >= num_trans)
  189060. *dp-- = 0xff;
  189061. else
  189062. *dp-- = trans[*sp];
  189063. *dp-- = palette[*sp].blue;
  189064. *dp-- = palette[*sp].green;
  189065. *dp-- = palette[*sp].red;
  189066. sp--;
  189067. }
  189068. row_info->bit_depth = 8;
  189069. row_info->pixel_depth = 32;
  189070. row_info->rowbytes = row_width * 4;
  189071. row_info->color_type = 6;
  189072. row_info->channels = 4;
  189073. }
  189074. else
  189075. {
  189076. sp = row + (png_size_t)row_width - 1;
  189077. dp = row + (png_size_t)(row_width * 3) - 1;
  189078. for (i = 0; i < row_width; i++)
  189079. {
  189080. *dp-- = palette[*sp].blue;
  189081. *dp-- = palette[*sp].green;
  189082. *dp-- = palette[*sp].red;
  189083. sp--;
  189084. }
  189085. row_info->bit_depth = 8;
  189086. row_info->pixel_depth = 24;
  189087. row_info->rowbytes = row_width * 3;
  189088. row_info->color_type = 2;
  189089. row_info->channels = 3;
  189090. }
  189091. break;
  189092. }
  189093. }
  189094. }
  189095. }
  189096. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  189097. * expanded transparency value is supplied, an alpha channel is built.
  189098. */
  189099. void /* PRIVATE */
  189100. png_do_expand(png_row_infop row_info, png_bytep row,
  189101. png_color_16p trans_value)
  189102. {
  189103. int shift, value;
  189104. png_bytep sp, dp;
  189105. png_uint_32 i;
  189106. png_uint_32 row_width=row_info->width;
  189107. png_debug(1, "in png_do_expand\n");
  189108. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189109. if (row != NULL && row_info != NULL)
  189110. #endif
  189111. {
  189112. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  189113. {
  189114. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  189115. if (row_info->bit_depth < 8)
  189116. {
  189117. switch (row_info->bit_depth)
  189118. {
  189119. case 1:
  189120. {
  189121. gray = (png_uint_16)((gray&0x01)*0xff);
  189122. sp = row + (png_size_t)((row_width - 1) >> 3);
  189123. dp = row + (png_size_t)row_width - 1;
  189124. shift = 7 - (int)((row_width + 7) & 0x07);
  189125. for (i = 0; i < row_width; i++)
  189126. {
  189127. if ((*sp >> shift) & 0x01)
  189128. *dp = 0xff;
  189129. else
  189130. *dp = 0;
  189131. if (shift == 7)
  189132. {
  189133. shift = 0;
  189134. sp--;
  189135. }
  189136. else
  189137. shift++;
  189138. dp--;
  189139. }
  189140. break;
  189141. }
  189142. case 2:
  189143. {
  189144. gray = (png_uint_16)((gray&0x03)*0x55);
  189145. sp = row + (png_size_t)((row_width - 1) >> 2);
  189146. dp = row + (png_size_t)row_width - 1;
  189147. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189148. for (i = 0; i < row_width; i++)
  189149. {
  189150. value = (*sp >> shift) & 0x03;
  189151. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  189152. (value << 6));
  189153. if (shift == 6)
  189154. {
  189155. shift = 0;
  189156. sp--;
  189157. }
  189158. else
  189159. shift += 2;
  189160. dp--;
  189161. }
  189162. break;
  189163. }
  189164. case 4:
  189165. {
  189166. gray = (png_uint_16)((gray&0x0f)*0x11);
  189167. sp = row + (png_size_t)((row_width - 1) >> 1);
  189168. dp = row + (png_size_t)row_width - 1;
  189169. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  189170. for (i = 0; i < row_width; i++)
  189171. {
  189172. value = (*sp >> shift) & 0x0f;
  189173. *dp = (png_byte)(value | (value << 4));
  189174. if (shift == 4)
  189175. {
  189176. shift = 0;
  189177. sp--;
  189178. }
  189179. else
  189180. shift = 4;
  189181. dp--;
  189182. }
  189183. break;
  189184. }
  189185. }
  189186. row_info->bit_depth = 8;
  189187. row_info->pixel_depth = 8;
  189188. row_info->rowbytes = row_width;
  189189. }
  189190. if (trans_value != NULL)
  189191. {
  189192. if (row_info->bit_depth == 8)
  189193. {
  189194. gray = gray & 0xff;
  189195. sp = row + (png_size_t)row_width - 1;
  189196. dp = row + (png_size_t)(row_width << 1) - 1;
  189197. for (i = 0; i < row_width; i++)
  189198. {
  189199. if (*sp == gray)
  189200. *dp-- = 0;
  189201. else
  189202. *dp-- = 0xff;
  189203. *dp-- = *sp--;
  189204. }
  189205. }
  189206. else if (row_info->bit_depth == 16)
  189207. {
  189208. png_byte gray_high = (gray >> 8) & 0xff;
  189209. png_byte gray_low = gray & 0xff;
  189210. sp = row + row_info->rowbytes - 1;
  189211. dp = row + (row_info->rowbytes << 1) - 1;
  189212. for (i = 0; i < row_width; i++)
  189213. {
  189214. if (*(sp-1) == gray_high && *(sp) == gray_low)
  189215. {
  189216. *dp-- = 0;
  189217. *dp-- = 0;
  189218. }
  189219. else
  189220. {
  189221. *dp-- = 0xff;
  189222. *dp-- = 0xff;
  189223. }
  189224. *dp-- = *sp--;
  189225. *dp-- = *sp--;
  189226. }
  189227. }
  189228. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  189229. row_info->channels = 2;
  189230. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  189231. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  189232. row_width);
  189233. }
  189234. }
  189235. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  189236. {
  189237. if (row_info->bit_depth == 8)
  189238. {
  189239. png_byte red = trans_value->red & 0xff;
  189240. png_byte green = trans_value->green & 0xff;
  189241. png_byte blue = trans_value->blue & 0xff;
  189242. sp = row + (png_size_t)row_info->rowbytes - 1;
  189243. dp = row + (png_size_t)(row_width << 2) - 1;
  189244. for (i = 0; i < row_width; i++)
  189245. {
  189246. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  189247. *dp-- = 0;
  189248. else
  189249. *dp-- = 0xff;
  189250. *dp-- = *sp--;
  189251. *dp-- = *sp--;
  189252. *dp-- = *sp--;
  189253. }
  189254. }
  189255. else if (row_info->bit_depth == 16)
  189256. {
  189257. png_byte red_high = (trans_value->red >> 8) & 0xff;
  189258. png_byte green_high = (trans_value->green >> 8) & 0xff;
  189259. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  189260. png_byte red_low = trans_value->red & 0xff;
  189261. png_byte green_low = trans_value->green & 0xff;
  189262. png_byte blue_low = trans_value->blue & 0xff;
  189263. sp = row + row_info->rowbytes - 1;
  189264. dp = row + (png_size_t)(row_width << 3) - 1;
  189265. for (i = 0; i < row_width; i++)
  189266. {
  189267. if (*(sp - 5) == red_high &&
  189268. *(sp - 4) == red_low &&
  189269. *(sp - 3) == green_high &&
  189270. *(sp - 2) == green_low &&
  189271. *(sp - 1) == blue_high &&
  189272. *(sp ) == blue_low)
  189273. {
  189274. *dp-- = 0;
  189275. *dp-- = 0;
  189276. }
  189277. else
  189278. {
  189279. *dp-- = 0xff;
  189280. *dp-- = 0xff;
  189281. }
  189282. *dp-- = *sp--;
  189283. *dp-- = *sp--;
  189284. *dp-- = *sp--;
  189285. *dp-- = *sp--;
  189286. *dp-- = *sp--;
  189287. *dp-- = *sp--;
  189288. }
  189289. }
  189290. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  189291. row_info->channels = 4;
  189292. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  189293. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189294. }
  189295. }
  189296. }
  189297. #endif
  189298. #if defined(PNG_READ_DITHER_SUPPORTED)
  189299. void /* PRIVATE */
  189300. png_do_dither(png_row_infop row_info, png_bytep row,
  189301. png_bytep palette_lookup, png_bytep dither_lookup)
  189302. {
  189303. png_bytep sp, dp;
  189304. png_uint_32 i;
  189305. png_uint_32 row_width=row_info->width;
  189306. png_debug(1, "in png_do_dither\n");
  189307. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189308. if (row != NULL && row_info != NULL)
  189309. #endif
  189310. {
  189311. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  189312. palette_lookup && row_info->bit_depth == 8)
  189313. {
  189314. int r, g, b, p;
  189315. sp = row;
  189316. dp = row;
  189317. for (i = 0; i < row_width; i++)
  189318. {
  189319. r = *sp++;
  189320. g = *sp++;
  189321. b = *sp++;
  189322. /* this looks real messy, but the compiler will reduce
  189323. it down to a reasonable formula. For example, with
  189324. 5 bits per color, we get:
  189325. p = (((r >> 3) & 0x1f) << 10) |
  189326. (((g >> 3) & 0x1f) << 5) |
  189327. ((b >> 3) & 0x1f);
  189328. */
  189329. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189330. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189331. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189332. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189333. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189334. (PNG_DITHER_BLUE_BITS)) |
  189335. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189336. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189337. *dp++ = palette_lookup[p];
  189338. }
  189339. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189340. row_info->channels = 1;
  189341. row_info->pixel_depth = row_info->bit_depth;
  189342. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189343. }
  189344. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  189345. palette_lookup != NULL && row_info->bit_depth == 8)
  189346. {
  189347. int r, g, b, p;
  189348. sp = row;
  189349. dp = row;
  189350. for (i = 0; i < row_width; i++)
  189351. {
  189352. r = *sp++;
  189353. g = *sp++;
  189354. b = *sp++;
  189355. sp++;
  189356. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189357. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189358. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189359. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189360. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189361. (PNG_DITHER_BLUE_BITS)) |
  189362. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189363. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189364. *dp++ = palette_lookup[p];
  189365. }
  189366. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189367. row_info->channels = 1;
  189368. row_info->pixel_depth = row_info->bit_depth;
  189369. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189370. }
  189371. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  189372. dither_lookup && row_info->bit_depth == 8)
  189373. {
  189374. sp = row;
  189375. for (i = 0; i < row_width; i++, sp++)
  189376. {
  189377. *sp = dither_lookup[*sp];
  189378. }
  189379. }
  189380. }
  189381. }
  189382. #endif
  189383. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189384. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189385. static PNG_CONST int png_gamma_shift[] =
  189386. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  189387. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  189388. * tables, we don't make a full table if we are reducing to 8-bit in
  189389. * the future. Note also how the gamma_16 tables are segmented so that
  189390. * we don't need to allocate > 64K chunks for a full 16-bit table.
  189391. */
  189392. void /* PRIVATE */
  189393. png_build_gamma_table(png_structp png_ptr)
  189394. {
  189395. png_debug(1, "in png_build_gamma_table\n");
  189396. if (png_ptr->bit_depth <= 8)
  189397. {
  189398. int i;
  189399. double g;
  189400. if (png_ptr->screen_gamma > .000001)
  189401. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189402. else
  189403. g = 1.0;
  189404. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  189405. (png_uint_32)256);
  189406. for (i = 0; i < 256; i++)
  189407. {
  189408. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  189409. g) * 255.0 + .5);
  189410. }
  189411. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189412. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189413. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  189414. {
  189415. g = 1.0 / (png_ptr->gamma);
  189416. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  189417. (png_uint_32)256);
  189418. for (i = 0; i < 256; i++)
  189419. {
  189420. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  189421. g) * 255.0 + .5);
  189422. }
  189423. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  189424. (png_uint_32)256);
  189425. if(png_ptr->screen_gamma > 0.000001)
  189426. g = 1.0 / png_ptr->screen_gamma;
  189427. else
  189428. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189429. for (i = 0; i < 256; i++)
  189430. {
  189431. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  189432. g) * 255.0 + .5);
  189433. }
  189434. }
  189435. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189436. }
  189437. else
  189438. {
  189439. double g;
  189440. int i, j, shift, num;
  189441. int sig_bit;
  189442. png_uint_32 ig;
  189443. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189444. {
  189445. sig_bit = (int)png_ptr->sig_bit.red;
  189446. if ((int)png_ptr->sig_bit.green > sig_bit)
  189447. sig_bit = png_ptr->sig_bit.green;
  189448. if ((int)png_ptr->sig_bit.blue > sig_bit)
  189449. sig_bit = png_ptr->sig_bit.blue;
  189450. }
  189451. else
  189452. {
  189453. sig_bit = (int)png_ptr->sig_bit.gray;
  189454. }
  189455. if (sig_bit > 0)
  189456. shift = 16 - sig_bit;
  189457. else
  189458. shift = 0;
  189459. if (png_ptr->transformations & PNG_16_TO_8)
  189460. {
  189461. if (shift < (16 - PNG_MAX_GAMMA_8))
  189462. shift = (16 - PNG_MAX_GAMMA_8);
  189463. }
  189464. if (shift > 8)
  189465. shift = 8;
  189466. if (shift < 0)
  189467. shift = 0;
  189468. png_ptr->gamma_shift = (png_byte)shift;
  189469. num = (1 << (8 - shift));
  189470. if (png_ptr->screen_gamma > .000001)
  189471. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189472. else
  189473. g = 1.0;
  189474. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  189475. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189476. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  189477. {
  189478. double fin, fout;
  189479. png_uint_32 last, max;
  189480. for (i = 0; i < num; i++)
  189481. {
  189482. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189483. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189484. }
  189485. g = 1.0 / g;
  189486. last = 0;
  189487. for (i = 0; i < 256; i++)
  189488. {
  189489. fout = ((double)i + 0.5) / 256.0;
  189490. fin = pow(fout, g);
  189491. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  189492. while (last <= max)
  189493. {
  189494. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189495. [(int)(last >> (8 - shift))] = (png_uint_16)(
  189496. (png_uint_16)i | ((png_uint_16)i << 8));
  189497. last++;
  189498. }
  189499. }
  189500. while (last < ((png_uint_32)num << 8))
  189501. {
  189502. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189503. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  189504. last++;
  189505. }
  189506. }
  189507. else
  189508. {
  189509. for (i = 0; i < num; i++)
  189510. {
  189511. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189512. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189513. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  189514. for (j = 0; j < 256; j++)
  189515. {
  189516. png_ptr->gamma_16_table[i][j] =
  189517. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189518. 65535.0, g) * 65535.0 + .5);
  189519. }
  189520. }
  189521. }
  189522. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189523. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189524. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  189525. {
  189526. g = 1.0 / (png_ptr->gamma);
  189527. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  189528. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  189529. for (i = 0; i < num; i++)
  189530. {
  189531. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189532. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189533. ig = (((png_uint_32)i *
  189534. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189535. for (j = 0; j < 256; j++)
  189536. {
  189537. png_ptr->gamma_16_to_1[i][j] =
  189538. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189539. 65535.0, g) * 65535.0 + .5);
  189540. }
  189541. }
  189542. if(png_ptr->screen_gamma > 0.000001)
  189543. g = 1.0 / png_ptr->screen_gamma;
  189544. else
  189545. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189546. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  189547. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189548. for (i = 0; i < num; i++)
  189549. {
  189550. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189551. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189552. ig = (((png_uint_32)i *
  189553. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189554. for (j = 0; j < 256; j++)
  189555. {
  189556. png_ptr->gamma_16_from_1[i][j] =
  189557. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189558. 65535.0, g) * 65535.0 + .5);
  189559. }
  189560. }
  189561. }
  189562. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189563. }
  189564. }
  189565. #endif
  189566. /* To do: install integer version of png_build_gamma_table here */
  189567. #endif
  189568. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189569. /* undoes intrapixel differencing */
  189570. void /* PRIVATE */
  189571. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  189572. {
  189573. png_debug(1, "in png_do_read_intrapixel\n");
  189574. if (
  189575. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189576. row != NULL && row_info != NULL &&
  189577. #endif
  189578. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  189579. {
  189580. int bytes_per_pixel;
  189581. png_uint_32 row_width = row_info->width;
  189582. if (row_info->bit_depth == 8)
  189583. {
  189584. png_bytep rp;
  189585. png_uint_32 i;
  189586. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189587. bytes_per_pixel = 3;
  189588. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189589. bytes_per_pixel = 4;
  189590. else
  189591. return;
  189592. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189593. {
  189594. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  189595. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  189596. }
  189597. }
  189598. else if (row_info->bit_depth == 16)
  189599. {
  189600. png_bytep rp;
  189601. png_uint_32 i;
  189602. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189603. bytes_per_pixel = 6;
  189604. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189605. bytes_per_pixel = 8;
  189606. else
  189607. return;
  189608. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189609. {
  189610. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  189611. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  189612. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  189613. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  189614. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  189615. *(rp ) = (png_byte)((red >> 8) & 0xff);
  189616. *(rp+1) = (png_byte)(red & 0xff);
  189617. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  189618. *(rp+5) = (png_byte)(blue & 0xff);
  189619. }
  189620. }
  189621. }
  189622. }
  189623. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  189624. #endif /* PNG_READ_SUPPORTED */
  189625. /********* End of inlined file: pngrtran.c *********/
  189626. /********* Start of inlined file: pngrutil.c *********/
  189627. /* pngrutil.c - utilities to read a PNG file
  189628. *
  189629. * Last changed in libpng 1.2.21 [October 4, 2007]
  189630. * For conditions of distribution and use, see copyright notice in png.h
  189631. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189632. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189633. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189634. *
  189635. * This file contains routines that are only called from within
  189636. * libpng itself during the course of reading an image.
  189637. */
  189638. #define PNG_INTERNAL
  189639. #if defined(PNG_READ_SUPPORTED)
  189640. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  189641. # define WIN32_WCE_OLD
  189642. #endif
  189643. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189644. # if defined(WIN32_WCE_OLD)
  189645. /* strtod() function is not supported on WindowsCE */
  189646. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  189647. {
  189648. double result = 0;
  189649. int len;
  189650. wchar_t *str, *end;
  189651. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  189652. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  189653. if ( NULL != str )
  189654. {
  189655. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  189656. result = wcstod(str, &end);
  189657. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  189658. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  189659. png_free(png_ptr, str);
  189660. }
  189661. return result;
  189662. }
  189663. # else
  189664. # define png_strtod(p,a,b) strtod(a,b)
  189665. # endif
  189666. #endif
  189667. png_uint_32 PNGAPI
  189668. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  189669. {
  189670. png_uint_32 i = png_get_uint_32(buf);
  189671. if (i > PNG_UINT_31_MAX)
  189672. png_error(png_ptr, "PNG unsigned integer out of range.");
  189673. return (i);
  189674. }
  189675. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  189676. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  189677. png_uint_32 PNGAPI
  189678. png_get_uint_32(png_bytep buf)
  189679. {
  189680. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  189681. ((png_uint_32)(*(buf + 1)) << 16) +
  189682. ((png_uint_32)(*(buf + 2)) << 8) +
  189683. (png_uint_32)(*(buf + 3));
  189684. return (i);
  189685. }
  189686. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  189687. * data is stored in the PNG file in two's complement format, and it is
  189688. * assumed that the machine format for signed integers is the same. */
  189689. png_int_32 PNGAPI
  189690. png_get_int_32(png_bytep buf)
  189691. {
  189692. png_int_32 i = ((png_int_32)(*buf) << 24) +
  189693. ((png_int_32)(*(buf + 1)) << 16) +
  189694. ((png_int_32)(*(buf + 2)) << 8) +
  189695. (png_int_32)(*(buf + 3));
  189696. return (i);
  189697. }
  189698. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  189699. png_uint_16 PNGAPI
  189700. png_get_uint_16(png_bytep buf)
  189701. {
  189702. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  189703. (png_uint_16)(*(buf + 1)));
  189704. return (i);
  189705. }
  189706. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  189707. /* Read data, and (optionally) run it through the CRC. */
  189708. void /* PRIVATE */
  189709. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  189710. {
  189711. if(png_ptr == NULL) return;
  189712. png_read_data(png_ptr, buf, length);
  189713. png_calculate_crc(png_ptr, buf, length);
  189714. }
  189715. /* Optionally skip data and then check the CRC. Depending on whether we
  189716. are reading a ancillary or critical chunk, and how the program has set
  189717. things up, we may calculate the CRC on the data and print a message.
  189718. Returns '1' if there was a CRC error, '0' otherwise. */
  189719. int /* PRIVATE */
  189720. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  189721. {
  189722. png_size_t i;
  189723. png_size_t istop = png_ptr->zbuf_size;
  189724. for (i = (png_size_t)skip; i > istop; i -= istop)
  189725. {
  189726. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  189727. }
  189728. if (i)
  189729. {
  189730. png_crc_read(png_ptr, png_ptr->zbuf, i);
  189731. }
  189732. if (png_crc_error(png_ptr))
  189733. {
  189734. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  189735. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  189736. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  189737. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  189738. {
  189739. png_chunk_warning(png_ptr, "CRC error");
  189740. }
  189741. else
  189742. {
  189743. png_chunk_error(png_ptr, "CRC error");
  189744. }
  189745. return (1);
  189746. }
  189747. return (0);
  189748. }
  189749. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  189750. the data it has read thus far. */
  189751. int /* PRIVATE */
  189752. png_crc_error(png_structp png_ptr)
  189753. {
  189754. png_byte crc_bytes[4];
  189755. png_uint_32 crc;
  189756. int need_crc = 1;
  189757. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  189758. {
  189759. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  189760. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189761. need_crc = 0;
  189762. }
  189763. else /* critical */
  189764. {
  189765. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  189766. need_crc = 0;
  189767. }
  189768. png_read_data(png_ptr, crc_bytes, 4);
  189769. if (need_crc)
  189770. {
  189771. crc = png_get_uint_32(crc_bytes);
  189772. return ((int)(crc != png_ptr->crc));
  189773. }
  189774. else
  189775. return (0);
  189776. }
  189777. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  189778. defined(PNG_READ_iCCP_SUPPORTED)
  189779. /*
  189780. * Decompress trailing data in a chunk. The assumption is that chunkdata
  189781. * points at an allocated area holding the contents of a chunk with a
  189782. * trailing compressed part. What we get back is an allocated area
  189783. * holding the original prefix part and an uncompressed version of the
  189784. * trailing part (the malloc area passed in is freed).
  189785. */
  189786. png_charp /* PRIVATE */
  189787. png_decompress_chunk(png_structp png_ptr, int comp_type,
  189788. png_charp chunkdata, png_size_t chunklength,
  189789. png_size_t prefix_size, png_size_t *newlength)
  189790. {
  189791. static PNG_CONST char msg[] = "Error decoding compressed text";
  189792. png_charp text;
  189793. png_size_t text_size;
  189794. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  189795. {
  189796. int ret = Z_OK;
  189797. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  189798. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  189799. png_ptr->zstream.next_out = png_ptr->zbuf;
  189800. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189801. text_size = 0;
  189802. text = NULL;
  189803. while (png_ptr->zstream.avail_in)
  189804. {
  189805. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189806. if (ret != Z_OK && ret != Z_STREAM_END)
  189807. {
  189808. if (png_ptr->zstream.msg != NULL)
  189809. png_warning(png_ptr, png_ptr->zstream.msg);
  189810. else
  189811. png_warning(png_ptr, msg);
  189812. inflateReset(&png_ptr->zstream);
  189813. png_ptr->zstream.avail_in = 0;
  189814. if (text == NULL)
  189815. {
  189816. text_size = prefix_size + png_sizeof(msg) + 1;
  189817. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  189818. if (text == NULL)
  189819. {
  189820. png_free(png_ptr,chunkdata);
  189821. png_error(png_ptr,"Not enough memory to decompress chunk");
  189822. }
  189823. png_memcpy(text, chunkdata, prefix_size);
  189824. }
  189825. text[text_size - 1] = 0x00;
  189826. /* Copy what we can of the error message into the text chunk */
  189827. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  189828. text_size = png_sizeof(msg) > text_size ? text_size :
  189829. png_sizeof(msg);
  189830. png_memcpy(text + prefix_size, msg, text_size + 1);
  189831. break;
  189832. }
  189833. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  189834. {
  189835. if (text == NULL)
  189836. {
  189837. text_size = prefix_size +
  189838. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189839. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  189840. if (text == NULL)
  189841. {
  189842. png_free(png_ptr,chunkdata);
  189843. png_error(png_ptr,"Not enough memory to decompress chunk.");
  189844. }
  189845. png_memcpy(text + prefix_size, png_ptr->zbuf,
  189846. text_size - prefix_size);
  189847. png_memcpy(text, chunkdata, prefix_size);
  189848. *(text + text_size) = 0x00;
  189849. }
  189850. else
  189851. {
  189852. png_charp tmp;
  189853. tmp = text;
  189854. text = (png_charp)png_malloc_warn(png_ptr,
  189855. (png_uint_32)(text_size +
  189856. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  189857. if (text == NULL)
  189858. {
  189859. png_free(png_ptr, tmp);
  189860. png_free(png_ptr, chunkdata);
  189861. png_error(png_ptr,"Not enough memory to decompress chunk..");
  189862. }
  189863. png_memcpy(text, tmp, text_size);
  189864. png_free(png_ptr, tmp);
  189865. png_memcpy(text + text_size, png_ptr->zbuf,
  189866. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  189867. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189868. *(text + text_size) = 0x00;
  189869. }
  189870. if (ret == Z_STREAM_END)
  189871. break;
  189872. else
  189873. {
  189874. png_ptr->zstream.next_out = png_ptr->zbuf;
  189875. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189876. }
  189877. }
  189878. }
  189879. if (ret != Z_STREAM_END)
  189880. {
  189881. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189882. char umsg[52];
  189883. if (ret == Z_BUF_ERROR)
  189884. png_snprintf(umsg, 52,
  189885. "Buffer error in compressed datastream in %s chunk",
  189886. png_ptr->chunk_name);
  189887. else if (ret == Z_DATA_ERROR)
  189888. png_snprintf(umsg, 52,
  189889. "Data error in compressed datastream in %s chunk",
  189890. png_ptr->chunk_name);
  189891. else
  189892. png_snprintf(umsg, 52,
  189893. "Incomplete compressed datastream in %s chunk",
  189894. png_ptr->chunk_name);
  189895. png_warning(png_ptr, umsg);
  189896. #else
  189897. png_warning(png_ptr,
  189898. "Incomplete compressed datastream in chunk other than IDAT");
  189899. #endif
  189900. text_size=prefix_size;
  189901. if (text == NULL)
  189902. {
  189903. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  189904. if (text == NULL)
  189905. {
  189906. png_free(png_ptr, chunkdata);
  189907. png_error(png_ptr,"Not enough memory for text.");
  189908. }
  189909. png_memcpy(text, chunkdata, prefix_size);
  189910. }
  189911. *(text + text_size) = 0x00;
  189912. }
  189913. inflateReset(&png_ptr->zstream);
  189914. png_ptr->zstream.avail_in = 0;
  189915. png_free(png_ptr, chunkdata);
  189916. chunkdata = text;
  189917. *newlength=text_size;
  189918. }
  189919. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  189920. {
  189921. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189922. char umsg[50];
  189923. png_snprintf(umsg, 50,
  189924. "Unknown zTXt compression type %d", comp_type);
  189925. png_warning(png_ptr, umsg);
  189926. #else
  189927. png_warning(png_ptr, "Unknown zTXt compression type");
  189928. #endif
  189929. *(chunkdata + prefix_size) = 0x00;
  189930. *newlength=prefix_size;
  189931. }
  189932. return chunkdata;
  189933. }
  189934. #endif
  189935. /* read and check the IDHR chunk */
  189936. void /* PRIVATE */
  189937. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189938. {
  189939. png_byte buf[13];
  189940. png_uint_32 width, height;
  189941. int bit_depth, color_type, compression_type, filter_type;
  189942. int interlace_type;
  189943. png_debug(1, "in png_handle_IHDR\n");
  189944. if (png_ptr->mode & PNG_HAVE_IHDR)
  189945. png_error(png_ptr, "Out of place IHDR");
  189946. /* check the length */
  189947. if (length != 13)
  189948. png_error(png_ptr, "Invalid IHDR chunk");
  189949. png_ptr->mode |= PNG_HAVE_IHDR;
  189950. png_crc_read(png_ptr, buf, 13);
  189951. png_crc_finish(png_ptr, 0);
  189952. width = png_get_uint_31(png_ptr, buf);
  189953. height = png_get_uint_31(png_ptr, buf + 4);
  189954. bit_depth = buf[8];
  189955. color_type = buf[9];
  189956. compression_type = buf[10];
  189957. filter_type = buf[11];
  189958. interlace_type = buf[12];
  189959. /* set internal variables */
  189960. png_ptr->width = width;
  189961. png_ptr->height = height;
  189962. png_ptr->bit_depth = (png_byte)bit_depth;
  189963. png_ptr->interlaced = (png_byte)interlace_type;
  189964. png_ptr->color_type = (png_byte)color_type;
  189965. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189966. png_ptr->filter_type = (png_byte)filter_type;
  189967. #endif
  189968. png_ptr->compression_type = (png_byte)compression_type;
  189969. /* find number of channels */
  189970. switch (png_ptr->color_type)
  189971. {
  189972. case PNG_COLOR_TYPE_GRAY:
  189973. case PNG_COLOR_TYPE_PALETTE:
  189974. png_ptr->channels = 1;
  189975. break;
  189976. case PNG_COLOR_TYPE_RGB:
  189977. png_ptr->channels = 3;
  189978. break;
  189979. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189980. png_ptr->channels = 2;
  189981. break;
  189982. case PNG_COLOR_TYPE_RGB_ALPHA:
  189983. png_ptr->channels = 4;
  189984. break;
  189985. }
  189986. /* set up other useful info */
  189987. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  189988. png_ptr->channels);
  189989. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  189990. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  189991. png_debug1(3,"channels = %d\n", png_ptr->channels);
  189992. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  189993. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  189994. color_type, interlace_type, compression_type, filter_type);
  189995. }
  189996. /* read and check the palette */
  189997. void /* PRIVATE */
  189998. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189999. {
  190000. png_color palette[PNG_MAX_PALETTE_LENGTH];
  190001. int num, i;
  190002. #ifndef PNG_NO_POINTER_INDEXING
  190003. png_colorp pal_ptr;
  190004. #endif
  190005. png_debug(1, "in png_handle_PLTE\n");
  190006. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190007. png_error(png_ptr, "Missing IHDR before PLTE");
  190008. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190009. {
  190010. png_warning(png_ptr, "Invalid PLTE after IDAT");
  190011. png_crc_finish(png_ptr, length);
  190012. return;
  190013. }
  190014. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190015. png_error(png_ptr, "Duplicate PLTE chunk");
  190016. png_ptr->mode |= PNG_HAVE_PLTE;
  190017. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  190018. {
  190019. png_warning(png_ptr,
  190020. "Ignoring PLTE chunk in grayscale PNG");
  190021. png_crc_finish(png_ptr, length);
  190022. return;
  190023. }
  190024. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190025. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190026. {
  190027. png_crc_finish(png_ptr, length);
  190028. return;
  190029. }
  190030. #endif
  190031. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  190032. {
  190033. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190034. {
  190035. png_warning(png_ptr, "Invalid palette chunk");
  190036. png_crc_finish(png_ptr, length);
  190037. return;
  190038. }
  190039. else
  190040. {
  190041. png_error(png_ptr, "Invalid palette chunk");
  190042. }
  190043. }
  190044. num = (int)length / 3;
  190045. #ifndef PNG_NO_POINTER_INDEXING
  190046. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  190047. {
  190048. png_byte buf[3];
  190049. png_crc_read(png_ptr, buf, 3);
  190050. pal_ptr->red = buf[0];
  190051. pal_ptr->green = buf[1];
  190052. pal_ptr->blue = buf[2];
  190053. }
  190054. #else
  190055. for (i = 0; i < num; i++)
  190056. {
  190057. png_byte buf[3];
  190058. png_crc_read(png_ptr, buf, 3);
  190059. /* don't depend upon png_color being any order */
  190060. palette[i].red = buf[0];
  190061. palette[i].green = buf[1];
  190062. palette[i].blue = buf[2];
  190063. }
  190064. #endif
  190065. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  190066. whatever the normal CRC configuration tells us. However, if we
  190067. have an RGB image, the PLTE can be considered ancillary, so
  190068. we will act as though it is. */
  190069. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190070. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190071. #endif
  190072. {
  190073. png_crc_finish(png_ptr, 0);
  190074. }
  190075. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190076. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  190077. {
  190078. /* If we don't want to use the data from an ancillary chunk,
  190079. we have two options: an error abort, or a warning and we
  190080. ignore the data in this chunk (which should be OK, since
  190081. it's considered ancillary for a RGB or RGBA image). */
  190082. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  190083. {
  190084. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  190085. {
  190086. png_chunk_error(png_ptr, "CRC error");
  190087. }
  190088. else
  190089. {
  190090. png_chunk_warning(png_ptr, "CRC error");
  190091. return;
  190092. }
  190093. }
  190094. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  190095. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  190096. {
  190097. png_chunk_warning(png_ptr, "CRC error");
  190098. }
  190099. }
  190100. #endif
  190101. png_set_PLTE(png_ptr, info_ptr, palette, num);
  190102. #if defined(PNG_READ_tRNS_SUPPORTED)
  190103. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190104. {
  190105. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190106. {
  190107. if (png_ptr->num_trans > (png_uint_16)num)
  190108. {
  190109. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  190110. png_ptr->num_trans = (png_uint_16)num;
  190111. }
  190112. if (info_ptr->num_trans > (png_uint_16)num)
  190113. {
  190114. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  190115. info_ptr->num_trans = (png_uint_16)num;
  190116. }
  190117. }
  190118. }
  190119. #endif
  190120. }
  190121. void /* PRIVATE */
  190122. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190123. {
  190124. png_debug(1, "in png_handle_IEND\n");
  190125. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  190126. {
  190127. png_error(png_ptr, "No image in file");
  190128. }
  190129. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  190130. if (length != 0)
  190131. {
  190132. png_warning(png_ptr, "Incorrect IEND chunk length");
  190133. }
  190134. png_crc_finish(png_ptr, length);
  190135. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  190136. }
  190137. #if defined(PNG_READ_gAMA_SUPPORTED)
  190138. void /* PRIVATE */
  190139. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190140. {
  190141. png_fixed_point igamma;
  190142. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190143. float file_gamma;
  190144. #endif
  190145. png_byte buf[4];
  190146. png_debug(1, "in png_handle_gAMA\n");
  190147. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190148. png_error(png_ptr, "Missing IHDR before gAMA");
  190149. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190150. {
  190151. png_warning(png_ptr, "Invalid gAMA after IDAT");
  190152. png_crc_finish(png_ptr, length);
  190153. return;
  190154. }
  190155. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190156. /* Should be an error, but we can cope with it */
  190157. png_warning(png_ptr, "Out of place gAMA chunk");
  190158. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  190159. #if defined(PNG_READ_sRGB_SUPPORTED)
  190160. && !(info_ptr->valid & PNG_INFO_sRGB)
  190161. #endif
  190162. )
  190163. {
  190164. png_warning(png_ptr, "Duplicate gAMA chunk");
  190165. png_crc_finish(png_ptr, length);
  190166. return;
  190167. }
  190168. if (length != 4)
  190169. {
  190170. png_warning(png_ptr, "Incorrect gAMA chunk length");
  190171. png_crc_finish(png_ptr, length);
  190172. return;
  190173. }
  190174. png_crc_read(png_ptr, buf, 4);
  190175. if (png_crc_finish(png_ptr, 0))
  190176. return;
  190177. igamma = (png_fixed_point)png_get_uint_32(buf);
  190178. /* check for zero gamma */
  190179. if (igamma == 0)
  190180. {
  190181. png_warning(png_ptr,
  190182. "Ignoring gAMA chunk with gamma=0");
  190183. return;
  190184. }
  190185. #if defined(PNG_READ_sRGB_SUPPORTED)
  190186. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190187. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190188. {
  190189. png_warning(png_ptr,
  190190. "Ignoring incorrect gAMA value when sRGB is also present");
  190191. #ifndef PNG_NO_CONSOLE_IO
  190192. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  190193. #endif
  190194. return;
  190195. }
  190196. #endif /* PNG_READ_sRGB_SUPPORTED */
  190197. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190198. file_gamma = (float)igamma / (float)100000.0;
  190199. # ifdef PNG_READ_GAMMA_SUPPORTED
  190200. png_ptr->gamma = file_gamma;
  190201. # endif
  190202. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  190203. #endif
  190204. #ifdef PNG_FIXED_POINT_SUPPORTED
  190205. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  190206. #endif
  190207. }
  190208. #endif
  190209. #if defined(PNG_READ_sBIT_SUPPORTED)
  190210. void /* PRIVATE */
  190211. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190212. {
  190213. png_size_t truelen;
  190214. png_byte buf[4];
  190215. png_debug(1, "in png_handle_sBIT\n");
  190216. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  190217. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190218. png_error(png_ptr, "Missing IHDR before sBIT");
  190219. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190220. {
  190221. png_warning(png_ptr, "Invalid sBIT after IDAT");
  190222. png_crc_finish(png_ptr, length);
  190223. return;
  190224. }
  190225. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190226. {
  190227. /* Should be an error, but we can cope with it */
  190228. png_warning(png_ptr, "Out of place sBIT chunk");
  190229. }
  190230. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  190231. {
  190232. png_warning(png_ptr, "Duplicate sBIT chunk");
  190233. png_crc_finish(png_ptr, length);
  190234. return;
  190235. }
  190236. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190237. truelen = 3;
  190238. else
  190239. truelen = (png_size_t)png_ptr->channels;
  190240. if (length != truelen || length > 4)
  190241. {
  190242. png_warning(png_ptr, "Incorrect sBIT chunk length");
  190243. png_crc_finish(png_ptr, length);
  190244. return;
  190245. }
  190246. png_crc_read(png_ptr, buf, truelen);
  190247. if (png_crc_finish(png_ptr, 0))
  190248. return;
  190249. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190250. {
  190251. png_ptr->sig_bit.red = buf[0];
  190252. png_ptr->sig_bit.green = buf[1];
  190253. png_ptr->sig_bit.blue = buf[2];
  190254. png_ptr->sig_bit.alpha = buf[3];
  190255. }
  190256. else
  190257. {
  190258. png_ptr->sig_bit.gray = buf[0];
  190259. png_ptr->sig_bit.red = buf[0];
  190260. png_ptr->sig_bit.green = buf[0];
  190261. png_ptr->sig_bit.blue = buf[0];
  190262. png_ptr->sig_bit.alpha = buf[1];
  190263. }
  190264. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  190265. }
  190266. #endif
  190267. #if defined(PNG_READ_cHRM_SUPPORTED)
  190268. void /* PRIVATE */
  190269. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190270. {
  190271. png_byte buf[4];
  190272. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190273. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  190274. #endif
  190275. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190276. int_y_green, int_x_blue, int_y_blue;
  190277. png_uint_32 uint_x, uint_y;
  190278. png_debug(1, "in png_handle_cHRM\n");
  190279. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190280. png_error(png_ptr, "Missing IHDR before cHRM");
  190281. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190282. {
  190283. png_warning(png_ptr, "Invalid cHRM after IDAT");
  190284. png_crc_finish(png_ptr, length);
  190285. return;
  190286. }
  190287. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190288. /* Should be an error, but we can cope with it */
  190289. png_warning(png_ptr, "Missing PLTE before cHRM");
  190290. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  190291. #if defined(PNG_READ_sRGB_SUPPORTED)
  190292. && !(info_ptr->valid & PNG_INFO_sRGB)
  190293. #endif
  190294. )
  190295. {
  190296. png_warning(png_ptr, "Duplicate cHRM chunk");
  190297. png_crc_finish(png_ptr, length);
  190298. return;
  190299. }
  190300. if (length != 32)
  190301. {
  190302. png_warning(png_ptr, "Incorrect cHRM chunk length");
  190303. png_crc_finish(png_ptr, length);
  190304. return;
  190305. }
  190306. png_crc_read(png_ptr, buf, 4);
  190307. uint_x = png_get_uint_32(buf);
  190308. png_crc_read(png_ptr, buf, 4);
  190309. uint_y = png_get_uint_32(buf);
  190310. if (uint_x > 80000L || uint_y > 80000L ||
  190311. uint_x + uint_y > 100000L)
  190312. {
  190313. png_warning(png_ptr, "Invalid cHRM white point");
  190314. png_crc_finish(png_ptr, 24);
  190315. return;
  190316. }
  190317. int_x_white = (png_fixed_point)uint_x;
  190318. int_y_white = (png_fixed_point)uint_y;
  190319. png_crc_read(png_ptr, buf, 4);
  190320. uint_x = png_get_uint_32(buf);
  190321. png_crc_read(png_ptr, buf, 4);
  190322. uint_y = png_get_uint_32(buf);
  190323. if (uint_x + uint_y > 100000L)
  190324. {
  190325. png_warning(png_ptr, "Invalid cHRM red point");
  190326. png_crc_finish(png_ptr, 16);
  190327. return;
  190328. }
  190329. int_x_red = (png_fixed_point)uint_x;
  190330. int_y_red = (png_fixed_point)uint_y;
  190331. png_crc_read(png_ptr, buf, 4);
  190332. uint_x = png_get_uint_32(buf);
  190333. png_crc_read(png_ptr, buf, 4);
  190334. uint_y = png_get_uint_32(buf);
  190335. if (uint_x + uint_y > 100000L)
  190336. {
  190337. png_warning(png_ptr, "Invalid cHRM green point");
  190338. png_crc_finish(png_ptr, 8);
  190339. return;
  190340. }
  190341. int_x_green = (png_fixed_point)uint_x;
  190342. int_y_green = (png_fixed_point)uint_y;
  190343. png_crc_read(png_ptr, buf, 4);
  190344. uint_x = png_get_uint_32(buf);
  190345. png_crc_read(png_ptr, buf, 4);
  190346. uint_y = png_get_uint_32(buf);
  190347. if (uint_x + uint_y > 100000L)
  190348. {
  190349. png_warning(png_ptr, "Invalid cHRM blue point");
  190350. png_crc_finish(png_ptr, 0);
  190351. return;
  190352. }
  190353. int_x_blue = (png_fixed_point)uint_x;
  190354. int_y_blue = (png_fixed_point)uint_y;
  190355. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190356. white_x = (float)int_x_white / (float)100000.0;
  190357. white_y = (float)int_y_white / (float)100000.0;
  190358. red_x = (float)int_x_red / (float)100000.0;
  190359. red_y = (float)int_y_red / (float)100000.0;
  190360. green_x = (float)int_x_green / (float)100000.0;
  190361. green_y = (float)int_y_green / (float)100000.0;
  190362. blue_x = (float)int_x_blue / (float)100000.0;
  190363. blue_y = (float)int_y_blue / (float)100000.0;
  190364. #endif
  190365. #if defined(PNG_READ_sRGB_SUPPORTED)
  190366. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  190367. {
  190368. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  190369. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  190370. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  190371. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  190372. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  190373. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  190374. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  190375. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  190376. {
  190377. png_warning(png_ptr,
  190378. "Ignoring incorrect cHRM value when sRGB is also present");
  190379. #ifndef PNG_NO_CONSOLE_IO
  190380. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190381. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  190382. white_x, white_y, red_x, red_y);
  190383. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  190384. green_x, green_y, blue_x, blue_y);
  190385. #else
  190386. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  190387. int_x_white, int_y_white, int_x_red, int_y_red);
  190388. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  190389. int_x_green, int_y_green, int_x_blue, int_y_blue);
  190390. #endif
  190391. #endif /* PNG_NO_CONSOLE_IO */
  190392. }
  190393. png_crc_finish(png_ptr, 0);
  190394. return;
  190395. }
  190396. #endif /* PNG_READ_sRGB_SUPPORTED */
  190397. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190398. png_set_cHRM(png_ptr, info_ptr,
  190399. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  190400. #endif
  190401. #ifdef PNG_FIXED_POINT_SUPPORTED
  190402. png_set_cHRM_fixed(png_ptr, info_ptr,
  190403. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190404. int_y_green, int_x_blue, int_y_blue);
  190405. #endif
  190406. if (png_crc_finish(png_ptr, 0))
  190407. return;
  190408. }
  190409. #endif
  190410. #if defined(PNG_READ_sRGB_SUPPORTED)
  190411. void /* PRIVATE */
  190412. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190413. {
  190414. int intent;
  190415. png_byte buf[1];
  190416. png_debug(1, "in png_handle_sRGB\n");
  190417. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190418. png_error(png_ptr, "Missing IHDR before sRGB");
  190419. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190420. {
  190421. png_warning(png_ptr, "Invalid sRGB after IDAT");
  190422. png_crc_finish(png_ptr, length);
  190423. return;
  190424. }
  190425. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190426. /* Should be an error, but we can cope with it */
  190427. png_warning(png_ptr, "Out of place sRGB chunk");
  190428. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190429. {
  190430. png_warning(png_ptr, "Duplicate sRGB chunk");
  190431. png_crc_finish(png_ptr, length);
  190432. return;
  190433. }
  190434. if (length != 1)
  190435. {
  190436. png_warning(png_ptr, "Incorrect sRGB chunk length");
  190437. png_crc_finish(png_ptr, length);
  190438. return;
  190439. }
  190440. png_crc_read(png_ptr, buf, 1);
  190441. if (png_crc_finish(png_ptr, 0))
  190442. return;
  190443. intent = buf[0];
  190444. /* check for bad intent */
  190445. if (intent >= PNG_sRGB_INTENT_LAST)
  190446. {
  190447. png_warning(png_ptr, "Unknown sRGB intent");
  190448. return;
  190449. }
  190450. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190451. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  190452. {
  190453. png_fixed_point igamma;
  190454. #ifdef PNG_FIXED_POINT_SUPPORTED
  190455. igamma=info_ptr->int_gamma;
  190456. #else
  190457. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190458. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  190459. # endif
  190460. #endif
  190461. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190462. {
  190463. png_warning(png_ptr,
  190464. "Ignoring incorrect gAMA value when sRGB is also present");
  190465. #ifndef PNG_NO_CONSOLE_IO
  190466. # ifdef PNG_FIXED_POINT_SUPPORTED
  190467. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  190468. # else
  190469. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190470. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  190471. # endif
  190472. # endif
  190473. #endif
  190474. }
  190475. }
  190476. #endif /* PNG_READ_gAMA_SUPPORTED */
  190477. #ifdef PNG_READ_cHRM_SUPPORTED
  190478. #ifdef PNG_FIXED_POINT_SUPPORTED
  190479. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  190480. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  190481. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  190482. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  190483. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  190484. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  190485. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  190486. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  190487. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  190488. {
  190489. png_warning(png_ptr,
  190490. "Ignoring incorrect cHRM value when sRGB is also present");
  190491. }
  190492. #endif /* PNG_FIXED_POINT_SUPPORTED */
  190493. #endif /* PNG_READ_cHRM_SUPPORTED */
  190494. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  190495. }
  190496. #endif /* PNG_READ_sRGB_SUPPORTED */
  190497. #if defined(PNG_READ_iCCP_SUPPORTED)
  190498. void /* PRIVATE */
  190499. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190500. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190501. {
  190502. png_charp chunkdata;
  190503. png_byte compression_type;
  190504. png_bytep pC;
  190505. png_charp profile;
  190506. png_uint_32 skip = 0;
  190507. png_uint_32 profile_size, profile_length;
  190508. png_size_t slength, prefix_length, data_length;
  190509. png_debug(1, "in png_handle_iCCP\n");
  190510. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190511. png_error(png_ptr, "Missing IHDR before iCCP");
  190512. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190513. {
  190514. png_warning(png_ptr, "Invalid iCCP after IDAT");
  190515. png_crc_finish(png_ptr, length);
  190516. return;
  190517. }
  190518. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190519. /* Should be an error, but we can cope with it */
  190520. png_warning(png_ptr, "Out of place iCCP chunk");
  190521. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  190522. {
  190523. png_warning(png_ptr, "Duplicate iCCP chunk");
  190524. png_crc_finish(png_ptr, length);
  190525. return;
  190526. }
  190527. #ifdef PNG_MAX_MALLOC_64K
  190528. if (length > (png_uint_32)65535L)
  190529. {
  190530. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  190531. skip = length - (png_uint_32)65535L;
  190532. length = (png_uint_32)65535L;
  190533. }
  190534. #endif
  190535. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  190536. slength = (png_size_t)length;
  190537. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190538. if (png_crc_finish(png_ptr, skip))
  190539. {
  190540. png_free(png_ptr, chunkdata);
  190541. return;
  190542. }
  190543. chunkdata[slength] = 0x00;
  190544. for (profile = chunkdata; *profile; profile++)
  190545. /* empty loop to find end of name */ ;
  190546. ++profile;
  190547. /* there should be at least one zero (the compression type byte)
  190548. following the separator, and we should be on it */
  190549. if ( profile >= chunkdata + slength - 1)
  190550. {
  190551. png_free(png_ptr, chunkdata);
  190552. png_warning(png_ptr, "Malformed iCCP chunk");
  190553. return;
  190554. }
  190555. /* compression_type should always be zero */
  190556. compression_type = *profile++;
  190557. if (compression_type)
  190558. {
  190559. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  190560. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  190561. wrote nonzero) */
  190562. }
  190563. prefix_length = profile - chunkdata;
  190564. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  190565. slength, prefix_length, &data_length);
  190566. profile_length = data_length - prefix_length;
  190567. if ( prefix_length > data_length || profile_length < 4)
  190568. {
  190569. png_free(png_ptr, chunkdata);
  190570. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  190571. return;
  190572. }
  190573. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  190574. pC = (png_bytep)(chunkdata+prefix_length);
  190575. profile_size = ((*(pC ))<<24) |
  190576. ((*(pC+1))<<16) |
  190577. ((*(pC+2))<< 8) |
  190578. ((*(pC+3)) );
  190579. if(profile_size < profile_length)
  190580. profile_length = profile_size;
  190581. if(profile_size > profile_length)
  190582. {
  190583. png_free(png_ptr, chunkdata);
  190584. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  190585. return;
  190586. }
  190587. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  190588. chunkdata + prefix_length, profile_length);
  190589. png_free(png_ptr, chunkdata);
  190590. }
  190591. #endif /* PNG_READ_iCCP_SUPPORTED */
  190592. #if defined(PNG_READ_sPLT_SUPPORTED)
  190593. void /* PRIVATE */
  190594. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190595. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190596. {
  190597. png_bytep chunkdata;
  190598. png_bytep entry_start;
  190599. png_sPLT_t new_palette;
  190600. #ifdef PNG_NO_POINTER_INDEXING
  190601. png_sPLT_entryp pp;
  190602. #endif
  190603. int data_length, entry_size, i;
  190604. png_uint_32 skip = 0;
  190605. png_size_t slength;
  190606. png_debug(1, "in png_handle_sPLT\n");
  190607. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190608. png_error(png_ptr, "Missing IHDR before sPLT");
  190609. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190610. {
  190611. png_warning(png_ptr, "Invalid sPLT after IDAT");
  190612. png_crc_finish(png_ptr, length);
  190613. return;
  190614. }
  190615. #ifdef PNG_MAX_MALLOC_64K
  190616. if (length > (png_uint_32)65535L)
  190617. {
  190618. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  190619. skip = length - (png_uint_32)65535L;
  190620. length = (png_uint_32)65535L;
  190621. }
  190622. #endif
  190623. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  190624. slength = (png_size_t)length;
  190625. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190626. if (png_crc_finish(png_ptr, skip))
  190627. {
  190628. png_free(png_ptr, chunkdata);
  190629. return;
  190630. }
  190631. chunkdata[slength] = 0x00;
  190632. for (entry_start = chunkdata; *entry_start; entry_start++)
  190633. /* empty loop to find end of name */ ;
  190634. ++entry_start;
  190635. /* a sample depth should follow the separator, and we should be on it */
  190636. if (entry_start > chunkdata + slength - 2)
  190637. {
  190638. png_free(png_ptr, chunkdata);
  190639. png_warning(png_ptr, "malformed sPLT chunk");
  190640. return;
  190641. }
  190642. new_palette.depth = *entry_start++;
  190643. entry_size = (new_palette.depth == 8 ? 6 : 10);
  190644. data_length = (slength - (entry_start - chunkdata));
  190645. /* integrity-check the data length */
  190646. if (data_length % entry_size)
  190647. {
  190648. png_free(png_ptr, chunkdata);
  190649. png_warning(png_ptr, "sPLT chunk has bad length");
  190650. return;
  190651. }
  190652. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  190653. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  190654. png_sizeof(png_sPLT_entry)))
  190655. {
  190656. png_warning(png_ptr, "sPLT chunk too long");
  190657. return;
  190658. }
  190659. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  190660. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  190661. if (new_palette.entries == NULL)
  190662. {
  190663. png_warning(png_ptr, "sPLT chunk requires too much memory");
  190664. return;
  190665. }
  190666. #ifndef PNG_NO_POINTER_INDEXING
  190667. for (i = 0; i < new_palette.nentries; i++)
  190668. {
  190669. png_sPLT_entryp pp = new_palette.entries + i;
  190670. if (new_palette.depth == 8)
  190671. {
  190672. pp->red = *entry_start++;
  190673. pp->green = *entry_start++;
  190674. pp->blue = *entry_start++;
  190675. pp->alpha = *entry_start++;
  190676. }
  190677. else
  190678. {
  190679. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  190680. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  190681. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  190682. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  190683. }
  190684. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190685. }
  190686. #else
  190687. pp = new_palette.entries;
  190688. for (i = 0; i < new_palette.nentries; i++)
  190689. {
  190690. if (new_palette.depth == 8)
  190691. {
  190692. pp[i].red = *entry_start++;
  190693. pp[i].green = *entry_start++;
  190694. pp[i].blue = *entry_start++;
  190695. pp[i].alpha = *entry_start++;
  190696. }
  190697. else
  190698. {
  190699. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  190700. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  190701. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  190702. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  190703. }
  190704. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190705. }
  190706. #endif
  190707. /* discard all chunk data except the name and stash that */
  190708. new_palette.name = (png_charp)chunkdata;
  190709. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  190710. png_free(png_ptr, chunkdata);
  190711. png_free(png_ptr, new_palette.entries);
  190712. }
  190713. #endif /* PNG_READ_sPLT_SUPPORTED */
  190714. #if defined(PNG_READ_tRNS_SUPPORTED)
  190715. void /* PRIVATE */
  190716. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190717. {
  190718. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  190719. int bit_mask;
  190720. png_debug(1, "in png_handle_tRNS\n");
  190721. /* For non-indexed color, mask off any bits in the tRNS value that
  190722. * exceed the bit depth. Some creators were writing extra bits there.
  190723. * This is not needed for indexed color. */
  190724. bit_mask = (1 << png_ptr->bit_depth) - 1;
  190725. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190726. png_error(png_ptr, "Missing IHDR before tRNS");
  190727. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190728. {
  190729. png_warning(png_ptr, "Invalid tRNS after IDAT");
  190730. png_crc_finish(png_ptr, length);
  190731. return;
  190732. }
  190733. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190734. {
  190735. png_warning(png_ptr, "Duplicate tRNS chunk");
  190736. png_crc_finish(png_ptr, length);
  190737. return;
  190738. }
  190739. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190740. {
  190741. png_byte buf[2];
  190742. if (length != 2)
  190743. {
  190744. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190745. png_crc_finish(png_ptr, length);
  190746. return;
  190747. }
  190748. png_crc_read(png_ptr, buf, 2);
  190749. png_ptr->num_trans = 1;
  190750. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  190751. }
  190752. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190753. {
  190754. png_byte buf[6];
  190755. if (length != 6)
  190756. {
  190757. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190758. png_crc_finish(png_ptr, length);
  190759. return;
  190760. }
  190761. png_crc_read(png_ptr, buf, (png_size_t)length);
  190762. png_ptr->num_trans = 1;
  190763. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  190764. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  190765. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  190766. }
  190767. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190768. {
  190769. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190770. {
  190771. /* Should be an error, but we can cope with it. */
  190772. png_warning(png_ptr, "Missing PLTE before tRNS");
  190773. }
  190774. if (length > (png_uint_32)png_ptr->num_palette ||
  190775. length > PNG_MAX_PALETTE_LENGTH)
  190776. {
  190777. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190778. png_crc_finish(png_ptr, length);
  190779. return;
  190780. }
  190781. if (length == 0)
  190782. {
  190783. png_warning(png_ptr, "Zero length tRNS chunk");
  190784. png_crc_finish(png_ptr, length);
  190785. return;
  190786. }
  190787. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  190788. png_ptr->num_trans = (png_uint_16)length;
  190789. }
  190790. else
  190791. {
  190792. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  190793. png_crc_finish(png_ptr, length);
  190794. return;
  190795. }
  190796. if (png_crc_finish(png_ptr, 0))
  190797. {
  190798. png_ptr->num_trans = 0;
  190799. return;
  190800. }
  190801. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  190802. &(png_ptr->trans_values));
  190803. }
  190804. #endif
  190805. #if defined(PNG_READ_bKGD_SUPPORTED)
  190806. void /* PRIVATE */
  190807. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190808. {
  190809. png_size_t truelen;
  190810. png_byte buf[6];
  190811. png_debug(1, "in png_handle_bKGD\n");
  190812. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190813. png_error(png_ptr, "Missing IHDR before bKGD");
  190814. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190815. {
  190816. png_warning(png_ptr, "Invalid bKGD after IDAT");
  190817. png_crc_finish(png_ptr, length);
  190818. return;
  190819. }
  190820. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  190821. !(png_ptr->mode & PNG_HAVE_PLTE))
  190822. {
  190823. png_warning(png_ptr, "Missing PLTE before bKGD");
  190824. png_crc_finish(png_ptr, length);
  190825. return;
  190826. }
  190827. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  190828. {
  190829. png_warning(png_ptr, "Duplicate bKGD chunk");
  190830. png_crc_finish(png_ptr, length);
  190831. return;
  190832. }
  190833. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190834. truelen = 1;
  190835. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190836. truelen = 6;
  190837. else
  190838. truelen = 2;
  190839. if (length != truelen)
  190840. {
  190841. png_warning(png_ptr, "Incorrect bKGD chunk length");
  190842. png_crc_finish(png_ptr, length);
  190843. return;
  190844. }
  190845. png_crc_read(png_ptr, buf, truelen);
  190846. if (png_crc_finish(png_ptr, 0))
  190847. return;
  190848. /* We convert the index value into RGB components so that we can allow
  190849. * arbitrary RGB values for background when we have transparency, and
  190850. * so it is easy to determine the RGB values of the background color
  190851. * from the info_ptr struct. */
  190852. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190853. {
  190854. png_ptr->background.index = buf[0];
  190855. if(info_ptr->num_palette)
  190856. {
  190857. if(buf[0] > info_ptr->num_palette)
  190858. {
  190859. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  190860. return;
  190861. }
  190862. png_ptr->background.red =
  190863. (png_uint_16)png_ptr->palette[buf[0]].red;
  190864. png_ptr->background.green =
  190865. (png_uint_16)png_ptr->palette[buf[0]].green;
  190866. png_ptr->background.blue =
  190867. (png_uint_16)png_ptr->palette[buf[0]].blue;
  190868. }
  190869. }
  190870. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  190871. {
  190872. png_ptr->background.red =
  190873. png_ptr->background.green =
  190874. png_ptr->background.blue =
  190875. png_ptr->background.gray = png_get_uint_16(buf);
  190876. }
  190877. else
  190878. {
  190879. png_ptr->background.red = png_get_uint_16(buf);
  190880. png_ptr->background.green = png_get_uint_16(buf + 2);
  190881. png_ptr->background.blue = png_get_uint_16(buf + 4);
  190882. }
  190883. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  190884. }
  190885. #endif
  190886. #if defined(PNG_READ_hIST_SUPPORTED)
  190887. void /* PRIVATE */
  190888. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190889. {
  190890. unsigned int num, i;
  190891. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  190892. png_debug(1, "in png_handle_hIST\n");
  190893. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190894. png_error(png_ptr, "Missing IHDR before hIST");
  190895. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190896. {
  190897. png_warning(png_ptr, "Invalid hIST after IDAT");
  190898. png_crc_finish(png_ptr, length);
  190899. return;
  190900. }
  190901. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190902. {
  190903. png_warning(png_ptr, "Missing PLTE before hIST");
  190904. png_crc_finish(png_ptr, length);
  190905. return;
  190906. }
  190907. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  190908. {
  190909. png_warning(png_ptr, "Duplicate hIST chunk");
  190910. png_crc_finish(png_ptr, length);
  190911. return;
  190912. }
  190913. num = length / 2 ;
  190914. if (num != (unsigned int) png_ptr->num_palette || num >
  190915. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  190916. {
  190917. png_warning(png_ptr, "Incorrect hIST chunk length");
  190918. png_crc_finish(png_ptr, length);
  190919. return;
  190920. }
  190921. for (i = 0; i < num; i++)
  190922. {
  190923. png_byte buf[2];
  190924. png_crc_read(png_ptr, buf, 2);
  190925. readbuf[i] = png_get_uint_16(buf);
  190926. }
  190927. if (png_crc_finish(png_ptr, 0))
  190928. return;
  190929. png_set_hIST(png_ptr, info_ptr, readbuf);
  190930. }
  190931. #endif
  190932. #if defined(PNG_READ_pHYs_SUPPORTED)
  190933. void /* PRIVATE */
  190934. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190935. {
  190936. png_byte buf[9];
  190937. png_uint_32 res_x, res_y;
  190938. int unit_type;
  190939. png_debug(1, "in png_handle_pHYs\n");
  190940. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190941. png_error(png_ptr, "Missing IHDR before pHYs");
  190942. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190943. {
  190944. png_warning(png_ptr, "Invalid pHYs after IDAT");
  190945. png_crc_finish(png_ptr, length);
  190946. return;
  190947. }
  190948. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  190949. {
  190950. png_warning(png_ptr, "Duplicate pHYs chunk");
  190951. png_crc_finish(png_ptr, length);
  190952. return;
  190953. }
  190954. if (length != 9)
  190955. {
  190956. png_warning(png_ptr, "Incorrect pHYs chunk length");
  190957. png_crc_finish(png_ptr, length);
  190958. return;
  190959. }
  190960. png_crc_read(png_ptr, buf, 9);
  190961. if (png_crc_finish(png_ptr, 0))
  190962. return;
  190963. res_x = png_get_uint_32(buf);
  190964. res_y = png_get_uint_32(buf + 4);
  190965. unit_type = buf[8];
  190966. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  190967. }
  190968. #endif
  190969. #if defined(PNG_READ_oFFs_SUPPORTED)
  190970. void /* PRIVATE */
  190971. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190972. {
  190973. png_byte buf[9];
  190974. png_int_32 offset_x, offset_y;
  190975. int unit_type;
  190976. png_debug(1, "in png_handle_oFFs\n");
  190977. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190978. png_error(png_ptr, "Missing IHDR before oFFs");
  190979. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190980. {
  190981. png_warning(png_ptr, "Invalid oFFs after IDAT");
  190982. png_crc_finish(png_ptr, length);
  190983. return;
  190984. }
  190985. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  190986. {
  190987. png_warning(png_ptr, "Duplicate oFFs chunk");
  190988. png_crc_finish(png_ptr, length);
  190989. return;
  190990. }
  190991. if (length != 9)
  190992. {
  190993. png_warning(png_ptr, "Incorrect oFFs chunk length");
  190994. png_crc_finish(png_ptr, length);
  190995. return;
  190996. }
  190997. png_crc_read(png_ptr, buf, 9);
  190998. if (png_crc_finish(png_ptr, 0))
  190999. return;
  191000. offset_x = png_get_int_32(buf);
  191001. offset_y = png_get_int_32(buf + 4);
  191002. unit_type = buf[8];
  191003. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  191004. }
  191005. #endif
  191006. #if defined(PNG_READ_pCAL_SUPPORTED)
  191007. /* read the pCAL chunk (described in the PNG Extensions document) */
  191008. void /* PRIVATE */
  191009. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191010. {
  191011. png_charp purpose;
  191012. png_int_32 X0, X1;
  191013. png_byte type, nparams;
  191014. png_charp buf, units, endptr;
  191015. png_charpp params;
  191016. png_size_t slength;
  191017. int i;
  191018. png_debug(1, "in png_handle_pCAL\n");
  191019. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191020. png_error(png_ptr, "Missing IHDR before pCAL");
  191021. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191022. {
  191023. png_warning(png_ptr, "Invalid pCAL after IDAT");
  191024. png_crc_finish(png_ptr, length);
  191025. return;
  191026. }
  191027. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  191028. {
  191029. png_warning(png_ptr, "Duplicate pCAL chunk");
  191030. png_crc_finish(png_ptr, length);
  191031. return;
  191032. }
  191033. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  191034. length + 1);
  191035. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191036. if (purpose == NULL)
  191037. {
  191038. png_warning(png_ptr, "No memory for pCAL purpose.");
  191039. return;
  191040. }
  191041. slength = (png_size_t)length;
  191042. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  191043. if (png_crc_finish(png_ptr, 0))
  191044. {
  191045. png_free(png_ptr, purpose);
  191046. return;
  191047. }
  191048. purpose[slength] = 0x00; /* null terminate the last string */
  191049. png_debug(3, "Finding end of pCAL purpose string\n");
  191050. for (buf = purpose; *buf; buf++)
  191051. /* empty loop */ ;
  191052. endptr = purpose + slength;
  191053. /* We need to have at least 12 bytes after the purpose string
  191054. in order to get the parameter information. */
  191055. if (endptr <= buf + 12)
  191056. {
  191057. png_warning(png_ptr, "Invalid pCAL data");
  191058. png_free(png_ptr, purpose);
  191059. return;
  191060. }
  191061. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  191062. X0 = png_get_int_32((png_bytep)buf+1);
  191063. X1 = png_get_int_32((png_bytep)buf+5);
  191064. type = buf[9];
  191065. nparams = buf[10];
  191066. units = buf + 11;
  191067. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  191068. /* Check that we have the right number of parameters for known
  191069. equation types. */
  191070. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  191071. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  191072. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  191073. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  191074. {
  191075. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  191076. png_free(png_ptr, purpose);
  191077. return;
  191078. }
  191079. else if (type >= PNG_EQUATION_LAST)
  191080. {
  191081. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  191082. }
  191083. for (buf = units; *buf; buf++)
  191084. /* Empty loop to move past the units string. */ ;
  191085. png_debug(3, "Allocating pCAL parameters array\n");
  191086. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  191087. *png_sizeof(png_charp))) ;
  191088. if (params == NULL)
  191089. {
  191090. png_free(png_ptr, purpose);
  191091. png_warning(png_ptr, "No memory for pCAL params.");
  191092. return;
  191093. }
  191094. /* Get pointers to the start of each parameter string. */
  191095. for (i = 0; i < (int)nparams; i++)
  191096. {
  191097. buf++; /* Skip the null string terminator from previous parameter. */
  191098. png_debug1(3, "Reading pCAL parameter %d\n", i);
  191099. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  191100. /* Empty loop to move past each parameter string */ ;
  191101. /* Make sure we haven't run out of data yet */
  191102. if (buf > endptr)
  191103. {
  191104. png_warning(png_ptr, "Invalid pCAL data");
  191105. png_free(png_ptr, purpose);
  191106. png_free(png_ptr, params);
  191107. return;
  191108. }
  191109. }
  191110. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  191111. units, params);
  191112. png_free(png_ptr, purpose);
  191113. png_free(png_ptr, params);
  191114. }
  191115. #endif
  191116. #if defined(PNG_READ_sCAL_SUPPORTED)
  191117. /* read the sCAL chunk */
  191118. void /* PRIVATE */
  191119. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191120. {
  191121. png_charp buffer, ep;
  191122. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191123. double width, height;
  191124. png_charp vp;
  191125. #else
  191126. #ifdef PNG_FIXED_POINT_SUPPORTED
  191127. png_charp swidth, sheight;
  191128. #endif
  191129. #endif
  191130. png_size_t slength;
  191131. png_debug(1, "in png_handle_sCAL\n");
  191132. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191133. png_error(png_ptr, "Missing IHDR before sCAL");
  191134. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191135. {
  191136. png_warning(png_ptr, "Invalid sCAL after IDAT");
  191137. png_crc_finish(png_ptr, length);
  191138. return;
  191139. }
  191140. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  191141. {
  191142. png_warning(png_ptr, "Duplicate sCAL chunk");
  191143. png_crc_finish(png_ptr, length);
  191144. return;
  191145. }
  191146. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  191147. length + 1);
  191148. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191149. if (buffer == NULL)
  191150. {
  191151. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  191152. return;
  191153. }
  191154. slength = (png_size_t)length;
  191155. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  191156. if (png_crc_finish(png_ptr, 0))
  191157. {
  191158. png_free(png_ptr, buffer);
  191159. return;
  191160. }
  191161. buffer[slength] = 0x00; /* null terminate the last string */
  191162. ep = buffer + 1; /* skip unit byte */
  191163. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191164. width = png_strtod(png_ptr, ep, &vp);
  191165. if (*vp)
  191166. {
  191167. png_warning(png_ptr, "malformed width string in sCAL chunk");
  191168. return;
  191169. }
  191170. #else
  191171. #ifdef PNG_FIXED_POINT_SUPPORTED
  191172. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191173. if (swidth == NULL)
  191174. {
  191175. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  191176. return;
  191177. }
  191178. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  191179. #endif
  191180. #endif
  191181. for (ep = buffer; *ep; ep++)
  191182. /* empty loop */ ;
  191183. ep++;
  191184. if (buffer + slength < ep)
  191185. {
  191186. png_warning(png_ptr, "Truncated sCAL chunk");
  191187. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  191188. !defined(PNG_FLOATING_POINT_SUPPORTED)
  191189. png_free(png_ptr, swidth);
  191190. #endif
  191191. png_free(png_ptr, buffer);
  191192. return;
  191193. }
  191194. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191195. height = png_strtod(png_ptr, ep, &vp);
  191196. if (*vp)
  191197. {
  191198. png_warning(png_ptr, "malformed height string in sCAL chunk");
  191199. return;
  191200. }
  191201. #else
  191202. #ifdef PNG_FIXED_POINT_SUPPORTED
  191203. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191204. if (swidth == NULL)
  191205. {
  191206. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  191207. return;
  191208. }
  191209. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  191210. #endif
  191211. #endif
  191212. if (buffer + slength < ep
  191213. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191214. || width <= 0. || height <= 0.
  191215. #endif
  191216. )
  191217. {
  191218. png_warning(png_ptr, "Invalid sCAL data");
  191219. png_free(png_ptr, buffer);
  191220. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191221. png_free(png_ptr, swidth);
  191222. png_free(png_ptr, sheight);
  191223. #endif
  191224. return;
  191225. }
  191226. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191227. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  191228. #else
  191229. #ifdef PNG_FIXED_POINT_SUPPORTED
  191230. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  191231. #endif
  191232. #endif
  191233. png_free(png_ptr, buffer);
  191234. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191235. png_free(png_ptr, swidth);
  191236. png_free(png_ptr, sheight);
  191237. #endif
  191238. }
  191239. #endif
  191240. #if defined(PNG_READ_tIME_SUPPORTED)
  191241. void /* PRIVATE */
  191242. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191243. {
  191244. png_byte buf[7];
  191245. png_time mod_time;
  191246. png_debug(1, "in png_handle_tIME\n");
  191247. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191248. png_error(png_ptr, "Out of place tIME chunk");
  191249. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  191250. {
  191251. png_warning(png_ptr, "Duplicate tIME chunk");
  191252. png_crc_finish(png_ptr, length);
  191253. return;
  191254. }
  191255. if (png_ptr->mode & PNG_HAVE_IDAT)
  191256. png_ptr->mode |= PNG_AFTER_IDAT;
  191257. if (length != 7)
  191258. {
  191259. png_warning(png_ptr, "Incorrect tIME chunk length");
  191260. png_crc_finish(png_ptr, length);
  191261. return;
  191262. }
  191263. png_crc_read(png_ptr, buf, 7);
  191264. if (png_crc_finish(png_ptr, 0))
  191265. return;
  191266. mod_time.second = buf[6];
  191267. mod_time.minute = buf[5];
  191268. mod_time.hour = buf[4];
  191269. mod_time.day = buf[3];
  191270. mod_time.month = buf[2];
  191271. mod_time.year = png_get_uint_16(buf);
  191272. png_set_tIME(png_ptr, info_ptr, &mod_time);
  191273. }
  191274. #endif
  191275. #if defined(PNG_READ_tEXt_SUPPORTED)
  191276. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191277. void /* PRIVATE */
  191278. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191279. {
  191280. png_textp text_ptr;
  191281. png_charp key;
  191282. png_charp text;
  191283. png_uint_32 skip = 0;
  191284. png_size_t slength;
  191285. int ret;
  191286. png_debug(1, "in png_handle_tEXt\n");
  191287. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191288. png_error(png_ptr, "Missing IHDR before tEXt");
  191289. if (png_ptr->mode & PNG_HAVE_IDAT)
  191290. png_ptr->mode |= PNG_AFTER_IDAT;
  191291. #ifdef PNG_MAX_MALLOC_64K
  191292. if (length > (png_uint_32)65535L)
  191293. {
  191294. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  191295. skip = length - (png_uint_32)65535L;
  191296. length = (png_uint_32)65535L;
  191297. }
  191298. #endif
  191299. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191300. if (key == NULL)
  191301. {
  191302. png_warning(png_ptr, "No memory to process text chunk.");
  191303. return;
  191304. }
  191305. slength = (png_size_t)length;
  191306. png_crc_read(png_ptr, (png_bytep)key, slength);
  191307. if (png_crc_finish(png_ptr, skip))
  191308. {
  191309. png_free(png_ptr, key);
  191310. return;
  191311. }
  191312. key[slength] = 0x00;
  191313. for (text = key; *text; text++)
  191314. /* empty loop to find end of key */ ;
  191315. if (text != key + slength)
  191316. text++;
  191317. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191318. (png_uint_32)png_sizeof(png_text));
  191319. if (text_ptr == NULL)
  191320. {
  191321. png_warning(png_ptr, "Not enough memory to process text chunk.");
  191322. png_free(png_ptr, key);
  191323. return;
  191324. }
  191325. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  191326. text_ptr->key = key;
  191327. #ifdef PNG_iTXt_SUPPORTED
  191328. text_ptr->lang = NULL;
  191329. text_ptr->lang_key = NULL;
  191330. text_ptr->itxt_length = 0;
  191331. #endif
  191332. text_ptr->text = text;
  191333. text_ptr->text_length = png_strlen(text);
  191334. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191335. png_free(png_ptr, key);
  191336. png_free(png_ptr, text_ptr);
  191337. if (ret)
  191338. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  191339. }
  191340. #endif
  191341. #if defined(PNG_READ_zTXt_SUPPORTED)
  191342. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191343. void /* PRIVATE */
  191344. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191345. {
  191346. png_textp text_ptr;
  191347. png_charp chunkdata;
  191348. png_charp text;
  191349. int comp_type;
  191350. int ret;
  191351. png_size_t slength, prefix_len, data_len;
  191352. png_debug(1, "in png_handle_zTXt\n");
  191353. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191354. png_error(png_ptr, "Missing IHDR before zTXt");
  191355. if (png_ptr->mode & PNG_HAVE_IDAT)
  191356. png_ptr->mode |= PNG_AFTER_IDAT;
  191357. #ifdef PNG_MAX_MALLOC_64K
  191358. /* We will no doubt have problems with chunks even half this size, but
  191359. there is no hard and fast rule to tell us where to stop. */
  191360. if (length > (png_uint_32)65535L)
  191361. {
  191362. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  191363. png_crc_finish(png_ptr, length);
  191364. return;
  191365. }
  191366. #endif
  191367. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191368. if (chunkdata == NULL)
  191369. {
  191370. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  191371. return;
  191372. }
  191373. slength = (png_size_t)length;
  191374. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191375. if (png_crc_finish(png_ptr, 0))
  191376. {
  191377. png_free(png_ptr, chunkdata);
  191378. return;
  191379. }
  191380. chunkdata[slength] = 0x00;
  191381. for (text = chunkdata; *text; text++)
  191382. /* empty loop */ ;
  191383. /* zTXt must have some text after the chunkdataword */
  191384. if (text >= chunkdata + slength - 2)
  191385. {
  191386. png_warning(png_ptr, "Truncated zTXt chunk");
  191387. png_free(png_ptr, chunkdata);
  191388. return;
  191389. }
  191390. else
  191391. {
  191392. comp_type = *(++text);
  191393. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  191394. {
  191395. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  191396. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  191397. }
  191398. text++; /* skip the compression_method byte */
  191399. }
  191400. prefix_len = text - chunkdata;
  191401. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191402. (png_size_t)length, prefix_len, &data_len);
  191403. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191404. (png_uint_32)png_sizeof(png_text));
  191405. if (text_ptr == NULL)
  191406. {
  191407. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  191408. png_free(png_ptr, chunkdata);
  191409. return;
  191410. }
  191411. text_ptr->compression = comp_type;
  191412. text_ptr->key = chunkdata;
  191413. #ifdef PNG_iTXt_SUPPORTED
  191414. text_ptr->lang = NULL;
  191415. text_ptr->lang_key = NULL;
  191416. text_ptr->itxt_length = 0;
  191417. #endif
  191418. text_ptr->text = chunkdata + prefix_len;
  191419. text_ptr->text_length = data_len;
  191420. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191421. png_free(png_ptr, text_ptr);
  191422. png_free(png_ptr, chunkdata);
  191423. if (ret)
  191424. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  191425. }
  191426. #endif
  191427. #if defined(PNG_READ_iTXt_SUPPORTED)
  191428. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191429. void /* PRIVATE */
  191430. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191431. {
  191432. png_textp text_ptr;
  191433. png_charp chunkdata;
  191434. png_charp key, lang, text, lang_key;
  191435. int comp_flag;
  191436. int comp_type = 0;
  191437. int ret;
  191438. png_size_t slength, prefix_len, data_len;
  191439. png_debug(1, "in png_handle_iTXt\n");
  191440. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191441. png_error(png_ptr, "Missing IHDR before iTXt");
  191442. if (png_ptr->mode & PNG_HAVE_IDAT)
  191443. png_ptr->mode |= PNG_AFTER_IDAT;
  191444. #ifdef PNG_MAX_MALLOC_64K
  191445. /* We will no doubt have problems with chunks even half this size, but
  191446. there is no hard and fast rule to tell us where to stop. */
  191447. if (length > (png_uint_32)65535L)
  191448. {
  191449. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  191450. png_crc_finish(png_ptr, length);
  191451. return;
  191452. }
  191453. #endif
  191454. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191455. if (chunkdata == NULL)
  191456. {
  191457. png_warning(png_ptr, "No memory to process iTXt chunk.");
  191458. return;
  191459. }
  191460. slength = (png_size_t)length;
  191461. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191462. if (png_crc_finish(png_ptr, 0))
  191463. {
  191464. png_free(png_ptr, chunkdata);
  191465. return;
  191466. }
  191467. chunkdata[slength] = 0x00;
  191468. for (lang = chunkdata; *lang; lang++)
  191469. /* empty loop */ ;
  191470. lang++; /* skip NUL separator */
  191471. /* iTXt must have a language tag (possibly empty), two compression bytes,
  191472. translated keyword (possibly empty), and possibly some text after the
  191473. keyword */
  191474. if (lang >= chunkdata + slength - 3)
  191475. {
  191476. png_warning(png_ptr, "Truncated iTXt chunk");
  191477. png_free(png_ptr, chunkdata);
  191478. return;
  191479. }
  191480. else
  191481. {
  191482. comp_flag = *lang++;
  191483. comp_type = *lang++;
  191484. }
  191485. for (lang_key = lang; *lang_key; lang_key++)
  191486. /* empty loop */ ;
  191487. lang_key++; /* skip NUL separator */
  191488. if (lang_key >= chunkdata + slength)
  191489. {
  191490. png_warning(png_ptr, "Truncated iTXt chunk");
  191491. png_free(png_ptr, chunkdata);
  191492. return;
  191493. }
  191494. for (text = lang_key; *text; text++)
  191495. /* empty loop */ ;
  191496. text++; /* skip NUL separator */
  191497. if (text >= chunkdata + slength)
  191498. {
  191499. png_warning(png_ptr, "Malformed iTXt chunk");
  191500. png_free(png_ptr, chunkdata);
  191501. return;
  191502. }
  191503. prefix_len = text - chunkdata;
  191504. key=chunkdata;
  191505. if (comp_flag)
  191506. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191507. (size_t)length, prefix_len, &data_len);
  191508. else
  191509. data_len=png_strlen(chunkdata + prefix_len);
  191510. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191511. (png_uint_32)png_sizeof(png_text));
  191512. if (text_ptr == NULL)
  191513. {
  191514. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  191515. png_free(png_ptr, chunkdata);
  191516. return;
  191517. }
  191518. text_ptr->compression = (int)comp_flag + 1;
  191519. text_ptr->lang_key = chunkdata+(lang_key-key);
  191520. text_ptr->lang = chunkdata+(lang-key);
  191521. text_ptr->itxt_length = data_len;
  191522. text_ptr->text_length = 0;
  191523. text_ptr->key = chunkdata;
  191524. text_ptr->text = chunkdata + prefix_len;
  191525. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191526. png_free(png_ptr, text_ptr);
  191527. png_free(png_ptr, chunkdata);
  191528. if (ret)
  191529. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  191530. }
  191531. #endif
  191532. /* This function is called when we haven't found a handler for a
  191533. chunk. If there isn't a problem with the chunk itself (ie bad
  191534. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  191535. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  191536. case it will be saved away to be written out later. */
  191537. void /* PRIVATE */
  191538. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191539. {
  191540. png_uint_32 skip = 0;
  191541. png_debug(1, "in png_handle_unknown\n");
  191542. if (png_ptr->mode & PNG_HAVE_IDAT)
  191543. {
  191544. #ifdef PNG_USE_LOCAL_ARRAYS
  191545. PNG_CONST PNG_IDAT;
  191546. #endif
  191547. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  191548. png_ptr->mode |= PNG_AFTER_IDAT;
  191549. }
  191550. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  191551. if (!(png_ptr->chunk_name[0] & 0x20))
  191552. {
  191553. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191554. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191555. PNG_HANDLE_CHUNK_ALWAYS
  191556. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191557. && png_ptr->read_user_chunk_fn == NULL
  191558. #endif
  191559. )
  191560. #endif
  191561. png_chunk_error(png_ptr, "unknown critical chunk");
  191562. }
  191563. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191564. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  191565. (png_ptr->read_user_chunk_fn != NULL))
  191566. {
  191567. #ifdef PNG_MAX_MALLOC_64K
  191568. if (length > (png_uint_32)65535L)
  191569. {
  191570. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  191571. skip = length - (png_uint_32)65535L;
  191572. length = (png_uint_32)65535L;
  191573. }
  191574. #endif
  191575. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  191576. (png_charp)png_ptr->chunk_name, 5);
  191577. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  191578. png_ptr->unknown_chunk.size = (png_size_t)length;
  191579. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  191580. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191581. if(png_ptr->read_user_chunk_fn != NULL)
  191582. {
  191583. /* callback to user unknown chunk handler */
  191584. int ret;
  191585. ret = (*(png_ptr->read_user_chunk_fn))
  191586. (png_ptr, &png_ptr->unknown_chunk);
  191587. if (ret < 0)
  191588. png_chunk_error(png_ptr, "error in user chunk");
  191589. if (ret == 0)
  191590. {
  191591. if (!(png_ptr->chunk_name[0] & 0x20))
  191592. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191593. PNG_HANDLE_CHUNK_ALWAYS)
  191594. png_chunk_error(png_ptr, "unknown critical chunk");
  191595. png_set_unknown_chunks(png_ptr, info_ptr,
  191596. &png_ptr->unknown_chunk, 1);
  191597. }
  191598. }
  191599. #else
  191600. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  191601. #endif
  191602. png_free(png_ptr, png_ptr->unknown_chunk.data);
  191603. png_ptr->unknown_chunk.data = NULL;
  191604. }
  191605. else
  191606. #endif
  191607. skip = length;
  191608. png_crc_finish(png_ptr, skip);
  191609. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191610. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  191611. #endif
  191612. }
  191613. /* This function is called to verify that a chunk name is valid.
  191614. This function can't have the "critical chunk check" incorporated
  191615. into it, since in the future we will need to be able to call user
  191616. functions to handle unknown critical chunks after we check that
  191617. the chunk name itself is valid. */
  191618. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  191619. void /* PRIVATE */
  191620. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  191621. {
  191622. png_debug(1, "in png_check_chunk_name\n");
  191623. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  191624. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  191625. {
  191626. png_chunk_error(png_ptr, "invalid chunk type");
  191627. }
  191628. }
  191629. /* Combines the row recently read in with the existing pixels in the
  191630. row. This routine takes care of alpha and transparency if requested.
  191631. This routine also handles the two methods of progressive display
  191632. of interlaced images, depending on the mask value.
  191633. The mask value describes which pixels are to be combined with
  191634. the row. The pattern always repeats every 8 pixels, so just 8
  191635. bits are needed. A one indicates the pixel is to be combined,
  191636. a zero indicates the pixel is to be skipped. This is in addition
  191637. to any alpha or transparency value associated with the pixel. If
  191638. you want all pixels to be combined, pass 0xff (255) in mask. */
  191639. void /* PRIVATE */
  191640. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  191641. {
  191642. png_debug(1,"in png_combine_row\n");
  191643. if (mask == 0xff)
  191644. {
  191645. png_memcpy(row, png_ptr->row_buf + 1,
  191646. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  191647. }
  191648. else
  191649. {
  191650. switch (png_ptr->row_info.pixel_depth)
  191651. {
  191652. case 1:
  191653. {
  191654. png_bytep sp = png_ptr->row_buf + 1;
  191655. png_bytep dp = row;
  191656. int s_inc, s_start, s_end;
  191657. int m = 0x80;
  191658. int shift;
  191659. png_uint_32 i;
  191660. png_uint_32 row_width = png_ptr->width;
  191661. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191662. if (png_ptr->transformations & PNG_PACKSWAP)
  191663. {
  191664. s_start = 0;
  191665. s_end = 7;
  191666. s_inc = 1;
  191667. }
  191668. else
  191669. #endif
  191670. {
  191671. s_start = 7;
  191672. s_end = 0;
  191673. s_inc = -1;
  191674. }
  191675. shift = s_start;
  191676. for (i = 0; i < row_width; i++)
  191677. {
  191678. if (m & mask)
  191679. {
  191680. int value;
  191681. value = (*sp >> shift) & 0x01;
  191682. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191683. *dp |= (png_byte)(value << shift);
  191684. }
  191685. if (shift == s_end)
  191686. {
  191687. shift = s_start;
  191688. sp++;
  191689. dp++;
  191690. }
  191691. else
  191692. shift += s_inc;
  191693. if (m == 1)
  191694. m = 0x80;
  191695. else
  191696. m >>= 1;
  191697. }
  191698. break;
  191699. }
  191700. case 2:
  191701. {
  191702. png_bytep sp = png_ptr->row_buf + 1;
  191703. png_bytep dp = row;
  191704. int s_start, s_end, s_inc;
  191705. int m = 0x80;
  191706. int shift;
  191707. png_uint_32 i;
  191708. png_uint_32 row_width = png_ptr->width;
  191709. int value;
  191710. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191711. if (png_ptr->transformations & PNG_PACKSWAP)
  191712. {
  191713. s_start = 0;
  191714. s_end = 6;
  191715. s_inc = 2;
  191716. }
  191717. else
  191718. #endif
  191719. {
  191720. s_start = 6;
  191721. s_end = 0;
  191722. s_inc = -2;
  191723. }
  191724. shift = s_start;
  191725. for (i = 0; i < row_width; i++)
  191726. {
  191727. if (m & mask)
  191728. {
  191729. value = (*sp >> shift) & 0x03;
  191730. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191731. *dp |= (png_byte)(value << shift);
  191732. }
  191733. if (shift == s_end)
  191734. {
  191735. shift = s_start;
  191736. sp++;
  191737. dp++;
  191738. }
  191739. else
  191740. shift += s_inc;
  191741. if (m == 1)
  191742. m = 0x80;
  191743. else
  191744. m >>= 1;
  191745. }
  191746. break;
  191747. }
  191748. case 4:
  191749. {
  191750. png_bytep sp = png_ptr->row_buf + 1;
  191751. png_bytep dp = row;
  191752. int s_start, s_end, s_inc;
  191753. int m = 0x80;
  191754. int shift;
  191755. png_uint_32 i;
  191756. png_uint_32 row_width = png_ptr->width;
  191757. int value;
  191758. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191759. if (png_ptr->transformations & PNG_PACKSWAP)
  191760. {
  191761. s_start = 0;
  191762. s_end = 4;
  191763. s_inc = 4;
  191764. }
  191765. else
  191766. #endif
  191767. {
  191768. s_start = 4;
  191769. s_end = 0;
  191770. s_inc = -4;
  191771. }
  191772. shift = s_start;
  191773. for (i = 0; i < row_width; i++)
  191774. {
  191775. if (m & mask)
  191776. {
  191777. value = (*sp >> shift) & 0xf;
  191778. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191779. *dp |= (png_byte)(value << shift);
  191780. }
  191781. if (shift == s_end)
  191782. {
  191783. shift = s_start;
  191784. sp++;
  191785. dp++;
  191786. }
  191787. else
  191788. shift += s_inc;
  191789. if (m == 1)
  191790. m = 0x80;
  191791. else
  191792. m >>= 1;
  191793. }
  191794. break;
  191795. }
  191796. default:
  191797. {
  191798. png_bytep sp = png_ptr->row_buf + 1;
  191799. png_bytep dp = row;
  191800. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  191801. png_uint_32 i;
  191802. png_uint_32 row_width = png_ptr->width;
  191803. png_byte m = 0x80;
  191804. for (i = 0; i < row_width; i++)
  191805. {
  191806. if (m & mask)
  191807. {
  191808. png_memcpy(dp, sp, pixel_bytes);
  191809. }
  191810. sp += pixel_bytes;
  191811. dp += pixel_bytes;
  191812. if (m == 1)
  191813. m = 0x80;
  191814. else
  191815. m >>= 1;
  191816. }
  191817. break;
  191818. }
  191819. }
  191820. }
  191821. }
  191822. #ifdef PNG_READ_INTERLACING_SUPPORTED
  191823. /* OLD pre-1.0.9 interface:
  191824. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  191825. png_uint_32 transformations)
  191826. */
  191827. void /* PRIVATE */
  191828. png_do_read_interlace(png_structp png_ptr)
  191829. {
  191830. png_row_infop row_info = &(png_ptr->row_info);
  191831. png_bytep row = png_ptr->row_buf + 1;
  191832. int pass = png_ptr->pass;
  191833. png_uint_32 transformations = png_ptr->transformations;
  191834. #ifdef PNG_USE_LOCAL_ARRAYS
  191835. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191836. /* offset to next interlace block */
  191837. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191838. #endif
  191839. png_debug(1,"in png_do_read_interlace\n");
  191840. if (row != NULL && row_info != NULL)
  191841. {
  191842. png_uint_32 final_width;
  191843. final_width = row_info->width * png_pass_inc[pass];
  191844. switch (row_info->pixel_depth)
  191845. {
  191846. case 1:
  191847. {
  191848. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  191849. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  191850. int sshift, dshift;
  191851. int s_start, s_end, s_inc;
  191852. int jstop = png_pass_inc[pass];
  191853. png_byte v;
  191854. png_uint_32 i;
  191855. int j;
  191856. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191857. if (transformations & PNG_PACKSWAP)
  191858. {
  191859. sshift = (int)((row_info->width + 7) & 0x07);
  191860. dshift = (int)((final_width + 7) & 0x07);
  191861. s_start = 7;
  191862. s_end = 0;
  191863. s_inc = -1;
  191864. }
  191865. else
  191866. #endif
  191867. {
  191868. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  191869. dshift = 7 - (int)((final_width + 7) & 0x07);
  191870. s_start = 0;
  191871. s_end = 7;
  191872. s_inc = 1;
  191873. }
  191874. for (i = 0; i < row_info->width; i++)
  191875. {
  191876. v = (png_byte)((*sp >> sshift) & 0x01);
  191877. for (j = 0; j < jstop; j++)
  191878. {
  191879. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  191880. *dp |= (png_byte)(v << dshift);
  191881. if (dshift == s_end)
  191882. {
  191883. dshift = s_start;
  191884. dp--;
  191885. }
  191886. else
  191887. dshift += s_inc;
  191888. }
  191889. if (sshift == s_end)
  191890. {
  191891. sshift = s_start;
  191892. sp--;
  191893. }
  191894. else
  191895. sshift += s_inc;
  191896. }
  191897. break;
  191898. }
  191899. case 2:
  191900. {
  191901. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  191902. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  191903. int sshift, dshift;
  191904. int s_start, s_end, s_inc;
  191905. int jstop = png_pass_inc[pass];
  191906. png_uint_32 i;
  191907. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191908. if (transformations & PNG_PACKSWAP)
  191909. {
  191910. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  191911. dshift = (int)(((final_width + 3) & 0x03) << 1);
  191912. s_start = 6;
  191913. s_end = 0;
  191914. s_inc = -2;
  191915. }
  191916. else
  191917. #endif
  191918. {
  191919. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  191920. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  191921. s_start = 0;
  191922. s_end = 6;
  191923. s_inc = 2;
  191924. }
  191925. for (i = 0; i < row_info->width; i++)
  191926. {
  191927. png_byte v;
  191928. int j;
  191929. v = (png_byte)((*sp >> sshift) & 0x03);
  191930. for (j = 0; j < jstop; j++)
  191931. {
  191932. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  191933. *dp |= (png_byte)(v << dshift);
  191934. if (dshift == s_end)
  191935. {
  191936. dshift = s_start;
  191937. dp--;
  191938. }
  191939. else
  191940. dshift += s_inc;
  191941. }
  191942. if (sshift == s_end)
  191943. {
  191944. sshift = s_start;
  191945. sp--;
  191946. }
  191947. else
  191948. sshift += s_inc;
  191949. }
  191950. break;
  191951. }
  191952. case 4:
  191953. {
  191954. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  191955. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  191956. int sshift, dshift;
  191957. int s_start, s_end, s_inc;
  191958. png_uint_32 i;
  191959. int jstop = png_pass_inc[pass];
  191960. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191961. if (transformations & PNG_PACKSWAP)
  191962. {
  191963. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  191964. dshift = (int)(((final_width + 1) & 0x01) << 2);
  191965. s_start = 4;
  191966. s_end = 0;
  191967. s_inc = -4;
  191968. }
  191969. else
  191970. #endif
  191971. {
  191972. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  191973. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  191974. s_start = 0;
  191975. s_end = 4;
  191976. s_inc = 4;
  191977. }
  191978. for (i = 0; i < row_info->width; i++)
  191979. {
  191980. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  191981. int j;
  191982. for (j = 0; j < jstop; j++)
  191983. {
  191984. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  191985. *dp |= (png_byte)(v << dshift);
  191986. if (dshift == s_end)
  191987. {
  191988. dshift = s_start;
  191989. dp--;
  191990. }
  191991. else
  191992. dshift += s_inc;
  191993. }
  191994. if (sshift == s_end)
  191995. {
  191996. sshift = s_start;
  191997. sp--;
  191998. }
  191999. else
  192000. sshift += s_inc;
  192001. }
  192002. break;
  192003. }
  192004. default:
  192005. {
  192006. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  192007. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  192008. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  192009. int jstop = png_pass_inc[pass];
  192010. png_uint_32 i;
  192011. for (i = 0; i < row_info->width; i++)
  192012. {
  192013. png_byte v[8];
  192014. int j;
  192015. png_memcpy(v, sp, pixel_bytes);
  192016. for (j = 0; j < jstop; j++)
  192017. {
  192018. png_memcpy(dp, v, pixel_bytes);
  192019. dp -= pixel_bytes;
  192020. }
  192021. sp -= pixel_bytes;
  192022. }
  192023. break;
  192024. }
  192025. }
  192026. row_info->width = final_width;
  192027. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  192028. }
  192029. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  192030. transformations = transformations; /* silence compiler warning */
  192031. #endif
  192032. }
  192033. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  192034. void /* PRIVATE */
  192035. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  192036. png_bytep prev_row, int filter)
  192037. {
  192038. png_debug(1, "in png_read_filter_row\n");
  192039. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  192040. switch (filter)
  192041. {
  192042. case PNG_FILTER_VALUE_NONE:
  192043. break;
  192044. case PNG_FILTER_VALUE_SUB:
  192045. {
  192046. png_uint_32 i;
  192047. png_uint_32 istop = row_info->rowbytes;
  192048. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192049. png_bytep rp = row + bpp;
  192050. png_bytep lp = row;
  192051. for (i = bpp; i < istop; i++)
  192052. {
  192053. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  192054. rp++;
  192055. }
  192056. break;
  192057. }
  192058. case PNG_FILTER_VALUE_UP:
  192059. {
  192060. png_uint_32 i;
  192061. png_uint_32 istop = row_info->rowbytes;
  192062. png_bytep rp = row;
  192063. png_bytep pp = prev_row;
  192064. for (i = 0; i < istop; i++)
  192065. {
  192066. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192067. rp++;
  192068. }
  192069. break;
  192070. }
  192071. case PNG_FILTER_VALUE_AVG:
  192072. {
  192073. png_uint_32 i;
  192074. png_bytep rp = row;
  192075. png_bytep pp = prev_row;
  192076. png_bytep lp = row;
  192077. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192078. png_uint_32 istop = row_info->rowbytes - bpp;
  192079. for (i = 0; i < bpp; i++)
  192080. {
  192081. *rp = (png_byte)(((int)(*rp) +
  192082. ((int)(*pp++) / 2 )) & 0xff);
  192083. rp++;
  192084. }
  192085. for (i = 0; i < istop; i++)
  192086. {
  192087. *rp = (png_byte)(((int)(*rp) +
  192088. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  192089. rp++;
  192090. }
  192091. break;
  192092. }
  192093. case PNG_FILTER_VALUE_PAETH:
  192094. {
  192095. png_uint_32 i;
  192096. png_bytep rp = row;
  192097. png_bytep pp = prev_row;
  192098. png_bytep lp = row;
  192099. png_bytep cp = prev_row;
  192100. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192101. png_uint_32 istop=row_info->rowbytes - bpp;
  192102. for (i = 0; i < bpp; i++)
  192103. {
  192104. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192105. rp++;
  192106. }
  192107. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  192108. {
  192109. int a, b, c, pa, pb, pc, p;
  192110. a = *lp++;
  192111. b = *pp++;
  192112. c = *cp++;
  192113. p = b - c;
  192114. pc = a - c;
  192115. #ifdef PNG_USE_ABS
  192116. pa = abs(p);
  192117. pb = abs(pc);
  192118. pc = abs(p + pc);
  192119. #else
  192120. pa = p < 0 ? -p : p;
  192121. pb = pc < 0 ? -pc : pc;
  192122. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  192123. #endif
  192124. /*
  192125. if (pa <= pb && pa <= pc)
  192126. p = a;
  192127. else if (pb <= pc)
  192128. p = b;
  192129. else
  192130. p = c;
  192131. */
  192132. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  192133. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  192134. rp++;
  192135. }
  192136. break;
  192137. }
  192138. default:
  192139. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  192140. *row=0;
  192141. break;
  192142. }
  192143. }
  192144. void /* PRIVATE */
  192145. png_read_finish_row(png_structp png_ptr)
  192146. {
  192147. #ifdef PNG_USE_LOCAL_ARRAYS
  192148. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192149. /* start of interlace block */
  192150. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192151. /* offset to next interlace block */
  192152. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192153. /* start of interlace block in the y direction */
  192154. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192155. /* offset to next interlace block in the y direction */
  192156. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192157. #endif
  192158. png_debug(1, "in png_read_finish_row\n");
  192159. png_ptr->row_number++;
  192160. if (png_ptr->row_number < png_ptr->num_rows)
  192161. return;
  192162. if (png_ptr->interlaced)
  192163. {
  192164. png_ptr->row_number = 0;
  192165. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  192166. png_ptr->rowbytes + 1);
  192167. do
  192168. {
  192169. png_ptr->pass++;
  192170. if (png_ptr->pass >= 7)
  192171. break;
  192172. png_ptr->iwidth = (png_ptr->width +
  192173. png_pass_inc[png_ptr->pass] - 1 -
  192174. png_pass_start[png_ptr->pass]) /
  192175. png_pass_inc[png_ptr->pass];
  192176. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  192177. png_ptr->iwidth) + 1;
  192178. if (!(png_ptr->transformations & PNG_INTERLACE))
  192179. {
  192180. png_ptr->num_rows = (png_ptr->height +
  192181. png_pass_yinc[png_ptr->pass] - 1 -
  192182. png_pass_ystart[png_ptr->pass]) /
  192183. png_pass_yinc[png_ptr->pass];
  192184. if (!(png_ptr->num_rows))
  192185. continue;
  192186. }
  192187. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  192188. break;
  192189. } while (png_ptr->iwidth == 0);
  192190. if (png_ptr->pass < 7)
  192191. return;
  192192. }
  192193. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  192194. {
  192195. #ifdef PNG_USE_LOCAL_ARRAYS
  192196. PNG_CONST PNG_IDAT;
  192197. #endif
  192198. char extra;
  192199. int ret;
  192200. png_ptr->zstream.next_out = (Bytef *)&extra;
  192201. png_ptr->zstream.avail_out = (uInt)1;
  192202. for(;;)
  192203. {
  192204. if (!(png_ptr->zstream.avail_in))
  192205. {
  192206. while (!png_ptr->idat_size)
  192207. {
  192208. png_byte chunk_length[4];
  192209. png_crc_finish(png_ptr, 0);
  192210. png_read_data(png_ptr, chunk_length, 4);
  192211. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  192212. png_reset_crc(png_ptr);
  192213. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  192214. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  192215. png_error(png_ptr, "Not enough image data");
  192216. }
  192217. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  192218. png_ptr->zstream.next_in = png_ptr->zbuf;
  192219. if (png_ptr->zbuf_size > png_ptr->idat_size)
  192220. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  192221. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  192222. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  192223. }
  192224. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  192225. if (ret == Z_STREAM_END)
  192226. {
  192227. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  192228. png_ptr->idat_size)
  192229. png_warning(png_ptr, "Extra compressed data");
  192230. png_ptr->mode |= PNG_AFTER_IDAT;
  192231. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192232. break;
  192233. }
  192234. if (ret != Z_OK)
  192235. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  192236. "Decompression Error");
  192237. if (!(png_ptr->zstream.avail_out))
  192238. {
  192239. png_warning(png_ptr, "Extra compressed data.");
  192240. png_ptr->mode |= PNG_AFTER_IDAT;
  192241. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192242. break;
  192243. }
  192244. }
  192245. png_ptr->zstream.avail_out = 0;
  192246. }
  192247. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  192248. png_warning(png_ptr, "Extra compression data");
  192249. inflateReset(&png_ptr->zstream);
  192250. png_ptr->mode |= PNG_AFTER_IDAT;
  192251. }
  192252. void /* PRIVATE */
  192253. png_read_start_row(png_structp png_ptr)
  192254. {
  192255. #ifdef PNG_USE_LOCAL_ARRAYS
  192256. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192257. /* start of interlace block */
  192258. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192259. /* offset to next interlace block */
  192260. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192261. /* start of interlace block in the y direction */
  192262. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192263. /* offset to next interlace block in the y direction */
  192264. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192265. #endif
  192266. int max_pixel_depth;
  192267. png_uint_32 row_bytes;
  192268. png_debug(1, "in png_read_start_row\n");
  192269. png_ptr->zstream.avail_in = 0;
  192270. png_init_read_transformations(png_ptr);
  192271. if (png_ptr->interlaced)
  192272. {
  192273. if (!(png_ptr->transformations & PNG_INTERLACE))
  192274. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  192275. png_pass_ystart[0]) / png_pass_yinc[0];
  192276. else
  192277. png_ptr->num_rows = png_ptr->height;
  192278. png_ptr->iwidth = (png_ptr->width +
  192279. png_pass_inc[png_ptr->pass] - 1 -
  192280. png_pass_start[png_ptr->pass]) /
  192281. png_pass_inc[png_ptr->pass];
  192282. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  192283. png_ptr->irowbytes = (png_size_t)row_bytes;
  192284. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  192285. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  192286. }
  192287. else
  192288. {
  192289. png_ptr->num_rows = png_ptr->height;
  192290. png_ptr->iwidth = png_ptr->width;
  192291. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  192292. }
  192293. max_pixel_depth = png_ptr->pixel_depth;
  192294. #if defined(PNG_READ_PACK_SUPPORTED)
  192295. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  192296. max_pixel_depth = 8;
  192297. #endif
  192298. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192299. if (png_ptr->transformations & PNG_EXPAND)
  192300. {
  192301. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192302. {
  192303. if (png_ptr->num_trans)
  192304. max_pixel_depth = 32;
  192305. else
  192306. max_pixel_depth = 24;
  192307. }
  192308. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192309. {
  192310. if (max_pixel_depth < 8)
  192311. max_pixel_depth = 8;
  192312. if (png_ptr->num_trans)
  192313. max_pixel_depth *= 2;
  192314. }
  192315. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192316. {
  192317. if (png_ptr->num_trans)
  192318. {
  192319. max_pixel_depth *= 4;
  192320. max_pixel_depth /= 3;
  192321. }
  192322. }
  192323. }
  192324. #endif
  192325. #if defined(PNG_READ_FILLER_SUPPORTED)
  192326. if (png_ptr->transformations & (PNG_FILLER))
  192327. {
  192328. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192329. max_pixel_depth = 32;
  192330. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192331. {
  192332. if (max_pixel_depth <= 8)
  192333. max_pixel_depth = 16;
  192334. else
  192335. max_pixel_depth = 32;
  192336. }
  192337. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192338. {
  192339. if (max_pixel_depth <= 32)
  192340. max_pixel_depth = 32;
  192341. else
  192342. max_pixel_depth = 64;
  192343. }
  192344. }
  192345. #endif
  192346. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192347. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  192348. {
  192349. if (
  192350. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192351. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  192352. #endif
  192353. #if defined(PNG_READ_FILLER_SUPPORTED)
  192354. (png_ptr->transformations & (PNG_FILLER)) ||
  192355. #endif
  192356. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192357. {
  192358. if (max_pixel_depth <= 16)
  192359. max_pixel_depth = 32;
  192360. else
  192361. max_pixel_depth = 64;
  192362. }
  192363. else
  192364. {
  192365. if (max_pixel_depth <= 8)
  192366. {
  192367. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192368. max_pixel_depth = 32;
  192369. else
  192370. max_pixel_depth = 24;
  192371. }
  192372. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192373. max_pixel_depth = 64;
  192374. else
  192375. max_pixel_depth = 48;
  192376. }
  192377. }
  192378. #endif
  192379. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  192380. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192381. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  192382. {
  192383. int user_pixel_depth=png_ptr->user_transform_depth*
  192384. png_ptr->user_transform_channels;
  192385. if(user_pixel_depth > max_pixel_depth)
  192386. max_pixel_depth=user_pixel_depth;
  192387. }
  192388. #endif
  192389. /* align the width on the next larger 8 pixels. Mainly used
  192390. for interlacing */
  192391. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  192392. /* calculate the maximum bytes needed, adding a byte and a pixel
  192393. for safety's sake */
  192394. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  192395. 1 + ((max_pixel_depth + 7) >> 3);
  192396. #ifdef PNG_MAX_MALLOC_64K
  192397. if (row_bytes > (png_uint_32)65536L)
  192398. png_error(png_ptr, "This image requires a row greater than 64KB");
  192399. #endif
  192400. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  192401. png_ptr->row_buf = png_ptr->big_row_buf+32;
  192402. #ifdef PNG_MAX_MALLOC_64K
  192403. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  192404. png_error(png_ptr, "This image requires a row greater than 64KB");
  192405. #endif
  192406. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  192407. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  192408. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  192409. png_ptr->rowbytes + 1));
  192410. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  192411. png_debug1(3, "width = %lu,\n", png_ptr->width);
  192412. png_debug1(3, "height = %lu,\n", png_ptr->height);
  192413. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  192414. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  192415. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  192416. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  192417. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  192418. }
  192419. #endif /* PNG_READ_SUPPORTED */
  192420. /********* End of inlined file: pngrutil.c *********/
  192421. /********* Start of inlined file: pngset.c *********/
  192422. /* pngset.c - storage of image information into info struct
  192423. *
  192424. * Last changed in libpng 1.2.21 [October 4, 2007]
  192425. * For conditions of distribution and use, see copyright notice in png.h
  192426. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192427. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192428. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192429. *
  192430. * The functions here are used during reads to store data from the file
  192431. * into the info struct, and during writes to store application data
  192432. * into the info struct for writing into the file. This abstracts the
  192433. * info struct and allows us to change the structure in the future.
  192434. */
  192435. #define PNG_INTERNAL
  192436. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  192437. #if defined(PNG_bKGD_SUPPORTED)
  192438. void PNGAPI
  192439. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  192440. {
  192441. png_debug1(1, "in %s storage function\n", "bKGD");
  192442. if (png_ptr == NULL || info_ptr == NULL)
  192443. return;
  192444. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  192445. info_ptr->valid |= PNG_INFO_bKGD;
  192446. }
  192447. #endif
  192448. #if defined(PNG_cHRM_SUPPORTED)
  192449. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192450. void PNGAPI
  192451. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  192452. double white_x, double white_y, double red_x, double red_y,
  192453. double green_x, double green_y, double blue_x, double blue_y)
  192454. {
  192455. png_debug1(1, "in %s storage function\n", "cHRM");
  192456. if (png_ptr == NULL || info_ptr == NULL)
  192457. return;
  192458. if (white_x < 0.0 || white_y < 0.0 ||
  192459. red_x < 0.0 || red_y < 0.0 ||
  192460. green_x < 0.0 || green_y < 0.0 ||
  192461. blue_x < 0.0 || blue_y < 0.0)
  192462. {
  192463. png_warning(png_ptr,
  192464. "Ignoring attempt to set negative chromaticity value");
  192465. return;
  192466. }
  192467. if (white_x > 21474.83 || white_y > 21474.83 ||
  192468. red_x > 21474.83 || red_y > 21474.83 ||
  192469. green_x > 21474.83 || green_y > 21474.83 ||
  192470. blue_x > 21474.83 || blue_y > 21474.83)
  192471. {
  192472. png_warning(png_ptr,
  192473. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192474. return;
  192475. }
  192476. info_ptr->x_white = (float)white_x;
  192477. info_ptr->y_white = (float)white_y;
  192478. info_ptr->x_red = (float)red_x;
  192479. info_ptr->y_red = (float)red_y;
  192480. info_ptr->x_green = (float)green_x;
  192481. info_ptr->y_green = (float)green_y;
  192482. info_ptr->x_blue = (float)blue_x;
  192483. info_ptr->y_blue = (float)blue_y;
  192484. #ifdef PNG_FIXED_POINT_SUPPORTED
  192485. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  192486. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  192487. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  192488. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  192489. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  192490. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  192491. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  192492. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  192493. #endif
  192494. info_ptr->valid |= PNG_INFO_cHRM;
  192495. }
  192496. #endif
  192497. #ifdef PNG_FIXED_POINT_SUPPORTED
  192498. void PNGAPI
  192499. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  192500. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  192501. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  192502. png_fixed_point blue_x, png_fixed_point blue_y)
  192503. {
  192504. png_debug1(1, "in %s storage function\n", "cHRM");
  192505. if (png_ptr == NULL || info_ptr == NULL)
  192506. return;
  192507. if (white_x < 0 || white_y < 0 ||
  192508. red_x < 0 || red_y < 0 ||
  192509. green_x < 0 || green_y < 0 ||
  192510. blue_x < 0 || blue_y < 0)
  192511. {
  192512. png_warning(png_ptr,
  192513. "Ignoring attempt to set negative chromaticity value");
  192514. return;
  192515. }
  192516. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192517. if (white_x > (double) PNG_UINT_31_MAX ||
  192518. white_y > (double) PNG_UINT_31_MAX ||
  192519. red_x > (double) PNG_UINT_31_MAX ||
  192520. red_y > (double) PNG_UINT_31_MAX ||
  192521. green_x > (double) PNG_UINT_31_MAX ||
  192522. green_y > (double) PNG_UINT_31_MAX ||
  192523. blue_x > (double) PNG_UINT_31_MAX ||
  192524. blue_y > (double) PNG_UINT_31_MAX)
  192525. #else
  192526. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192527. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192528. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192529. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192530. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192531. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192532. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192533. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  192534. #endif
  192535. {
  192536. png_warning(png_ptr,
  192537. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192538. return;
  192539. }
  192540. info_ptr->int_x_white = white_x;
  192541. info_ptr->int_y_white = white_y;
  192542. info_ptr->int_x_red = red_x;
  192543. info_ptr->int_y_red = red_y;
  192544. info_ptr->int_x_green = green_x;
  192545. info_ptr->int_y_green = green_y;
  192546. info_ptr->int_x_blue = blue_x;
  192547. info_ptr->int_y_blue = blue_y;
  192548. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192549. info_ptr->x_white = (float)(white_x/100000.);
  192550. info_ptr->y_white = (float)(white_y/100000.);
  192551. info_ptr->x_red = (float)( red_x/100000.);
  192552. info_ptr->y_red = (float)( red_y/100000.);
  192553. info_ptr->x_green = (float)(green_x/100000.);
  192554. info_ptr->y_green = (float)(green_y/100000.);
  192555. info_ptr->x_blue = (float)( blue_x/100000.);
  192556. info_ptr->y_blue = (float)( blue_y/100000.);
  192557. #endif
  192558. info_ptr->valid |= PNG_INFO_cHRM;
  192559. }
  192560. #endif
  192561. #endif
  192562. #if defined(PNG_gAMA_SUPPORTED)
  192563. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192564. void PNGAPI
  192565. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  192566. {
  192567. double gamma;
  192568. png_debug1(1, "in %s storage function\n", "gAMA");
  192569. if (png_ptr == NULL || info_ptr == NULL)
  192570. return;
  192571. /* Check for overflow */
  192572. if (file_gamma > 21474.83)
  192573. {
  192574. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192575. gamma=21474.83;
  192576. }
  192577. else
  192578. gamma=file_gamma;
  192579. info_ptr->gamma = (float)gamma;
  192580. #ifdef PNG_FIXED_POINT_SUPPORTED
  192581. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  192582. #endif
  192583. info_ptr->valid |= PNG_INFO_gAMA;
  192584. if(gamma == 0.0)
  192585. png_warning(png_ptr, "Setting gamma=0");
  192586. }
  192587. #endif
  192588. void PNGAPI
  192589. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  192590. int_gamma)
  192591. {
  192592. png_fixed_point gamma;
  192593. png_debug1(1, "in %s storage function\n", "gAMA");
  192594. if (png_ptr == NULL || info_ptr == NULL)
  192595. return;
  192596. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  192597. {
  192598. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192599. gamma=PNG_UINT_31_MAX;
  192600. }
  192601. else
  192602. {
  192603. if (int_gamma < 0)
  192604. {
  192605. png_warning(png_ptr, "Setting negative gamma to zero");
  192606. gamma=0;
  192607. }
  192608. else
  192609. gamma=int_gamma;
  192610. }
  192611. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192612. info_ptr->gamma = (float)(gamma/100000.);
  192613. #endif
  192614. #ifdef PNG_FIXED_POINT_SUPPORTED
  192615. info_ptr->int_gamma = gamma;
  192616. #endif
  192617. info_ptr->valid |= PNG_INFO_gAMA;
  192618. if(gamma == 0)
  192619. png_warning(png_ptr, "Setting gamma=0");
  192620. }
  192621. #endif
  192622. #if defined(PNG_hIST_SUPPORTED)
  192623. void PNGAPI
  192624. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  192625. {
  192626. int i;
  192627. png_debug1(1, "in %s storage function\n", "hIST");
  192628. if (png_ptr == NULL || info_ptr == NULL)
  192629. return;
  192630. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  192631. > PNG_MAX_PALETTE_LENGTH)
  192632. {
  192633. png_warning(png_ptr,
  192634. "Invalid palette size, hIST allocation skipped.");
  192635. return;
  192636. }
  192637. #ifdef PNG_FREE_ME_SUPPORTED
  192638. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  192639. #endif
  192640. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  192641. 1.2.1 */
  192642. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  192643. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  192644. if (png_ptr->hist == NULL)
  192645. {
  192646. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  192647. return;
  192648. }
  192649. for (i = 0; i < info_ptr->num_palette; i++)
  192650. png_ptr->hist[i] = hist[i];
  192651. info_ptr->hist = png_ptr->hist;
  192652. info_ptr->valid |= PNG_INFO_hIST;
  192653. #ifdef PNG_FREE_ME_SUPPORTED
  192654. info_ptr->free_me |= PNG_FREE_HIST;
  192655. #else
  192656. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  192657. #endif
  192658. }
  192659. #endif
  192660. void PNGAPI
  192661. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  192662. png_uint_32 width, png_uint_32 height, int bit_depth,
  192663. int color_type, int interlace_type, int compression_type,
  192664. int filter_type)
  192665. {
  192666. png_debug1(1, "in %s storage function\n", "IHDR");
  192667. if (png_ptr == NULL || info_ptr == NULL)
  192668. return;
  192669. /* check for width and height valid values */
  192670. if (width == 0 || height == 0)
  192671. png_error(png_ptr, "Image width or height is zero in IHDR");
  192672. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192673. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  192674. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192675. #else
  192676. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  192677. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192678. #endif
  192679. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  192680. png_error(png_ptr, "Invalid image size in IHDR");
  192681. if ( width > (PNG_UINT_32_MAX
  192682. >> 3) /* 8-byte RGBA pixels */
  192683. - 64 /* bigrowbuf hack */
  192684. - 1 /* filter byte */
  192685. - 7*8 /* rounding of width to multiple of 8 pixels */
  192686. - 8) /* extra max_pixel_depth pad */
  192687. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  192688. /* check other values */
  192689. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  192690. bit_depth != 8 && bit_depth != 16)
  192691. png_error(png_ptr, "Invalid bit depth in IHDR");
  192692. if (color_type < 0 || color_type == 1 ||
  192693. color_type == 5 || color_type > 6)
  192694. png_error(png_ptr, "Invalid color type in IHDR");
  192695. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  192696. ((color_type == PNG_COLOR_TYPE_RGB ||
  192697. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  192698. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  192699. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  192700. if (interlace_type >= PNG_INTERLACE_LAST)
  192701. png_error(png_ptr, "Unknown interlace method in IHDR");
  192702. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  192703. png_error(png_ptr, "Unknown compression method in IHDR");
  192704. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192705. /* Accept filter_method 64 (intrapixel differencing) only if
  192706. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192707. * 2. Libpng did not read a PNG signature (this filter_method is only
  192708. * used in PNG datastreams that are embedded in MNG datastreams) and
  192709. * 3. The application called png_permit_mng_features with a mask that
  192710. * included PNG_FLAG_MNG_FILTER_64 and
  192711. * 4. The filter_method is 64 and
  192712. * 5. The color_type is RGB or RGBA
  192713. */
  192714. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  192715. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192716. if(filter_type != PNG_FILTER_TYPE_BASE)
  192717. {
  192718. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192719. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  192720. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  192721. (color_type == PNG_COLOR_TYPE_RGB ||
  192722. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  192723. png_error(png_ptr, "Unknown filter method in IHDR");
  192724. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  192725. png_warning(png_ptr, "Invalid filter method in IHDR");
  192726. }
  192727. #else
  192728. if(filter_type != PNG_FILTER_TYPE_BASE)
  192729. png_error(png_ptr, "Unknown filter method in IHDR");
  192730. #endif
  192731. info_ptr->width = width;
  192732. info_ptr->height = height;
  192733. info_ptr->bit_depth = (png_byte)bit_depth;
  192734. info_ptr->color_type =(png_byte) color_type;
  192735. info_ptr->compression_type = (png_byte)compression_type;
  192736. info_ptr->filter_type = (png_byte)filter_type;
  192737. info_ptr->interlace_type = (png_byte)interlace_type;
  192738. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192739. info_ptr->channels = 1;
  192740. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192741. info_ptr->channels = 3;
  192742. else
  192743. info_ptr->channels = 1;
  192744. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  192745. info_ptr->channels++;
  192746. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  192747. /* check for potential overflow */
  192748. if (width > (PNG_UINT_32_MAX
  192749. >> 3) /* 8-byte RGBA pixels */
  192750. - 64 /* bigrowbuf hack */
  192751. - 1 /* filter byte */
  192752. - 7*8 /* rounding of width to multiple of 8 pixels */
  192753. - 8) /* extra max_pixel_depth pad */
  192754. info_ptr->rowbytes = (png_size_t)0;
  192755. else
  192756. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  192757. }
  192758. #if defined(PNG_oFFs_SUPPORTED)
  192759. void PNGAPI
  192760. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  192761. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  192762. {
  192763. png_debug1(1, "in %s storage function\n", "oFFs");
  192764. if (png_ptr == NULL || info_ptr == NULL)
  192765. return;
  192766. info_ptr->x_offset = offset_x;
  192767. info_ptr->y_offset = offset_y;
  192768. info_ptr->offset_unit_type = (png_byte)unit_type;
  192769. info_ptr->valid |= PNG_INFO_oFFs;
  192770. }
  192771. #endif
  192772. #if defined(PNG_pCAL_SUPPORTED)
  192773. void PNGAPI
  192774. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  192775. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  192776. png_charp units, png_charpp params)
  192777. {
  192778. png_uint_32 length;
  192779. int i;
  192780. png_debug1(1, "in %s storage function\n", "pCAL");
  192781. if (png_ptr == NULL || info_ptr == NULL)
  192782. return;
  192783. length = png_strlen(purpose) + 1;
  192784. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  192785. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  192786. if (info_ptr->pcal_purpose == NULL)
  192787. {
  192788. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  192789. return;
  192790. }
  192791. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  192792. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  192793. info_ptr->pcal_X0 = X0;
  192794. info_ptr->pcal_X1 = X1;
  192795. info_ptr->pcal_type = (png_byte)type;
  192796. info_ptr->pcal_nparams = (png_byte)nparams;
  192797. length = png_strlen(units) + 1;
  192798. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  192799. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  192800. if (info_ptr->pcal_units == NULL)
  192801. {
  192802. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  192803. return;
  192804. }
  192805. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  192806. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  192807. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  192808. if (info_ptr->pcal_params == NULL)
  192809. {
  192810. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  192811. return;
  192812. }
  192813. info_ptr->pcal_params[nparams] = NULL;
  192814. for (i = 0; i < nparams; i++)
  192815. {
  192816. length = png_strlen(params[i]) + 1;
  192817. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  192818. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  192819. if (info_ptr->pcal_params[i] == NULL)
  192820. {
  192821. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  192822. return;
  192823. }
  192824. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  192825. }
  192826. info_ptr->valid |= PNG_INFO_pCAL;
  192827. #ifdef PNG_FREE_ME_SUPPORTED
  192828. info_ptr->free_me |= PNG_FREE_PCAL;
  192829. #endif
  192830. }
  192831. #endif
  192832. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  192833. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192834. void PNGAPI
  192835. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  192836. int unit, double width, double height)
  192837. {
  192838. png_debug1(1, "in %s storage function\n", "sCAL");
  192839. if (png_ptr == NULL || info_ptr == NULL)
  192840. return;
  192841. info_ptr->scal_unit = (png_byte)unit;
  192842. info_ptr->scal_pixel_width = width;
  192843. info_ptr->scal_pixel_height = height;
  192844. info_ptr->valid |= PNG_INFO_sCAL;
  192845. }
  192846. #else
  192847. #ifdef PNG_FIXED_POINT_SUPPORTED
  192848. void PNGAPI
  192849. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  192850. int unit, png_charp swidth, png_charp sheight)
  192851. {
  192852. png_uint_32 length;
  192853. png_debug1(1, "in %s storage function\n", "sCAL");
  192854. if (png_ptr == NULL || info_ptr == NULL)
  192855. return;
  192856. info_ptr->scal_unit = (png_byte)unit;
  192857. length = png_strlen(swidth) + 1;
  192858. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192859. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  192860. if (info_ptr->scal_s_width == NULL)
  192861. {
  192862. png_warning(png_ptr,
  192863. "Memory allocation failed while processing sCAL.");
  192864. }
  192865. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  192866. length = png_strlen(sheight) + 1;
  192867. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192868. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  192869. if (info_ptr->scal_s_height == NULL)
  192870. {
  192871. png_free (png_ptr, info_ptr->scal_s_width);
  192872. png_warning(png_ptr,
  192873. "Memory allocation failed while processing sCAL.");
  192874. }
  192875. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  192876. info_ptr->valid |= PNG_INFO_sCAL;
  192877. #ifdef PNG_FREE_ME_SUPPORTED
  192878. info_ptr->free_me |= PNG_FREE_SCAL;
  192879. #endif
  192880. }
  192881. #endif
  192882. #endif
  192883. #endif
  192884. #if defined(PNG_pHYs_SUPPORTED)
  192885. void PNGAPI
  192886. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  192887. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  192888. {
  192889. png_debug1(1, "in %s storage function\n", "pHYs");
  192890. if (png_ptr == NULL || info_ptr == NULL)
  192891. return;
  192892. info_ptr->x_pixels_per_unit = res_x;
  192893. info_ptr->y_pixels_per_unit = res_y;
  192894. info_ptr->phys_unit_type = (png_byte)unit_type;
  192895. info_ptr->valid |= PNG_INFO_pHYs;
  192896. }
  192897. #endif
  192898. void PNGAPI
  192899. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  192900. png_colorp palette, int num_palette)
  192901. {
  192902. png_debug1(1, "in %s storage function\n", "PLTE");
  192903. if (png_ptr == NULL || info_ptr == NULL)
  192904. return;
  192905. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  192906. {
  192907. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192908. png_error(png_ptr, "Invalid palette length");
  192909. else
  192910. {
  192911. png_warning(png_ptr, "Invalid palette length");
  192912. return;
  192913. }
  192914. }
  192915. /*
  192916. * It may not actually be necessary to set png_ptr->palette here;
  192917. * we do it for backward compatibility with the way the png_handle_tRNS
  192918. * function used to do the allocation.
  192919. */
  192920. #ifdef PNG_FREE_ME_SUPPORTED
  192921. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  192922. #endif
  192923. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  192924. of num_palette entries,
  192925. in case of an invalid PNG file that has too-large sample values. */
  192926. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  192927. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  192928. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  192929. png_sizeof(png_color));
  192930. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  192931. info_ptr->palette = png_ptr->palette;
  192932. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  192933. #ifdef PNG_FREE_ME_SUPPORTED
  192934. info_ptr->free_me |= PNG_FREE_PLTE;
  192935. #else
  192936. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  192937. #endif
  192938. info_ptr->valid |= PNG_INFO_PLTE;
  192939. }
  192940. #if defined(PNG_sBIT_SUPPORTED)
  192941. void PNGAPI
  192942. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  192943. png_color_8p sig_bit)
  192944. {
  192945. png_debug1(1, "in %s storage function\n", "sBIT");
  192946. if (png_ptr == NULL || info_ptr == NULL)
  192947. return;
  192948. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  192949. info_ptr->valid |= PNG_INFO_sBIT;
  192950. }
  192951. #endif
  192952. #if defined(PNG_sRGB_SUPPORTED)
  192953. void PNGAPI
  192954. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  192955. {
  192956. png_debug1(1, "in %s storage function\n", "sRGB");
  192957. if (png_ptr == NULL || info_ptr == NULL)
  192958. return;
  192959. info_ptr->srgb_intent = (png_byte)intent;
  192960. info_ptr->valid |= PNG_INFO_sRGB;
  192961. }
  192962. void PNGAPI
  192963. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  192964. int intent)
  192965. {
  192966. #if defined(PNG_gAMA_SUPPORTED)
  192967. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192968. float file_gamma;
  192969. #endif
  192970. #ifdef PNG_FIXED_POINT_SUPPORTED
  192971. png_fixed_point int_file_gamma;
  192972. #endif
  192973. #endif
  192974. #if defined(PNG_cHRM_SUPPORTED)
  192975. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192976. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  192977. #endif
  192978. #ifdef PNG_FIXED_POINT_SUPPORTED
  192979. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  192980. int_green_y, int_blue_x, int_blue_y;
  192981. #endif
  192982. #endif
  192983. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  192984. if (png_ptr == NULL || info_ptr == NULL)
  192985. return;
  192986. png_set_sRGB(png_ptr, info_ptr, intent);
  192987. #if defined(PNG_gAMA_SUPPORTED)
  192988. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192989. file_gamma = (float).45455;
  192990. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  192991. #endif
  192992. #ifdef PNG_FIXED_POINT_SUPPORTED
  192993. int_file_gamma = 45455L;
  192994. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  192995. #endif
  192996. #endif
  192997. #if defined(PNG_cHRM_SUPPORTED)
  192998. #ifdef PNG_FIXED_POINT_SUPPORTED
  192999. int_white_x = 31270L;
  193000. int_white_y = 32900L;
  193001. int_red_x = 64000L;
  193002. int_red_y = 33000L;
  193003. int_green_x = 30000L;
  193004. int_green_y = 60000L;
  193005. int_blue_x = 15000L;
  193006. int_blue_y = 6000L;
  193007. png_set_cHRM_fixed(png_ptr, info_ptr,
  193008. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  193009. int_blue_x, int_blue_y);
  193010. #endif
  193011. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193012. white_x = (float).3127;
  193013. white_y = (float).3290;
  193014. red_x = (float).64;
  193015. red_y = (float).33;
  193016. green_x = (float).30;
  193017. green_y = (float).60;
  193018. blue_x = (float).15;
  193019. blue_y = (float).06;
  193020. png_set_cHRM(png_ptr, info_ptr,
  193021. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193022. #endif
  193023. #endif
  193024. }
  193025. #endif
  193026. #if defined(PNG_iCCP_SUPPORTED)
  193027. void PNGAPI
  193028. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  193029. png_charp name, int compression_type,
  193030. png_charp profile, png_uint_32 proflen)
  193031. {
  193032. png_charp new_iccp_name;
  193033. png_charp new_iccp_profile;
  193034. png_debug1(1, "in %s storage function\n", "iCCP");
  193035. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  193036. return;
  193037. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  193038. if (new_iccp_name == NULL)
  193039. {
  193040. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  193041. return;
  193042. }
  193043. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  193044. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  193045. if (new_iccp_profile == NULL)
  193046. {
  193047. png_free (png_ptr, new_iccp_name);
  193048. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  193049. return;
  193050. }
  193051. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  193052. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  193053. info_ptr->iccp_proflen = proflen;
  193054. info_ptr->iccp_name = new_iccp_name;
  193055. info_ptr->iccp_profile = new_iccp_profile;
  193056. /* Compression is always zero but is here so the API and info structure
  193057. * does not have to change if we introduce multiple compression types */
  193058. info_ptr->iccp_compression = (png_byte)compression_type;
  193059. #ifdef PNG_FREE_ME_SUPPORTED
  193060. info_ptr->free_me |= PNG_FREE_ICCP;
  193061. #endif
  193062. info_ptr->valid |= PNG_INFO_iCCP;
  193063. }
  193064. #endif
  193065. #if defined(PNG_TEXT_SUPPORTED)
  193066. void PNGAPI
  193067. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193068. int num_text)
  193069. {
  193070. int ret;
  193071. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  193072. if (ret)
  193073. png_error(png_ptr, "Insufficient memory to store text");
  193074. }
  193075. int /* PRIVATE */
  193076. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193077. int num_text)
  193078. {
  193079. int i;
  193080. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  193081. "text" : (png_const_charp)png_ptr->chunk_name));
  193082. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  193083. return(0);
  193084. /* Make sure we have enough space in the "text" array in info_struct
  193085. * to hold all of the incoming text_ptr objects.
  193086. */
  193087. if (info_ptr->num_text + num_text > info_ptr->max_text)
  193088. {
  193089. if (info_ptr->text != NULL)
  193090. {
  193091. png_textp old_text;
  193092. int old_max;
  193093. old_max = info_ptr->max_text;
  193094. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  193095. old_text = info_ptr->text;
  193096. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193097. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193098. if (info_ptr->text == NULL)
  193099. {
  193100. png_free(png_ptr, old_text);
  193101. return(1);
  193102. }
  193103. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  193104. png_sizeof(png_text)));
  193105. png_free(png_ptr, old_text);
  193106. }
  193107. else
  193108. {
  193109. info_ptr->max_text = num_text + 8;
  193110. info_ptr->num_text = 0;
  193111. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193112. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193113. if (info_ptr->text == NULL)
  193114. return(1);
  193115. #ifdef PNG_FREE_ME_SUPPORTED
  193116. info_ptr->free_me |= PNG_FREE_TEXT;
  193117. #endif
  193118. }
  193119. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  193120. info_ptr->max_text);
  193121. }
  193122. for (i = 0; i < num_text; i++)
  193123. {
  193124. png_size_t text_length,key_len;
  193125. png_size_t lang_len,lang_key_len;
  193126. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  193127. if (text_ptr[i].key == NULL)
  193128. continue;
  193129. key_len = png_strlen(text_ptr[i].key);
  193130. if(text_ptr[i].compression <= 0)
  193131. {
  193132. lang_len = 0;
  193133. lang_key_len = 0;
  193134. }
  193135. else
  193136. #ifdef PNG_iTXt_SUPPORTED
  193137. {
  193138. /* set iTXt data */
  193139. if (text_ptr[i].lang != NULL)
  193140. lang_len = png_strlen(text_ptr[i].lang);
  193141. else
  193142. lang_len = 0;
  193143. if (text_ptr[i].lang_key != NULL)
  193144. lang_key_len = png_strlen(text_ptr[i].lang_key);
  193145. else
  193146. lang_key_len = 0;
  193147. }
  193148. #else
  193149. {
  193150. png_warning(png_ptr, "iTXt chunk not supported.");
  193151. continue;
  193152. }
  193153. #endif
  193154. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  193155. {
  193156. text_length = 0;
  193157. #ifdef PNG_iTXt_SUPPORTED
  193158. if(text_ptr[i].compression > 0)
  193159. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  193160. else
  193161. #endif
  193162. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  193163. }
  193164. else
  193165. {
  193166. text_length = png_strlen(text_ptr[i].text);
  193167. textp->compression = text_ptr[i].compression;
  193168. }
  193169. textp->key = (png_charp)png_malloc_warn(png_ptr,
  193170. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  193171. if (textp->key == NULL)
  193172. return(1);
  193173. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  193174. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  193175. (int)textp->key);
  193176. png_memcpy(textp->key, text_ptr[i].key,
  193177. (png_size_t)(key_len));
  193178. *(textp->key+key_len) = '\0';
  193179. #ifdef PNG_iTXt_SUPPORTED
  193180. if (text_ptr[i].compression > 0)
  193181. {
  193182. textp->lang=textp->key + key_len + 1;
  193183. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  193184. *(textp->lang+lang_len) = '\0';
  193185. textp->lang_key=textp->lang + lang_len + 1;
  193186. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  193187. *(textp->lang_key+lang_key_len) = '\0';
  193188. textp->text=textp->lang_key + lang_key_len + 1;
  193189. }
  193190. else
  193191. #endif
  193192. {
  193193. #ifdef PNG_iTXt_SUPPORTED
  193194. textp->lang=NULL;
  193195. textp->lang_key=NULL;
  193196. #endif
  193197. textp->text=textp->key + key_len + 1;
  193198. }
  193199. if(text_length)
  193200. png_memcpy(textp->text, text_ptr[i].text,
  193201. (png_size_t)(text_length));
  193202. *(textp->text+text_length) = '\0';
  193203. #ifdef PNG_iTXt_SUPPORTED
  193204. if(textp->compression > 0)
  193205. {
  193206. textp->text_length = 0;
  193207. textp->itxt_length = text_length;
  193208. }
  193209. else
  193210. #endif
  193211. {
  193212. textp->text_length = text_length;
  193213. #ifdef PNG_iTXt_SUPPORTED
  193214. textp->itxt_length = 0;
  193215. #endif
  193216. }
  193217. info_ptr->num_text++;
  193218. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  193219. }
  193220. return(0);
  193221. }
  193222. #endif
  193223. #if defined(PNG_tIME_SUPPORTED)
  193224. void PNGAPI
  193225. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  193226. {
  193227. png_debug1(1, "in %s storage function\n", "tIME");
  193228. if (png_ptr == NULL || info_ptr == NULL ||
  193229. (png_ptr->mode & PNG_WROTE_tIME))
  193230. return;
  193231. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  193232. info_ptr->valid |= PNG_INFO_tIME;
  193233. }
  193234. #endif
  193235. #if defined(PNG_tRNS_SUPPORTED)
  193236. void PNGAPI
  193237. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  193238. png_bytep trans, int num_trans, png_color_16p trans_values)
  193239. {
  193240. png_debug1(1, "in %s storage function\n", "tRNS");
  193241. if (png_ptr == NULL || info_ptr == NULL)
  193242. return;
  193243. if (trans != NULL)
  193244. {
  193245. /*
  193246. * It may not actually be necessary to set png_ptr->trans here;
  193247. * we do it for backward compatibility with the way the png_handle_tRNS
  193248. * function used to do the allocation.
  193249. */
  193250. #ifdef PNG_FREE_ME_SUPPORTED
  193251. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  193252. #endif
  193253. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  193254. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  193255. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  193256. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  193257. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  193258. #ifdef PNG_FREE_ME_SUPPORTED
  193259. info_ptr->free_me |= PNG_FREE_TRNS;
  193260. #else
  193261. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  193262. #endif
  193263. }
  193264. if (trans_values != NULL)
  193265. {
  193266. png_memcpy(&(info_ptr->trans_values), trans_values,
  193267. png_sizeof(png_color_16));
  193268. if (num_trans == 0)
  193269. num_trans = 1;
  193270. }
  193271. info_ptr->num_trans = (png_uint_16)num_trans;
  193272. info_ptr->valid |= PNG_INFO_tRNS;
  193273. }
  193274. #endif
  193275. #if defined(PNG_sPLT_SUPPORTED)
  193276. void PNGAPI
  193277. png_set_sPLT(png_structp png_ptr,
  193278. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  193279. {
  193280. png_sPLT_tp np;
  193281. int i;
  193282. if (png_ptr == NULL || info_ptr == NULL)
  193283. return;
  193284. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  193285. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  193286. if (np == NULL)
  193287. {
  193288. png_warning(png_ptr, "No memory for sPLT palettes.");
  193289. return;
  193290. }
  193291. png_memcpy(np, info_ptr->splt_palettes,
  193292. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  193293. png_free(png_ptr, info_ptr->splt_palettes);
  193294. info_ptr->splt_palettes=NULL;
  193295. for (i = 0; i < nentries; i++)
  193296. {
  193297. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  193298. png_sPLT_tp from = entries + i;
  193299. to->name = (png_charp)png_malloc_warn(png_ptr,
  193300. png_strlen(from->name) + 1);
  193301. if (to->name == NULL)
  193302. {
  193303. png_warning(png_ptr,
  193304. "Out of memory while processing sPLT chunk");
  193305. }
  193306. /* TODO: use png_malloc_warn */
  193307. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  193308. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  193309. from->nentries * png_sizeof(png_sPLT_entry));
  193310. /* TODO: use png_malloc_warn */
  193311. png_memcpy(to->entries, from->entries,
  193312. from->nentries * png_sizeof(png_sPLT_entry));
  193313. if (to->entries == NULL)
  193314. {
  193315. png_warning(png_ptr,
  193316. "Out of memory while processing sPLT chunk");
  193317. png_free(png_ptr,to->name);
  193318. to->name = NULL;
  193319. }
  193320. to->nentries = from->nentries;
  193321. to->depth = from->depth;
  193322. }
  193323. info_ptr->splt_palettes = np;
  193324. info_ptr->splt_palettes_num += nentries;
  193325. info_ptr->valid |= PNG_INFO_sPLT;
  193326. #ifdef PNG_FREE_ME_SUPPORTED
  193327. info_ptr->free_me |= PNG_FREE_SPLT;
  193328. #endif
  193329. }
  193330. #endif /* PNG_sPLT_SUPPORTED */
  193331. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193332. void PNGAPI
  193333. png_set_unknown_chunks(png_structp png_ptr,
  193334. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  193335. {
  193336. png_unknown_chunkp np;
  193337. int i;
  193338. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  193339. return;
  193340. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  193341. (info_ptr->unknown_chunks_num + num_unknowns) *
  193342. png_sizeof(png_unknown_chunk));
  193343. if (np == NULL)
  193344. {
  193345. png_warning(png_ptr,
  193346. "Out of memory while processing unknown chunk.");
  193347. return;
  193348. }
  193349. png_memcpy(np, info_ptr->unknown_chunks,
  193350. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  193351. png_free(png_ptr, info_ptr->unknown_chunks);
  193352. info_ptr->unknown_chunks=NULL;
  193353. for (i = 0; i < num_unknowns; i++)
  193354. {
  193355. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  193356. png_unknown_chunkp from = unknowns + i;
  193357. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  193358. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  193359. if (to->data == NULL)
  193360. {
  193361. png_warning(png_ptr,
  193362. "Out of memory while processing unknown chunk.");
  193363. }
  193364. else
  193365. {
  193366. png_memcpy(to->data, from->data, from->size);
  193367. to->size = from->size;
  193368. /* note our location in the read or write sequence */
  193369. to->location = (png_byte)(png_ptr->mode & 0xff);
  193370. }
  193371. }
  193372. info_ptr->unknown_chunks = np;
  193373. info_ptr->unknown_chunks_num += num_unknowns;
  193374. #ifdef PNG_FREE_ME_SUPPORTED
  193375. info_ptr->free_me |= PNG_FREE_UNKN;
  193376. #endif
  193377. }
  193378. void PNGAPI
  193379. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  193380. int chunk, int location)
  193381. {
  193382. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  193383. (int)info_ptr->unknown_chunks_num)
  193384. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  193385. }
  193386. #endif
  193387. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193388. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  193389. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  193390. void PNGAPI
  193391. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  193392. {
  193393. /* This function is deprecated in favor of png_permit_mng_features()
  193394. and will be removed from libpng-1.3.0 */
  193395. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  193396. if (png_ptr == NULL)
  193397. return;
  193398. png_ptr->mng_features_permitted = (png_byte)
  193399. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  193400. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  193401. }
  193402. #endif
  193403. #endif
  193404. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193405. png_uint_32 PNGAPI
  193406. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  193407. {
  193408. png_debug(1, "in png_permit_mng_features\n");
  193409. if (png_ptr == NULL)
  193410. return (png_uint_32)0;
  193411. png_ptr->mng_features_permitted =
  193412. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  193413. return (png_uint_32)png_ptr->mng_features_permitted;
  193414. }
  193415. #endif
  193416. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193417. void PNGAPI
  193418. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  193419. chunk_list, int num_chunks)
  193420. {
  193421. png_bytep new_list, p;
  193422. int i, old_num_chunks;
  193423. if (png_ptr == NULL)
  193424. return;
  193425. if (num_chunks == 0)
  193426. {
  193427. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  193428. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193429. else
  193430. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193431. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  193432. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193433. else
  193434. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193435. return;
  193436. }
  193437. if (chunk_list == NULL)
  193438. return;
  193439. old_num_chunks=png_ptr->num_chunk_list;
  193440. new_list=(png_bytep)png_malloc(png_ptr,
  193441. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  193442. if(png_ptr->chunk_list != NULL)
  193443. {
  193444. png_memcpy(new_list, png_ptr->chunk_list,
  193445. (png_size_t)(5*old_num_chunks));
  193446. png_free(png_ptr, png_ptr->chunk_list);
  193447. png_ptr->chunk_list=NULL;
  193448. }
  193449. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  193450. (png_size_t)(5*num_chunks));
  193451. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  193452. *p=(png_byte)keep;
  193453. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  193454. png_ptr->chunk_list=new_list;
  193455. #ifdef PNG_FREE_ME_SUPPORTED
  193456. png_ptr->free_me |= PNG_FREE_LIST;
  193457. #endif
  193458. }
  193459. #endif
  193460. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193461. void PNGAPI
  193462. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  193463. png_user_chunk_ptr read_user_chunk_fn)
  193464. {
  193465. png_debug(1, "in png_set_read_user_chunk_fn\n");
  193466. if (png_ptr == NULL)
  193467. return;
  193468. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  193469. png_ptr->user_chunk_ptr = user_chunk_ptr;
  193470. }
  193471. #endif
  193472. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193473. void PNGAPI
  193474. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  193475. {
  193476. png_debug1(1, "in %s storage function\n", "rows");
  193477. if (png_ptr == NULL || info_ptr == NULL)
  193478. return;
  193479. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  193480. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  193481. info_ptr->row_pointers = row_pointers;
  193482. if(row_pointers)
  193483. info_ptr->valid |= PNG_INFO_IDAT;
  193484. }
  193485. #endif
  193486. #ifdef PNG_WRITE_SUPPORTED
  193487. void PNGAPI
  193488. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  193489. {
  193490. if (png_ptr == NULL)
  193491. return;
  193492. if(png_ptr->zbuf)
  193493. png_free(png_ptr, png_ptr->zbuf);
  193494. png_ptr->zbuf_size = (png_size_t)size;
  193495. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  193496. png_ptr->zstream.next_out = png_ptr->zbuf;
  193497. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193498. }
  193499. #endif
  193500. void PNGAPI
  193501. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  193502. {
  193503. if (png_ptr && info_ptr)
  193504. info_ptr->valid &= ~(mask);
  193505. }
  193506. #ifndef PNG_1_0_X
  193507. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  193508. /* function was added to libpng 1.2.0 and should always exist by default */
  193509. void PNGAPI
  193510. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  193511. {
  193512. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193513. if (png_ptr != NULL)
  193514. png_ptr->asm_flags = 0;
  193515. }
  193516. /* this function was added to libpng 1.2.0 */
  193517. void PNGAPI
  193518. png_set_mmx_thresholds (png_structp png_ptr,
  193519. png_byte mmx_bitdepth_threshold,
  193520. png_uint_32 mmx_rowbytes_threshold)
  193521. {
  193522. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193523. if (png_ptr == NULL)
  193524. return;
  193525. }
  193526. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  193527. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193528. /* this function was added to libpng 1.2.6 */
  193529. void PNGAPI
  193530. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  193531. png_uint_32 user_height_max)
  193532. {
  193533. /* Images with dimensions larger than these limits will be
  193534. * rejected by png_set_IHDR(). To accept any PNG datastream
  193535. * regardless of dimensions, set both limits to 0x7ffffffL.
  193536. */
  193537. if(png_ptr == NULL) return;
  193538. png_ptr->user_width_max = user_width_max;
  193539. png_ptr->user_height_max = user_height_max;
  193540. }
  193541. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  193542. #endif /* ?PNG_1_0_X */
  193543. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  193544. /********* End of inlined file: pngset.c *********/
  193545. /********* Start of inlined file: pngtrans.c *********/
  193546. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  193547. *
  193548. * Last changed in libpng 1.2.17 May 15, 2007
  193549. * For conditions of distribution and use, see copyright notice in png.h
  193550. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193551. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193552. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193553. */
  193554. #define PNG_INTERNAL
  193555. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193556. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193557. /* turn on BGR-to-RGB mapping */
  193558. void PNGAPI
  193559. png_set_bgr(png_structp png_ptr)
  193560. {
  193561. png_debug(1, "in png_set_bgr\n");
  193562. if(png_ptr == NULL) return;
  193563. png_ptr->transformations |= PNG_BGR;
  193564. }
  193565. #endif
  193566. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193567. /* turn on 16 bit byte swapping */
  193568. void PNGAPI
  193569. png_set_swap(png_structp png_ptr)
  193570. {
  193571. png_debug(1, "in png_set_swap\n");
  193572. if(png_ptr == NULL) return;
  193573. if (png_ptr->bit_depth == 16)
  193574. png_ptr->transformations |= PNG_SWAP_BYTES;
  193575. }
  193576. #endif
  193577. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  193578. /* turn on pixel packing */
  193579. void PNGAPI
  193580. png_set_packing(png_structp png_ptr)
  193581. {
  193582. png_debug(1, "in png_set_packing\n");
  193583. if(png_ptr == NULL) return;
  193584. if (png_ptr->bit_depth < 8)
  193585. {
  193586. png_ptr->transformations |= PNG_PACK;
  193587. png_ptr->usr_bit_depth = 8;
  193588. }
  193589. }
  193590. #endif
  193591. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193592. /* turn on packed pixel swapping */
  193593. void PNGAPI
  193594. png_set_packswap(png_structp png_ptr)
  193595. {
  193596. png_debug(1, "in png_set_packswap\n");
  193597. if(png_ptr == NULL) return;
  193598. if (png_ptr->bit_depth < 8)
  193599. png_ptr->transformations |= PNG_PACKSWAP;
  193600. }
  193601. #endif
  193602. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  193603. void PNGAPI
  193604. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  193605. {
  193606. png_debug(1, "in png_set_shift\n");
  193607. if(png_ptr == NULL) return;
  193608. png_ptr->transformations |= PNG_SHIFT;
  193609. png_ptr->shift = *true_bits;
  193610. }
  193611. #endif
  193612. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  193613. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193614. int PNGAPI
  193615. png_set_interlace_handling(png_structp png_ptr)
  193616. {
  193617. png_debug(1, "in png_set_interlace handling\n");
  193618. if (png_ptr && png_ptr->interlaced)
  193619. {
  193620. png_ptr->transformations |= PNG_INTERLACE;
  193621. return (7);
  193622. }
  193623. return (1);
  193624. }
  193625. #endif
  193626. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  193627. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  193628. * The filler type has changed in v0.95 to allow future 2-byte fillers
  193629. * for 48-bit input data, as well as to avoid problems with some compilers
  193630. * that don't like bytes as parameters.
  193631. */
  193632. void PNGAPI
  193633. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193634. {
  193635. png_debug(1, "in png_set_filler\n");
  193636. if(png_ptr == NULL) return;
  193637. png_ptr->transformations |= PNG_FILLER;
  193638. png_ptr->filler = (png_byte)filler;
  193639. if (filler_loc == PNG_FILLER_AFTER)
  193640. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  193641. else
  193642. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  193643. /* This should probably go in the "do_read_filler" routine.
  193644. * I attempted to do that in libpng-1.0.1a but that caused problems
  193645. * so I restored it in libpng-1.0.2a
  193646. */
  193647. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193648. {
  193649. png_ptr->usr_channels = 4;
  193650. }
  193651. /* Also I added this in libpng-1.0.2a (what happens when we expand
  193652. * a less-than-8-bit grayscale to GA? */
  193653. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  193654. {
  193655. png_ptr->usr_channels = 2;
  193656. }
  193657. }
  193658. #if !defined(PNG_1_0_X)
  193659. /* Added to libpng-1.2.7 */
  193660. void PNGAPI
  193661. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193662. {
  193663. png_debug(1, "in png_set_add_alpha\n");
  193664. if(png_ptr == NULL) return;
  193665. png_set_filler(png_ptr, filler, filler_loc);
  193666. png_ptr->transformations |= PNG_ADD_ALPHA;
  193667. }
  193668. #endif
  193669. #endif
  193670. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  193671. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193672. void PNGAPI
  193673. png_set_swap_alpha(png_structp png_ptr)
  193674. {
  193675. png_debug(1, "in png_set_swap_alpha\n");
  193676. if(png_ptr == NULL) return;
  193677. png_ptr->transformations |= PNG_SWAP_ALPHA;
  193678. }
  193679. #endif
  193680. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  193681. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193682. void PNGAPI
  193683. png_set_invert_alpha(png_structp png_ptr)
  193684. {
  193685. png_debug(1, "in png_set_invert_alpha\n");
  193686. if(png_ptr == NULL) return;
  193687. png_ptr->transformations |= PNG_INVERT_ALPHA;
  193688. }
  193689. #endif
  193690. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  193691. void PNGAPI
  193692. png_set_invert_mono(png_structp png_ptr)
  193693. {
  193694. png_debug(1, "in png_set_invert_mono\n");
  193695. if(png_ptr == NULL) return;
  193696. png_ptr->transformations |= PNG_INVERT_MONO;
  193697. }
  193698. /* invert monochrome grayscale data */
  193699. void /* PRIVATE */
  193700. png_do_invert(png_row_infop row_info, png_bytep row)
  193701. {
  193702. png_debug(1, "in png_do_invert\n");
  193703. /* This test removed from libpng version 1.0.13 and 1.2.0:
  193704. * if (row_info->bit_depth == 1 &&
  193705. */
  193706. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193707. if (row == NULL || row_info == NULL)
  193708. return;
  193709. #endif
  193710. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193711. {
  193712. png_bytep rp = row;
  193713. png_uint_32 i;
  193714. png_uint_32 istop = row_info->rowbytes;
  193715. for (i = 0; i < istop; i++)
  193716. {
  193717. *rp = (png_byte)(~(*rp));
  193718. rp++;
  193719. }
  193720. }
  193721. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193722. row_info->bit_depth == 8)
  193723. {
  193724. png_bytep rp = row;
  193725. png_uint_32 i;
  193726. png_uint_32 istop = row_info->rowbytes;
  193727. for (i = 0; i < istop; i+=2)
  193728. {
  193729. *rp = (png_byte)(~(*rp));
  193730. rp+=2;
  193731. }
  193732. }
  193733. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193734. row_info->bit_depth == 16)
  193735. {
  193736. png_bytep rp = row;
  193737. png_uint_32 i;
  193738. png_uint_32 istop = row_info->rowbytes;
  193739. for (i = 0; i < istop; i+=4)
  193740. {
  193741. *rp = (png_byte)(~(*rp));
  193742. *(rp+1) = (png_byte)(~(*(rp+1)));
  193743. rp+=4;
  193744. }
  193745. }
  193746. }
  193747. #endif
  193748. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193749. /* swaps byte order on 16 bit depth images */
  193750. void /* PRIVATE */
  193751. png_do_swap(png_row_infop row_info, png_bytep row)
  193752. {
  193753. png_debug(1, "in png_do_swap\n");
  193754. if (
  193755. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193756. row != NULL && row_info != NULL &&
  193757. #endif
  193758. row_info->bit_depth == 16)
  193759. {
  193760. png_bytep rp = row;
  193761. png_uint_32 i;
  193762. png_uint_32 istop= row_info->width * row_info->channels;
  193763. for (i = 0; i < istop; i++, rp += 2)
  193764. {
  193765. png_byte t = *rp;
  193766. *rp = *(rp + 1);
  193767. *(rp + 1) = t;
  193768. }
  193769. }
  193770. }
  193771. #endif
  193772. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193773. static PNG_CONST png_byte onebppswaptable[256] = {
  193774. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  193775. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  193776. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  193777. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  193778. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  193779. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  193780. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  193781. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  193782. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  193783. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  193784. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  193785. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  193786. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  193787. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  193788. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  193789. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  193790. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  193791. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  193792. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  193793. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  193794. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  193795. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  193796. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  193797. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  193798. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  193799. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  193800. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  193801. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  193802. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  193803. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  193804. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  193805. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  193806. };
  193807. static PNG_CONST png_byte twobppswaptable[256] = {
  193808. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  193809. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  193810. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  193811. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  193812. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  193813. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  193814. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  193815. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  193816. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  193817. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  193818. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  193819. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  193820. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  193821. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  193822. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  193823. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  193824. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  193825. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  193826. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  193827. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  193828. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  193829. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  193830. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  193831. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  193832. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  193833. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  193834. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  193835. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  193836. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  193837. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  193838. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  193839. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  193840. };
  193841. static PNG_CONST png_byte fourbppswaptable[256] = {
  193842. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  193843. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  193844. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  193845. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  193846. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  193847. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  193848. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  193849. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  193850. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  193851. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  193852. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  193853. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  193854. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  193855. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  193856. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  193857. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  193858. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  193859. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  193860. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  193861. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  193862. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  193863. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  193864. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  193865. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  193866. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  193867. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  193868. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  193869. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  193870. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  193871. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  193872. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  193873. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  193874. };
  193875. /* swaps pixel packing order within bytes */
  193876. void /* PRIVATE */
  193877. png_do_packswap(png_row_infop row_info, png_bytep row)
  193878. {
  193879. png_debug(1, "in png_do_packswap\n");
  193880. if (
  193881. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193882. row != NULL && row_info != NULL &&
  193883. #endif
  193884. row_info->bit_depth < 8)
  193885. {
  193886. png_bytep rp, end, table;
  193887. end = row + row_info->rowbytes;
  193888. if (row_info->bit_depth == 1)
  193889. table = (png_bytep)onebppswaptable;
  193890. else if (row_info->bit_depth == 2)
  193891. table = (png_bytep)twobppswaptable;
  193892. else if (row_info->bit_depth == 4)
  193893. table = (png_bytep)fourbppswaptable;
  193894. else
  193895. return;
  193896. for (rp = row; rp < end; rp++)
  193897. *rp = table[*rp];
  193898. }
  193899. }
  193900. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  193901. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  193902. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  193903. /* remove filler or alpha byte(s) */
  193904. void /* PRIVATE */
  193905. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  193906. {
  193907. png_debug(1, "in png_do_strip_filler\n");
  193908. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193909. if (row != NULL && row_info != NULL)
  193910. #endif
  193911. {
  193912. png_bytep sp=row;
  193913. png_bytep dp=row;
  193914. png_uint_32 row_width=row_info->width;
  193915. png_uint_32 i;
  193916. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  193917. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193918. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193919. row_info->channels == 4)
  193920. {
  193921. if (row_info->bit_depth == 8)
  193922. {
  193923. /* This converts from RGBX or RGBA to RGB */
  193924. if (flags & PNG_FLAG_FILLER_AFTER)
  193925. {
  193926. dp+=3; sp+=4;
  193927. for (i = 1; i < row_width; i++)
  193928. {
  193929. *dp++ = *sp++;
  193930. *dp++ = *sp++;
  193931. *dp++ = *sp++;
  193932. sp++;
  193933. }
  193934. }
  193935. /* This converts from XRGB or ARGB to RGB */
  193936. else
  193937. {
  193938. for (i = 0; i < row_width; i++)
  193939. {
  193940. sp++;
  193941. *dp++ = *sp++;
  193942. *dp++ = *sp++;
  193943. *dp++ = *sp++;
  193944. }
  193945. }
  193946. row_info->pixel_depth = 24;
  193947. row_info->rowbytes = row_width * 3;
  193948. }
  193949. else /* if (row_info->bit_depth == 16) */
  193950. {
  193951. if (flags & PNG_FLAG_FILLER_AFTER)
  193952. {
  193953. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  193954. sp += 8; dp += 6;
  193955. for (i = 1; i < row_width; i++)
  193956. {
  193957. /* This could be (although png_memcpy is probably slower):
  193958. png_memcpy(dp, sp, 6);
  193959. sp += 8;
  193960. dp += 6;
  193961. */
  193962. *dp++ = *sp++;
  193963. *dp++ = *sp++;
  193964. *dp++ = *sp++;
  193965. *dp++ = *sp++;
  193966. *dp++ = *sp++;
  193967. *dp++ = *sp++;
  193968. sp += 2;
  193969. }
  193970. }
  193971. else
  193972. {
  193973. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  193974. for (i = 0; i < row_width; i++)
  193975. {
  193976. /* This could be (although png_memcpy is probably slower):
  193977. png_memcpy(dp, sp, 6);
  193978. sp += 8;
  193979. dp += 6;
  193980. */
  193981. sp+=2;
  193982. *dp++ = *sp++;
  193983. *dp++ = *sp++;
  193984. *dp++ = *sp++;
  193985. *dp++ = *sp++;
  193986. *dp++ = *sp++;
  193987. *dp++ = *sp++;
  193988. }
  193989. }
  193990. row_info->pixel_depth = 48;
  193991. row_info->rowbytes = row_width * 6;
  193992. }
  193993. row_info->channels = 3;
  193994. }
  193995. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  193996. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193997. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193998. row_info->channels == 2)
  193999. {
  194000. if (row_info->bit_depth == 8)
  194001. {
  194002. /* This converts from GX or GA to G */
  194003. if (flags & PNG_FLAG_FILLER_AFTER)
  194004. {
  194005. for (i = 0; i < row_width; i++)
  194006. {
  194007. *dp++ = *sp++;
  194008. sp++;
  194009. }
  194010. }
  194011. /* This converts from XG or AG to G */
  194012. else
  194013. {
  194014. for (i = 0; i < row_width; i++)
  194015. {
  194016. sp++;
  194017. *dp++ = *sp++;
  194018. }
  194019. }
  194020. row_info->pixel_depth = 8;
  194021. row_info->rowbytes = row_width;
  194022. }
  194023. else /* if (row_info->bit_depth == 16) */
  194024. {
  194025. if (flags & PNG_FLAG_FILLER_AFTER)
  194026. {
  194027. /* This converts from GGXX or GGAA to GG */
  194028. sp += 4; dp += 2;
  194029. for (i = 1; i < row_width; i++)
  194030. {
  194031. *dp++ = *sp++;
  194032. *dp++ = *sp++;
  194033. sp += 2;
  194034. }
  194035. }
  194036. else
  194037. {
  194038. /* This converts from XXGG or AAGG to GG */
  194039. for (i = 0; i < row_width; i++)
  194040. {
  194041. sp += 2;
  194042. *dp++ = *sp++;
  194043. *dp++ = *sp++;
  194044. }
  194045. }
  194046. row_info->pixel_depth = 16;
  194047. row_info->rowbytes = row_width * 2;
  194048. }
  194049. row_info->channels = 1;
  194050. }
  194051. if (flags & PNG_FLAG_STRIP_ALPHA)
  194052. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  194053. }
  194054. }
  194055. #endif
  194056. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194057. /* swaps red and blue bytes within a pixel */
  194058. void /* PRIVATE */
  194059. png_do_bgr(png_row_infop row_info, png_bytep row)
  194060. {
  194061. png_debug(1, "in png_do_bgr\n");
  194062. if (
  194063. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194064. row != NULL && row_info != NULL &&
  194065. #endif
  194066. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194067. {
  194068. png_uint_32 row_width = row_info->width;
  194069. if (row_info->bit_depth == 8)
  194070. {
  194071. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194072. {
  194073. png_bytep rp;
  194074. png_uint_32 i;
  194075. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  194076. {
  194077. png_byte save = *rp;
  194078. *rp = *(rp + 2);
  194079. *(rp + 2) = save;
  194080. }
  194081. }
  194082. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194083. {
  194084. png_bytep rp;
  194085. png_uint_32 i;
  194086. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  194087. {
  194088. png_byte save = *rp;
  194089. *rp = *(rp + 2);
  194090. *(rp + 2) = save;
  194091. }
  194092. }
  194093. }
  194094. else if (row_info->bit_depth == 16)
  194095. {
  194096. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194097. {
  194098. png_bytep rp;
  194099. png_uint_32 i;
  194100. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  194101. {
  194102. png_byte save = *rp;
  194103. *rp = *(rp + 4);
  194104. *(rp + 4) = save;
  194105. save = *(rp + 1);
  194106. *(rp + 1) = *(rp + 5);
  194107. *(rp + 5) = save;
  194108. }
  194109. }
  194110. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194111. {
  194112. png_bytep rp;
  194113. png_uint_32 i;
  194114. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  194115. {
  194116. png_byte save = *rp;
  194117. *rp = *(rp + 4);
  194118. *(rp + 4) = save;
  194119. save = *(rp + 1);
  194120. *(rp + 1) = *(rp + 5);
  194121. *(rp + 5) = save;
  194122. }
  194123. }
  194124. }
  194125. }
  194126. }
  194127. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  194128. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  194129. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  194130. defined(PNG_LEGACY_SUPPORTED)
  194131. void PNGAPI
  194132. png_set_user_transform_info(png_structp png_ptr, png_voidp
  194133. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  194134. {
  194135. png_debug(1, "in png_set_user_transform_info\n");
  194136. if(png_ptr == NULL) return;
  194137. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194138. png_ptr->user_transform_ptr = user_transform_ptr;
  194139. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  194140. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  194141. #else
  194142. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  194143. png_warning(png_ptr,
  194144. "This version of libpng does not support user transform info");
  194145. #endif
  194146. }
  194147. #endif
  194148. /* This function returns a pointer to the user_transform_ptr associated with
  194149. * the user transform functions. The application should free any memory
  194150. * associated with this pointer before png_write_destroy and png_read_destroy
  194151. * are called.
  194152. */
  194153. png_voidp PNGAPI
  194154. png_get_user_transform_ptr(png_structp png_ptr)
  194155. {
  194156. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194157. if (png_ptr == NULL) return (NULL);
  194158. return ((png_voidp)png_ptr->user_transform_ptr);
  194159. #else
  194160. return (NULL);
  194161. #endif
  194162. }
  194163. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194164. /********* End of inlined file: pngtrans.c *********/
  194165. /********* Start of inlined file: pngwio.c *********/
  194166. /* pngwio.c - functions for data output
  194167. *
  194168. * Last changed in libpng 1.2.13 November 13, 2006
  194169. * For conditions of distribution and use, see copyright notice in png.h
  194170. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194171. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194172. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194173. *
  194174. * This file provides a location for all output. Users who need
  194175. * special handling are expected to write functions that have the same
  194176. * arguments as these and perform similar functions, but that possibly
  194177. * use different output methods. Note that you shouldn't change these
  194178. * functions, but rather write replacement functions and then change
  194179. * them at run time with png_set_write_fn(...).
  194180. */
  194181. #define PNG_INTERNAL
  194182. #ifdef PNG_WRITE_SUPPORTED
  194183. /* Write the data to whatever output you are using. The default routine
  194184. writes to a file pointer. Note that this routine sometimes gets called
  194185. with very small lengths, so you should implement some kind of simple
  194186. buffering if you are using unbuffered writes. This should never be asked
  194187. to write more than 64K on a 16 bit machine. */
  194188. void /* PRIVATE */
  194189. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194190. {
  194191. if (png_ptr->write_data_fn != NULL )
  194192. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  194193. else
  194194. png_error(png_ptr, "Call to NULL write function");
  194195. }
  194196. #if !defined(PNG_NO_STDIO)
  194197. /* This is the function that does the actual writing of data. If you are
  194198. not writing to a standard C stream, you should create a replacement
  194199. write_data function and use it at run time with png_set_write_fn(), rather
  194200. than changing the library. */
  194201. #ifndef USE_FAR_KEYWORD
  194202. void PNGAPI
  194203. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194204. {
  194205. png_uint_32 check;
  194206. if(png_ptr == NULL) return;
  194207. #if defined(_WIN32_WCE)
  194208. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  194209. check = 0;
  194210. #else
  194211. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  194212. #endif
  194213. if (check != length)
  194214. png_error(png_ptr, "Write Error");
  194215. }
  194216. #else
  194217. /* this is the model-independent version. Since the standard I/O library
  194218. can't handle far buffers in the medium and small models, we have to copy
  194219. the data.
  194220. */
  194221. #define NEAR_BUF_SIZE 1024
  194222. #define MIN(a,b) (a <= b ? a : b)
  194223. void PNGAPI
  194224. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194225. {
  194226. png_uint_32 check;
  194227. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  194228. png_FILE_p io_ptr;
  194229. if(png_ptr == NULL) return;
  194230. /* Check if data really is near. If so, use usual code. */
  194231. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  194232. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  194233. if ((png_bytep)near_data == data)
  194234. {
  194235. #if defined(_WIN32_WCE)
  194236. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  194237. check = 0;
  194238. #else
  194239. check = fwrite(near_data, 1, length, io_ptr);
  194240. #endif
  194241. }
  194242. else
  194243. {
  194244. png_byte buf[NEAR_BUF_SIZE];
  194245. png_size_t written, remaining, err;
  194246. check = 0;
  194247. remaining = length;
  194248. do
  194249. {
  194250. written = MIN(NEAR_BUF_SIZE, remaining);
  194251. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  194252. #if defined(_WIN32_WCE)
  194253. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  194254. err = 0;
  194255. #else
  194256. err = fwrite(buf, 1, written, io_ptr);
  194257. #endif
  194258. if (err != written)
  194259. break;
  194260. else
  194261. check += err;
  194262. data += written;
  194263. remaining -= written;
  194264. }
  194265. while (remaining != 0);
  194266. }
  194267. if (check != length)
  194268. png_error(png_ptr, "Write Error");
  194269. }
  194270. #endif
  194271. #endif
  194272. /* This function is called to output any data pending writing (normally
  194273. to disk). After png_flush is called, there should be no data pending
  194274. writing in any buffers. */
  194275. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194276. void /* PRIVATE */
  194277. png_flush(png_structp png_ptr)
  194278. {
  194279. if (png_ptr->output_flush_fn != NULL)
  194280. (*(png_ptr->output_flush_fn))(png_ptr);
  194281. }
  194282. #if !defined(PNG_NO_STDIO)
  194283. void PNGAPI
  194284. png_default_flush(png_structp png_ptr)
  194285. {
  194286. #if !defined(_WIN32_WCE)
  194287. png_FILE_p io_ptr;
  194288. #endif
  194289. if(png_ptr == NULL) return;
  194290. #if !defined(_WIN32_WCE)
  194291. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  194292. if (io_ptr != NULL)
  194293. fflush(io_ptr);
  194294. #endif
  194295. }
  194296. #endif
  194297. #endif
  194298. /* This function allows the application to supply new output functions for
  194299. libpng if standard C streams aren't being used.
  194300. This function takes as its arguments:
  194301. png_ptr - pointer to a png output data structure
  194302. io_ptr - pointer to user supplied structure containing info about
  194303. the output functions. May be NULL.
  194304. write_data_fn - pointer to a new output function that takes as its
  194305. arguments a pointer to a png_struct, a pointer to
  194306. data to be written, and a 32-bit unsigned int that is
  194307. the number of bytes to be written. The new write
  194308. function should call png_error(png_ptr, "Error msg")
  194309. to exit and output any fatal error messages.
  194310. flush_data_fn - pointer to a new flush function that takes as its
  194311. arguments a pointer to a png_struct. After a call to
  194312. the flush function, there should be no data in any buffers
  194313. or pending transmission. If the output method doesn't do
  194314. any buffering of ouput, a function prototype must still be
  194315. supplied although it doesn't have to do anything. If
  194316. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  194317. time, output_flush_fn will be ignored, although it must be
  194318. supplied for compatibility. */
  194319. void PNGAPI
  194320. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  194321. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  194322. {
  194323. if(png_ptr == NULL) return;
  194324. png_ptr->io_ptr = io_ptr;
  194325. #if !defined(PNG_NO_STDIO)
  194326. if (write_data_fn != NULL)
  194327. png_ptr->write_data_fn = write_data_fn;
  194328. else
  194329. png_ptr->write_data_fn = png_default_write_data;
  194330. #else
  194331. png_ptr->write_data_fn = write_data_fn;
  194332. #endif
  194333. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194334. #if !defined(PNG_NO_STDIO)
  194335. if (output_flush_fn != NULL)
  194336. png_ptr->output_flush_fn = output_flush_fn;
  194337. else
  194338. png_ptr->output_flush_fn = png_default_flush;
  194339. #else
  194340. png_ptr->output_flush_fn = output_flush_fn;
  194341. #endif
  194342. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  194343. /* It is an error to read while writing a png file */
  194344. if (png_ptr->read_data_fn != NULL)
  194345. {
  194346. png_ptr->read_data_fn = NULL;
  194347. png_warning(png_ptr,
  194348. "Attempted to set both read_data_fn and write_data_fn in");
  194349. png_warning(png_ptr,
  194350. "the same structure. Resetting read_data_fn to NULL.");
  194351. }
  194352. }
  194353. #if defined(USE_FAR_KEYWORD)
  194354. #if defined(_MSC_VER)
  194355. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194356. {
  194357. void *near_ptr;
  194358. void FAR *far_ptr;
  194359. FP_OFF(near_ptr) = FP_OFF(ptr);
  194360. far_ptr = (void FAR *)near_ptr;
  194361. if(check != 0)
  194362. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  194363. png_error(png_ptr,"segment lost in conversion");
  194364. return(near_ptr);
  194365. }
  194366. # else
  194367. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194368. {
  194369. void *near_ptr;
  194370. void FAR *far_ptr;
  194371. near_ptr = (void FAR *)ptr;
  194372. far_ptr = (void FAR *)near_ptr;
  194373. if(check != 0)
  194374. if(far_ptr != ptr)
  194375. png_error(png_ptr,"segment lost in conversion");
  194376. return(near_ptr);
  194377. }
  194378. # endif
  194379. # endif
  194380. #endif /* PNG_WRITE_SUPPORTED */
  194381. /********* End of inlined file: pngwio.c *********/
  194382. /********* Start of inlined file: pngwrite.c *********/
  194383. /* pngwrite.c - general routines to write a PNG file
  194384. *
  194385. * Last changed in libpng 1.2.15 January 5, 2007
  194386. * For conditions of distribution and use, see copyright notice in png.h
  194387. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194388. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194389. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194390. */
  194391. /* get internal access to png.h */
  194392. #define PNG_INTERNAL
  194393. #ifdef PNG_WRITE_SUPPORTED
  194394. /* Writes all the PNG information. This is the suggested way to use the
  194395. * library. If you have a new chunk to add, make a function to write it,
  194396. * and put it in the correct location here. If you want the chunk written
  194397. * after the image data, put it in png_write_end(). I strongly encourage
  194398. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  194399. * the chunk, as that will keep the code from breaking if you want to just
  194400. * write a plain PNG file. If you have long comments, I suggest writing
  194401. * them in png_write_end(), and compressing them.
  194402. */
  194403. void PNGAPI
  194404. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  194405. {
  194406. png_debug(1, "in png_write_info_before_PLTE\n");
  194407. if (png_ptr == NULL || info_ptr == NULL)
  194408. return;
  194409. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194410. {
  194411. png_write_sig(png_ptr); /* write PNG signature */
  194412. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194413. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  194414. {
  194415. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  194416. png_ptr->mng_features_permitted=0;
  194417. }
  194418. #endif
  194419. /* write IHDR information. */
  194420. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  194421. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  194422. info_ptr->filter_type,
  194423. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194424. info_ptr->interlace_type);
  194425. #else
  194426. 0);
  194427. #endif
  194428. /* the rest of these check to see if the valid field has the appropriate
  194429. flag set, and if it does, writes the chunk. */
  194430. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  194431. if (info_ptr->valid & PNG_INFO_gAMA)
  194432. {
  194433. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194434. png_write_gAMA(png_ptr, info_ptr->gamma);
  194435. #else
  194436. #ifdef PNG_FIXED_POINT_SUPPORTED
  194437. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  194438. # endif
  194439. #endif
  194440. }
  194441. #endif
  194442. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  194443. if (info_ptr->valid & PNG_INFO_sRGB)
  194444. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  194445. #endif
  194446. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  194447. if (info_ptr->valid & PNG_INFO_iCCP)
  194448. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  194449. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  194450. #endif
  194451. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  194452. if (info_ptr->valid & PNG_INFO_sBIT)
  194453. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  194454. #endif
  194455. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  194456. if (info_ptr->valid & PNG_INFO_cHRM)
  194457. {
  194458. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194459. png_write_cHRM(png_ptr,
  194460. info_ptr->x_white, info_ptr->y_white,
  194461. info_ptr->x_red, info_ptr->y_red,
  194462. info_ptr->x_green, info_ptr->y_green,
  194463. info_ptr->x_blue, info_ptr->y_blue);
  194464. #else
  194465. # ifdef PNG_FIXED_POINT_SUPPORTED
  194466. png_write_cHRM_fixed(png_ptr,
  194467. info_ptr->int_x_white, info_ptr->int_y_white,
  194468. info_ptr->int_x_red, info_ptr->int_y_red,
  194469. info_ptr->int_x_green, info_ptr->int_y_green,
  194470. info_ptr->int_x_blue, info_ptr->int_y_blue);
  194471. # endif
  194472. #endif
  194473. }
  194474. #endif
  194475. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194476. if (info_ptr->unknown_chunks_num)
  194477. {
  194478. png_unknown_chunk *up;
  194479. png_debug(5, "writing extra chunks\n");
  194480. for (up = info_ptr->unknown_chunks;
  194481. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194482. up++)
  194483. {
  194484. int keep=png_handle_as_unknown(png_ptr, up->name);
  194485. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194486. up->location && !(up->location & PNG_HAVE_PLTE) &&
  194487. !(up->location & PNG_HAVE_IDAT) &&
  194488. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194489. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194490. {
  194491. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194492. }
  194493. }
  194494. }
  194495. #endif
  194496. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  194497. }
  194498. }
  194499. void PNGAPI
  194500. png_write_info(png_structp png_ptr, png_infop info_ptr)
  194501. {
  194502. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  194503. int i;
  194504. #endif
  194505. png_debug(1, "in png_write_info\n");
  194506. if (png_ptr == NULL || info_ptr == NULL)
  194507. return;
  194508. png_write_info_before_PLTE(png_ptr, info_ptr);
  194509. if (info_ptr->valid & PNG_INFO_PLTE)
  194510. png_write_PLTE(png_ptr, info_ptr->palette,
  194511. (png_uint_32)info_ptr->num_palette);
  194512. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194513. png_error(png_ptr, "Valid palette required for paletted images");
  194514. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  194515. if (info_ptr->valid & PNG_INFO_tRNS)
  194516. {
  194517. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194518. /* invert the alpha channel (in tRNS) */
  194519. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  194520. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194521. {
  194522. int j;
  194523. for (j=0; j<(int)info_ptr->num_trans; j++)
  194524. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  194525. }
  194526. #endif
  194527. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  194528. info_ptr->num_trans, info_ptr->color_type);
  194529. }
  194530. #endif
  194531. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  194532. if (info_ptr->valid & PNG_INFO_bKGD)
  194533. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  194534. #endif
  194535. #if defined(PNG_WRITE_hIST_SUPPORTED)
  194536. if (info_ptr->valid & PNG_INFO_hIST)
  194537. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  194538. #endif
  194539. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  194540. if (info_ptr->valid & PNG_INFO_oFFs)
  194541. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  194542. info_ptr->offset_unit_type);
  194543. #endif
  194544. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  194545. if (info_ptr->valid & PNG_INFO_pCAL)
  194546. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  194547. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  194548. info_ptr->pcal_units, info_ptr->pcal_params);
  194549. #endif
  194550. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  194551. if (info_ptr->valid & PNG_INFO_sCAL)
  194552. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  194553. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  194554. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  194555. #else
  194556. #ifdef PNG_FIXED_POINT_SUPPORTED
  194557. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  194558. info_ptr->scal_s_width, info_ptr->scal_s_height);
  194559. #else
  194560. png_warning(png_ptr,
  194561. "png_write_sCAL not supported; sCAL chunk not written.");
  194562. #endif
  194563. #endif
  194564. #endif
  194565. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  194566. if (info_ptr->valid & PNG_INFO_pHYs)
  194567. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  194568. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  194569. #endif
  194570. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194571. if (info_ptr->valid & PNG_INFO_tIME)
  194572. {
  194573. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194574. png_ptr->mode |= PNG_WROTE_tIME;
  194575. }
  194576. #endif
  194577. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  194578. if (info_ptr->valid & PNG_INFO_sPLT)
  194579. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  194580. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  194581. #endif
  194582. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194583. /* Check to see if we need to write text chunks */
  194584. for (i = 0; i < info_ptr->num_text; i++)
  194585. {
  194586. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  194587. info_ptr->text[i].compression);
  194588. /* an internationalized chunk? */
  194589. if (info_ptr->text[i].compression > 0)
  194590. {
  194591. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194592. /* write international chunk */
  194593. png_write_iTXt(png_ptr,
  194594. info_ptr->text[i].compression,
  194595. info_ptr->text[i].key,
  194596. info_ptr->text[i].lang,
  194597. info_ptr->text[i].lang_key,
  194598. info_ptr->text[i].text);
  194599. #else
  194600. png_warning(png_ptr, "Unable to write international text");
  194601. #endif
  194602. /* Mark this chunk as written */
  194603. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194604. }
  194605. /* If we want a compressed text chunk */
  194606. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  194607. {
  194608. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194609. /* write compressed chunk */
  194610. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194611. info_ptr->text[i].text, 0,
  194612. info_ptr->text[i].compression);
  194613. #else
  194614. png_warning(png_ptr, "Unable to write compressed text");
  194615. #endif
  194616. /* Mark this chunk as written */
  194617. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194618. }
  194619. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194620. {
  194621. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194622. /* write uncompressed chunk */
  194623. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194624. info_ptr->text[i].text,
  194625. 0);
  194626. #else
  194627. png_warning(png_ptr, "Unable to write uncompressed text");
  194628. #endif
  194629. /* Mark this chunk as written */
  194630. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194631. }
  194632. }
  194633. #endif
  194634. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194635. if (info_ptr->unknown_chunks_num)
  194636. {
  194637. png_unknown_chunk *up;
  194638. png_debug(5, "writing extra chunks\n");
  194639. for (up = info_ptr->unknown_chunks;
  194640. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194641. up++)
  194642. {
  194643. int keep=png_handle_as_unknown(png_ptr, up->name);
  194644. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194645. up->location && (up->location & PNG_HAVE_PLTE) &&
  194646. !(up->location & PNG_HAVE_IDAT) &&
  194647. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194648. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194649. {
  194650. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194651. }
  194652. }
  194653. }
  194654. #endif
  194655. }
  194656. /* Writes the end of the PNG file. If you don't want to write comments or
  194657. * time information, you can pass NULL for info. If you already wrote these
  194658. * in png_write_info(), do not write them again here. If you have long
  194659. * comments, I suggest writing them here, and compressing them.
  194660. */
  194661. void PNGAPI
  194662. png_write_end(png_structp png_ptr, png_infop info_ptr)
  194663. {
  194664. png_debug(1, "in png_write_end\n");
  194665. if (png_ptr == NULL)
  194666. return;
  194667. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  194668. png_error(png_ptr, "No IDATs written into file");
  194669. /* see if user wants us to write information chunks */
  194670. if (info_ptr != NULL)
  194671. {
  194672. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194673. int i; /* local index variable */
  194674. #endif
  194675. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194676. /* check to see if user has supplied a time chunk */
  194677. if ((info_ptr->valid & PNG_INFO_tIME) &&
  194678. !(png_ptr->mode & PNG_WROTE_tIME))
  194679. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194680. #endif
  194681. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194682. /* loop through comment chunks */
  194683. for (i = 0; i < info_ptr->num_text; i++)
  194684. {
  194685. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  194686. info_ptr->text[i].compression);
  194687. /* an internationalized chunk? */
  194688. if (info_ptr->text[i].compression > 0)
  194689. {
  194690. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194691. /* write international chunk */
  194692. png_write_iTXt(png_ptr,
  194693. info_ptr->text[i].compression,
  194694. info_ptr->text[i].key,
  194695. info_ptr->text[i].lang,
  194696. info_ptr->text[i].lang_key,
  194697. info_ptr->text[i].text);
  194698. #else
  194699. png_warning(png_ptr, "Unable to write international text");
  194700. #endif
  194701. /* Mark this chunk as written */
  194702. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194703. }
  194704. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  194705. {
  194706. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194707. /* write compressed chunk */
  194708. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194709. info_ptr->text[i].text, 0,
  194710. info_ptr->text[i].compression);
  194711. #else
  194712. png_warning(png_ptr, "Unable to write compressed text");
  194713. #endif
  194714. /* Mark this chunk as written */
  194715. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194716. }
  194717. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194718. {
  194719. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194720. /* write uncompressed chunk */
  194721. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194722. info_ptr->text[i].text, 0);
  194723. #else
  194724. png_warning(png_ptr, "Unable to write uncompressed text");
  194725. #endif
  194726. /* Mark this chunk as written */
  194727. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194728. }
  194729. }
  194730. #endif
  194731. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194732. if (info_ptr->unknown_chunks_num)
  194733. {
  194734. png_unknown_chunk *up;
  194735. png_debug(5, "writing extra chunks\n");
  194736. for (up = info_ptr->unknown_chunks;
  194737. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194738. up++)
  194739. {
  194740. int keep=png_handle_as_unknown(png_ptr, up->name);
  194741. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194742. up->location && (up->location & PNG_AFTER_IDAT) &&
  194743. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194744. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194745. {
  194746. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194747. }
  194748. }
  194749. }
  194750. #endif
  194751. }
  194752. png_ptr->mode |= PNG_AFTER_IDAT;
  194753. /* write end of PNG file */
  194754. png_write_IEND(png_ptr);
  194755. }
  194756. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194757. #if !defined(_WIN32_WCE)
  194758. /* "time.h" functions are not supported on WindowsCE */
  194759. void PNGAPI
  194760. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  194761. {
  194762. png_debug(1, "in png_convert_from_struct_tm\n");
  194763. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  194764. ptime->month = (png_byte)(ttime->tm_mon + 1);
  194765. ptime->day = (png_byte)ttime->tm_mday;
  194766. ptime->hour = (png_byte)ttime->tm_hour;
  194767. ptime->minute = (png_byte)ttime->tm_min;
  194768. ptime->second = (png_byte)ttime->tm_sec;
  194769. }
  194770. void PNGAPI
  194771. png_convert_from_time_t(png_timep ptime, time_t ttime)
  194772. {
  194773. struct tm *tbuf;
  194774. png_debug(1, "in png_convert_from_time_t\n");
  194775. tbuf = gmtime(&ttime);
  194776. png_convert_from_struct_tm(ptime, tbuf);
  194777. }
  194778. #endif
  194779. #endif
  194780. /* Initialize png_ptr structure, and allocate any memory needed */
  194781. png_structp PNGAPI
  194782. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  194783. png_error_ptr error_fn, png_error_ptr warn_fn)
  194784. {
  194785. #ifdef PNG_USER_MEM_SUPPORTED
  194786. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  194787. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  194788. }
  194789. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  194790. png_structp PNGAPI
  194791. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  194792. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  194793. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  194794. {
  194795. #endif /* PNG_USER_MEM_SUPPORTED */
  194796. png_structp png_ptr;
  194797. #ifdef PNG_SETJMP_SUPPORTED
  194798. #ifdef USE_FAR_KEYWORD
  194799. jmp_buf jmpbuf;
  194800. #endif
  194801. #endif
  194802. int i;
  194803. png_debug(1, "in png_create_write_struct\n");
  194804. #ifdef PNG_USER_MEM_SUPPORTED
  194805. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  194806. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  194807. #else
  194808. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194809. #endif /* PNG_USER_MEM_SUPPORTED */
  194810. if (png_ptr == NULL)
  194811. return (NULL);
  194812. /* added at libpng-1.2.6 */
  194813. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194814. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194815. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194816. #endif
  194817. #ifdef PNG_SETJMP_SUPPORTED
  194818. #ifdef USE_FAR_KEYWORD
  194819. if (setjmp(jmpbuf))
  194820. #else
  194821. if (setjmp(png_ptr->jmpbuf))
  194822. #endif
  194823. {
  194824. png_free(png_ptr, png_ptr->zbuf);
  194825. png_ptr->zbuf=NULL;
  194826. png_destroy_struct(png_ptr);
  194827. return (NULL);
  194828. }
  194829. #ifdef USE_FAR_KEYWORD
  194830. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194831. #endif
  194832. #endif
  194833. #ifdef PNG_USER_MEM_SUPPORTED
  194834. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  194835. #endif /* PNG_USER_MEM_SUPPORTED */
  194836. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  194837. i=0;
  194838. do
  194839. {
  194840. if(user_png_ver[i] != png_libpng_ver[i])
  194841. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194842. } while (png_libpng_ver[i++]);
  194843. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  194844. {
  194845. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  194846. * we must recompile any applications that use any older library version.
  194847. * For versions after libpng 1.0, we will be compatible, so we need
  194848. * only check the first digit.
  194849. */
  194850. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  194851. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  194852. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  194853. {
  194854. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194855. char msg[80];
  194856. if (user_png_ver)
  194857. {
  194858. png_snprintf(msg, 80,
  194859. "Application was compiled with png.h from libpng-%.20s",
  194860. user_png_ver);
  194861. png_warning(png_ptr, msg);
  194862. }
  194863. png_snprintf(msg, 80,
  194864. "Application is running with png.c from libpng-%.20s",
  194865. png_libpng_ver);
  194866. png_warning(png_ptr, msg);
  194867. #endif
  194868. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194869. png_ptr->flags=0;
  194870. #endif
  194871. png_error(png_ptr,
  194872. "Incompatible libpng version in application and library");
  194873. }
  194874. }
  194875. /* initialize zbuf - compression buffer */
  194876. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194877. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194878. (png_uint_32)png_ptr->zbuf_size);
  194879. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194880. png_flush_ptr_NULL);
  194881. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194882. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194883. 1, png_doublep_NULL, png_doublep_NULL);
  194884. #endif
  194885. #ifdef PNG_SETJMP_SUPPORTED
  194886. /* Applications that neglect to set up their own setjmp() and then encounter
  194887. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  194888. abort instead of returning. */
  194889. #ifdef USE_FAR_KEYWORD
  194890. if (setjmp(jmpbuf))
  194891. PNG_ABORT();
  194892. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194893. #else
  194894. if (setjmp(png_ptr->jmpbuf))
  194895. PNG_ABORT();
  194896. #endif
  194897. #endif
  194898. return (png_ptr);
  194899. }
  194900. /* Initialize png_ptr structure, and allocate any memory needed */
  194901. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194902. /* Deprecated. */
  194903. #undef png_write_init
  194904. void PNGAPI
  194905. png_write_init(png_structp png_ptr)
  194906. {
  194907. /* We only come here via pre-1.0.7-compiled applications */
  194908. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  194909. }
  194910. void PNGAPI
  194911. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  194912. png_size_t png_struct_size, png_size_t png_info_size)
  194913. {
  194914. /* We only come here via pre-1.0.12-compiled applications */
  194915. if(png_ptr == NULL) return;
  194916. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194917. if(png_sizeof(png_struct) > png_struct_size ||
  194918. png_sizeof(png_info) > png_info_size)
  194919. {
  194920. char msg[80];
  194921. png_ptr->warning_fn=NULL;
  194922. if (user_png_ver)
  194923. {
  194924. png_snprintf(msg, 80,
  194925. "Application was compiled with png.h from libpng-%.20s",
  194926. user_png_ver);
  194927. png_warning(png_ptr, msg);
  194928. }
  194929. png_snprintf(msg, 80,
  194930. "Application is running with png.c from libpng-%.20s",
  194931. png_libpng_ver);
  194932. png_warning(png_ptr, msg);
  194933. }
  194934. #endif
  194935. if(png_sizeof(png_struct) > png_struct_size)
  194936. {
  194937. png_ptr->error_fn=NULL;
  194938. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194939. png_ptr->flags=0;
  194940. #endif
  194941. png_error(png_ptr,
  194942. "The png struct allocated by the application for writing is too small.");
  194943. }
  194944. if(png_sizeof(png_info) > png_info_size)
  194945. {
  194946. png_ptr->error_fn=NULL;
  194947. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194948. png_ptr->flags=0;
  194949. #endif
  194950. png_error(png_ptr,
  194951. "The info struct allocated by the application for writing is too small.");
  194952. }
  194953. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  194954. }
  194955. #endif /* PNG_1_0_X || PNG_1_2_X */
  194956. void PNGAPI
  194957. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  194958. png_size_t png_struct_size)
  194959. {
  194960. png_structp png_ptr=*ptr_ptr;
  194961. #ifdef PNG_SETJMP_SUPPORTED
  194962. jmp_buf tmp_jmp; /* to save current jump buffer */
  194963. #endif
  194964. int i = 0;
  194965. if (png_ptr == NULL)
  194966. return;
  194967. do
  194968. {
  194969. if (user_png_ver[i] != png_libpng_ver[i])
  194970. {
  194971. #ifdef PNG_LEGACY_SUPPORTED
  194972. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194973. #else
  194974. png_ptr->warning_fn=NULL;
  194975. png_warning(png_ptr,
  194976. "Application uses deprecated png_write_init() and should be recompiled.");
  194977. break;
  194978. #endif
  194979. }
  194980. } while (png_libpng_ver[i++]);
  194981. png_debug(1, "in png_write_init_3\n");
  194982. #ifdef PNG_SETJMP_SUPPORTED
  194983. /* save jump buffer and error functions */
  194984. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194985. #endif
  194986. if (png_sizeof(png_struct) > png_struct_size)
  194987. {
  194988. png_destroy_struct(png_ptr);
  194989. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194990. *ptr_ptr = png_ptr;
  194991. }
  194992. /* reset all variables to 0 */
  194993. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194994. /* added at libpng-1.2.6 */
  194995. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194996. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194997. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194998. #endif
  194999. #ifdef PNG_SETJMP_SUPPORTED
  195000. /* restore jump buffer */
  195001. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195002. #endif
  195003. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  195004. png_flush_ptr_NULL);
  195005. /* initialize zbuf - compression buffer */
  195006. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  195007. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  195008. (png_uint_32)png_ptr->zbuf_size);
  195009. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195010. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  195011. 1, png_doublep_NULL, png_doublep_NULL);
  195012. #endif
  195013. }
  195014. /* Write a few rows of image data. If the image is interlaced,
  195015. * either you will have to write the 7 sub images, or, if you
  195016. * have called png_set_interlace_handling(), you will have to
  195017. * "write" the image seven times.
  195018. */
  195019. void PNGAPI
  195020. png_write_rows(png_structp png_ptr, png_bytepp row,
  195021. png_uint_32 num_rows)
  195022. {
  195023. png_uint_32 i; /* row counter */
  195024. png_bytepp rp; /* row pointer */
  195025. png_debug(1, "in png_write_rows\n");
  195026. if (png_ptr == NULL)
  195027. return;
  195028. /* loop through the rows */
  195029. for (i = 0, rp = row; i < num_rows; i++, rp++)
  195030. {
  195031. png_write_row(png_ptr, *rp);
  195032. }
  195033. }
  195034. /* Write the image. You only need to call this function once, even
  195035. * if you are writing an interlaced image.
  195036. */
  195037. void PNGAPI
  195038. png_write_image(png_structp png_ptr, png_bytepp image)
  195039. {
  195040. png_uint_32 i; /* row index */
  195041. int pass, num_pass; /* pass variables */
  195042. png_bytepp rp; /* points to current row */
  195043. if (png_ptr == NULL)
  195044. return;
  195045. png_debug(1, "in png_write_image\n");
  195046. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195047. /* intialize interlace handling. If image is not interlaced,
  195048. this will set pass to 1 */
  195049. num_pass = png_set_interlace_handling(png_ptr);
  195050. #else
  195051. num_pass = 1;
  195052. #endif
  195053. /* loop through passes */
  195054. for (pass = 0; pass < num_pass; pass++)
  195055. {
  195056. /* loop through image */
  195057. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  195058. {
  195059. png_write_row(png_ptr, *rp);
  195060. }
  195061. }
  195062. }
  195063. /* called by user to write a row of image data */
  195064. void PNGAPI
  195065. png_write_row(png_structp png_ptr, png_bytep row)
  195066. {
  195067. if (png_ptr == NULL)
  195068. return;
  195069. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  195070. png_ptr->row_number, png_ptr->pass);
  195071. /* initialize transformations and other stuff if first time */
  195072. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  195073. {
  195074. /* make sure we wrote the header info */
  195075. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195076. png_error(png_ptr,
  195077. "png_write_info was never called before png_write_row.");
  195078. /* check for transforms that have been set but were defined out */
  195079. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  195080. if (png_ptr->transformations & PNG_INVERT_MONO)
  195081. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  195082. #endif
  195083. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  195084. if (png_ptr->transformations & PNG_FILLER)
  195085. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  195086. #endif
  195087. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  195088. if (png_ptr->transformations & PNG_PACKSWAP)
  195089. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  195090. #endif
  195091. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  195092. if (png_ptr->transformations & PNG_PACK)
  195093. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  195094. #endif
  195095. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  195096. if (png_ptr->transformations & PNG_SHIFT)
  195097. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  195098. #endif
  195099. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  195100. if (png_ptr->transformations & PNG_BGR)
  195101. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  195102. #endif
  195103. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  195104. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195105. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  195106. #endif
  195107. png_write_start_row(png_ptr);
  195108. }
  195109. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195110. /* if interlaced and not interested in row, return */
  195111. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  195112. {
  195113. switch (png_ptr->pass)
  195114. {
  195115. case 0:
  195116. if (png_ptr->row_number & 0x07)
  195117. {
  195118. png_write_finish_row(png_ptr);
  195119. return;
  195120. }
  195121. break;
  195122. case 1:
  195123. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  195124. {
  195125. png_write_finish_row(png_ptr);
  195126. return;
  195127. }
  195128. break;
  195129. case 2:
  195130. if ((png_ptr->row_number & 0x07) != 4)
  195131. {
  195132. png_write_finish_row(png_ptr);
  195133. return;
  195134. }
  195135. break;
  195136. case 3:
  195137. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  195138. {
  195139. png_write_finish_row(png_ptr);
  195140. return;
  195141. }
  195142. break;
  195143. case 4:
  195144. if ((png_ptr->row_number & 0x03) != 2)
  195145. {
  195146. png_write_finish_row(png_ptr);
  195147. return;
  195148. }
  195149. break;
  195150. case 5:
  195151. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  195152. {
  195153. png_write_finish_row(png_ptr);
  195154. return;
  195155. }
  195156. break;
  195157. case 6:
  195158. if (!(png_ptr->row_number & 0x01))
  195159. {
  195160. png_write_finish_row(png_ptr);
  195161. return;
  195162. }
  195163. break;
  195164. }
  195165. }
  195166. #endif
  195167. /* set up row info for transformations */
  195168. png_ptr->row_info.color_type = png_ptr->color_type;
  195169. png_ptr->row_info.width = png_ptr->usr_width;
  195170. png_ptr->row_info.channels = png_ptr->usr_channels;
  195171. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  195172. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  195173. png_ptr->row_info.channels);
  195174. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  195175. png_ptr->row_info.width);
  195176. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  195177. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  195178. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  195179. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  195180. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  195181. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  195182. /* Copy user's row into buffer, leaving room for filter byte. */
  195183. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  195184. png_ptr->row_info.rowbytes);
  195185. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195186. /* handle interlacing */
  195187. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  195188. (png_ptr->transformations & PNG_INTERLACE))
  195189. {
  195190. png_do_write_interlace(&(png_ptr->row_info),
  195191. png_ptr->row_buf + 1, png_ptr->pass);
  195192. /* this should always get caught above, but still ... */
  195193. if (!(png_ptr->row_info.width))
  195194. {
  195195. png_write_finish_row(png_ptr);
  195196. return;
  195197. }
  195198. }
  195199. #endif
  195200. /* handle other transformations */
  195201. if (png_ptr->transformations)
  195202. png_do_write_transformations(png_ptr);
  195203. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195204. /* Write filter_method 64 (intrapixel differencing) only if
  195205. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195206. * 2. Libpng did not write a PNG signature (this filter_method is only
  195207. * used in PNG datastreams that are embedded in MNG datastreams) and
  195208. * 3. The application called png_permit_mng_features with a mask that
  195209. * included PNG_FLAG_MNG_FILTER_64 and
  195210. * 4. The filter_method is 64 and
  195211. * 5. The color_type is RGB or RGBA
  195212. */
  195213. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195214. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  195215. {
  195216. /* Intrapixel differencing */
  195217. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195218. }
  195219. #endif
  195220. /* Find a filter if necessary, filter the row and write it out. */
  195221. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  195222. if (png_ptr->write_row_fn != NULL)
  195223. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  195224. }
  195225. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195226. /* Set the automatic flush interval or 0 to turn flushing off */
  195227. void PNGAPI
  195228. png_set_flush(png_structp png_ptr, int nrows)
  195229. {
  195230. png_debug(1, "in png_set_flush\n");
  195231. if (png_ptr == NULL)
  195232. return;
  195233. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  195234. }
  195235. /* flush the current output buffers now */
  195236. void PNGAPI
  195237. png_write_flush(png_structp png_ptr)
  195238. {
  195239. int wrote_IDAT;
  195240. png_debug(1, "in png_write_flush\n");
  195241. if (png_ptr == NULL)
  195242. return;
  195243. /* We have already written out all of the data */
  195244. if (png_ptr->row_number >= png_ptr->num_rows)
  195245. return;
  195246. do
  195247. {
  195248. int ret;
  195249. /* compress the data */
  195250. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  195251. wrote_IDAT = 0;
  195252. /* check for compression errors */
  195253. if (ret != Z_OK)
  195254. {
  195255. if (png_ptr->zstream.msg != NULL)
  195256. png_error(png_ptr, png_ptr->zstream.msg);
  195257. else
  195258. png_error(png_ptr, "zlib error");
  195259. }
  195260. if (!(png_ptr->zstream.avail_out))
  195261. {
  195262. /* write the IDAT and reset the zlib output buffer */
  195263. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195264. png_ptr->zbuf_size);
  195265. png_ptr->zstream.next_out = png_ptr->zbuf;
  195266. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195267. wrote_IDAT = 1;
  195268. }
  195269. } while(wrote_IDAT == 1);
  195270. /* If there is any data left to be output, write it into a new IDAT */
  195271. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  195272. {
  195273. /* write the IDAT and reset the zlib output buffer */
  195274. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195275. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195276. png_ptr->zstream.next_out = png_ptr->zbuf;
  195277. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195278. }
  195279. png_ptr->flush_rows = 0;
  195280. png_flush(png_ptr);
  195281. }
  195282. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195283. /* free all memory used by the write */
  195284. void PNGAPI
  195285. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  195286. {
  195287. png_structp png_ptr = NULL;
  195288. png_infop info_ptr = NULL;
  195289. #ifdef PNG_USER_MEM_SUPPORTED
  195290. png_free_ptr free_fn = NULL;
  195291. png_voidp mem_ptr = NULL;
  195292. #endif
  195293. png_debug(1, "in png_destroy_write_struct\n");
  195294. if (png_ptr_ptr != NULL)
  195295. {
  195296. png_ptr = *png_ptr_ptr;
  195297. #ifdef PNG_USER_MEM_SUPPORTED
  195298. free_fn = png_ptr->free_fn;
  195299. mem_ptr = png_ptr->mem_ptr;
  195300. #endif
  195301. }
  195302. if (info_ptr_ptr != NULL)
  195303. info_ptr = *info_ptr_ptr;
  195304. if (info_ptr != NULL)
  195305. {
  195306. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  195307. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  195308. if (png_ptr->num_chunk_list)
  195309. {
  195310. png_free(png_ptr, png_ptr->chunk_list);
  195311. png_ptr->chunk_list=NULL;
  195312. png_ptr->num_chunk_list=0;
  195313. }
  195314. #endif
  195315. #ifdef PNG_USER_MEM_SUPPORTED
  195316. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  195317. (png_voidp)mem_ptr);
  195318. #else
  195319. png_destroy_struct((png_voidp)info_ptr);
  195320. #endif
  195321. *info_ptr_ptr = NULL;
  195322. }
  195323. if (png_ptr != NULL)
  195324. {
  195325. png_write_destroy(png_ptr);
  195326. #ifdef PNG_USER_MEM_SUPPORTED
  195327. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  195328. (png_voidp)mem_ptr);
  195329. #else
  195330. png_destroy_struct((png_voidp)png_ptr);
  195331. #endif
  195332. *png_ptr_ptr = NULL;
  195333. }
  195334. }
  195335. /* Free any memory used in png_ptr struct (old method) */
  195336. void /* PRIVATE */
  195337. png_write_destroy(png_structp png_ptr)
  195338. {
  195339. #ifdef PNG_SETJMP_SUPPORTED
  195340. jmp_buf tmp_jmp; /* save jump buffer */
  195341. #endif
  195342. png_error_ptr error_fn;
  195343. png_error_ptr warning_fn;
  195344. png_voidp error_ptr;
  195345. #ifdef PNG_USER_MEM_SUPPORTED
  195346. png_free_ptr free_fn;
  195347. #endif
  195348. png_debug(1, "in png_write_destroy\n");
  195349. /* free any memory zlib uses */
  195350. deflateEnd(&png_ptr->zstream);
  195351. /* free our memory. png_free checks NULL for us. */
  195352. png_free(png_ptr, png_ptr->zbuf);
  195353. png_free(png_ptr, png_ptr->row_buf);
  195354. png_free(png_ptr, png_ptr->prev_row);
  195355. png_free(png_ptr, png_ptr->sub_row);
  195356. png_free(png_ptr, png_ptr->up_row);
  195357. png_free(png_ptr, png_ptr->avg_row);
  195358. png_free(png_ptr, png_ptr->paeth_row);
  195359. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  195360. png_free(png_ptr, png_ptr->time_buffer);
  195361. #endif
  195362. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195363. png_free(png_ptr, png_ptr->prev_filters);
  195364. png_free(png_ptr, png_ptr->filter_weights);
  195365. png_free(png_ptr, png_ptr->inv_filter_weights);
  195366. png_free(png_ptr, png_ptr->filter_costs);
  195367. png_free(png_ptr, png_ptr->inv_filter_costs);
  195368. #endif
  195369. #ifdef PNG_SETJMP_SUPPORTED
  195370. /* reset structure */
  195371. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195372. #endif
  195373. error_fn = png_ptr->error_fn;
  195374. warning_fn = png_ptr->warning_fn;
  195375. error_ptr = png_ptr->error_ptr;
  195376. #ifdef PNG_USER_MEM_SUPPORTED
  195377. free_fn = png_ptr->free_fn;
  195378. #endif
  195379. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195380. png_ptr->error_fn = error_fn;
  195381. png_ptr->warning_fn = warning_fn;
  195382. png_ptr->error_ptr = error_ptr;
  195383. #ifdef PNG_USER_MEM_SUPPORTED
  195384. png_ptr->free_fn = free_fn;
  195385. #endif
  195386. #ifdef PNG_SETJMP_SUPPORTED
  195387. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195388. #endif
  195389. }
  195390. /* Allow the application to select one or more row filters to use. */
  195391. void PNGAPI
  195392. png_set_filter(png_structp png_ptr, int method, int filters)
  195393. {
  195394. png_debug(1, "in png_set_filter\n");
  195395. if (png_ptr == NULL)
  195396. return;
  195397. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195398. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195399. (method == PNG_INTRAPIXEL_DIFFERENCING))
  195400. method = PNG_FILTER_TYPE_BASE;
  195401. #endif
  195402. if (method == PNG_FILTER_TYPE_BASE)
  195403. {
  195404. switch (filters & (PNG_ALL_FILTERS | 0x07))
  195405. {
  195406. #ifndef PNG_NO_WRITE_FILTER
  195407. case 5:
  195408. case 6:
  195409. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  195410. #endif /* PNG_NO_WRITE_FILTER */
  195411. case PNG_FILTER_VALUE_NONE:
  195412. png_ptr->do_filter=PNG_FILTER_NONE; break;
  195413. #ifndef PNG_NO_WRITE_FILTER
  195414. case PNG_FILTER_VALUE_SUB:
  195415. png_ptr->do_filter=PNG_FILTER_SUB; break;
  195416. case PNG_FILTER_VALUE_UP:
  195417. png_ptr->do_filter=PNG_FILTER_UP; break;
  195418. case PNG_FILTER_VALUE_AVG:
  195419. png_ptr->do_filter=PNG_FILTER_AVG; break;
  195420. case PNG_FILTER_VALUE_PAETH:
  195421. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  195422. default: png_ptr->do_filter = (png_byte)filters; break;
  195423. #else
  195424. default: png_warning(png_ptr, "Unknown row filter for method 0");
  195425. #endif /* PNG_NO_WRITE_FILTER */
  195426. }
  195427. /* If we have allocated the row_buf, this means we have already started
  195428. * with the image and we should have allocated all of the filter buffers
  195429. * that have been selected. If prev_row isn't already allocated, then
  195430. * it is too late to start using the filters that need it, since we
  195431. * will be missing the data in the previous row. If an application
  195432. * wants to start and stop using particular filters during compression,
  195433. * it should start out with all of the filters, and then add and
  195434. * remove them after the start of compression.
  195435. */
  195436. if (png_ptr->row_buf != NULL)
  195437. {
  195438. #ifndef PNG_NO_WRITE_FILTER
  195439. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  195440. {
  195441. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  195442. (png_ptr->rowbytes + 1));
  195443. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  195444. }
  195445. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  195446. {
  195447. if (png_ptr->prev_row == NULL)
  195448. {
  195449. png_warning(png_ptr, "Can't add Up filter after starting");
  195450. png_ptr->do_filter &= ~PNG_FILTER_UP;
  195451. }
  195452. else
  195453. {
  195454. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  195455. (png_ptr->rowbytes + 1));
  195456. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  195457. }
  195458. }
  195459. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  195460. {
  195461. if (png_ptr->prev_row == NULL)
  195462. {
  195463. png_warning(png_ptr, "Can't add Average filter after starting");
  195464. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  195465. }
  195466. else
  195467. {
  195468. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  195469. (png_ptr->rowbytes + 1));
  195470. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  195471. }
  195472. }
  195473. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  195474. png_ptr->paeth_row == NULL)
  195475. {
  195476. if (png_ptr->prev_row == NULL)
  195477. {
  195478. png_warning(png_ptr, "Can't add Paeth filter after starting");
  195479. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  195480. }
  195481. else
  195482. {
  195483. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  195484. (png_ptr->rowbytes + 1));
  195485. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  195486. }
  195487. }
  195488. if (png_ptr->do_filter == PNG_NO_FILTERS)
  195489. #endif /* PNG_NO_WRITE_FILTER */
  195490. png_ptr->do_filter = PNG_FILTER_NONE;
  195491. }
  195492. }
  195493. else
  195494. png_error(png_ptr, "Unknown custom filter method");
  195495. }
  195496. /* This allows us to influence the way in which libpng chooses the "best"
  195497. * filter for the current scanline. While the "minimum-sum-of-absolute-
  195498. * differences metric is relatively fast and effective, there is some
  195499. * question as to whether it can be improved upon by trying to keep the
  195500. * filtered data going to zlib more consistent, hopefully resulting in
  195501. * better compression.
  195502. */
  195503. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  195504. void PNGAPI
  195505. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  195506. int num_weights, png_doublep filter_weights,
  195507. png_doublep filter_costs)
  195508. {
  195509. int i;
  195510. png_debug(1, "in png_set_filter_heuristics\n");
  195511. if (png_ptr == NULL)
  195512. return;
  195513. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  195514. {
  195515. png_warning(png_ptr, "Unknown filter heuristic method");
  195516. return;
  195517. }
  195518. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  195519. {
  195520. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  195521. }
  195522. if (num_weights < 0 || filter_weights == NULL ||
  195523. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  195524. {
  195525. num_weights = 0;
  195526. }
  195527. png_ptr->num_prev_filters = (png_byte)num_weights;
  195528. png_ptr->heuristic_method = (png_byte)heuristic_method;
  195529. if (num_weights > 0)
  195530. {
  195531. if (png_ptr->prev_filters == NULL)
  195532. {
  195533. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  195534. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  195535. /* To make sure that the weighting starts out fairly */
  195536. for (i = 0; i < num_weights; i++)
  195537. {
  195538. png_ptr->prev_filters[i] = 255;
  195539. }
  195540. }
  195541. if (png_ptr->filter_weights == NULL)
  195542. {
  195543. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195544. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195545. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195546. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195547. for (i = 0; i < num_weights; i++)
  195548. {
  195549. png_ptr->inv_filter_weights[i] =
  195550. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195551. }
  195552. }
  195553. for (i = 0; i < num_weights; i++)
  195554. {
  195555. if (filter_weights[i] < 0.0)
  195556. {
  195557. png_ptr->inv_filter_weights[i] =
  195558. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195559. }
  195560. else
  195561. {
  195562. png_ptr->inv_filter_weights[i] =
  195563. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  195564. png_ptr->filter_weights[i] =
  195565. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  195566. }
  195567. }
  195568. }
  195569. /* If, in the future, there are other filter methods, this would
  195570. * need to be based on png_ptr->filter.
  195571. */
  195572. if (png_ptr->filter_costs == NULL)
  195573. {
  195574. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195575. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195576. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195577. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195578. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195579. {
  195580. png_ptr->inv_filter_costs[i] =
  195581. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195582. }
  195583. }
  195584. /* Here is where we set the relative costs of the different filters. We
  195585. * should take the desired compression level into account when setting
  195586. * the costs, so that Paeth, for instance, has a high relative cost at low
  195587. * compression levels, while it has a lower relative cost at higher
  195588. * compression settings. The filter types are in order of increasing
  195589. * relative cost, so it would be possible to do this with an algorithm.
  195590. */
  195591. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195592. {
  195593. if (filter_costs == NULL || filter_costs[i] < 0.0)
  195594. {
  195595. png_ptr->inv_filter_costs[i] =
  195596. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195597. }
  195598. else if (filter_costs[i] >= 1.0)
  195599. {
  195600. png_ptr->inv_filter_costs[i] =
  195601. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  195602. png_ptr->filter_costs[i] =
  195603. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  195604. }
  195605. }
  195606. }
  195607. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  195608. void PNGAPI
  195609. png_set_compression_level(png_structp png_ptr, int level)
  195610. {
  195611. png_debug(1, "in png_set_compression_level\n");
  195612. if (png_ptr == NULL)
  195613. return;
  195614. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  195615. png_ptr->zlib_level = level;
  195616. }
  195617. void PNGAPI
  195618. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  195619. {
  195620. png_debug(1, "in png_set_compression_mem_level\n");
  195621. if (png_ptr == NULL)
  195622. return;
  195623. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  195624. png_ptr->zlib_mem_level = mem_level;
  195625. }
  195626. void PNGAPI
  195627. png_set_compression_strategy(png_structp png_ptr, int strategy)
  195628. {
  195629. png_debug(1, "in png_set_compression_strategy\n");
  195630. if (png_ptr == NULL)
  195631. return;
  195632. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  195633. png_ptr->zlib_strategy = strategy;
  195634. }
  195635. void PNGAPI
  195636. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  195637. {
  195638. if (png_ptr == NULL)
  195639. return;
  195640. if (window_bits > 15)
  195641. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  195642. else if (window_bits < 8)
  195643. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  195644. #ifndef WBITS_8_OK
  195645. /* avoid libpng bug with 256-byte windows */
  195646. if (window_bits == 8)
  195647. {
  195648. png_warning(png_ptr, "Compression window is being reset to 512");
  195649. window_bits=9;
  195650. }
  195651. #endif
  195652. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  195653. png_ptr->zlib_window_bits = window_bits;
  195654. }
  195655. void PNGAPI
  195656. png_set_compression_method(png_structp png_ptr, int method)
  195657. {
  195658. png_debug(1, "in png_set_compression_method\n");
  195659. if (png_ptr == NULL)
  195660. return;
  195661. if (method != 8)
  195662. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  195663. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  195664. png_ptr->zlib_method = method;
  195665. }
  195666. void PNGAPI
  195667. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  195668. {
  195669. if (png_ptr == NULL)
  195670. return;
  195671. png_ptr->write_row_fn = write_row_fn;
  195672. }
  195673. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195674. void PNGAPI
  195675. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  195676. write_user_transform_fn)
  195677. {
  195678. png_debug(1, "in png_set_write_user_transform_fn\n");
  195679. if (png_ptr == NULL)
  195680. return;
  195681. png_ptr->transformations |= PNG_USER_TRANSFORM;
  195682. png_ptr->write_user_transform_fn = write_user_transform_fn;
  195683. }
  195684. #endif
  195685. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  195686. void PNGAPI
  195687. png_write_png(png_structp png_ptr, png_infop info_ptr,
  195688. int transforms, voidp params)
  195689. {
  195690. if (png_ptr == NULL || info_ptr == NULL)
  195691. return;
  195692. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195693. /* invert the alpha channel from opacity to transparency */
  195694. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  195695. png_set_invert_alpha(png_ptr);
  195696. #endif
  195697. /* Write the file header information. */
  195698. png_write_info(png_ptr, info_ptr);
  195699. /* ------ these transformations don't touch the info structure ------- */
  195700. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195701. /* invert monochrome pixels */
  195702. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  195703. png_set_invert_mono(png_ptr);
  195704. #endif
  195705. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195706. /* Shift the pixels up to a legal bit depth and fill in
  195707. * as appropriate to correctly scale the image.
  195708. */
  195709. if ((transforms & PNG_TRANSFORM_SHIFT)
  195710. && (info_ptr->valid & PNG_INFO_sBIT))
  195711. png_set_shift(png_ptr, &info_ptr->sig_bit);
  195712. #endif
  195713. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195714. /* pack pixels into bytes */
  195715. if (transforms & PNG_TRANSFORM_PACKING)
  195716. png_set_packing(png_ptr);
  195717. #endif
  195718. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195719. /* swap location of alpha bytes from ARGB to RGBA */
  195720. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  195721. png_set_swap_alpha(png_ptr);
  195722. #endif
  195723. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195724. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  195725. * RGB (4 channels -> 3 channels). The second parameter is not used.
  195726. */
  195727. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  195728. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  195729. #endif
  195730. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195731. /* flip BGR pixels to RGB */
  195732. if (transforms & PNG_TRANSFORM_BGR)
  195733. png_set_bgr(png_ptr);
  195734. #endif
  195735. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195736. /* swap bytes of 16-bit files to most significant byte first */
  195737. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  195738. png_set_swap(png_ptr);
  195739. #endif
  195740. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195741. /* swap bits of 1, 2, 4 bit packed pixel formats */
  195742. if (transforms & PNG_TRANSFORM_PACKSWAP)
  195743. png_set_packswap(png_ptr);
  195744. #endif
  195745. /* ----------------------- end of transformations ------------------- */
  195746. /* write the bits */
  195747. if (info_ptr->valid & PNG_INFO_IDAT)
  195748. png_write_image(png_ptr, info_ptr->row_pointers);
  195749. /* It is REQUIRED to call this to finish writing the rest of the file */
  195750. png_write_end(png_ptr, info_ptr);
  195751. transforms = transforms; /* quiet compiler warnings */
  195752. params = params;
  195753. }
  195754. #endif
  195755. #endif /* PNG_WRITE_SUPPORTED */
  195756. /********* End of inlined file: pngwrite.c *********/
  195757. /********* Start of inlined file: pngwtran.c *********/
  195758. /* pngwtran.c - transforms the data in a row for PNG writers
  195759. *
  195760. * Last changed in libpng 1.2.9 April 14, 2006
  195761. * For conditions of distribution and use, see copyright notice in png.h
  195762. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195763. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195764. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195765. */
  195766. #define PNG_INTERNAL
  195767. #ifdef PNG_WRITE_SUPPORTED
  195768. /* Transform the data according to the user's wishes. The order of
  195769. * transformations is significant.
  195770. */
  195771. void /* PRIVATE */
  195772. png_do_write_transformations(png_structp png_ptr)
  195773. {
  195774. png_debug(1, "in png_do_write_transformations\n");
  195775. if (png_ptr == NULL)
  195776. return;
  195777. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195778. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  195779. if(png_ptr->write_user_transform_fn != NULL)
  195780. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  195781. (png_ptr, /* png_ptr */
  195782. &(png_ptr->row_info), /* row_info: */
  195783. /* png_uint_32 width; width of row */
  195784. /* png_uint_32 rowbytes; number of bytes in row */
  195785. /* png_byte color_type; color type of pixels */
  195786. /* png_byte bit_depth; bit depth of samples */
  195787. /* png_byte channels; number of channels (1-4) */
  195788. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  195789. png_ptr->row_buf + 1); /* start of pixel data for row */
  195790. #endif
  195791. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195792. if (png_ptr->transformations & PNG_FILLER)
  195793. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195794. png_ptr->flags);
  195795. #endif
  195796. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195797. if (png_ptr->transformations & PNG_PACKSWAP)
  195798. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195799. #endif
  195800. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195801. if (png_ptr->transformations & PNG_PACK)
  195802. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195803. (png_uint_32)png_ptr->bit_depth);
  195804. #endif
  195805. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195806. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195807. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195808. #endif
  195809. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195810. if (png_ptr->transformations & PNG_SHIFT)
  195811. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195812. &(png_ptr->shift));
  195813. #endif
  195814. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195815. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  195816. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195817. #endif
  195818. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195819. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  195820. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195821. #endif
  195822. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195823. if (png_ptr->transformations & PNG_BGR)
  195824. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195825. #endif
  195826. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195827. if (png_ptr->transformations & PNG_INVERT_MONO)
  195828. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195829. #endif
  195830. }
  195831. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195832. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  195833. * row_info bit depth should be 8 (one pixel per byte). The channels
  195834. * should be 1 (this only happens on grayscale and paletted images).
  195835. */
  195836. void /* PRIVATE */
  195837. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  195838. {
  195839. png_debug(1, "in png_do_pack\n");
  195840. if (row_info->bit_depth == 8 &&
  195841. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195842. row != NULL && row_info != NULL &&
  195843. #endif
  195844. row_info->channels == 1)
  195845. {
  195846. switch ((int)bit_depth)
  195847. {
  195848. case 1:
  195849. {
  195850. png_bytep sp, dp;
  195851. int mask, v;
  195852. png_uint_32 i;
  195853. png_uint_32 row_width = row_info->width;
  195854. sp = row;
  195855. dp = row;
  195856. mask = 0x80;
  195857. v = 0;
  195858. for (i = 0; i < row_width; i++)
  195859. {
  195860. if (*sp != 0)
  195861. v |= mask;
  195862. sp++;
  195863. if (mask > 1)
  195864. mask >>= 1;
  195865. else
  195866. {
  195867. mask = 0x80;
  195868. *dp = (png_byte)v;
  195869. dp++;
  195870. v = 0;
  195871. }
  195872. }
  195873. if (mask != 0x80)
  195874. *dp = (png_byte)v;
  195875. break;
  195876. }
  195877. case 2:
  195878. {
  195879. png_bytep sp, dp;
  195880. int shift, v;
  195881. png_uint_32 i;
  195882. png_uint_32 row_width = row_info->width;
  195883. sp = row;
  195884. dp = row;
  195885. shift = 6;
  195886. v = 0;
  195887. for (i = 0; i < row_width; i++)
  195888. {
  195889. png_byte value;
  195890. value = (png_byte)(*sp & 0x03);
  195891. v |= (value << shift);
  195892. if (shift == 0)
  195893. {
  195894. shift = 6;
  195895. *dp = (png_byte)v;
  195896. dp++;
  195897. v = 0;
  195898. }
  195899. else
  195900. shift -= 2;
  195901. sp++;
  195902. }
  195903. if (shift != 6)
  195904. *dp = (png_byte)v;
  195905. break;
  195906. }
  195907. case 4:
  195908. {
  195909. png_bytep sp, dp;
  195910. int shift, v;
  195911. png_uint_32 i;
  195912. png_uint_32 row_width = row_info->width;
  195913. sp = row;
  195914. dp = row;
  195915. shift = 4;
  195916. v = 0;
  195917. for (i = 0; i < row_width; i++)
  195918. {
  195919. png_byte value;
  195920. value = (png_byte)(*sp & 0x0f);
  195921. v |= (value << shift);
  195922. if (shift == 0)
  195923. {
  195924. shift = 4;
  195925. *dp = (png_byte)v;
  195926. dp++;
  195927. v = 0;
  195928. }
  195929. else
  195930. shift -= 4;
  195931. sp++;
  195932. }
  195933. if (shift != 4)
  195934. *dp = (png_byte)v;
  195935. break;
  195936. }
  195937. }
  195938. row_info->bit_depth = (png_byte)bit_depth;
  195939. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  195940. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195941. row_info->width);
  195942. }
  195943. }
  195944. #endif
  195945. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195946. /* Shift pixel values to take advantage of whole range. Pass the
  195947. * true number of bits in bit_depth. The row should be packed
  195948. * according to row_info->bit_depth. Thus, if you had a row of
  195949. * bit depth 4, but the pixels only had values from 0 to 7, you
  195950. * would pass 3 as bit_depth, and this routine would translate the
  195951. * data to 0 to 15.
  195952. */
  195953. void /* PRIVATE */
  195954. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  195955. {
  195956. png_debug(1, "in png_do_shift\n");
  195957. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195958. if (row != NULL && row_info != NULL &&
  195959. #else
  195960. if (
  195961. #endif
  195962. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  195963. {
  195964. int shift_start[4], shift_dec[4];
  195965. int channels = 0;
  195966. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  195967. {
  195968. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  195969. shift_dec[channels] = bit_depth->red;
  195970. channels++;
  195971. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  195972. shift_dec[channels] = bit_depth->green;
  195973. channels++;
  195974. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  195975. shift_dec[channels] = bit_depth->blue;
  195976. channels++;
  195977. }
  195978. else
  195979. {
  195980. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  195981. shift_dec[channels] = bit_depth->gray;
  195982. channels++;
  195983. }
  195984. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  195985. {
  195986. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  195987. shift_dec[channels] = bit_depth->alpha;
  195988. channels++;
  195989. }
  195990. /* with low row depths, could only be grayscale, so one channel */
  195991. if (row_info->bit_depth < 8)
  195992. {
  195993. png_bytep bp = row;
  195994. png_uint_32 i;
  195995. png_byte mask;
  195996. png_uint_32 row_bytes = row_info->rowbytes;
  195997. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  195998. mask = 0x55;
  195999. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  196000. mask = 0x11;
  196001. else
  196002. mask = 0xff;
  196003. for (i = 0; i < row_bytes; i++, bp++)
  196004. {
  196005. png_uint_16 v;
  196006. int j;
  196007. v = *bp;
  196008. *bp = 0;
  196009. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  196010. {
  196011. if (j > 0)
  196012. *bp |= (png_byte)((v << j) & 0xff);
  196013. else
  196014. *bp |= (png_byte)((v >> (-j)) & mask);
  196015. }
  196016. }
  196017. }
  196018. else if (row_info->bit_depth == 8)
  196019. {
  196020. png_bytep bp = row;
  196021. png_uint_32 i;
  196022. png_uint_32 istop = channels * row_info->width;
  196023. for (i = 0; i < istop; i++, bp++)
  196024. {
  196025. png_uint_16 v;
  196026. int j;
  196027. int c = (int)(i%channels);
  196028. v = *bp;
  196029. *bp = 0;
  196030. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196031. {
  196032. if (j > 0)
  196033. *bp |= (png_byte)((v << j) & 0xff);
  196034. else
  196035. *bp |= (png_byte)((v >> (-j)) & 0xff);
  196036. }
  196037. }
  196038. }
  196039. else
  196040. {
  196041. png_bytep bp;
  196042. png_uint_32 i;
  196043. png_uint_32 istop = channels * row_info->width;
  196044. for (bp = row, i = 0; i < istop; i++)
  196045. {
  196046. int c = (int)(i%channels);
  196047. png_uint_16 value, v;
  196048. int j;
  196049. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  196050. value = 0;
  196051. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196052. {
  196053. if (j > 0)
  196054. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  196055. else
  196056. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  196057. }
  196058. *bp++ = (png_byte)(value >> 8);
  196059. *bp++ = (png_byte)(value & 0xff);
  196060. }
  196061. }
  196062. }
  196063. }
  196064. #endif
  196065. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196066. void /* PRIVATE */
  196067. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  196068. {
  196069. png_debug(1, "in png_do_write_swap_alpha\n");
  196070. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196071. if (row != NULL && row_info != NULL)
  196072. #endif
  196073. {
  196074. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196075. {
  196076. /* This converts from ARGB to RGBA */
  196077. if (row_info->bit_depth == 8)
  196078. {
  196079. png_bytep sp, dp;
  196080. png_uint_32 i;
  196081. png_uint_32 row_width = row_info->width;
  196082. for (i = 0, sp = dp = row; i < row_width; i++)
  196083. {
  196084. png_byte save = *(sp++);
  196085. *(dp++) = *(sp++);
  196086. *(dp++) = *(sp++);
  196087. *(dp++) = *(sp++);
  196088. *(dp++) = save;
  196089. }
  196090. }
  196091. /* This converts from AARRGGBB to RRGGBBAA */
  196092. else
  196093. {
  196094. png_bytep sp, dp;
  196095. png_uint_32 i;
  196096. png_uint_32 row_width = row_info->width;
  196097. for (i = 0, sp = dp = row; i < row_width; i++)
  196098. {
  196099. png_byte save[2];
  196100. save[0] = *(sp++);
  196101. save[1] = *(sp++);
  196102. *(dp++) = *(sp++);
  196103. *(dp++) = *(sp++);
  196104. *(dp++) = *(sp++);
  196105. *(dp++) = *(sp++);
  196106. *(dp++) = *(sp++);
  196107. *(dp++) = *(sp++);
  196108. *(dp++) = save[0];
  196109. *(dp++) = save[1];
  196110. }
  196111. }
  196112. }
  196113. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196114. {
  196115. /* This converts from AG to GA */
  196116. if (row_info->bit_depth == 8)
  196117. {
  196118. png_bytep sp, dp;
  196119. png_uint_32 i;
  196120. png_uint_32 row_width = row_info->width;
  196121. for (i = 0, sp = dp = row; i < row_width; i++)
  196122. {
  196123. png_byte save = *(sp++);
  196124. *(dp++) = *(sp++);
  196125. *(dp++) = save;
  196126. }
  196127. }
  196128. /* This converts from AAGG to GGAA */
  196129. else
  196130. {
  196131. png_bytep sp, dp;
  196132. png_uint_32 i;
  196133. png_uint_32 row_width = row_info->width;
  196134. for (i = 0, sp = dp = row; i < row_width; i++)
  196135. {
  196136. png_byte save[2];
  196137. save[0] = *(sp++);
  196138. save[1] = *(sp++);
  196139. *(dp++) = *(sp++);
  196140. *(dp++) = *(sp++);
  196141. *(dp++) = save[0];
  196142. *(dp++) = save[1];
  196143. }
  196144. }
  196145. }
  196146. }
  196147. }
  196148. #endif
  196149. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196150. void /* PRIVATE */
  196151. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  196152. {
  196153. png_debug(1, "in png_do_write_invert_alpha\n");
  196154. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196155. if (row != NULL && row_info != NULL)
  196156. #endif
  196157. {
  196158. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196159. {
  196160. /* This inverts the alpha channel in RGBA */
  196161. if (row_info->bit_depth == 8)
  196162. {
  196163. png_bytep sp, dp;
  196164. png_uint_32 i;
  196165. png_uint_32 row_width = row_info->width;
  196166. for (i = 0, sp = dp = row; i < row_width; i++)
  196167. {
  196168. /* does nothing
  196169. *(dp++) = *(sp++);
  196170. *(dp++) = *(sp++);
  196171. *(dp++) = *(sp++);
  196172. */
  196173. sp+=3; dp = sp;
  196174. *(dp++) = (png_byte)(255 - *(sp++));
  196175. }
  196176. }
  196177. /* This inverts the alpha channel in RRGGBBAA */
  196178. else
  196179. {
  196180. png_bytep sp, dp;
  196181. png_uint_32 i;
  196182. png_uint_32 row_width = row_info->width;
  196183. for (i = 0, sp = dp = row; i < row_width; i++)
  196184. {
  196185. /* does nothing
  196186. *(dp++) = *(sp++);
  196187. *(dp++) = *(sp++);
  196188. *(dp++) = *(sp++);
  196189. *(dp++) = *(sp++);
  196190. *(dp++) = *(sp++);
  196191. *(dp++) = *(sp++);
  196192. */
  196193. sp+=6; dp = sp;
  196194. *(dp++) = (png_byte)(255 - *(sp++));
  196195. *(dp++) = (png_byte)(255 - *(sp++));
  196196. }
  196197. }
  196198. }
  196199. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196200. {
  196201. /* This inverts the alpha channel in GA */
  196202. if (row_info->bit_depth == 8)
  196203. {
  196204. png_bytep sp, dp;
  196205. png_uint_32 i;
  196206. png_uint_32 row_width = row_info->width;
  196207. for (i = 0, sp = dp = row; i < row_width; i++)
  196208. {
  196209. *(dp++) = *(sp++);
  196210. *(dp++) = (png_byte)(255 - *(sp++));
  196211. }
  196212. }
  196213. /* This inverts the alpha channel in GGAA */
  196214. else
  196215. {
  196216. png_bytep sp, dp;
  196217. png_uint_32 i;
  196218. png_uint_32 row_width = row_info->width;
  196219. for (i = 0, sp = dp = row; i < row_width; i++)
  196220. {
  196221. /* does nothing
  196222. *(dp++) = *(sp++);
  196223. *(dp++) = *(sp++);
  196224. */
  196225. sp+=2; dp = sp;
  196226. *(dp++) = (png_byte)(255 - *(sp++));
  196227. *(dp++) = (png_byte)(255 - *(sp++));
  196228. }
  196229. }
  196230. }
  196231. }
  196232. }
  196233. #endif
  196234. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196235. /* undoes intrapixel differencing */
  196236. void /* PRIVATE */
  196237. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  196238. {
  196239. png_debug(1, "in png_do_write_intrapixel\n");
  196240. if (
  196241. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196242. row != NULL && row_info != NULL &&
  196243. #endif
  196244. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  196245. {
  196246. int bytes_per_pixel;
  196247. png_uint_32 row_width = row_info->width;
  196248. if (row_info->bit_depth == 8)
  196249. {
  196250. png_bytep rp;
  196251. png_uint_32 i;
  196252. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196253. bytes_per_pixel = 3;
  196254. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196255. bytes_per_pixel = 4;
  196256. else
  196257. return;
  196258. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196259. {
  196260. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  196261. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  196262. }
  196263. }
  196264. else if (row_info->bit_depth == 16)
  196265. {
  196266. png_bytep rp;
  196267. png_uint_32 i;
  196268. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196269. bytes_per_pixel = 6;
  196270. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196271. bytes_per_pixel = 8;
  196272. else
  196273. return;
  196274. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196275. {
  196276. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  196277. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  196278. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  196279. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  196280. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  196281. *(rp ) = (png_byte)((red >> 8) & 0xff);
  196282. *(rp+1) = (png_byte)(red & 0xff);
  196283. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  196284. *(rp+5) = (png_byte)(blue & 0xff);
  196285. }
  196286. }
  196287. }
  196288. }
  196289. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  196290. #endif /* PNG_WRITE_SUPPORTED */
  196291. /********* End of inlined file: pngwtran.c *********/
  196292. /********* Start of inlined file: pngwutil.c *********/
  196293. /* pngwutil.c - utilities to write a PNG file
  196294. *
  196295. * Last changed in libpng 1.2.20 Septhember 3, 2007
  196296. * For conditions of distribution and use, see copyright notice in png.h
  196297. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196298. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196299. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196300. */
  196301. #define PNG_INTERNAL
  196302. #ifdef PNG_WRITE_SUPPORTED
  196303. /* Place a 32-bit number into a buffer in PNG byte order. We work
  196304. * with unsigned numbers for convenience, although one supported
  196305. * ancillary chunk uses signed (two's complement) numbers.
  196306. */
  196307. void PNGAPI
  196308. png_save_uint_32(png_bytep buf, png_uint_32 i)
  196309. {
  196310. buf[0] = (png_byte)((i >> 24) & 0xff);
  196311. buf[1] = (png_byte)((i >> 16) & 0xff);
  196312. buf[2] = (png_byte)((i >> 8) & 0xff);
  196313. buf[3] = (png_byte)(i & 0xff);
  196314. }
  196315. /* The png_save_int_32 function assumes integers are stored in two's
  196316. * complement format. If this isn't the case, then this routine needs to
  196317. * be modified to write data in two's complement format.
  196318. */
  196319. void PNGAPI
  196320. png_save_int_32(png_bytep buf, png_int_32 i)
  196321. {
  196322. buf[0] = (png_byte)((i >> 24) & 0xff);
  196323. buf[1] = (png_byte)((i >> 16) & 0xff);
  196324. buf[2] = (png_byte)((i >> 8) & 0xff);
  196325. buf[3] = (png_byte)(i & 0xff);
  196326. }
  196327. /* Place a 16-bit number into a buffer in PNG byte order.
  196328. * The parameter is declared unsigned int, not png_uint_16,
  196329. * just to avoid potential problems on pre-ANSI C compilers.
  196330. */
  196331. void PNGAPI
  196332. png_save_uint_16(png_bytep buf, unsigned int i)
  196333. {
  196334. buf[0] = (png_byte)((i >> 8) & 0xff);
  196335. buf[1] = (png_byte)(i & 0xff);
  196336. }
  196337. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  196338. * representing the chunk name. The array must be at least 4 bytes in
  196339. * length, and does not need to be null terminated. To be safe, pass the
  196340. * pre-defined chunk names here, and if you need a new one, define it
  196341. * where the others are defined. The length is the length of the data.
  196342. * All the data must be present. If that is not possible, use the
  196343. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  196344. * functions instead.
  196345. */
  196346. void PNGAPI
  196347. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  196348. png_bytep data, png_size_t length)
  196349. {
  196350. if(png_ptr == NULL) return;
  196351. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  196352. png_write_chunk_data(png_ptr, data, length);
  196353. png_write_chunk_end(png_ptr);
  196354. }
  196355. /* Write the start of a PNG chunk. The type is the chunk type.
  196356. * The total_length is the sum of the lengths of all the data you will be
  196357. * passing in png_write_chunk_data().
  196358. */
  196359. void PNGAPI
  196360. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  196361. png_uint_32 length)
  196362. {
  196363. png_byte buf[4];
  196364. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  196365. if(png_ptr == NULL) return;
  196366. /* write the length */
  196367. png_save_uint_32(buf, length);
  196368. png_write_data(png_ptr, buf, (png_size_t)4);
  196369. /* write the chunk name */
  196370. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  196371. /* reset the crc and run it over the chunk name */
  196372. png_reset_crc(png_ptr);
  196373. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  196374. }
  196375. /* Write the data of a PNG chunk started with png_write_chunk_start().
  196376. * Note that multiple calls to this function are allowed, and that the
  196377. * sum of the lengths from these calls *must* add up to the total_length
  196378. * given to png_write_chunk_start().
  196379. */
  196380. void PNGAPI
  196381. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  196382. {
  196383. /* write the data, and run the CRC over it */
  196384. if(png_ptr == NULL) return;
  196385. if (data != NULL && length > 0)
  196386. {
  196387. png_calculate_crc(png_ptr, data, length);
  196388. png_write_data(png_ptr, data, length);
  196389. }
  196390. }
  196391. /* Finish a chunk started with png_write_chunk_start(). */
  196392. void PNGAPI
  196393. png_write_chunk_end(png_structp png_ptr)
  196394. {
  196395. png_byte buf[4];
  196396. if(png_ptr == NULL) return;
  196397. /* write the crc */
  196398. png_save_uint_32(buf, png_ptr->crc);
  196399. png_write_data(png_ptr, buf, (png_size_t)4);
  196400. }
  196401. /* Simple function to write the signature. If we have already written
  196402. * the magic bytes of the signature, or more likely, the PNG stream is
  196403. * being embedded into another stream and doesn't need its own signature,
  196404. * we should call png_set_sig_bytes() to tell libpng how many of the
  196405. * bytes have already been written.
  196406. */
  196407. void /* PRIVATE */
  196408. png_write_sig(png_structp png_ptr)
  196409. {
  196410. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  196411. /* write the rest of the 8 byte signature */
  196412. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  196413. (png_size_t)8 - png_ptr->sig_bytes);
  196414. if(png_ptr->sig_bytes < 3)
  196415. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  196416. }
  196417. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  196418. /*
  196419. * This pair of functions encapsulates the operation of (a) compressing a
  196420. * text string, and (b) issuing it later as a series of chunk data writes.
  196421. * The compression_state structure is shared context for these functions
  196422. * set up by the caller in order to make the whole mess thread-safe.
  196423. */
  196424. typedef struct
  196425. {
  196426. char *input; /* the uncompressed input data */
  196427. int input_len; /* its length */
  196428. int num_output_ptr; /* number of output pointers used */
  196429. int max_output_ptr; /* size of output_ptr */
  196430. png_charpp output_ptr; /* array of pointers to output */
  196431. } compression_state;
  196432. /* compress given text into storage in the png_ptr structure */
  196433. static int /* PRIVATE */
  196434. png_text_compress(png_structp png_ptr,
  196435. png_charp text, png_size_t text_len, int compression,
  196436. compression_state *comp)
  196437. {
  196438. int ret;
  196439. comp->num_output_ptr = 0;
  196440. comp->max_output_ptr = 0;
  196441. comp->output_ptr = NULL;
  196442. comp->input = NULL;
  196443. comp->input_len = 0;
  196444. /* we may just want to pass the text right through */
  196445. if (compression == PNG_TEXT_COMPRESSION_NONE)
  196446. {
  196447. comp->input = text;
  196448. comp->input_len = text_len;
  196449. return((int)text_len);
  196450. }
  196451. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  196452. {
  196453. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196454. char msg[50];
  196455. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  196456. png_warning(png_ptr, msg);
  196457. #else
  196458. png_warning(png_ptr, "Unknown compression type");
  196459. #endif
  196460. }
  196461. /* We can't write the chunk until we find out how much data we have,
  196462. * which means we need to run the compressor first and save the
  196463. * output. This shouldn't be a problem, as the vast majority of
  196464. * comments should be reasonable, but we will set up an array of
  196465. * malloc'd pointers to be sure.
  196466. *
  196467. * If we knew the application was well behaved, we could simplify this
  196468. * greatly by assuming we can always malloc an output buffer large
  196469. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  196470. * and malloc this directly. The only time this would be a bad idea is
  196471. * if we can't malloc more than 64K and we have 64K of random input
  196472. * data, or if the input string is incredibly large (although this
  196473. * wouldn't cause a failure, just a slowdown due to swapping).
  196474. */
  196475. /* set up the compression buffers */
  196476. png_ptr->zstream.avail_in = (uInt)text_len;
  196477. png_ptr->zstream.next_in = (Bytef *)text;
  196478. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196479. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  196480. /* this is the same compression loop as in png_write_row() */
  196481. do
  196482. {
  196483. /* compress the data */
  196484. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  196485. if (ret != Z_OK)
  196486. {
  196487. /* error */
  196488. if (png_ptr->zstream.msg != NULL)
  196489. png_error(png_ptr, png_ptr->zstream.msg);
  196490. else
  196491. png_error(png_ptr, "zlib error");
  196492. }
  196493. /* check to see if we need more room */
  196494. if (!(png_ptr->zstream.avail_out))
  196495. {
  196496. /* make sure the output array has room */
  196497. if (comp->num_output_ptr >= comp->max_output_ptr)
  196498. {
  196499. int old_max;
  196500. old_max = comp->max_output_ptr;
  196501. comp->max_output_ptr = comp->num_output_ptr + 4;
  196502. if (comp->output_ptr != NULL)
  196503. {
  196504. png_charpp old_ptr;
  196505. old_ptr = comp->output_ptr;
  196506. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196507. (png_uint_32)(comp->max_output_ptr *
  196508. png_sizeof (png_charpp)));
  196509. png_memcpy(comp->output_ptr, old_ptr, old_max
  196510. * png_sizeof (png_charp));
  196511. png_free(png_ptr, old_ptr);
  196512. }
  196513. else
  196514. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196515. (png_uint_32)(comp->max_output_ptr *
  196516. png_sizeof (png_charp)));
  196517. }
  196518. /* save the data */
  196519. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  196520. (png_uint_32)png_ptr->zbuf_size);
  196521. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196522. png_ptr->zbuf_size);
  196523. comp->num_output_ptr++;
  196524. /* and reset the buffer */
  196525. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196526. png_ptr->zstream.next_out = png_ptr->zbuf;
  196527. }
  196528. /* continue until we don't have any more to compress */
  196529. } while (png_ptr->zstream.avail_in);
  196530. /* finish the compression */
  196531. do
  196532. {
  196533. /* tell zlib we are finished */
  196534. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196535. if (ret == Z_OK)
  196536. {
  196537. /* check to see if we need more room */
  196538. if (!(png_ptr->zstream.avail_out))
  196539. {
  196540. /* check to make sure our output array has room */
  196541. if (comp->num_output_ptr >= comp->max_output_ptr)
  196542. {
  196543. int old_max;
  196544. old_max = comp->max_output_ptr;
  196545. comp->max_output_ptr = comp->num_output_ptr + 4;
  196546. if (comp->output_ptr != NULL)
  196547. {
  196548. png_charpp old_ptr;
  196549. old_ptr = comp->output_ptr;
  196550. /* This could be optimized to realloc() */
  196551. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196552. (png_uint_32)(comp->max_output_ptr *
  196553. png_sizeof (png_charpp)));
  196554. png_memcpy(comp->output_ptr, old_ptr,
  196555. old_max * png_sizeof (png_charp));
  196556. png_free(png_ptr, old_ptr);
  196557. }
  196558. else
  196559. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196560. (png_uint_32)(comp->max_output_ptr *
  196561. png_sizeof (png_charp)));
  196562. }
  196563. /* save off the data */
  196564. comp->output_ptr[comp->num_output_ptr] =
  196565. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  196566. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196567. png_ptr->zbuf_size);
  196568. comp->num_output_ptr++;
  196569. /* and reset the buffer pointers */
  196570. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196571. png_ptr->zstream.next_out = png_ptr->zbuf;
  196572. }
  196573. }
  196574. else if (ret != Z_STREAM_END)
  196575. {
  196576. /* we got an error */
  196577. if (png_ptr->zstream.msg != NULL)
  196578. png_error(png_ptr, png_ptr->zstream.msg);
  196579. else
  196580. png_error(png_ptr, "zlib error");
  196581. }
  196582. } while (ret != Z_STREAM_END);
  196583. /* text length is number of buffers plus last buffer */
  196584. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  196585. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196586. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  196587. return((int)text_len);
  196588. }
  196589. /* ship the compressed text out via chunk writes */
  196590. static void /* PRIVATE */
  196591. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  196592. {
  196593. int i;
  196594. /* handle the no-compression case */
  196595. if (comp->input)
  196596. {
  196597. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  196598. (png_size_t)comp->input_len);
  196599. return;
  196600. }
  196601. /* write saved output buffers, if any */
  196602. for (i = 0; i < comp->num_output_ptr; i++)
  196603. {
  196604. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  196605. png_ptr->zbuf_size);
  196606. png_free(png_ptr, comp->output_ptr[i]);
  196607. comp->output_ptr[i]=NULL;
  196608. }
  196609. if (comp->max_output_ptr != 0)
  196610. png_free(png_ptr, comp->output_ptr);
  196611. comp->output_ptr=NULL;
  196612. /* write anything left in zbuf */
  196613. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  196614. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  196615. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196616. /* reset zlib for another zTXt/iTXt or image data */
  196617. deflateReset(&png_ptr->zstream);
  196618. png_ptr->zstream.data_type = Z_BINARY;
  196619. }
  196620. #endif
  196621. /* Write the IHDR chunk, and update the png_struct with the necessary
  196622. * information. Note that the rest of this code depends upon this
  196623. * information being correct.
  196624. */
  196625. void /* PRIVATE */
  196626. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  196627. int bit_depth, int color_type, int compression_type, int filter_type,
  196628. int interlace_type)
  196629. {
  196630. #ifdef PNG_USE_LOCAL_ARRAYS
  196631. PNG_IHDR;
  196632. #endif
  196633. png_byte buf[13]; /* buffer to store the IHDR info */
  196634. png_debug(1, "in png_write_IHDR\n");
  196635. /* Check that we have valid input data from the application info */
  196636. switch (color_type)
  196637. {
  196638. case PNG_COLOR_TYPE_GRAY:
  196639. switch (bit_depth)
  196640. {
  196641. case 1:
  196642. case 2:
  196643. case 4:
  196644. case 8:
  196645. case 16: png_ptr->channels = 1; break;
  196646. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  196647. }
  196648. break;
  196649. case PNG_COLOR_TYPE_RGB:
  196650. if (bit_depth != 8 && bit_depth != 16)
  196651. png_error(png_ptr, "Invalid bit depth for RGB image");
  196652. png_ptr->channels = 3;
  196653. break;
  196654. case PNG_COLOR_TYPE_PALETTE:
  196655. switch (bit_depth)
  196656. {
  196657. case 1:
  196658. case 2:
  196659. case 4:
  196660. case 8: png_ptr->channels = 1; break;
  196661. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  196662. }
  196663. break;
  196664. case PNG_COLOR_TYPE_GRAY_ALPHA:
  196665. if (bit_depth != 8 && bit_depth != 16)
  196666. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  196667. png_ptr->channels = 2;
  196668. break;
  196669. case PNG_COLOR_TYPE_RGB_ALPHA:
  196670. if (bit_depth != 8 && bit_depth != 16)
  196671. png_error(png_ptr, "Invalid bit depth for RGBA image");
  196672. png_ptr->channels = 4;
  196673. break;
  196674. default:
  196675. png_error(png_ptr, "Invalid image color type specified");
  196676. }
  196677. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196678. {
  196679. png_warning(png_ptr, "Invalid compression type specified");
  196680. compression_type = PNG_COMPRESSION_TYPE_BASE;
  196681. }
  196682. /* Write filter_method 64 (intrapixel differencing) only if
  196683. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196684. * 2. Libpng did not write a PNG signature (this filter_method is only
  196685. * used in PNG datastreams that are embedded in MNG datastreams) and
  196686. * 3. The application called png_permit_mng_features with a mask that
  196687. * included PNG_FLAG_MNG_FILTER_64 and
  196688. * 4. The filter_method is 64 and
  196689. * 5. The color_type is RGB or RGBA
  196690. */
  196691. if (
  196692. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196693. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196694. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196695. (color_type == PNG_COLOR_TYPE_RGB ||
  196696. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  196697. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  196698. #endif
  196699. filter_type != PNG_FILTER_TYPE_BASE)
  196700. {
  196701. png_warning(png_ptr, "Invalid filter type specified");
  196702. filter_type = PNG_FILTER_TYPE_BASE;
  196703. }
  196704. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196705. if (interlace_type != PNG_INTERLACE_NONE &&
  196706. interlace_type != PNG_INTERLACE_ADAM7)
  196707. {
  196708. png_warning(png_ptr, "Invalid interlace type specified");
  196709. interlace_type = PNG_INTERLACE_ADAM7;
  196710. }
  196711. #else
  196712. interlace_type=PNG_INTERLACE_NONE;
  196713. #endif
  196714. /* save off the relevent information */
  196715. png_ptr->bit_depth = (png_byte)bit_depth;
  196716. png_ptr->color_type = (png_byte)color_type;
  196717. png_ptr->interlaced = (png_byte)interlace_type;
  196718. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196719. png_ptr->filter_type = (png_byte)filter_type;
  196720. #endif
  196721. png_ptr->compression_type = (png_byte)compression_type;
  196722. png_ptr->width = width;
  196723. png_ptr->height = height;
  196724. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  196725. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  196726. /* set the usr info, so any transformations can modify it */
  196727. png_ptr->usr_width = png_ptr->width;
  196728. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  196729. png_ptr->usr_channels = png_ptr->channels;
  196730. /* pack the header information into the buffer */
  196731. png_save_uint_32(buf, width);
  196732. png_save_uint_32(buf + 4, height);
  196733. buf[8] = (png_byte)bit_depth;
  196734. buf[9] = (png_byte)color_type;
  196735. buf[10] = (png_byte)compression_type;
  196736. buf[11] = (png_byte)filter_type;
  196737. buf[12] = (png_byte)interlace_type;
  196738. /* write the chunk */
  196739. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  196740. /* initialize zlib with PNG info */
  196741. png_ptr->zstream.zalloc = png_zalloc;
  196742. png_ptr->zstream.zfree = png_zfree;
  196743. png_ptr->zstream.opaque = (voidpf)png_ptr;
  196744. if (!(png_ptr->do_filter))
  196745. {
  196746. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  196747. png_ptr->bit_depth < 8)
  196748. png_ptr->do_filter = PNG_FILTER_NONE;
  196749. else
  196750. png_ptr->do_filter = PNG_ALL_FILTERS;
  196751. }
  196752. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  196753. {
  196754. if (png_ptr->do_filter != PNG_FILTER_NONE)
  196755. png_ptr->zlib_strategy = Z_FILTERED;
  196756. else
  196757. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  196758. }
  196759. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  196760. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  196761. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  196762. png_ptr->zlib_mem_level = 8;
  196763. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  196764. png_ptr->zlib_window_bits = 15;
  196765. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  196766. png_ptr->zlib_method = 8;
  196767. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  196768. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  196769. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  196770. png_error(png_ptr, "zlib failed to initialize compressor");
  196771. png_ptr->zstream.next_out = png_ptr->zbuf;
  196772. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196773. /* libpng is not interested in zstream.data_type */
  196774. /* set it to a predefined value, to avoid its evaluation inside zlib */
  196775. png_ptr->zstream.data_type = Z_BINARY;
  196776. png_ptr->mode = PNG_HAVE_IHDR;
  196777. }
  196778. /* write the palette. We are careful not to trust png_color to be in the
  196779. * correct order for PNG, so people can redefine it to any convenient
  196780. * structure.
  196781. */
  196782. void /* PRIVATE */
  196783. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  196784. {
  196785. #ifdef PNG_USE_LOCAL_ARRAYS
  196786. PNG_PLTE;
  196787. #endif
  196788. png_uint_32 i;
  196789. png_colorp pal_ptr;
  196790. png_byte buf[3];
  196791. png_debug(1, "in png_write_PLTE\n");
  196792. if ((
  196793. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196794. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  196795. #endif
  196796. num_pal == 0) || num_pal > 256)
  196797. {
  196798. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196799. {
  196800. png_error(png_ptr, "Invalid number of colors in palette");
  196801. }
  196802. else
  196803. {
  196804. png_warning(png_ptr, "Invalid number of colors in palette");
  196805. return;
  196806. }
  196807. }
  196808. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  196809. {
  196810. png_warning(png_ptr,
  196811. "Ignoring request to write a PLTE chunk in grayscale PNG");
  196812. return;
  196813. }
  196814. png_ptr->num_palette = (png_uint_16)num_pal;
  196815. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  196816. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  196817. #ifndef PNG_NO_POINTER_INDEXING
  196818. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  196819. {
  196820. buf[0] = pal_ptr->red;
  196821. buf[1] = pal_ptr->green;
  196822. buf[2] = pal_ptr->blue;
  196823. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196824. }
  196825. #else
  196826. /* This is a little slower but some buggy compilers need to do this instead */
  196827. pal_ptr=palette;
  196828. for (i = 0; i < num_pal; i++)
  196829. {
  196830. buf[0] = pal_ptr[i].red;
  196831. buf[1] = pal_ptr[i].green;
  196832. buf[2] = pal_ptr[i].blue;
  196833. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196834. }
  196835. #endif
  196836. png_write_chunk_end(png_ptr);
  196837. png_ptr->mode |= PNG_HAVE_PLTE;
  196838. }
  196839. /* write an IDAT chunk */
  196840. void /* PRIVATE */
  196841. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  196842. {
  196843. #ifdef PNG_USE_LOCAL_ARRAYS
  196844. PNG_IDAT;
  196845. #endif
  196846. png_debug(1, "in png_write_IDAT\n");
  196847. /* Optimize the CMF field in the zlib stream. */
  196848. /* This hack of the zlib stream is compliant to the stream specification. */
  196849. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  196850. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  196851. {
  196852. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  196853. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  196854. {
  196855. /* Avoid memory underflows and multiplication overflows. */
  196856. /* The conditions below are practically always satisfied;
  196857. however, they still must be checked. */
  196858. if (length >= 2 &&
  196859. png_ptr->height < 16384 && png_ptr->width < 16384)
  196860. {
  196861. png_uint_32 uncompressed_idat_size = png_ptr->height *
  196862. ((png_ptr->width *
  196863. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  196864. unsigned int z_cinfo = z_cmf >> 4;
  196865. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  196866. while (uncompressed_idat_size <= half_z_window_size &&
  196867. half_z_window_size >= 256)
  196868. {
  196869. z_cinfo--;
  196870. half_z_window_size >>= 1;
  196871. }
  196872. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  196873. if (data[0] != (png_byte)z_cmf)
  196874. {
  196875. data[0] = (png_byte)z_cmf;
  196876. data[1] &= 0xe0;
  196877. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  196878. }
  196879. }
  196880. }
  196881. else
  196882. png_error(png_ptr,
  196883. "Invalid zlib compression method or flags in IDAT");
  196884. }
  196885. png_write_chunk(png_ptr, png_IDAT, data, length);
  196886. png_ptr->mode |= PNG_HAVE_IDAT;
  196887. }
  196888. /* write an IEND chunk */
  196889. void /* PRIVATE */
  196890. png_write_IEND(png_structp png_ptr)
  196891. {
  196892. #ifdef PNG_USE_LOCAL_ARRAYS
  196893. PNG_IEND;
  196894. #endif
  196895. png_debug(1, "in png_write_IEND\n");
  196896. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  196897. (png_size_t)0);
  196898. png_ptr->mode |= PNG_HAVE_IEND;
  196899. }
  196900. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  196901. /* write a gAMA chunk */
  196902. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196903. void /* PRIVATE */
  196904. png_write_gAMA(png_structp png_ptr, double file_gamma)
  196905. {
  196906. #ifdef PNG_USE_LOCAL_ARRAYS
  196907. PNG_gAMA;
  196908. #endif
  196909. png_uint_32 igamma;
  196910. png_byte buf[4];
  196911. png_debug(1, "in png_write_gAMA\n");
  196912. /* file_gamma is saved in 1/100,000ths */
  196913. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  196914. png_save_uint_32(buf, igamma);
  196915. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196916. }
  196917. #endif
  196918. #ifdef PNG_FIXED_POINT_SUPPORTED
  196919. void /* PRIVATE */
  196920. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  196921. {
  196922. #ifdef PNG_USE_LOCAL_ARRAYS
  196923. PNG_gAMA;
  196924. #endif
  196925. png_byte buf[4];
  196926. png_debug(1, "in png_write_gAMA\n");
  196927. /* file_gamma is saved in 1/100,000ths */
  196928. png_save_uint_32(buf, (png_uint_32)file_gamma);
  196929. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196930. }
  196931. #endif
  196932. #endif
  196933. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  196934. /* write a sRGB chunk */
  196935. void /* PRIVATE */
  196936. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  196937. {
  196938. #ifdef PNG_USE_LOCAL_ARRAYS
  196939. PNG_sRGB;
  196940. #endif
  196941. png_byte buf[1];
  196942. png_debug(1, "in png_write_sRGB\n");
  196943. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  196944. png_warning(png_ptr,
  196945. "Invalid sRGB rendering intent specified");
  196946. buf[0]=(png_byte)srgb_intent;
  196947. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  196948. }
  196949. #endif
  196950. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  196951. /* write an iCCP chunk */
  196952. void /* PRIVATE */
  196953. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  196954. png_charp profile, int profile_len)
  196955. {
  196956. #ifdef PNG_USE_LOCAL_ARRAYS
  196957. PNG_iCCP;
  196958. #endif
  196959. png_size_t name_len;
  196960. png_charp new_name;
  196961. compression_state comp;
  196962. int embedded_profile_len = 0;
  196963. png_debug(1, "in png_write_iCCP\n");
  196964. comp.num_output_ptr = 0;
  196965. comp.max_output_ptr = 0;
  196966. comp.output_ptr = NULL;
  196967. comp.input = NULL;
  196968. comp.input_len = 0;
  196969. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  196970. &new_name)) == 0)
  196971. {
  196972. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  196973. return;
  196974. }
  196975. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196976. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  196977. if (profile == NULL)
  196978. profile_len = 0;
  196979. if (profile_len > 3)
  196980. embedded_profile_len =
  196981. ((*( (png_bytep)profile ))<<24) |
  196982. ((*( (png_bytep)profile+1))<<16) |
  196983. ((*( (png_bytep)profile+2))<< 8) |
  196984. ((*( (png_bytep)profile+3)) );
  196985. if (profile_len < embedded_profile_len)
  196986. {
  196987. png_warning(png_ptr,
  196988. "Embedded profile length too large in iCCP chunk");
  196989. return;
  196990. }
  196991. if (profile_len > embedded_profile_len)
  196992. {
  196993. png_warning(png_ptr,
  196994. "Truncating profile to actual length in iCCP chunk");
  196995. profile_len = embedded_profile_len;
  196996. }
  196997. if (profile_len)
  196998. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  196999. PNG_COMPRESSION_TYPE_BASE, &comp);
  197000. /* make sure we include the NULL after the name and the compression type */
  197001. png_write_chunk_start(png_ptr, png_iCCP,
  197002. (png_uint_32)name_len+profile_len+2);
  197003. new_name[name_len+1]=0x00;
  197004. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  197005. if (profile_len)
  197006. png_write_compressed_data_out(png_ptr, &comp);
  197007. png_write_chunk_end(png_ptr);
  197008. png_free(png_ptr, new_name);
  197009. }
  197010. #endif
  197011. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  197012. /* write a sPLT chunk */
  197013. void /* PRIVATE */
  197014. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  197015. {
  197016. #ifdef PNG_USE_LOCAL_ARRAYS
  197017. PNG_sPLT;
  197018. #endif
  197019. png_size_t name_len;
  197020. png_charp new_name;
  197021. png_byte entrybuf[10];
  197022. int entry_size = (spalette->depth == 8 ? 6 : 10);
  197023. int palette_size = entry_size * spalette->nentries;
  197024. png_sPLT_entryp ep;
  197025. #ifdef PNG_NO_POINTER_INDEXING
  197026. int i;
  197027. #endif
  197028. png_debug(1, "in png_write_sPLT\n");
  197029. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  197030. spalette->name, &new_name))==0)
  197031. {
  197032. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  197033. return;
  197034. }
  197035. /* make sure we include the NULL after the name */
  197036. png_write_chunk_start(png_ptr, png_sPLT,
  197037. (png_uint_32)(name_len + 2 + palette_size));
  197038. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  197039. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  197040. /* loop through each palette entry, writing appropriately */
  197041. #ifndef PNG_NO_POINTER_INDEXING
  197042. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  197043. {
  197044. if (spalette->depth == 8)
  197045. {
  197046. entrybuf[0] = (png_byte)ep->red;
  197047. entrybuf[1] = (png_byte)ep->green;
  197048. entrybuf[2] = (png_byte)ep->blue;
  197049. entrybuf[3] = (png_byte)ep->alpha;
  197050. png_save_uint_16(entrybuf + 4, ep->frequency);
  197051. }
  197052. else
  197053. {
  197054. png_save_uint_16(entrybuf + 0, ep->red);
  197055. png_save_uint_16(entrybuf + 2, ep->green);
  197056. png_save_uint_16(entrybuf + 4, ep->blue);
  197057. png_save_uint_16(entrybuf + 6, ep->alpha);
  197058. png_save_uint_16(entrybuf + 8, ep->frequency);
  197059. }
  197060. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  197061. }
  197062. #else
  197063. ep=spalette->entries;
  197064. for (i=0; i>spalette->nentries; i++)
  197065. {
  197066. if (spalette->depth == 8)
  197067. {
  197068. entrybuf[0] = (png_byte)ep[i].red;
  197069. entrybuf[1] = (png_byte)ep[i].green;
  197070. entrybuf[2] = (png_byte)ep[i].blue;
  197071. entrybuf[3] = (png_byte)ep[i].alpha;
  197072. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  197073. }
  197074. else
  197075. {
  197076. png_save_uint_16(entrybuf + 0, ep[i].red);
  197077. png_save_uint_16(entrybuf + 2, ep[i].green);
  197078. png_save_uint_16(entrybuf + 4, ep[i].blue);
  197079. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  197080. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  197081. }
  197082. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  197083. }
  197084. #endif
  197085. png_write_chunk_end(png_ptr);
  197086. png_free(png_ptr, new_name);
  197087. }
  197088. #endif
  197089. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197090. /* write the sBIT chunk */
  197091. void /* PRIVATE */
  197092. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  197093. {
  197094. #ifdef PNG_USE_LOCAL_ARRAYS
  197095. PNG_sBIT;
  197096. #endif
  197097. png_byte buf[4];
  197098. png_size_t size;
  197099. png_debug(1, "in png_write_sBIT\n");
  197100. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  197101. if (color_type & PNG_COLOR_MASK_COLOR)
  197102. {
  197103. png_byte maxbits;
  197104. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  197105. png_ptr->usr_bit_depth);
  197106. if (sbit->red == 0 || sbit->red > maxbits ||
  197107. sbit->green == 0 || sbit->green > maxbits ||
  197108. sbit->blue == 0 || sbit->blue > maxbits)
  197109. {
  197110. png_warning(png_ptr, "Invalid sBIT depth specified");
  197111. return;
  197112. }
  197113. buf[0] = sbit->red;
  197114. buf[1] = sbit->green;
  197115. buf[2] = sbit->blue;
  197116. size = 3;
  197117. }
  197118. else
  197119. {
  197120. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  197121. {
  197122. png_warning(png_ptr, "Invalid sBIT depth specified");
  197123. return;
  197124. }
  197125. buf[0] = sbit->gray;
  197126. size = 1;
  197127. }
  197128. if (color_type & PNG_COLOR_MASK_ALPHA)
  197129. {
  197130. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  197131. {
  197132. png_warning(png_ptr, "Invalid sBIT depth specified");
  197133. return;
  197134. }
  197135. buf[size++] = sbit->alpha;
  197136. }
  197137. png_write_chunk(png_ptr, png_sBIT, buf, size);
  197138. }
  197139. #endif
  197140. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197141. /* write the cHRM chunk */
  197142. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197143. void /* PRIVATE */
  197144. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  197145. double red_x, double red_y, double green_x, double green_y,
  197146. double blue_x, double blue_y)
  197147. {
  197148. #ifdef PNG_USE_LOCAL_ARRAYS
  197149. PNG_cHRM;
  197150. #endif
  197151. png_byte buf[32];
  197152. png_uint_32 itemp;
  197153. png_debug(1, "in png_write_cHRM\n");
  197154. /* each value is saved in 1/100,000ths */
  197155. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  197156. white_x + white_y > 1.0)
  197157. {
  197158. png_warning(png_ptr, "Invalid cHRM white point specified");
  197159. #if !defined(PNG_NO_CONSOLE_IO)
  197160. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  197161. #endif
  197162. return;
  197163. }
  197164. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  197165. png_save_uint_32(buf, itemp);
  197166. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  197167. png_save_uint_32(buf + 4, itemp);
  197168. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  197169. {
  197170. png_warning(png_ptr, "Invalid cHRM red point specified");
  197171. return;
  197172. }
  197173. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  197174. png_save_uint_32(buf + 8, itemp);
  197175. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  197176. png_save_uint_32(buf + 12, itemp);
  197177. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  197178. {
  197179. png_warning(png_ptr, "Invalid cHRM green point specified");
  197180. return;
  197181. }
  197182. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  197183. png_save_uint_32(buf + 16, itemp);
  197184. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  197185. png_save_uint_32(buf + 20, itemp);
  197186. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  197187. {
  197188. png_warning(png_ptr, "Invalid cHRM blue point specified");
  197189. return;
  197190. }
  197191. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  197192. png_save_uint_32(buf + 24, itemp);
  197193. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  197194. png_save_uint_32(buf + 28, itemp);
  197195. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197196. }
  197197. #endif
  197198. #ifdef PNG_FIXED_POINT_SUPPORTED
  197199. void /* PRIVATE */
  197200. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  197201. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  197202. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  197203. png_fixed_point blue_y)
  197204. {
  197205. #ifdef PNG_USE_LOCAL_ARRAYS
  197206. PNG_cHRM;
  197207. #endif
  197208. png_byte buf[32];
  197209. png_debug(1, "in png_write_cHRM\n");
  197210. /* each value is saved in 1/100,000ths */
  197211. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  197212. {
  197213. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  197214. #if !defined(PNG_NO_CONSOLE_IO)
  197215. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  197216. #endif
  197217. return;
  197218. }
  197219. png_save_uint_32(buf, (png_uint_32)white_x);
  197220. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  197221. if (red_x + red_y > 100000L)
  197222. {
  197223. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  197224. return;
  197225. }
  197226. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  197227. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  197228. if (green_x + green_y > 100000L)
  197229. {
  197230. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  197231. return;
  197232. }
  197233. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  197234. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  197235. if (blue_x + blue_y > 100000L)
  197236. {
  197237. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  197238. return;
  197239. }
  197240. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  197241. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  197242. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197243. }
  197244. #endif
  197245. #endif
  197246. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197247. /* write the tRNS chunk */
  197248. void /* PRIVATE */
  197249. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  197250. int num_trans, int color_type)
  197251. {
  197252. #ifdef PNG_USE_LOCAL_ARRAYS
  197253. PNG_tRNS;
  197254. #endif
  197255. png_byte buf[6];
  197256. png_debug(1, "in png_write_tRNS\n");
  197257. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197258. {
  197259. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  197260. {
  197261. png_warning(png_ptr,"Invalid number of transparent colors specified");
  197262. return;
  197263. }
  197264. /* write the chunk out as it is */
  197265. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  197266. }
  197267. else if (color_type == PNG_COLOR_TYPE_GRAY)
  197268. {
  197269. /* one 16 bit value */
  197270. if(tran->gray >= (1 << png_ptr->bit_depth))
  197271. {
  197272. png_warning(png_ptr,
  197273. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  197274. return;
  197275. }
  197276. png_save_uint_16(buf, tran->gray);
  197277. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  197278. }
  197279. else if (color_type == PNG_COLOR_TYPE_RGB)
  197280. {
  197281. /* three 16 bit values */
  197282. png_save_uint_16(buf, tran->red);
  197283. png_save_uint_16(buf + 2, tran->green);
  197284. png_save_uint_16(buf + 4, tran->blue);
  197285. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197286. {
  197287. png_warning(png_ptr,
  197288. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  197289. return;
  197290. }
  197291. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  197292. }
  197293. else
  197294. {
  197295. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  197296. }
  197297. }
  197298. #endif
  197299. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197300. /* write the background chunk */
  197301. void /* PRIVATE */
  197302. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  197303. {
  197304. #ifdef PNG_USE_LOCAL_ARRAYS
  197305. PNG_bKGD;
  197306. #endif
  197307. png_byte buf[6];
  197308. png_debug(1, "in png_write_bKGD\n");
  197309. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197310. {
  197311. if (
  197312. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197313. (png_ptr->num_palette ||
  197314. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  197315. #endif
  197316. back->index > png_ptr->num_palette)
  197317. {
  197318. png_warning(png_ptr, "Invalid background palette index");
  197319. return;
  197320. }
  197321. buf[0] = back->index;
  197322. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  197323. }
  197324. else if (color_type & PNG_COLOR_MASK_COLOR)
  197325. {
  197326. png_save_uint_16(buf, back->red);
  197327. png_save_uint_16(buf + 2, back->green);
  197328. png_save_uint_16(buf + 4, back->blue);
  197329. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197330. {
  197331. png_warning(png_ptr,
  197332. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  197333. return;
  197334. }
  197335. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  197336. }
  197337. else
  197338. {
  197339. if(back->gray >= (1 << png_ptr->bit_depth))
  197340. {
  197341. png_warning(png_ptr,
  197342. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  197343. return;
  197344. }
  197345. png_save_uint_16(buf, back->gray);
  197346. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  197347. }
  197348. }
  197349. #endif
  197350. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197351. /* write the histogram */
  197352. void /* PRIVATE */
  197353. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  197354. {
  197355. #ifdef PNG_USE_LOCAL_ARRAYS
  197356. PNG_hIST;
  197357. #endif
  197358. int i;
  197359. png_byte buf[3];
  197360. png_debug(1, "in png_write_hIST\n");
  197361. if (num_hist > (int)png_ptr->num_palette)
  197362. {
  197363. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  197364. png_ptr->num_palette);
  197365. png_warning(png_ptr, "Invalid number of histogram entries specified");
  197366. return;
  197367. }
  197368. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  197369. for (i = 0; i < num_hist; i++)
  197370. {
  197371. png_save_uint_16(buf, hist[i]);
  197372. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  197373. }
  197374. png_write_chunk_end(png_ptr);
  197375. }
  197376. #endif
  197377. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  197378. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197379. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  197380. * and if invalid, correct the keyword rather than discarding the entire
  197381. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  197382. * length, forbids leading or trailing whitespace, multiple internal spaces,
  197383. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  197384. *
  197385. * The new_key is allocated to hold the corrected keyword and must be freed
  197386. * by the calling routine. This avoids problems with trying to write to
  197387. * static keywords without having to have duplicate copies of the strings.
  197388. */
  197389. png_size_t /* PRIVATE */
  197390. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  197391. {
  197392. png_size_t key_len;
  197393. png_charp kp, dp;
  197394. int kflag;
  197395. int kwarn=0;
  197396. png_debug(1, "in png_check_keyword\n");
  197397. *new_key = NULL;
  197398. if (key == NULL || (key_len = png_strlen(key)) == 0)
  197399. {
  197400. png_warning(png_ptr, "zero length keyword");
  197401. return ((png_size_t)0);
  197402. }
  197403. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  197404. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  197405. if (*new_key == NULL)
  197406. {
  197407. png_warning(png_ptr, "Out of memory while procesing keyword");
  197408. return ((png_size_t)0);
  197409. }
  197410. /* Replace non-printing characters with a blank and print a warning */
  197411. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  197412. {
  197413. if ((png_byte)*kp < 0x20 ||
  197414. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  197415. {
  197416. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197417. char msg[40];
  197418. png_snprintf(msg, 40,
  197419. "invalid keyword character 0x%02X", (png_byte)*kp);
  197420. png_warning(png_ptr, msg);
  197421. #else
  197422. png_warning(png_ptr, "invalid character in keyword");
  197423. #endif
  197424. *dp = ' ';
  197425. }
  197426. else
  197427. {
  197428. *dp = *kp;
  197429. }
  197430. }
  197431. *dp = '\0';
  197432. /* Remove any trailing white space. */
  197433. kp = *new_key + key_len - 1;
  197434. if (*kp == ' ')
  197435. {
  197436. png_warning(png_ptr, "trailing spaces removed from keyword");
  197437. while (*kp == ' ')
  197438. {
  197439. *(kp--) = '\0';
  197440. key_len--;
  197441. }
  197442. }
  197443. /* Remove any leading white space. */
  197444. kp = *new_key;
  197445. if (*kp == ' ')
  197446. {
  197447. png_warning(png_ptr, "leading spaces removed from keyword");
  197448. while (*kp == ' ')
  197449. {
  197450. kp++;
  197451. key_len--;
  197452. }
  197453. }
  197454. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  197455. /* Remove multiple internal spaces. */
  197456. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  197457. {
  197458. if (*kp == ' ' && kflag == 0)
  197459. {
  197460. *(dp++) = *kp;
  197461. kflag = 1;
  197462. }
  197463. else if (*kp == ' ')
  197464. {
  197465. key_len--;
  197466. kwarn=1;
  197467. }
  197468. else
  197469. {
  197470. *(dp++) = *kp;
  197471. kflag = 0;
  197472. }
  197473. }
  197474. *dp = '\0';
  197475. if(kwarn)
  197476. png_warning(png_ptr, "extra interior spaces removed from keyword");
  197477. if (key_len == 0)
  197478. {
  197479. png_free(png_ptr, *new_key);
  197480. *new_key=NULL;
  197481. png_warning(png_ptr, "Zero length keyword");
  197482. }
  197483. if (key_len > 79)
  197484. {
  197485. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  197486. new_key[79] = '\0';
  197487. key_len = 79;
  197488. }
  197489. return (key_len);
  197490. }
  197491. #endif
  197492. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197493. /* write a tEXt chunk */
  197494. void /* PRIVATE */
  197495. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  197496. png_size_t text_len)
  197497. {
  197498. #ifdef PNG_USE_LOCAL_ARRAYS
  197499. PNG_tEXt;
  197500. #endif
  197501. png_size_t key_len;
  197502. png_charp new_key;
  197503. png_debug(1, "in png_write_tEXt\n");
  197504. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197505. {
  197506. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  197507. return;
  197508. }
  197509. if (text == NULL || *text == '\0')
  197510. text_len = 0;
  197511. else
  197512. text_len = png_strlen(text);
  197513. /* make sure we include the 0 after the key */
  197514. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  197515. /*
  197516. * We leave it to the application to meet PNG-1.0 requirements on the
  197517. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197518. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197519. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197520. */
  197521. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197522. if (text_len)
  197523. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  197524. png_write_chunk_end(png_ptr);
  197525. png_free(png_ptr, new_key);
  197526. }
  197527. #endif
  197528. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197529. /* write a compressed text chunk */
  197530. void /* PRIVATE */
  197531. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  197532. png_size_t text_len, int compression)
  197533. {
  197534. #ifdef PNG_USE_LOCAL_ARRAYS
  197535. PNG_zTXt;
  197536. #endif
  197537. png_size_t key_len;
  197538. char buf[1];
  197539. png_charp new_key;
  197540. compression_state comp;
  197541. png_debug(1, "in png_write_zTXt\n");
  197542. comp.num_output_ptr = 0;
  197543. comp.max_output_ptr = 0;
  197544. comp.output_ptr = NULL;
  197545. comp.input = NULL;
  197546. comp.input_len = 0;
  197547. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197548. {
  197549. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  197550. return;
  197551. }
  197552. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  197553. {
  197554. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  197555. png_free(png_ptr, new_key);
  197556. return;
  197557. }
  197558. text_len = png_strlen(text);
  197559. /* compute the compressed data; do it now for the length */
  197560. text_len = png_text_compress(png_ptr, text, text_len, compression,
  197561. &comp);
  197562. /* write start of chunk */
  197563. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  197564. (key_len+text_len+2));
  197565. /* write key */
  197566. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197567. png_free(png_ptr, new_key);
  197568. buf[0] = (png_byte)compression;
  197569. /* write compression */
  197570. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  197571. /* write the compressed data */
  197572. png_write_compressed_data_out(png_ptr, &comp);
  197573. /* close the chunk */
  197574. png_write_chunk_end(png_ptr);
  197575. }
  197576. #endif
  197577. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197578. /* write an iTXt chunk */
  197579. void /* PRIVATE */
  197580. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  197581. png_charp lang, png_charp lang_key, png_charp text)
  197582. {
  197583. #ifdef PNG_USE_LOCAL_ARRAYS
  197584. PNG_iTXt;
  197585. #endif
  197586. png_size_t lang_len, key_len, lang_key_len, text_len;
  197587. png_charp new_lang, new_key;
  197588. png_byte cbuf[2];
  197589. compression_state comp;
  197590. png_debug(1, "in png_write_iTXt\n");
  197591. comp.num_output_ptr = 0;
  197592. comp.max_output_ptr = 0;
  197593. comp.output_ptr = NULL;
  197594. comp.input = NULL;
  197595. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197596. {
  197597. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  197598. return;
  197599. }
  197600. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  197601. {
  197602. png_warning(png_ptr, "Empty language field in iTXt chunk");
  197603. new_lang = NULL;
  197604. lang_len = 0;
  197605. }
  197606. if (lang_key == NULL)
  197607. lang_key_len = 0;
  197608. else
  197609. lang_key_len = png_strlen(lang_key);
  197610. if (text == NULL)
  197611. text_len = 0;
  197612. else
  197613. text_len = png_strlen(text);
  197614. /* compute the compressed data; do it now for the length */
  197615. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  197616. &comp);
  197617. /* make sure we include the compression flag, the compression byte,
  197618. * and the NULs after the key, lang, and lang_key parts */
  197619. png_write_chunk_start(png_ptr, png_iTXt,
  197620. (png_uint_32)(
  197621. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  197622. + key_len
  197623. + lang_len
  197624. + lang_key_len
  197625. + text_len));
  197626. /*
  197627. * We leave it to the application to meet PNG-1.0 requirements on the
  197628. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197629. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197630. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197631. */
  197632. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197633. /* set the compression flag */
  197634. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  197635. compression == PNG_TEXT_COMPRESSION_NONE)
  197636. cbuf[0] = 0;
  197637. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  197638. cbuf[0] = 1;
  197639. /* set the compression method */
  197640. cbuf[1] = 0;
  197641. png_write_chunk_data(png_ptr, cbuf, 2);
  197642. cbuf[0] = 0;
  197643. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  197644. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  197645. png_write_compressed_data_out(png_ptr, &comp);
  197646. png_write_chunk_end(png_ptr);
  197647. png_free(png_ptr, new_key);
  197648. if (new_lang)
  197649. png_free(png_ptr, new_lang);
  197650. }
  197651. #endif
  197652. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  197653. /* write the oFFs chunk */
  197654. void /* PRIVATE */
  197655. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  197656. int unit_type)
  197657. {
  197658. #ifdef PNG_USE_LOCAL_ARRAYS
  197659. PNG_oFFs;
  197660. #endif
  197661. png_byte buf[9];
  197662. png_debug(1, "in png_write_oFFs\n");
  197663. if (unit_type >= PNG_OFFSET_LAST)
  197664. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  197665. png_save_int_32(buf, x_offset);
  197666. png_save_int_32(buf + 4, y_offset);
  197667. buf[8] = (png_byte)unit_type;
  197668. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  197669. }
  197670. #endif
  197671. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197672. /* write the pCAL chunk (described in the PNG extensions document) */
  197673. void /* PRIVATE */
  197674. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  197675. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  197676. {
  197677. #ifdef PNG_USE_LOCAL_ARRAYS
  197678. PNG_pCAL;
  197679. #endif
  197680. png_size_t purpose_len, units_len, total_len;
  197681. png_uint_32p params_len;
  197682. png_byte buf[10];
  197683. png_charp new_purpose;
  197684. int i;
  197685. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  197686. if (type >= PNG_EQUATION_LAST)
  197687. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  197688. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  197689. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  197690. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  197691. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  197692. total_len = purpose_len + units_len + 10;
  197693. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  197694. *png_sizeof(png_uint_32)));
  197695. /* Find the length of each parameter, making sure we don't count the
  197696. null terminator for the last parameter. */
  197697. for (i = 0; i < nparams; i++)
  197698. {
  197699. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  197700. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  197701. total_len += (png_size_t)params_len[i];
  197702. }
  197703. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  197704. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  197705. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  197706. png_save_int_32(buf, X0);
  197707. png_save_int_32(buf + 4, X1);
  197708. buf[8] = (png_byte)type;
  197709. buf[9] = (png_byte)nparams;
  197710. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  197711. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  197712. png_free(png_ptr, new_purpose);
  197713. for (i = 0; i < nparams; i++)
  197714. {
  197715. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  197716. (png_size_t)params_len[i]);
  197717. }
  197718. png_free(png_ptr, params_len);
  197719. png_write_chunk_end(png_ptr);
  197720. }
  197721. #endif
  197722. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197723. /* write the sCAL chunk */
  197724. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197725. void /* PRIVATE */
  197726. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  197727. {
  197728. #ifdef PNG_USE_LOCAL_ARRAYS
  197729. PNG_sCAL;
  197730. #endif
  197731. char buf[64];
  197732. png_size_t total_len;
  197733. png_debug(1, "in png_write_sCAL\n");
  197734. buf[0] = (char)unit;
  197735. #if defined(_WIN32_WCE)
  197736. /* sprintf() function is not supported on WindowsCE */
  197737. {
  197738. wchar_t wc_buf[32];
  197739. size_t wc_len;
  197740. swprintf(wc_buf, TEXT("%12.12e"), width);
  197741. wc_len = wcslen(wc_buf);
  197742. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  197743. total_len = wc_len + 2;
  197744. swprintf(wc_buf, TEXT("%12.12e"), height);
  197745. wc_len = wcslen(wc_buf);
  197746. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  197747. NULL, NULL);
  197748. total_len += wc_len;
  197749. }
  197750. #else
  197751. png_snprintf(buf + 1, 63, "%12.12e", width);
  197752. total_len = 1 + png_strlen(buf + 1) + 1;
  197753. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  197754. total_len += png_strlen(buf + total_len);
  197755. #endif
  197756. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197757. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  197758. }
  197759. #else
  197760. #ifdef PNG_FIXED_POINT_SUPPORTED
  197761. void /* PRIVATE */
  197762. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  197763. png_charp height)
  197764. {
  197765. #ifdef PNG_USE_LOCAL_ARRAYS
  197766. PNG_sCAL;
  197767. #endif
  197768. png_byte buf[64];
  197769. png_size_t wlen, hlen, total_len;
  197770. png_debug(1, "in png_write_sCAL_s\n");
  197771. wlen = png_strlen(width);
  197772. hlen = png_strlen(height);
  197773. total_len = wlen + hlen + 2;
  197774. if (total_len > 64)
  197775. {
  197776. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  197777. return;
  197778. }
  197779. buf[0] = (png_byte)unit;
  197780. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  197781. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  197782. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197783. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  197784. }
  197785. #endif
  197786. #endif
  197787. #endif
  197788. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197789. /* write the pHYs chunk */
  197790. void /* PRIVATE */
  197791. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  197792. png_uint_32 y_pixels_per_unit,
  197793. int unit_type)
  197794. {
  197795. #ifdef PNG_USE_LOCAL_ARRAYS
  197796. PNG_pHYs;
  197797. #endif
  197798. png_byte buf[9];
  197799. png_debug(1, "in png_write_pHYs\n");
  197800. if (unit_type >= PNG_RESOLUTION_LAST)
  197801. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  197802. png_save_uint_32(buf, x_pixels_per_unit);
  197803. png_save_uint_32(buf + 4, y_pixels_per_unit);
  197804. buf[8] = (png_byte)unit_type;
  197805. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  197806. }
  197807. #endif
  197808. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197809. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  197810. * or png_convert_from_time_t(), or fill in the structure yourself.
  197811. */
  197812. void /* PRIVATE */
  197813. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  197814. {
  197815. #ifdef PNG_USE_LOCAL_ARRAYS
  197816. PNG_tIME;
  197817. #endif
  197818. png_byte buf[7];
  197819. png_debug(1, "in png_write_tIME\n");
  197820. if (mod_time->month > 12 || mod_time->month < 1 ||
  197821. mod_time->day > 31 || mod_time->day < 1 ||
  197822. mod_time->hour > 23 || mod_time->second > 60)
  197823. {
  197824. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  197825. return;
  197826. }
  197827. png_save_uint_16(buf, mod_time->year);
  197828. buf[2] = mod_time->month;
  197829. buf[3] = mod_time->day;
  197830. buf[4] = mod_time->hour;
  197831. buf[5] = mod_time->minute;
  197832. buf[6] = mod_time->second;
  197833. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  197834. }
  197835. #endif
  197836. /* initializes the row writing capability of libpng */
  197837. void /* PRIVATE */
  197838. png_write_start_row(png_structp png_ptr)
  197839. {
  197840. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197841. #ifdef PNG_USE_LOCAL_ARRAYS
  197842. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197843. /* start of interlace block */
  197844. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197845. /* offset to next interlace block */
  197846. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197847. /* start of interlace block in the y direction */
  197848. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197849. /* offset to next interlace block in the y direction */
  197850. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197851. #endif
  197852. #endif
  197853. png_size_t buf_size;
  197854. png_debug(1, "in png_write_start_row\n");
  197855. buf_size = (png_size_t)(PNG_ROWBYTES(
  197856. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  197857. /* set up row buffer */
  197858. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197859. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  197860. #ifndef PNG_NO_WRITE_FILTERING
  197861. /* set up filtering buffer, if using this filter */
  197862. if (png_ptr->do_filter & PNG_FILTER_SUB)
  197863. {
  197864. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  197865. (png_ptr->rowbytes + 1));
  197866. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  197867. }
  197868. /* We only need to keep the previous row if we are using one of these. */
  197869. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  197870. {
  197871. /* set up previous row buffer */
  197872. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197873. png_memset(png_ptr->prev_row, 0, buf_size);
  197874. if (png_ptr->do_filter & PNG_FILTER_UP)
  197875. {
  197876. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  197877. (png_ptr->rowbytes + 1));
  197878. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  197879. }
  197880. if (png_ptr->do_filter & PNG_FILTER_AVG)
  197881. {
  197882. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  197883. (png_ptr->rowbytes + 1));
  197884. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  197885. }
  197886. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  197887. {
  197888. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  197889. (png_ptr->rowbytes + 1));
  197890. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  197891. }
  197892. #endif /* PNG_NO_WRITE_FILTERING */
  197893. }
  197894. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197895. /* if interlaced, we need to set up width and height of pass */
  197896. if (png_ptr->interlaced)
  197897. {
  197898. if (!(png_ptr->transformations & PNG_INTERLACE))
  197899. {
  197900. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197901. png_pass_ystart[0]) / png_pass_yinc[0];
  197902. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  197903. png_pass_start[0]) / png_pass_inc[0];
  197904. }
  197905. else
  197906. {
  197907. png_ptr->num_rows = png_ptr->height;
  197908. png_ptr->usr_width = png_ptr->width;
  197909. }
  197910. }
  197911. else
  197912. #endif
  197913. {
  197914. png_ptr->num_rows = png_ptr->height;
  197915. png_ptr->usr_width = png_ptr->width;
  197916. }
  197917. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197918. png_ptr->zstream.next_out = png_ptr->zbuf;
  197919. }
  197920. /* Internal use only. Called when finished processing a row of data. */
  197921. void /* PRIVATE */
  197922. png_write_finish_row(png_structp png_ptr)
  197923. {
  197924. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197925. #ifdef PNG_USE_LOCAL_ARRAYS
  197926. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197927. /* start of interlace block */
  197928. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197929. /* offset to next interlace block */
  197930. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197931. /* start of interlace block in the y direction */
  197932. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197933. /* offset to next interlace block in the y direction */
  197934. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197935. #endif
  197936. #endif
  197937. int ret;
  197938. png_debug(1, "in png_write_finish_row\n");
  197939. /* next row */
  197940. png_ptr->row_number++;
  197941. /* see if we are done */
  197942. if (png_ptr->row_number < png_ptr->num_rows)
  197943. return;
  197944. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197945. /* if interlaced, go to next pass */
  197946. if (png_ptr->interlaced)
  197947. {
  197948. png_ptr->row_number = 0;
  197949. if (png_ptr->transformations & PNG_INTERLACE)
  197950. {
  197951. png_ptr->pass++;
  197952. }
  197953. else
  197954. {
  197955. /* loop until we find a non-zero width or height pass */
  197956. do
  197957. {
  197958. png_ptr->pass++;
  197959. if (png_ptr->pass >= 7)
  197960. break;
  197961. png_ptr->usr_width = (png_ptr->width +
  197962. png_pass_inc[png_ptr->pass] - 1 -
  197963. png_pass_start[png_ptr->pass]) /
  197964. png_pass_inc[png_ptr->pass];
  197965. png_ptr->num_rows = (png_ptr->height +
  197966. png_pass_yinc[png_ptr->pass] - 1 -
  197967. png_pass_ystart[png_ptr->pass]) /
  197968. png_pass_yinc[png_ptr->pass];
  197969. if (png_ptr->transformations & PNG_INTERLACE)
  197970. break;
  197971. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  197972. }
  197973. /* reset the row above the image for the next pass */
  197974. if (png_ptr->pass < 7)
  197975. {
  197976. if (png_ptr->prev_row != NULL)
  197977. png_memset(png_ptr->prev_row, 0,
  197978. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  197979. png_ptr->usr_bit_depth,png_ptr->width))+1);
  197980. return;
  197981. }
  197982. }
  197983. #endif
  197984. /* if we get here, we've just written the last row, so we need
  197985. to flush the compressor */
  197986. do
  197987. {
  197988. /* tell the compressor we are done */
  197989. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197990. /* check for an error */
  197991. if (ret == Z_OK)
  197992. {
  197993. /* check to see if we need more room */
  197994. if (!(png_ptr->zstream.avail_out))
  197995. {
  197996. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197997. png_ptr->zstream.next_out = png_ptr->zbuf;
  197998. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197999. }
  198000. }
  198001. else if (ret != Z_STREAM_END)
  198002. {
  198003. if (png_ptr->zstream.msg != NULL)
  198004. png_error(png_ptr, png_ptr->zstream.msg);
  198005. else
  198006. png_error(png_ptr, "zlib error");
  198007. }
  198008. } while (ret != Z_STREAM_END);
  198009. /* write any extra space */
  198010. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  198011. {
  198012. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  198013. png_ptr->zstream.avail_out);
  198014. }
  198015. deflateReset(&png_ptr->zstream);
  198016. png_ptr->zstream.data_type = Z_BINARY;
  198017. }
  198018. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198019. /* Pick out the correct pixels for the interlace pass.
  198020. * The basic idea here is to go through the row with a source
  198021. * pointer and a destination pointer (sp and dp), and copy the
  198022. * correct pixels for the pass. As the row gets compacted,
  198023. * sp will always be >= dp, so we should never overwrite anything.
  198024. * See the default: case for the easiest code to understand.
  198025. */
  198026. void /* PRIVATE */
  198027. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  198028. {
  198029. #ifdef PNG_USE_LOCAL_ARRAYS
  198030. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198031. /* start of interlace block */
  198032. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198033. /* offset to next interlace block */
  198034. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198035. #endif
  198036. png_debug(1, "in png_do_write_interlace\n");
  198037. /* we don't have to do anything on the last pass (6) */
  198038. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198039. if (row != NULL && row_info != NULL && pass < 6)
  198040. #else
  198041. if (pass < 6)
  198042. #endif
  198043. {
  198044. /* each pixel depth is handled separately */
  198045. switch (row_info->pixel_depth)
  198046. {
  198047. case 1:
  198048. {
  198049. png_bytep sp;
  198050. png_bytep dp;
  198051. int shift;
  198052. int d;
  198053. int value;
  198054. png_uint_32 i;
  198055. png_uint_32 row_width = row_info->width;
  198056. dp = row;
  198057. d = 0;
  198058. shift = 7;
  198059. for (i = png_pass_start[pass]; i < row_width;
  198060. i += png_pass_inc[pass])
  198061. {
  198062. sp = row + (png_size_t)(i >> 3);
  198063. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  198064. d |= (value << shift);
  198065. if (shift == 0)
  198066. {
  198067. shift = 7;
  198068. *dp++ = (png_byte)d;
  198069. d = 0;
  198070. }
  198071. else
  198072. shift--;
  198073. }
  198074. if (shift != 7)
  198075. *dp = (png_byte)d;
  198076. break;
  198077. }
  198078. case 2:
  198079. {
  198080. png_bytep sp;
  198081. png_bytep dp;
  198082. int shift;
  198083. int d;
  198084. int value;
  198085. png_uint_32 i;
  198086. png_uint_32 row_width = row_info->width;
  198087. dp = row;
  198088. shift = 6;
  198089. d = 0;
  198090. for (i = png_pass_start[pass]; i < row_width;
  198091. i += png_pass_inc[pass])
  198092. {
  198093. sp = row + (png_size_t)(i >> 2);
  198094. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  198095. d |= (value << shift);
  198096. if (shift == 0)
  198097. {
  198098. shift = 6;
  198099. *dp++ = (png_byte)d;
  198100. d = 0;
  198101. }
  198102. else
  198103. shift -= 2;
  198104. }
  198105. if (shift != 6)
  198106. *dp = (png_byte)d;
  198107. break;
  198108. }
  198109. case 4:
  198110. {
  198111. png_bytep sp;
  198112. png_bytep dp;
  198113. int shift;
  198114. int d;
  198115. int value;
  198116. png_uint_32 i;
  198117. png_uint_32 row_width = row_info->width;
  198118. dp = row;
  198119. shift = 4;
  198120. d = 0;
  198121. for (i = png_pass_start[pass]; i < row_width;
  198122. i += png_pass_inc[pass])
  198123. {
  198124. sp = row + (png_size_t)(i >> 1);
  198125. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  198126. d |= (value << shift);
  198127. if (shift == 0)
  198128. {
  198129. shift = 4;
  198130. *dp++ = (png_byte)d;
  198131. d = 0;
  198132. }
  198133. else
  198134. shift -= 4;
  198135. }
  198136. if (shift != 4)
  198137. *dp = (png_byte)d;
  198138. break;
  198139. }
  198140. default:
  198141. {
  198142. png_bytep sp;
  198143. png_bytep dp;
  198144. png_uint_32 i;
  198145. png_uint_32 row_width = row_info->width;
  198146. png_size_t pixel_bytes;
  198147. /* start at the beginning */
  198148. dp = row;
  198149. /* find out how many bytes each pixel takes up */
  198150. pixel_bytes = (row_info->pixel_depth >> 3);
  198151. /* loop through the row, only looking at the pixels that
  198152. matter */
  198153. for (i = png_pass_start[pass]; i < row_width;
  198154. i += png_pass_inc[pass])
  198155. {
  198156. /* find out where the original pixel is */
  198157. sp = row + (png_size_t)i * pixel_bytes;
  198158. /* move the pixel */
  198159. if (dp != sp)
  198160. png_memcpy(dp, sp, pixel_bytes);
  198161. /* next pixel */
  198162. dp += pixel_bytes;
  198163. }
  198164. break;
  198165. }
  198166. }
  198167. /* set new row width */
  198168. row_info->width = (row_info->width +
  198169. png_pass_inc[pass] - 1 -
  198170. png_pass_start[pass]) /
  198171. png_pass_inc[pass];
  198172. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  198173. row_info->width);
  198174. }
  198175. }
  198176. #endif
  198177. /* This filters the row, chooses which filter to use, if it has not already
  198178. * been specified by the application, and then writes the row out with the
  198179. * chosen filter.
  198180. */
  198181. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  198182. #define PNG_HISHIFT 10
  198183. #define PNG_LOMASK ((png_uint_32)0xffffL)
  198184. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  198185. void /* PRIVATE */
  198186. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  198187. {
  198188. png_bytep best_row;
  198189. #ifndef PNG_NO_WRITE_FILTER
  198190. png_bytep prev_row, row_buf;
  198191. png_uint_32 mins, bpp;
  198192. png_byte filter_to_do = png_ptr->do_filter;
  198193. png_uint_32 row_bytes = row_info->rowbytes;
  198194. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198195. int num_p_filters = (int)png_ptr->num_prev_filters;
  198196. #endif
  198197. png_debug(1, "in png_write_find_filter\n");
  198198. /* find out how many bytes offset each pixel is */
  198199. bpp = (row_info->pixel_depth + 7) >> 3;
  198200. prev_row = png_ptr->prev_row;
  198201. #endif
  198202. best_row = png_ptr->row_buf;
  198203. #ifndef PNG_NO_WRITE_FILTER
  198204. row_buf = best_row;
  198205. mins = PNG_MAXSUM;
  198206. /* The prediction method we use is to find which method provides the
  198207. * smallest value when summing the absolute values of the distances
  198208. * from zero, using anything >= 128 as negative numbers. This is known
  198209. * as the "minimum sum of absolute differences" heuristic. Other
  198210. * heuristics are the "weighted minimum sum of absolute differences"
  198211. * (experimental and can in theory improve compression), and the "zlib
  198212. * predictive" method (not implemented yet), which does test compressions
  198213. * of lines using different filter methods, and then chooses the
  198214. * (series of) filter(s) that give minimum compressed data size (VERY
  198215. * computationally expensive).
  198216. *
  198217. * GRR 980525: consider also
  198218. * (1) minimum sum of absolute differences from running average (i.e.,
  198219. * keep running sum of non-absolute differences & count of bytes)
  198220. * [track dispersion, too? restart average if dispersion too large?]
  198221. * (1b) minimum sum of absolute differences from sliding average, probably
  198222. * with window size <= deflate window (usually 32K)
  198223. * (2) minimum sum of squared differences from zero or running average
  198224. * (i.e., ~ root-mean-square approach)
  198225. */
  198226. /* We don't need to test the 'no filter' case if this is the only filter
  198227. * that has been chosen, as it doesn't actually do anything to the data.
  198228. */
  198229. if ((filter_to_do & PNG_FILTER_NONE) &&
  198230. filter_to_do != PNG_FILTER_NONE)
  198231. {
  198232. png_bytep rp;
  198233. png_uint_32 sum = 0;
  198234. png_uint_32 i;
  198235. int v;
  198236. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  198237. {
  198238. v = *rp;
  198239. sum += (v < 128) ? v : 256 - v;
  198240. }
  198241. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198242. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198243. {
  198244. png_uint_32 sumhi, sumlo;
  198245. int j;
  198246. sumlo = sum & PNG_LOMASK;
  198247. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  198248. /* Reduce the sum if we match any of the previous rows */
  198249. for (j = 0; j < num_p_filters; j++)
  198250. {
  198251. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198252. {
  198253. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198254. PNG_WEIGHT_SHIFT;
  198255. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198256. PNG_WEIGHT_SHIFT;
  198257. }
  198258. }
  198259. /* Factor in the cost of this filter (this is here for completeness,
  198260. * but it makes no sense to have a "cost" for the NONE filter, as
  198261. * it has the minimum possible computational cost - none).
  198262. */
  198263. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198264. PNG_COST_SHIFT;
  198265. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198266. PNG_COST_SHIFT;
  198267. if (sumhi > PNG_HIMASK)
  198268. sum = PNG_MAXSUM;
  198269. else
  198270. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198271. }
  198272. #endif
  198273. mins = sum;
  198274. }
  198275. /* sub filter */
  198276. if (filter_to_do == PNG_FILTER_SUB)
  198277. /* it's the only filter so no testing is needed */
  198278. {
  198279. png_bytep rp, lp, dp;
  198280. png_uint_32 i;
  198281. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198282. i++, rp++, dp++)
  198283. {
  198284. *dp = *rp;
  198285. }
  198286. for (lp = row_buf + 1; i < row_bytes;
  198287. i++, rp++, lp++, dp++)
  198288. {
  198289. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198290. }
  198291. best_row = png_ptr->sub_row;
  198292. }
  198293. else if (filter_to_do & PNG_FILTER_SUB)
  198294. {
  198295. png_bytep rp, dp, lp;
  198296. png_uint_32 sum = 0, lmins = mins;
  198297. png_uint_32 i;
  198298. int v;
  198299. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198300. /* We temporarily increase the "minimum sum" by the factor we
  198301. * would reduce the sum of this filter, so that we can do the
  198302. * early exit comparison without scaling the sum each time.
  198303. */
  198304. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198305. {
  198306. int j;
  198307. png_uint_32 lmhi, lmlo;
  198308. lmlo = lmins & PNG_LOMASK;
  198309. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198310. for (j = 0; j < num_p_filters; j++)
  198311. {
  198312. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198313. {
  198314. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198315. PNG_WEIGHT_SHIFT;
  198316. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198317. PNG_WEIGHT_SHIFT;
  198318. }
  198319. }
  198320. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198321. PNG_COST_SHIFT;
  198322. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198323. PNG_COST_SHIFT;
  198324. if (lmhi > PNG_HIMASK)
  198325. lmins = PNG_MAXSUM;
  198326. else
  198327. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198328. }
  198329. #endif
  198330. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198331. i++, rp++, dp++)
  198332. {
  198333. v = *dp = *rp;
  198334. sum += (v < 128) ? v : 256 - v;
  198335. }
  198336. for (lp = row_buf + 1; i < row_bytes;
  198337. i++, rp++, lp++, dp++)
  198338. {
  198339. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198340. sum += (v < 128) ? v : 256 - v;
  198341. if (sum > lmins) /* We are already worse, don't continue. */
  198342. break;
  198343. }
  198344. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198345. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198346. {
  198347. int j;
  198348. png_uint_32 sumhi, sumlo;
  198349. sumlo = sum & PNG_LOMASK;
  198350. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198351. for (j = 0; j < num_p_filters; j++)
  198352. {
  198353. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198354. {
  198355. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  198356. PNG_WEIGHT_SHIFT;
  198357. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  198358. PNG_WEIGHT_SHIFT;
  198359. }
  198360. }
  198361. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198362. PNG_COST_SHIFT;
  198363. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198364. PNG_COST_SHIFT;
  198365. if (sumhi > PNG_HIMASK)
  198366. sum = PNG_MAXSUM;
  198367. else
  198368. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198369. }
  198370. #endif
  198371. if (sum < mins)
  198372. {
  198373. mins = sum;
  198374. best_row = png_ptr->sub_row;
  198375. }
  198376. }
  198377. /* up filter */
  198378. if (filter_to_do == PNG_FILTER_UP)
  198379. {
  198380. png_bytep rp, dp, pp;
  198381. png_uint_32 i;
  198382. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198383. pp = prev_row + 1; i < row_bytes;
  198384. i++, rp++, pp++, dp++)
  198385. {
  198386. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  198387. }
  198388. best_row = png_ptr->up_row;
  198389. }
  198390. else if (filter_to_do & PNG_FILTER_UP)
  198391. {
  198392. png_bytep rp, dp, pp;
  198393. png_uint_32 sum = 0, lmins = mins;
  198394. png_uint_32 i;
  198395. int v;
  198396. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198397. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198398. {
  198399. int j;
  198400. png_uint_32 lmhi, lmlo;
  198401. lmlo = lmins & PNG_LOMASK;
  198402. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198403. for (j = 0; j < num_p_filters; j++)
  198404. {
  198405. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198406. {
  198407. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198408. PNG_WEIGHT_SHIFT;
  198409. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198410. PNG_WEIGHT_SHIFT;
  198411. }
  198412. }
  198413. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198414. PNG_COST_SHIFT;
  198415. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198416. PNG_COST_SHIFT;
  198417. if (lmhi > PNG_HIMASK)
  198418. lmins = PNG_MAXSUM;
  198419. else
  198420. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198421. }
  198422. #endif
  198423. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198424. pp = prev_row + 1; i < row_bytes; i++)
  198425. {
  198426. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198427. sum += (v < 128) ? v : 256 - v;
  198428. if (sum > lmins) /* We are already worse, don't continue. */
  198429. break;
  198430. }
  198431. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198432. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198433. {
  198434. int j;
  198435. png_uint_32 sumhi, sumlo;
  198436. sumlo = sum & PNG_LOMASK;
  198437. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198438. for (j = 0; j < num_p_filters; j++)
  198439. {
  198440. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198441. {
  198442. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198443. PNG_WEIGHT_SHIFT;
  198444. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198445. PNG_WEIGHT_SHIFT;
  198446. }
  198447. }
  198448. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198449. PNG_COST_SHIFT;
  198450. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198451. PNG_COST_SHIFT;
  198452. if (sumhi > PNG_HIMASK)
  198453. sum = PNG_MAXSUM;
  198454. else
  198455. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198456. }
  198457. #endif
  198458. if (sum < mins)
  198459. {
  198460. mins = sum;
  198461. best_row = png_ptr->up_row;
  198462. }
  198463. }
  198464. /* avg filter */
  198465. if (filter_to_do == PNG_FILTER_AVG)
  198466. {
  198467. png_bytep rp, dp, pp, lp;
  198468. png_uint_32 i;
  198469. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198470. pp = prev_row + 1; i < bpp; i++)
  198471. {
  198472. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198473. }
  198474. for (lp = row_buf + 1; i < row_bytes; i++)
  198475. {
  198476. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  198477. & 0xff);
  198478. }
  198479. best_row = png_ptr->avg_row;
  198480. }
  198481. else if (filter_to_do & PNG_FILTER_AVG)
  198482. {
  198483. png_bytep rp, dp, pp, lp;
  198484. png_uint_32 sum = 0, lmins = mins;
  198485. png_uint_32 i;
  198486. int v;
  198487. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198488. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198489. {
  198490. int j;
  198491. png_uint_32 lmhi, lmlo;
  198492. lmlo = lmins & PNG_LOMASK;
  198493. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198494. for (j = 0; j < num_p_filters; j++)
  198495. {
  198496. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  198497. {
  198498. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198499. PNG_WEIGHT_SHIFT;
  198500. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198501. PNG_WEIGHT_SHIFT;
  198502. }
  198503. }
  198504. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198505. PNG_COST_SHIFT;
  198506. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198507. PNG_COST_SHIFT;
  198508. if (lmhi > PNG_HIMASK)
  198509. lmins = PNG_MAXSUM;
  198510. else
  198511. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198512. }
  198513. #endif
  198514. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198515. pp = prev_row + 1; i < bpp; i++)
  198516. {
  198517. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198518. sum += (v < 128) ? v : 256 - v;
  198519. }
  198520. for (lp = row_buf + 1; i < row_bytes; i++)
  198521. {
  198522. v = *dp++ =
  198523. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  198524. sum += (v < 128) ? v : 256 - v;
  198525. if (sum > lmins) /* We are already worse, don't continue. */
  198526. break;
  198527. }
  198528. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198529. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198530. {
  198531. int j;
  198532. png_uint_32 sumhi, sumlo;
  198533. sumlo = sum & PNG_LOMASK;
  198534. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198535. for (j = 0; j < num_p_filters; j++)
  198536. {
  198537. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198538. {
  198539. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198540. PNG_WEIGHT_SHIFT;
  198541. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198542. PNG_WEIGHT_SHIFT;
  198543. }
  198544. }
  198545. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198546. PNG_COST_SHIFT;
  198547. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198548. PNG_COST_SHIFT;
  198549. if (sumhi > PNG_HIMASK)
  198550. sum = PNG_MAXSUM;
  198551. else
  198552. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198553. }
  198554. #endif
  198555. if (sum < mins)
  198556. {
  198557. mins = sum;
  198558. best_row = png_ptr->avg_row;
  198559. }
  198560. }
  198561. /* Paeth filter */
  198562. if (filter_to_do == PNG_FILTER_PAETH)
  198563. {
  198564. png_bytep rp, dp, pp, cp, lp;
  198565. png_uint_32 i;
  198566. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198567. pp = prev_row + 1; i < bpp; i++)
  198568. {
  198569. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198570. }
  198571. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198572. {
  198573. int a, b, c, pa, pb, pc, p;
  198574. b = *pp++;
  198575. c = *cp++;
  198576. a = *lp++;
  198577. p = b - c;
  198578. pc = a - c;
  198579. #ifdef PNG_USE_ABS
  198580. pa = abs(p);
  198581. pb = abs(pc);
  198582. pc = abs(p + pc);
  198583. #else
  198584. pa = p < 0 ? -p : p;
  198585. pb = pc < 0 ? -pc : pc;
  198586. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198587. #endif
  198588. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198589. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198590. }
  198591. best_row = png_ptr->paeth_row;
  198592. }
  198593. else if (filter_to_do & PNG_FILTER_PAETH)
  198594. {
  198595. png_bytep rp, dp, pp, cp, lp;
  198596. png_uint_32 sum = 0, lmins = mins;
  198597. png_uint_32 i;
  198598. int v;
  198599. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198600. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198601. {
  198602. int j;
  198603. png_uint_32 lmhi, lmlo;
  198604. lmlo = lmins & PNG_LOMASK;
  198605. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198606. for (j = 0; j < num_p_filters; j++)
  198607. {
  198608. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198609. {
  198610. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198611. PNG_WEIGHT_SHIFT;
  198612. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198613. PNG_WEIGHT_SHIFT;
  198614. }
  198615. }
  198616. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198617. PNG_COST_SHIFT;
  198618. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198619. PNG_COST_SHIFT;
  198620. if (lmhi > PNG_HIMASK)
  198621. lmins = PNG_MAXSUM;
  198622. else
  198623. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198624. }
  198625. #endif
  198626. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198627. pp = prev_row + 1; i < bpp; i++)
  198628. {
  198629. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198630. sum += (v < 128) ? v : 256 - v;
  198631. }
  198632. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198633. {
  198634. int a, b, c, pa, pb, pc, p;
  198635. b = *pp++;
  198636. c = *cp++;
  198637. a = *lp++;
  198638. #ifndef PNG_SLOW_PAETH
  198639. p = b - c;
  198640. pc = a - c;
  198641. #ifdef PNG_USE_ABS
  198642. pa = abs(p);
  198643. pb = abs(pc);
  198644. pc = abs(p + pc);
  198645. #else
  198646. pa = p < 0 ? -p : p;
  198647. pb = pc < 0 ? -pc : pc;
  198648. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198649. #endif
  198650. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198651. #else /* PNG_SLOW_PAETH */
  198652. p = a + b - c;
  198653. pa = abs(p - a);
  198654. pb = abs(p - b);
  198655. pc = abs(p - c);
  198656. if (pa <= pb && pa <= pc)
  198657. p = a;
  198658. else if (pb <= pc)
  198659. p = b;
  198660. else
  198661. p = c;
  198662. #endif /* PNG_SLOW_PAETH */
  198663. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198664. sum += (v < 128) ? v : 256 - v;
  198665. if (sum > lmins) /* We are already worse, don't continue. */
  198666. break;
  198667. }
  198668. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198669. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198670. {
  198671. int j;
  198672. png_uint_32 sumhi, sumlo;
  198673. sumlo = sum & PNG_LOMASK;
  198674. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198675. for (j = 0; j < num_p_filters; j++)
  198676. {
  198677. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198678. {
  198679. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198680. PNG_WEIGHT_SHIFT;
  198681. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198682. PNG_WEIGHT_SHIFT;
  198683. }
  198684. }
  198685. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198686. PNG_COST_SHIFT;
  198687. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198688. PNG_COST_SHIFT;
  198689. if (sumhi > PNG_HIMASK)
  198690. sum = PNG_MAXSUM;
  198691. else
  198692. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198693. }
  198694. #endif
  198695. if (sum < mins)
  198696. {
  198697. best_row = png_ptr->paeth_row;
  198698. }
  198699. }
  198700. #endif /* PNG_NO_WRITE_FILTER */
  198701. /* Do the actual writing of the filtered row data from the chosen filter. */
  198702. png_write_filtered_row(png_ptr, best_row);
  198703. #ifndef PNG_NO_WRITE_FILTER
  198704. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198705. /* Save the type of filter we picked this time for future calculations */
  198706. if (png_ptr->num_prev_filters > 0)
  198707. {
  198708. int j;
  198709. for (j = 1; j < num_p_filters; j++)
  198710. {
  198711. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  198712. }
  198713. png_ptr->prev_filters[j] = best_row[0];
  198714. }
  198715. #endif
  198716. #endif /* PNG_NO_WRITE_FILTER */
  198717. }
  198718. /* Do the actual writing of a previously filtered row. */
  198719. void /* PRIVATE */
  198720. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  198721. {
  198722. png_debug(1, "in png_write_filtered_row\n");
  198723. png_debug1(2, "filter = %d\n", filtered_row[0]);
  198724. /* set up the zlib input buffer */
  198725. png_ptr->zstream.next_in = filtered_row;
  198726. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  198727. /* repeat until we have compressed all the data */
  198728. do
  198729. {
  198730. int ret; /* return of zlib */
  198731. /* compress the data */
  198732. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  198733. /* check for compression errors */
  198734. if (ret != Z_OK)
  198735. {
  198736. if (png_ptr->zstream.msg != NULL)
  198737. png_error(png_ptr, png_ptr->zstream.msg);
  198738. else
  198739. png_error(png_ptr, "zlib error");
  198740. }
  198741. /* see if it is time to write another IDAT */
  198742. if (!(png_ptr->zstream.avail_out))
  198743. {
  198744. /* write the IDAT and reset the zlib output buffer */
  198745. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198746. png_ptr->zstream.next_out = png_ptr->zbuf;
  198747. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198748. }
  198749. /* repeat until all data has been compressed */
  198750. } while (png_ptr->zstream.avail_in);
  198751. /* swap the current and previous rows */
  198752. if (png_ptr->prev_row != NULL)
  198753. {
  198754. png_bytep tptr;
  198755. tptr = png_ptr->prev_row;
  198756. png_ptr->prev_row = png_ptr->row_buf;
  198757. png_ptr->row_buf = tptr;
  198758. }
  198759. /* finish row - updates counters and flushes zlib if last row */
  198760. png_write_finish_row(png_ptr);
  198761. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198762. png_ptr->flush_rows++;
  198763. if (png_ptr->flush_dist > 0 &&
  198764. png_ptr->flush_rows >= png_ptr->flush_dist)
  198765. {
  198766. png_write_flush(png_ptr);
  198767. }
  198768. #endif
  198769. }
  198770. #endif /* PNG_WRITE_SUPPORTED */
  198771. /********* End of inlined file: pngwutil.c *********/
  198772. }
  198773. #else
  198774. #define PNG_INTERNAL
  198775. #define PNG_SETJMP_NOT_SUPPORTED
  198776. #include <png.h>
  198777. #include <pngconf.h>
  198778. #endif
  198779. }
  198780. #ifdef _MSC_VER
  198781. #pragma warning (pop)
  198782. #endif
  198783. BEGIN_JUCE_NAMESPACE
  198784. using namespace pnglibNamespace;
  198785. using ::calloc;
  198786. using ::malloc;
  198787. using ::free;
  198788. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  198789. {
  198790. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  198791. in->read (data, (int) length);
  198792. }
  198793. struct PNGErrorStruct {};
  198794. static void pngErrorCallback (png_structp, png_const_charp)
  198795. {
  198796. throw PNGErrorStruct();
  198797. }
  198798. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  198799. {
  198800. Image* image = 0;
  198801. png_structp pngReadStruct;
  198802. png_infop pngInfoStruct;
  198803. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198804. if (pngReadStruct != 0)
  198805. {
  198806. pngInfoStruct = png_create_info_struct (pngReadStruct);
  198807. if (pngInfoStruct == 0)
  198808. {
  198809. png_destroy_read_struct (&pngReadStruct, 0, 0);
  198810. return 0;
  198811. }
  198812. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  198813. // read the header..
  198814. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  198815. png_uint_32 width, height;
  198816. int bitDepth, colorType, interlaceType;
  198817. png_read_info (pngReadStruct, pngInfoStruct);
  198818. png_get_IHDR (pngReadStruct, pngInfoStruct,
  198819. &width, &height,
  198820. &bitDepth, &colorType,
  198821. &interlaceType, 0, 0);
  198822. if (bitDepth == 16)
  198823. png_set_strip_16 (pngReadStruct);
  198824. if (colorType == PNG_COLOR_TYPE_PALETTE)
  198825. png_set_expand (pngReadStruct);
  198826. if (bitDepth < 8)
  198827. png_set_expand (pngReadStruct);
  198828. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  198829. png_set_expand (pngReadStruct);
  198830. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  198831. png_set_gray_to_rgb (pngReadStruct);
  198832. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  198833. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  198834. || pngInfoStruct->num_trans > 0;
  198835. // Load the image into a temp buffer in the pnglib format..
  198836. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  198837. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  198838. int y;
  198839. for (y = (int) height; --y >= 0;)
  198840. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  198841. png_read_image (pngReadStruct, rows);
  198842. png_read_end (pngReadStruct, pngInfoStruct);
  198843. juce_free (rows);
  198844. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  198845. // now convert the data to a juce image format..
  198846. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  198847. width, height, hasAlphaChan);
  198848. int stride, pixelStride;
  198849. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  198850. uint8* srcRow = tempBuffer;
  198851. uint8* destRow = pixels;
  198852. for (y = 0; y < (int) height; ++y)
  198853. {
  198854. const uint8* src = srcRow;
  198855. srcRow += (width << 2);
  198856. uint8* dest = destRow;
  198857. destRow += stride;
  198858. if (hasAlphaChan)
  198859. {
  198860. for (int i = width; --i >= 0;)
  198861. {
  198862. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  198863. ((PixelARGB*) dest)->premultiply();
  198864. dest += pixelStride;
  198865. src += 4;
  198866. }
  198867. }
  198868. else
  198869. {
  198870. for (int i = width; --i >= 0;)
  198871. {
  198872. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  198873. dest += pixelStride;
  198874. src += 4;
  198875. }
  198876. }
  198877. }
  198878. image->releasePixelDataReadWrite (pixels);
  198879. juce_free (tempBuffer);
  198880. }
  198881. return image;
  198882. }
  198883. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  198884. {
  198885. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  198886. const bool ok = out->write (data, length);
  198887. (void) ok;
  198888. jassert (ok);
  198889. }
  198890. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  198891. {
  198892. const int width = image.getWidth();
  198893. const int height = image.getHeight();
  198894. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198895. if (pngWriteStruct == 0)
  198896. return false;
  198897. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  198898. if (pngInfoStruct == 0)
  198899. {
  198900. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  198901. return false;
  198902. }
  198903. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  198904. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  198905. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  198906. : PNG_COLOR_TYPE_RGB,
  198907. PNG_INTERLACE_NONE,
  198908. PNG_COMPRESSION_TYPE_BASE,
  198909. PNG_FILTER_TYPE_BASE);
  198910. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  198911. png_color_8 sig_bit;
  198912. sig_bit.red = 8;
  198913. sig_bit.green = 8;
  198914. sig_bit.blue = 8;
  198915. sig_bit.alpha = 8;
  198916. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  198917. png_write_info (pngWriteStruct, pngInfoStruct);
  198918. png_set_shift (pngWriteStruct, &sig_bit);
  198919. png_set_packing (pngWriteStruct);
  198920. for (int y = 0; y < height; ++y)
  198921. {
  198922. uint8* dst = (uint8*) rowData;
  198923. int stride, pixelStride;
  198924. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  198925. const uint8* src = pixels;
  198926. if (image.hasAlphaChannel())
  198927. {
  198928. for (int i = width; --i >= 0;)
  198929. {
  198930. PixelARGB p (*(const PixelARGB*) src);
  198931. p.unpremultiply();
  198932. *dst++ = p.getRed();
  198933. *dst++ = p.getGreen();
  198934. *dst++ = p.getBlue();
  198935. *dst++ = p.getAlpha();
  198936. src += pixelStride;
  198937. }
  198938. }
  198939. else
  198940. {
  198941. for (int i = width; --i >= 0;)
  198942. {
  198943. *dst++ = ((const PixelRGB*) src)->getRed();
  198944. *dst++ = ((const PixelRGB*) src)->getGreen();
  198945. *dst++ = ((const PixelRGB*) src)->getBlue();
  198946. src += pixelStride;
  198947. }
  198948. }
  198949. png_write_rows (pngWriteStruct, &rowData, 1);
  198950. image.releasePixelDataReadOnly (pixels);
  198951. }
  198952. juce_free (rowData);
  198953. png_write_end (pngWriteStruct, pngInfoStruct);
  198954. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  198955. out.flush();
  198956. return true;
  198957. }
  198958. END_JUCE_NAMESPACE
  198959. /********* End of inlined file: juce_PNGLoader.cpp *********/
  198960. #endif
  198961. //==============================================================================
  198962. #if JUCE_WINDOWS
  198963. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  198964. /*
  198965. This file wraps together all the win32-specific code, so that
  198966. we can include all the native headers just once, and compile all our
  198967. platform-specific stuff in one big lump, keeping it out of the way of
  198968. the rest of the codebase.
  198969. */
  198970. BEGIN_JUCE_NAMESPACE
  198971. #define JUCE_INCLUDED_FILE 1
  198972. // Now include the actual code files..
  198973. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198974. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198975. // compiled on its own).
  198976. #if JUCE_INCLUDED_FILE
  198977. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198978. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198979. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198980. #ifndef DOXYGEN
  198981. // use with DynamicLibraryLoader to simplify importing functions
  198982. //
  198983. // functionName: function to import
  198984. // localFunctionName: name you want to use to actually call it (must be different)
  198985. // returnType: the return type
  198986. // object: the DynamicLibraryLoader to use
  198987. // params: list of params (bracketed)
  198988. //
  198989. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  198990. typedef returnType (WINAPI *type##localFunctionName) params; \
  198991. type##localFunctionName localFunctionName \
  198992. = (type##localFunctionName)object.findProcAddress (#functionName);
  198993. // loads and unloads a DLL automatically
  198994. class JUCE_API DynamicLibraryLoader
  198995. {
  198996. public:
  198997. DynamicLibraryLoader (const String& name);
  198998. ~DynamicLibraryLoader();
  198999. void* findProcAddress (const String& functionName);
  199000. private:
  199001. void* libHandle;
  199002. };
  199003. #endif
  199004. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199005. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  199006. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199007. {
  199008. libHandle = LoadLibrary (name);
  199009. }
  199010. DynamicLibraryLoader::~DynamicLibraryLoader()
  199011. {
  199012. FreeLibrary ((HMODULE) libHandle);
  199013. }
  199014. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199015. {
  199016. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  199017. }
  199018. #endif
  199019. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199020. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  199021. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199022. // compiled on its own).
  199023. #if JUCE_INCLUDED_FILE
  199024. extern void juce_updateMultiMonitorInfo() throw();
  199025. extern void juce_initialiseThreadEvents() throw();
  199026. void Logger::outputDebugString (const String& text) throw()
  199027. {
  199028. OutputDebugString (text + T("\n"));
  199029. }
  199030. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  199031. {
  199032. String text;
  199033. va_list args;
  199034. va_start (args, format);
  199035. text.vprintf(format, args);
  199036. outputDebugString (text);
  199037. }
  199038. static int64 hiResTicksPerSecond;
  199039. static double hiResTicksScaleFactor;
  199040. #if JUCE_USE_INTRINSICS
  199041. // CPU info functions using intrinsics...
  199042. #pragma intrinsic (__cpuid)
  199043. #pragma intrinsic (__rdtsc)
  199044. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  199045. {
  199046. int info [4];
  199047. __cpuid (info, 1);
  199048. if (familyModel != 0)
  199049. *familyModel = info [0];
  199050. if (extFeatures != 0)
  199051. *extFeatures = info[1];
  199052. return info[3];
  199053. }*/
  199054. const String SystemStats::getCpuVendor() throw()
  199055. {
  199056. int info [4];
  199057. __cpuid (info, 0);
  199058. char v [12];
  199059. memcpy (v, info + 1, 4);
  199060. memcpy (v + 4, info + 3, 4);
  199061. memcpy (v + 8, info + 2, 4);
  199062. return String (v, 12);
  199063. }
  199064. #else
  199065. // CPU info functions using old fashioned inline asm...
  199066. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  199067. {
  199068. unsigned int cpu = 0;
  199069. unsigned int ext = 0;
  199070. unsigned int family = 0;
  199071. #if JUCE_GCC
  199072. unsigned int dummy = 0;
  199073. #endif
  199074. #ifndef __MINGW32__
  199075. __try
  199076. #endif
  199077. {
  199078. #if JUCE_GCC
  199079. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  199080. #else
  199081. __asm
  199082. {
  199083. mov eax, 1
  199084. cpuid
  199085. mov cpu, edx
  199086. mov family, eax
  199087. mov ext, ebx
  199088. }
  199089. #endif
  199090. }
  199091. #ifndef __MINGW32__
  199092. __except (EXCEPTION_EXECUTE_HANDLER)
  199093. {
  199094. return 0;
  199095. }
  199096. #endif
  199097. if (familyModel != 0)
  199098. *familyModel = family;
  199099. if (extFeatures != 0)
  199100. *extFeatures = ext;
  199101. return cpu;
  199102. }*/
  199103. static void juce_getCpuVendor (char* const v)
  199104. {
  199105. int vendor[4];
  199106. zeromem (vendor, 16);
  199107. #ifdef JUCE_64BIT
  199108. #else
  199109. #ifndef __MINGW32__
  199110. __try
  199111. #endif
  199112. {
  199113. #if JUCE_GCC
  199114. unsigned int dummy = 0;
  199115. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  199116. #else
  199117. __asm
  199118. {
  199119. mov eax, 0
  199120. cpuid
  199121. mov [vendor], ebx
  199122. mov [vendor + 4], edx
  199123. mov [vendor + 8], ecx
  199124. }
  199125. #endif
  199126. }
  199127. #ifndef __MINGW32__
  199128. __except (EXCEPTION_EXECUTE_HANDLER)
  199129. {
  199130. *v = 0;
  199131. }
  199132. #endif
  199133. #endif
  199134. memcpy (v, vendor, 16);
  199135. }
  199136. const String SystemStats::getCpuVendor() throw()
  199137. {
  199138. char v [16];
  199139. juce_getCpuVendor (v);
  199140. return String (v, 16);
  199141. }
  199142. #endif
  199143. struct CPUFlags
  199144. {
  199145. bool hasMMX : 1;
  199146. bool hasSSE : 1;
  199147. bool hasSSE2 : 1;
  199148. bool has3DNow : 1;
  199149. };
  199150. static CPUFlags cpuFlags;
  199151. bool SystemStats::hasMMX() throw()
  199152. {
  199153. return cpuFlags.hasMMX;
  199154. }
  199155. bool SystemStats::hasSSE() throw()
  199156. {
  199157. return cpuFlags.hasSSE;
  199158. }
  199159. bool SystemStats::hasSSE2() throw()
  199160. {
  199161. return cpuFlags.hasSSE2;
  199162. }
  199163. bool SystemStats::has3DNow() throw()
  199164. {
  199165. return cpuFlags.has3DNow;
  199166. }
  199167. void SystemStats::initialiseStats() throw()
  199168. {
  199169. juce_initialiseThreadEvents();
  199170. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  199171. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  199172. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  199173. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  199174. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  199175. #else
  199176. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  199177. #endif
  199178. LARGE_INTEGER f;
  199179. QueryPerformanceFrequency (&f);
  199180. hiResTicksPerSecond = f.QuadPart;
  199181. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  199182. String s (SystemStats::getJUCEVersion());
  199183. #ifdef JUCE_DEBUG
  199184. const MMRESULT res = timeBeginPeriod (1);
  199185. jassert (res == TIMERR_NOERROR);
  199186. #else
  199187. timeBeginPeriod (1);
  199188. #endif
  199189. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199190. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  199191. #endif
  199192. }
  199193. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  199194. {
  199195. OSVERSIONINFO info;
  199196. info.dwOSVersionInfoSize = sizeof (info);
  199197. GetVersionEx (&info);
  199198. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  199199. {
  199200. switch (info.dwMajorVersion)
  199201. {
  199202. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  199203. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  199204. default: jassertfalse; break; // !! not a supported OS!
  199205. }
  199206. }
  199207. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  199208. {
  199209. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  199210. return Win98;
  199211. }
  199212. return UnknownOS;
  199213. }
  199214. const String SystemStats::getOperatingSystemName() throw()
  199215. {
  199216. const char* name = "Unknown OS";
  199217. switch (getOperatingSystemType())
  199218. {
  199219. case Windows7: name = "Windows 7"; break;
  199220. case WinVista: name = "Windows Vista"; break;
  199221. case WinXP: name = "Windows XP"; break;
  199222. case Win2000: name = "Windows 2000"; break;
  199223. case Win98: name = "Windows 98"; break;
  199224. default: jassertfalse; break; // !! new type of OS?
  199225. }
  199226. return name;
  199227. }
  199228. bool SystemStats::isOperatingSystem64Bit() throw()
  199229. {
  199230. #ifdef _WIN64
  199231. return true;
  199232. #else
  199233. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  199234. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  199235. BOOL isWow64 = FALSE;
  199236. return (fnIsWow64Process != 0)
  199237. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  199238. && (isWow64 != FALSE);
  199239. #endif
  199240. }
  199241. int SystemStats::getMemorySizeInMegabytes() throw()
  199242. {
  199243. MEMORYSTATUSEX mem;
  199244. mem.dwLength = sizeof (mem);
  199245. GlobalMemoryStatusEx (&mem);
  199246. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  199247. }
  199248. int SystemStats::getNumCpus() throw()
  199249. {
  199250. SYSTEM_INFO systemInfo;
  199251. GetSystemInfo (&systemInfo);
  199252. return systemInfo.dwNumberOfProcessors;
  199253. }
  199254. uint32 juce_millisecondsSinceStartup() throw()
  199255. {
  199256. return (uint32) GetTickCount();
  199257. }
  199258. int64 Time::getHighResolutionTicks() throw()
  199259. {
  199260. LARGE_INTEGER ticks;
  199261. QueryPerformanceCounter (&ticks);
  199262. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  199263. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  199264. // fix for a very obscure PCI hardware bug that can make the counter
  199265. // sometimes jump forwards by a few seconds..
  199266. static int64 hiResTicksOffset = 0;
  199267. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  199268. if (offsetDrift > (hiResTicksPerSecond >> 1))
  199269. hiResTicksOffset = newOffset;
  199270. return ticks.QuadPart + hiResTicksOffset;
  199271. }
  199272. double Time::getMillisecondCounterHiRes() throw()
  199273. {
  199274. return getHighResolutionTicks() * hiResTicksScaleFactor;
  199275. }
  199276. int64 Time::getHighResolutionTicksPerSecond() throw()
  199277. {
  199278. return hiResTicksPerSecond;
  199279. }
  199280. int64 SystemStats::getClockCycleCounter() throw()
  199281. {
  199282. #if JUCE_USE_INTRINSICS
  199283. // MS intrinsics version...
  199284. return __rdtsc();
  199285. #elif JUCE_GCC
  199286. // GNU inline asm version...
  199287. unsigned int hi = 0, lo = 0;
  199288. __asm__ __volatile__ (
  199289. "xor %%eax, %%eax \n\
  199290. xor %%edx, %%edx \n\
  199291. rdtsc \n\
  199292. movl %%eax, %[lo] \n\
  199293. movl %%edx, %[hi]"
  199294. :
  199295. : [hi] "m" (hi),
  199296. [lo] "m" (lo)
  199297. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  199298. return (int64) ((((uint64) hi) << 32) | lo);
  199299. #else
  199300. // MSVC inline asm version...
  199301. unsigned int hi = 0, lo = 0;
  199302. __asm
  199303. {
  199304. xor eax, eax
  199305. xor edx, edx
  199306. rdtsc
  199307. mov lo, eax
  199308. mov hi, edx
  199309. }
  199310. return (int64) ((((uint64) hi) << 32) | lo);
  199311. #endif
  199312. }
  199313. int SystemStats::getCpuSpeedInMegaherz() throw()
  199314. {
  199315. const int64 cycles = SystemStats::getClockCycleCounter();
  199316. const uint32 millis = Time::getMillisecondCounter();
  199317. int lastResult = 0;
  199318. for (;;)
  199319. {
  199320. int n = 1000000;
  199321. while (--n > 0) {}
  199322. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  199323. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  199324. if (millisElapsed > 80)
  199325. {
  199326. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  199327. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  199328. return newResult;
  199329. lastResult = newResult;
  199330. }
  199331. }
  199332. }
  199333. bool Time::setSystemTimeToThisTime() const throw()
  199334. {
  199335. SYSTEMTIME st;
  199336. st.wDayOfWeek = 0;
  199337. st.wYear = (WORD) getYear();
  199338. st.wMonth = (WORD) (getMonth() + 1);
  199339. st.wDay = (WORD) getDayOfMonth();
  199340. st.wHour = (WORD) getHours();
  199341. st.wMinute = (WORD) getMinutes();
  199342. st.wSecond = (WORD) getSeconds();
  199343. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  199344. // do this twice because of daylight saving conversion problems - the
  199345. // first one sets it up, the second one kicks it in.
  199346. return SetLocalTime (&st) != 0
  199347. && SetLocalTime (&st) != 0;
  199348. }
  199349. int SystemStats::getPageSize() throw()
  199350. {
  199351. SYSTEM_INFO systemInfo;
  199352. GetSystemInfo (&systemInfo);
  199353. return systemInfo.dwPageSize;
  199354. }
  199355. #endif
  199356. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  199357. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  199358. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199359. // compiled on its own).
  199360. #if JUCE_INCLUDED_FILE
  199361. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199362. extern HWND juce_messageWindowHandle;
  199363. #endif
  199364. CriticalSection::CriticalSection() throw()
  199365. {
  199366. // (just to check the MS haven't changed this structure and broken things...)
  199367. #if _MSC_VER >= 1400
  199368. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  199369. #else
  199370. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  199371. #endif
  199372. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  199373. }
  199374. CriticalSection::~CriticalSection() throw()
  199375. {
  199376. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  199377. }
  199378. void CriticalSection::enter() const throw()
  199379. {
  199380. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  199381. }
  199382. bool CriticalSection::tryEnter() const throw()
  199383. {
  199384. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  199385. }
  199386. void CriticalSection::exit() const throw()
  199387. {
  199388. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  199389. }
  199390. WaitableEvent::WaitableEvent() throw()
  199391. : internal (CreateEvent (0, FALSE, FALSE, 0))
  199392. {
  199393. }
  199394. WaitableEvent::~WaitableEvent() throw()
  199395. {
  199396. CloseHandle (internal);
  199397. }
  199398. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  199399. {
  199400. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  199401. }
  199402. void WaitableEvent::signal() const throw()
  199403. {
  199404. SetEvent (internal);
  199405. }
  199406. void WaitableEvent::reset() const throw()
  199407. {
  199408. ResetEvent (internal);
  199409. }
  199410. void JUCE_API juce_threadEntryPoint (void*);
  199411. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  199412. {
  199413. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199414. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  199415. GetCurrentThreadId(), TRUE);
  199416. #endif
  199417. juce_threadEntryPoint (userData);
  199418. _endthreadex (0);
  199419. return 0;
  199420. }
  199421. void juce_CloseThreadHandle (void* handle) throw()
  199422. {
  199423. CloseHandle ((HANDLE) handle);
  199424. }
  199425. void* juce_createThread (void* userData) throw()
  199426. {
  199427. unsigned int threadId;
  199428. return (void*) _beginthreadex (0, 0,
  199429. &threadEntryProc,
  199430. userData,
  199431. 0, &threadId);
  199432. }
  199433. void juce_killThread (void* handle) throw()
  199434. {
  199435. if (handle != 0)
  199436. {
  199437. #ifdef JUCE_DEBUG
  199438. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  199439. #endif
  199440. TerminateThread (handle, 0);
  199441. }
  199442. }
  199443. void juce_setCurrentThreadName (const String& name) throw()
  199444. {
  199445. #if defined (JUCE_DEBUG) && JUCE_MSVC
  199446. struct
  199447. {
  199448. DWORD dwType;
  199449. LPCSTR szName;
  199450. DWORD dwThreadID;
  199451. DWORD dwFlags;
  199452. } info;
  199453. info.dwType = 0x1000;
  199454. info.szName = name;
  199455. info.dwThreadID = GetCurrentThreadId();
  199456. info.dwFlags = 0;
  199457. #define MS_VC_EXCEPTION 0x406d1388
  199458. __try
  199459. {
  199460. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  199461. }
  199462. __except (EXCEPTION_CONTINUE_EXECUTION)
  199463. {}
  199464. #else
  199465. (void) name;
  199466. #endif
  199467. }
  199468. Thread::ThreadID Thread::getCurrentThreadId() throw()
  199469. {
  199470. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  199471. }
  199472. // priority 1 to 10 where 5=normal, 1=low
  199473. bool juce_setThreadPriority (void* threadHandle, int priority) throw()
  199474. {
  199475. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  199476. if (priority < 1)
  199477. pri = THREAD_PRIORITY_IDLE;
  199478. else if (priority < 2)
  199479. pri = THREAD_PRIORITY_LOWEST;
  199480. else if (priority < 5)
  199481. pri = THREAD_PRIORITY_BELOW_NORMAL;
  199482. else if (priority < 7)
  199483. pri = THREAD_PRIORITY_NORMAL;
  199484. else if (priority < 9)
  199485. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  199486. else if (priority < 10)
  199487. pri = THREAD_PRIORITY_HIGHEST;
  199488. if (threadHandle == 0)
  199489. threadHandle = GetCurrentThread();
  199490. return SetThreadPriority (threadHandle, pri) != FALSE;
  199491. }
  199492. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  199493. {
  199494. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  199495. }
  199496. static HANDLE sleepEvent = 0;
  199497. void juce_initialiseThreadEvents() throw()
  199498. {
  199499. if (sleepEvent == 0)
  199500. #ifdef JUCE_DEBUG
  199501. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  199502. #else
  199503. sleepEvent = CreateEvent (0, 0, 0, 0);
  199504. #endif
  199505. }
  199506. void Thread::yield() throw()
  199507. {
  199508. Sleep (0);
  199509. }
  199510. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  199511. {
  199512. if (millisecs >= 10)
  199513. {
  199514. Sleep (millisecs);
  199515. }
  199516. else
  199517. {
  199518. jassert (sleepEvent != 0);
  199519. // unlike Sleep() this is guaranteed to return to the current thread after
  199520. // the time expires, so we'll use this for short waits, which are more likely
  199521. // to need to be accurate
  199522. WaitForSingleObject (sleepEvent, millisecs);
  199523. }
  199524. }
  199525. static int lastProcessPriority = -1;
  199526. // called by WindowDriver because Windows does wierd things to process priority
  199527. // when you swap apps, and this forces an update when the app is brought to the front.
  199528. void juce_repeatLastProcessPriority() throw()
  199529. {
  199530. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  199531. {
  199532. DWORD p;
  199533. switch (lastProcessPriority)
  199534. {
  199535. case Process::LowPriority:
  199536. p = IDLE_PRIORITY_CLASS;
  199537. break;
  199538. case Process::NormalPriority:
  199539. p = NORMAL_PRIORITY_CLASS;
  199540. break;
  199541. case Process::HighPriority:
  199542. p = HIGH_PRIORITY_CLASS;
  199543. break;
  199544. case Process::RealtimePriority:
  199545. p = REALTIME_PRIORITY_CLASS;
  199546. break;
  199547. default:
  199548. jassertfalse // bad priority value
  199549. return;
  199550. }
  199551. SetPriorityClass (GetCurrentProcess(), p);
  199552. }
  199553. }
  199554. void Process::setPriority (ProcessPriority prior)
  199555. {
  199556. if (lastProcessPriority != (int) prior)
  199557. {
  199558. lastProcessPriority = (int) prior;
  199559. juce_repeatLastProcessPriority();
  199560. }
  199561. }
  199562. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199563. {
  199564. return IsDebuggerPresent() != FALSE;
  199565. }
  199566. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199567. {
  199568. return juce_isRunningUnderDebugger();
  199569. }
  199570. void Process::raisePrivilege()
  199571. {
  199572. jassertfalse // xxx not implemented
  199573. }
  199574. void Process::lowerPrivilege()
  199575. {
  199576. jassertfalse // xxx not implemented
  199577. }
  199578. void Process::terminate()
  199579. {
  199580. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199581. _CrtDumpMemoryLeaks();
  199582. #endif
  199583. // bullet in the head in case there's a problem shutting down..
  199584. ExitProcess (0);
  199585. }
  199586. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  199587. {
  199588. void* result = 0;
  199589. JUCE_TRY
  199590. {
  199591. result = (void*) LoadLibrary (name);
  199592. }
  199593. JUCE_CATCH_ALL
  199594. return result;
  199595. }
  199596. void PlatformUtilities::freeDynamicLibrary (void* h)
  199597. {
  199598. JUCE_TRY
  199599. {
  199600. if (h != 0)
  199601. FreeLibrary ((HMODULE) h);
  199602. }
  199603. JUCE_CATCH_ALL
  199604. }
  199605. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  199606. {
  199607. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199608. : 0;
  199609. }
  199610. InterProcessLock::InterProcessLock (const String& name_) throw()
  199611. : internal (0),
  199612. name (name_),
  199613. reentrancyLevel (0)
  199614. {
  199615. }
  199616. InterProcessLock::~InterProcessLock() throw()
  199617. {
  199618. exit();
  199619. }
  199620. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199621. {
  199622. if (reentrancyLevel++ == 0)
  199623. {
  199624. internal = CreateMutex (0, TRUE, name);
  199625. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199626. {
  199627. if (timeOutMillisecs == 0
  199628. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199629. == WAIT_TIMEOUT)
  199630. {
  199631. ReleaseMutex (internal);
  199632. CloseHandle (internal);
  199633. internal = 0;
  199634. }
  199635. }
  199636. }
  199637. return (internal != 0);
  199638. }
  199639. void InterProcessLock::exit() throw()
  199640. {
  199641. if (--reentrancyLevel == 0 && internal != 0)
  199642. {
  199643. ReleaseMutex (internal);
  199644. CloseHandle (internal);
  199645. internal = 0;
  199646. }
  199647. }
  199648. #endif
  199649. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199650. /********* Start of inlined file: juce_win32_Files.cpp *********/
  199651. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199652. // compiled on its own).
  199653. #if JUCE_INCLUDED_FILE
  199654. #ifndef CSIDL_MYMUSIC
  199655. #define CSIDL_MYMUSIC 0x000d
  199656. #endif
  199657. #ifndef CSIDL_MYVIDEO
  199658. #define CSIDL_MYVIDEO 0x000e
  199659. #endif
  199660. const tchar File::separator = T('\\');
  199661. const tchar* File::separatorString = T("\\");
  199662. bool juce_fileExists (const String& fileName,
  199663. const bool dontCountDirectories) throw()
  199664. {
  199665. if (fileName.isEmpty())
  199666. return false;
  199667. const DWORD attr = GetFileAttributes (fileName);
  199668. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  199669. : (attr != 0xffffffff);
  199670. }
  199671. bool juce_isDirectory (const String& fileName) throw()
  199672. {
  199673. const DWORD attr = GetFileAttributes (fileName);
  199674. return (attr != 0xffffffff)
  199675. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199676. }
  199677. bool juce_canWriteToFile (const String& fileName) throw()
  199678. {
  199679. const DWORD attr = GetFileAttributes (fileName);
  199680. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  199681. }
  199682. bool juce_setFileReadOnly (const String& fileName,
  199683. bool isReadOnly) throw()
  199684. {
  199685. DWORD attr = GetFileAttributes (fileName);
  199686. if (attr == 0xffffffff)
  199687. return false;
  199688. if (isReadOnly != juce_canWriteToFile (fileName))
  199689. return true;
  199690. if (isReadOnly)
  199691. attr |= FILE_ATTRIBUTE_READONLY;
  199692. else
  199693. attr &= ~FILE_ATTRIBUTE_READONLY;
  199694. return SetFileAttributes (fileName, attr) != FALSE;
  199695. }
  199696. bool File::isHidden() const throw()
  199697. {
  199698. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  199699. }
  199700. bool juce_deleteFile (const String& fileName) throw()
  199701. {
  199702. if (juce_isDirectory (fileName))
  199703. return RemoveDirectory (fileName) != 0;
  199704. return DeleteFile (fileName) != 0;
  199705. }
  199706. bool File::moveToTrash() const throw()
  199707. {
  199708. if (! exists())
  199709. return true;
  199710. SHFILEOPSTRUCT fos;
  199711. zerostruct (fos);
  199712. // The string we pass in must be double null terminated..
  199713. String doubleNullTermPath (getFullPathName() + " ");
  199714. TCHAR* p = (TCHAR*) (const TCHAR*) doubleNullTermPath;
  199715. p [getFullPathName().length()] = 0;
  199716. fos.wFunc = FO_DELETE;
  199717. fos.hwnd = (HWND) 0;
  199718. fos.pFrom = p;
  199719. fos.pTo = NULL;
  199720. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  199721. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  199722. return SHFileOperation (&fos) == 0;
  199723. }
  199724. bool juce_moveFile (const String& source, const String& dest) throw()
  199725. {
  199726. return MoveFile (source, dest) != 0;
  199727. }
  199728. bool juce_copyFile (const String& source, const String& dest) throw()
  199729. {
  199730. return CopyFile (source, dest, false) != 0;
  199731. }
  199732. void juce_createDirectory (const String& fileName) throw()
  199733. {
  199734. if (! juce_fileExists (fileName, true))
  199735. {
  199736. CreateDirectory (fileName, 0);
  199737. }
  199738. }
  199739. // return 0 if not possible
  199740. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  199741. {
  199742. HANDLE h;
  199743. if (forWriting)
  199744. {
  199745. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  199746. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  199747. if (h != INVALID_HANDLE_VALUE)
  199748. SetFilePointer (h, 0, 0, FILE_END);
  199749. else
  199750. h = 0;
  199751. }
  199752. else
  199753. {
  199754. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  199755. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  199756. if (h == INVALID_HANDLE_VALUE)
  199757. h = 0;
  199758. }
  199759. return (void*) h;
  199760. }
  199761. void juce_fileClose (void* handle) throw()
  199762. {
  199763. CloseHandle (handle);
  199764. }
  199765. int juce_fileRead (void* handle, void* buffer, int size) throw()
  199766. {
  199767. DWORD num = 0;
  199768. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  199769. return num;
  199770. }
  199771. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  199772. {
  199773. DWORD num;
  199774. WriteFile ((HANDLE) handle,
  199775. buffer, size,
  199776. &num, 0);
  199777. return num;
  199778. }
  199779. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  199780. {
  199781. LARGE_INTEGER li;
  199782. li.QuadPart = pos;
  199783. li.LowPart = SetFilePointer ((HANDLE) handle,
  199784. li.LowPart,
  199785. &li.HighPart,
  199786. FILE_BEGIN); // (returns -1 if it fails)
  199787. return li.QuadPart;
  199788. }
  199789. int64 juce_fileGetPosition (void* handle) throw()
  199790. {
  199791. LARGE_INTEGER li;
  199792. li.QuadPart = 0;
  199793. li.LowPart = SetFilePointer ((HANDLE) handle,
  199794. 0, &li.HighPart,
  199795. FILE_CURRENT); // (returns -1 if it fails)
  199796. return jmax ((int64) 0, li.QuadPart);
  199797. }
  199798. void juce_fileFlush (void* handle) throw()
  199799. {
  199800. FlushFileBuffers ((HANDLE) handle);
  199801. }
  199802. int64 juce_getFileSize (const String& fileName) throw()
  199803. {
  199804. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199805. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199806. {
  199807. return (((int64) attributes.nFileSizeHigh) << 32)
  199808. | attributes.nFileSizeLow;
  199809. }
  199810. return 0;
  199811. }
  199812. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  199813. {
  199814. // tell me if this fails!
  199815. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  199816. #if JUCE_GCC
  199817. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  199818. #else
  199819. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  199820. #endif
  199821. }
  199822. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  199823. {
  199824. #if JUCE_GCC
  199825. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  199826. #else
  199827. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  199828. #endif
  199829. }
  199830. void juce_getFileTimes (const String& fileName,
  199831. int64& modificationTime,
  199832. int64& accessTime,
  199833. int64& creationTime) throw()
  199834. {
  199835. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199836. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199837. {
  199838. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  199839. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  199840. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  199841. }
  199842. else
  199843. {
  199844. creationTime = accessTime = modificationTime = 0;
  199845. }
  199846. }
  199847. bool juce_setFileTimes (const String& fileName,
  199848. int64 modificationTime,
  199849. int64 accessTime,
  199850. int64 creationTime) throw()
  199851. {
  199852. FILETIME m, a, c;
  199853. if (modificationTime > 0)
  199854. timeToFileTime (modificationTime, &m);
  199855. if (accessTime > 0)
  199856. timeToFileTime (accessTime, &a);
  199857. if (creationTime > 0)
  199858. timeToFileTime (creationTime, &c);
  199859. void* const h = juce_fileOpen (fileName, true);
  199860. bool ok = false;
  199861. if (h != 0)
  199862. {
  199863. ok = SetFileTime ((HANDLE) h,
  199864. (creationTime > 0) ? &c : 0,
  199865. (accessTime > 0) ? &a : 0,
  199866. (modificationTime > 0) ? &m : 0) != 0;
  199867. juce_fileClose (h);
  199868. }
  199869. return ok;
  199870. }
  199871. // return '\0' separated list of strings
  199872. const StringArray juce_getFileSystemRoots() throw()
  199873. {
  199874. TCHAR buffer [2048];
  199875. buffer[0] = 0;
  199876. buffer[1] = 0;
  199877. GetLogicalDriveStrings (2048, buffer);
  199878. TCHAR* n = buffer;
  199879. StringArray roots;
  199880. while (*n != 0)
  199881. {
  199882. roots.add (String (n));
  199883. while (*n++ != 0)
  199884. {
  199885. }
  199886. }
  199887. roots.sort (true);
  199888. return roots;
  199889. }
  199890. const String juce_getVolumeLabel (const String& filenameOnVolume,
  199891. int& volumeSerialNumber) throw()
  199892. {
  199893. TCHAR n [4];
  199894. n[0] = *(const TCHAR*) filenameOnVolume;
  199895. n[1] = L':';
  199896. n[2] = L'\\';
  199897. n[3] = 0;
  199898. TCHAR dest [64];
  199899. DWORD serialNum;
  199900. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  199901. {
  199902. dest[0] = 0;
  199903. serialNum = 0;
  199904. }
  199905. volumeSerialNumber = serialNum;
  199906. return String (dest);
  199907. }
  199908. static int64 getDiskSpaceInfo (String fn, const bool total) throw()
  199909. {
  199910. if (fn[1] == T(':'))
  199911. fn = fn.substring (0, 2) + T("\\");
  199912. ULARGE_INTEGER spc, tot, totFree;
  199913. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  199914. return (int64) (total ? tot.QuadPart
  199915. : spc.QuadPart);
  199916. return 0;
  199917. }
  199918. int64 File::getBytesFreeOnVolume() const throw()
  199919. {
  199920. return getDiskSpaceInfo (getFullPathName(), false);
  199921. }
  199922. int64 File::getVolumeTotalSize() const throw()
  199923. {
  199924. return getDiskSpaceInfo (getFullPathName(), true);
  199925. }
  199926. static unsigned int getWindowsDriveType (const String& fileName) throw()
  199927. {
  199928. TCHAR n[4];
  199929. n[0] = *(const TCHAR*) fileName;
  199930. n[1] = L':';
  199931. n[2] = L'\\';
  199932. n[3] = 0;
  199933. return GetDriveType (n);
  199934. }
  199935. bool File::isOnCDRomDrive() const throw()
  199936. {
  199937. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  199938. }
  199939. bool File::isOnHardDisk() const throw()
  199940. {
  199941. if (fullPath.isEmpty())
  199942. return false;
  199943. const unsigned int n = getWindowsDriveType (getFullPathName());
  199944. if (fullPath.toLowerCase()[0] <= 'b'
  199945. && fullPath[1] == T(':'))
  199946. {
  199947. return n != DRIVE_REMOVABLE;
  199948. }
  199949. else
  199950. {
  199951. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  199952. }
  199953. }
  199954. bool File::isOnRemovableDrive() const throw()
  199955. {
  199956. if (fullPath.isEmpty())
  199957. return false;
  199958. const unsigned int n = getWindowsDriveType (getFullPathName());
  199959. return n == DRIVE_CDROM
  199960. || n == DRIVE_REMOTE
  199961. || n == DRIVE_REMOVABLE
  199962. || n == DRIVE_RAMDISK;
  199963. }
  199964. #define MAX_PATH_CHARS (MAX_PATH + 256)
  199965. static const File juce_getSpecialFolderPath (int type) throw()
  199966. {
  199967. WCHAR path [MAX_PATH_CHARS];
  199968. if (SHGetSpecialFolderPath (0, path, type, 0))
  199969. return File (String (path));
  199970. return File::nonexistent;
  199971. }
  199972. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  199973. {
  199974. int csidlType = 0;
  199975. switch (type)
  199976. {
  199977. case userHomeDirectory:
  199978. csidlType = CSIDL_PROFILE;
  199979. break;
  199980. case userDocumentsDirectory:
  199981. csidlType = CSIDL_PERSONAL;
  199982. break;
  199983. case userDesktopDirectory:
  199984. csidlType = CSIDL_DESKTOP;
  199985. break;
  199986. case userApplicationDataDirectory:
  199987. csidlType = CSIDL_APPDATA;
  199988. break;
  199989. case commonApplicationDataDirectory:
  199990. csidlType = CSIDL_COMMON_APPDATA;
  199991. break;
  199992. case globalApplicationsDirectory:
  199993. csidlType = CSIDL_PROGRAM_FILES;
  199994. break;
  199995. case userMusicDirectory:
  199996. csidlType = CSIDL_MYMUSIC;
  199997. break;
  199998. case userMoviesDirectory:
  199999. csidlType = CSIDL_MYVIDEO;
  200000. break;
  200001. case tempDirectory:
  200002. {
  200003. WCHAR dest [2048];
  200004. dest[0] = 0;
  200005. GetTempPath (2048, dest);
  200006. return File (String (dest));
  200007. }
  200008. case currentExecutableFile:
  200009. case currentApplicationFile:
  200010. {
  200011. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200012. WCHAR dest [MAX_PATH_CHARS];
  200013. dest[0] = 0;
  200014. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  200015. return File (String (dest));
  200016. }
  200017. break;
  200018. default:
  200019. jassertfalse // unknown type?
  200020. return File::nonexistent;
  200021. }
  200022. return juce_getSpecialFolderPath (csidlType);
  200023. }
  200024. const File File::getCurrentWorkingDirectory() throw()
  200025. {
  200026. WCHAR dest [MAX_PATH_CHARS];
  200027. dest[0] = 0;
  200028. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  200029. return File (String (dest));
  200030. }
  200031. bool File::setAsCurrentWorkingDirectory() const throw()
  200032. {
  200033. return SetCurrentDirectory (getFullPathName()) != FALSE;
  200034. }
  200035. const String File::getVersion() const throw()
  200036. {
  200037. String result;
  200038. DWORD handle = 0;
  200039. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  200040. void* buffer = juce_calloc (bufferSize);
  200041. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  200042. {
  200043. VS_FIXEDFILEINFO* vffi;
  200044. UINT len = 0;
  200045. if (VerQueryValue (buffer, _T("\\"), (LPVOID*) &vffi, &len))
  200046. {
  200047. result.printf (T("%d.%d.%d.%d"),
  200048. HIWORD (vffi->dwFileVersionMS),
  200049. LOWORD (vffi->dwFileVersionMS),
  200050. HIWORD (vffi->dwFileVersionLS),
  200051. LOWORD (vffi->dwFileVersionLS));
  200052. }
  200053. }
  200054. juce_free (buffer);
  200055. return result;
  200056. }
  200057. const File File::getLinkedTarget() const throw()
  200058. {
  200059. File result (*this);
  200060. String p (getFullPathName());
  200061. if (! exists())
  200062. p += T(".lnk");
  200063. else if (getFileExtension() != T(".lnk"))
  200064. return result;
  200065. ComSmartPtr <IShellLink> shellLink;
  200066. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink, CLSCTX_INPROC_SERVER)))
  200067. {
  200068. ComSmartPtr <IPersistFile> persistFile;
  200069. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  200070. {
  200071. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  200072. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  200073. {
  200074. WIN32_FIND_DATA winFindData;
  200075. WCHAR resolvedPath [MAX_PATH];
  200076. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  200077. result = File (resolvedPath);
  200078. }
  200079. }
  200080. }
  200081. return result;
  200082. }
  200083. template <class FindDataType>
  200084. static void getFindFileInfo (FindDataType& findData,
  200085. String& filename, bool* const isDir, bool* const isHidden,
  200086. int64* const fileSize, Time* const modTime, Time* const creationTime,
  200087. bool* const isReadOnly) throw()
  200088. {
  200089. filename = findData.cFileName;
  200090. if (isDir != 0)
  200091. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  200092. if (isHidden != 0)
  200093. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  200094. if (fileSize != 0)
  200095. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  200096. if (modTime != 0)
  200097. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  200098. if (creationTime != 0)
  200099. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  200100. if (isReadOnly != 0)
  200101. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  200102. }
  200103. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  200104. bool* isDir, bool* isHidden, int64* fileSize,
  200105. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  200106. {
  200107. String wc (directory);
  200108. if (! wc.endsWithChar (File::separator))
  200109. wc += File::separator;
  200110. wc += wildCard;
  200111. WIN32_FIND_DATA findData;
  200112. HANDLE h = FindFirstFile (wc, &findData);
  200113. if (h != INVALID_HANDLE_VALUE)
  200114. {
  200115. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  200116. modTime, creationTime, isReadOnly);
  200117. return h;
  200118. }
  200119. firstResult = String::empty;
  200120. return 0;
  200121. }
  200122. bool juce_findFileNext (void* handle, String& resultFile,
  200123. bool* isDir, bool* isHidden, int64* fileSize,
  200124. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  200125. {
  200126. WIN32_FIND_DATA findData;
  200127. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  200128. {
  200129. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  200130. modTime, creationTime, isReadOnly);
  200131. return true;
  200132. }
  200133. resultFile = String::empty;
  200134. return false;
  200135. }
  200136. void juce_findFileClose (void* handle) throw()
  200137. {
  200138. FindClose (handle);
  200139. }
  200140. bool juce_launchFile (const String& fileName,
  200141. const String& parameters) throw()
  200142. {
  200143. HINSTANCE hInstance = 0;
  200144. JUCE_TRY
  200145. {
  200146. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  200147. }
  200148. JUCE_CATCH_ALL
  200149. return hInstance > (HINSTANCE) 32;
  200150. }
  200151. struct NamedPipeInternal
  200152. {
  200153. HANDLE pipeH;
  200154. HANDLE cancelEvent;
  200155. bool connected, createdPipe;
  200156. NamedPipeInternal()
  200157. : pipeH (0),
  200158. cancelEvent (0),
  200159. connected (false),
  200160. createdPipe (false)
  200161. {
  200162. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  200163. }
  200164. ~NamedPipeInternal()
  200165. {
  200166. disconnect();
  200167. if (pipeH != 0)
  200168. CloseHandle (pipeH);
  200169. CloseHandle (cancelEvent);
  200170. }
  200171. bool connect (const int timeOutMs)
  200172. {
  200173. if (! createdPipe)
  200174. return true;
  200175. if (! connected)
  200176. {
  200177. OVERLAPPED over;
  200178. zerostruct (over);
  200179. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200180. if (ConnectNamedPipe (pipeH, &over))
  200181. {
  200182. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  200183. }
  200184. else
  200185. {
  200186. const int err = GetLastError();
  200187. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  200188. {
  200189. HANDLE handles[] = { over.hEvent, cancelEvent };
  200190. if (WaitForMultipleObjects (2, handles, FALSE,
  200191. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  200192. connected = true;
  200193. }
  200194. else if (err == ERROR_PIPE_CONNECTED)
  200195. {
  200196. connected = true;
  200197. }
  200198. }
  200199. CloseHandle (over.hEvent);
  200200. }
  200201. return connected;
  200202. }
  200203. void disconnect()
  200204. {
  200205. if (connected)
  200206. {
  200207. DisconnectNamedPipe (pipeH);
  200208. connected = false;
  200209. }
  200210. }
  200211. };
  200212. void NamedPipe::close()
  200213. {
  200214. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200215. delete intern;
  200216. internal = 0;
  200217. }
  200218. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  200219. {
  200220. close();
  200221. NamedPipeInternal* const intern = new NamedPipeInternal();
  200222. String file ("\\\\.\\pipe\\");
  200223. file += pipeName;
  200224. intern->createdPipe = createPipe;
  200225. if (createPipe)
  200226. {
  200227. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  200228. PIPE_UNLIMITED_INSTANCES,
  200229. 4096, 4096, 0, NULL);
  200230. }
  200231. else
  200232. {
  200233. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  200234. FILE_FLAG_OVERLAPPED, 0);
  200235. }
  200236. if (intern->pipeH != INVALID_HANDLE_VALUE)
  200237. {
  200238. internal = intern;
  200239. return true;
  200240. }
  200241. delete intern;
  200242. return false;
  200243. }
  200244. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  200245. {
  200246. int bytesRead = -1;
  200247. bool waitAgain = true;
  200248. while (waitAgain && internal != 0)
  200249. {
  200250. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200251. waitAgain = false;
  200252. if (! intern->connect (timeOutMilliseconds))
  200253. break;
  200254. if (maxBytesToRead <= 0)
  200255. return 0;
  200256. OVERLAPPED over;
  200257. zerostruct (over);
  200258. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200259. unsigned long numRead;
  200260. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  200261. {
  200262. bytesRead = (int) numRead;
  200263. }
  200264. else if (GetLastError() == ERROR_IO_PENDING)
  200265. {
  200266. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200267. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200268. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200269. : INFINITE);
  200270. if (waitResult != WAIT_OBJECT_0)
  200271. {
  200272. // if the operation timed out, let's cancel it...
  200273. CancelIo (intern->pipeH);
  200274. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  200275. }
  200276. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  200277. {
  200278. bytesRead = (int) numRead;
  200279. }
  200280. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200281. {
  200282. intern->disconnect();
  200283. waitAgain = true;
  200284. }
  200285. }
  200286. else
  200287. {
  200288. waitAgain = internal != 0;
  200289. Sleep (5);
  200290. }
  200291. CloseHandle (over.hEvent);
  200292. }
  200293. return bytesRead;
  200294. }
  200295. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  200296. {
  200297. int bytesWritten = -1;
  200298. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200299. if (intern != 0 && intern->connect (timeOutMilliseconds))
  200300. {
  200301. if (numBytesToWrite <= 0)
  200302. return 0;
  200303. OVERLAPPED over;
  200304. zerostruct (over);
  200305. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200306. unsigned long numWritten;
  200307. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  200308. {
  200309. bytesWritten = (int) numWritten;
  200310. }
  200311. else if (GetLastError() == ERROR_IO_PENDING)
  200312. {
  200313. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200314. DWORD waitResult;
  200315. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200316. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200317. : INFINITE);
  200318. if (waitResult != WAIT_OBJECT_0)
  200319. {
  200320. CancelIo (intern->pipeH);
  200321. WaitForSingleObject (over.hEvent, INFINITE);
  200322. }
  200323. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  200324. {
  200325. bytesWritten = (int) numWritten;
  200326. }
  200327. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200328. {
  200329. intern->disconnect();
  200330. }
  200331. }
  200332. CloseHandle (over.hEvent);
  200333. }
  200334. return bytesWritten;
  200335. }
  200336. void NamedPipe::cancelPendingReads()
  200337. {
  200338. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200339. if (intern != 0)
  200340. SetEvent (intern->cancelEvent);
  200341. }
  200342. #endif
  200343. /********* End of inlined file: juce_win32_Files.cpp *********/
  200344. /********* Start of inlined file: juce_win32_Network.cpp *********/
  200345. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200346. // compiled on its own).
  200347. #if JUCE_INCLUDED_FILE
  200348. #ifndef INTERNET_FLAG_NEED_FILE
  200349. #define INTERNET_FLAG_NEED_FILE 0x00000010
  200350. #endif
  200351. bool juce_isOnLine()
  200352. {
  200353. DWORD connectionType;
  200354. return InternetGetConnectedState (&connectionType, 0) != 0
  200355. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  200356. }
  200357. struct ConnectionAndRequestStruct
  200358. {
  200359. HINTERNET connection, request;
  200360. };
  200361. static HINTERNET sessionHandle = 0;
  200362. void* juce_openInternetFile (const String& url,
  200363. const String& headers,
  200364. const MemoryBlock& postData,
  200365. const bool isPost,
  200366. URL::OpenStreamProgressCallback* callback,
  200367. void* callbackContext,
  200368. int timeOutMs)
  200369. {
  200370. if (sessionHandle == 0)
  200371. sessionHandle = InternetOpen (_T("juce"),
  200372. INTERNET_OPEN_TYPE_PRECONFIG,
  200373. 0, 0, 0);
  200374. if (sessionHandle != 0)
  200375. {
  200376. // break up the url..
  200377. TCHAR file[1024], server[1024];
  200378. URL_COMPONENTS uc;
  200379. zerostruct (uc);
  200380. uc.dwStructSize = sizeof (uc);
  200381. uc.dwUrlPathLength = sizeof (file);
  200382. uc.dwHostNameLength = sizeof (server);
  200383. uc.lpszUrlPath = file;
  200384. uc.lpszHostName = server;
  200385. if (InternetCrackUrl (url, 0, 0, &uc))
  200386. {
  200387. if (timeOutMs == 0)
  200388. timeOutMs = 30000;
  200389. else if (timeOutMs < 0)
  200390. timeOutMs = -1;
  200391. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  200392. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  200393. HINTERNET connection = InternetConnect (sessionHandle,
  200394. uc.lpszHostName,
  200395. uc.nPort,
  200396. _T(""), _T(""),
  200397. isFtp ? INTERNET_SERVICE_FTP
  200398. : INTERNET_SERVICE_HTTP,
  200399. 0, 0);
  200400. if (connection != 0)
  200401. {
  200402. if (isFtp)
  200403. {
  200404. HINTERNET request = FtpOpenFile (connection,
  200405. uc.lpszUrlPath,
  200406. GENERIC_READ,
  200407. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  200408. 0);
  200409. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  200410. result->connection = connection;
  200411. result->request = request;
  200412. return result;
  200413. }
  200414. else
  200415. {
  200416. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  200417. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  200418. if (url.startsWithIgnoreCase (T("https:")))
  200419. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  200420. // IE7 seems to automatically work out when it's https)
  200421. HINTERNET request = HttpOpenRequest (connection,
  200422. isPost ? _T("POST")
  200423. : _T("GET"),
  200424. uc.lpszUrlPath,
  200425. 0, 0, mimeTypes, flags, 0);
  200426. if (request != 0)
  200427. {
  200428. INTERNET_BUFFERS buffers;
  200429. zerostruct (buffers);
  200430. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  200431. buffers.lpcszHeader = (LPCTSTR) headers;
  200432. buffers.dwHeadersLength = headers.length();
  200433. buffers.dwBufferTotal = (DWORD) postData.getSize();
  200434. ConnectionAndRequestStruct* result = 0;
  200435. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  200436. {
  200437. int bytesSent = 0;
  200438. for (;;)
  200439. {
  200440. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  200441. DWORD bytesDone = 0;
  200442. if (bytesToDo > 0
  200443. && ! InternetWriteFile (request,
  200444. ((const char*) postData.getData()) + bytesSent,
  200445. bytesToDo, &bytesDone))
  200446. {
  200447. break;
  200448. }
  200449. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  200450. {
  200451. result = new ConnectionAndRequestStruct();
  200452. result->connection = connection;
  200453. result->request = request;
  200454. HttpEndRequest (request, 0, 0, 0);
  200455. return result;
  200456. }
  200457. bytesSent += bytesDone;
  200458. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  200459. break;
  200460. }
  200461. }
  200462. InternetCloseHandle (request);
  200463. }
  200464. InternetCloseHandle (connection);
  200465. }
  200466. }
  200467. }
  200468. }
  200469. return 0;
  200470. }
  200471. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  200472. {
  200473. DWORD bytesRead = 0;
  200474. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200475. if (crs != 0)
  200476. InternetReadFile (crs->request,
  200477. buffer, bytesToRead,
  200478. &bytesRead);
  200479. return bytesRead;
  200480. }
  200481. int juce_seekInInternetFile (void* handle, int newPosition)
  200482. {
  200483. if (handle != 0)
  200484. {
  200485. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200486. return InternetSetFilePointer (crs->request,
  200487. newPosition, 0,
  200488. FILE_BEGIN, 0);
  200489. }
  200490. else
  200491. {
  200492. return -1;
  200493. }
  200494. }
  200495. int64 juce_getInternetFileContentLength (void* handle)
  200496. {
  200497. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200498. if (crs != 0)
  200499. {
  200500. DWORD index = 0;
  200501. DWORD result = 0;
  200502. DWORD size = sizeof (result);
  200503. if (HttpQueryInfo (crs->request,
  200504. HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  200505. &result,
  200506. &size,
  200507. &index))
  200508. {
  200509. return (int64) result;
  200510. }
  200511. }
  200512. return -1;
  200513. }
  200514. void juce_closeInternetFile (void* handle)
  200515. {
  200516. if (handle != 0)
  200517. {
  200518. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  200519. InternetCloseHandle (crs->request);
  200520. InternetCloseHandle (crs->connection);
  200521. delete crs;
  200522. }
  200523. }
  200524. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  200525. {
  200526. int numFound = 0;
  200527. DynamicLibraryLoader dll ("iphlpapi.dll");
  200528. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  200529. if (getAdaptersInfo != 0)
  200530. {
  200531. ULONG len = sizeof (IP_ADAPTER_INFO);
  200532. MemoryBlock mb;
  200533. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200534. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  200535. {
  200536. mb.setSize (len);
  200537. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200538. }
  200539. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  200540. {
  200541. PIP_ADAPTER_INFO adapter = adapterInfo;
  200542. while (adapter != 0)
  200543. {
  200544. int64 mac = 0;
  200545. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  200546. mac = (mac << 8) | adapter->Address[i];
  200547. if (littleEndian)
  200548. mac = (int64) swapByteOrder ((uint64) mac);
  200549. if (numFound < maxNum && mac != 0)
  200550. addresses [numFound++] = mac;
  200551. adapter = adapter->Next;
  200552. }
  200553. }
  200554. }
  200555. return numFound;
  200556. }
  200557. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  200558. {
  200559. int numFound = 0;
  200560. DynamicLibraryLoader dll ("netapi32.dll");
  200561. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  200562. if (NetbiosCall != 0)
  200563. {
  200564. NCB ncb;
  200565. zerostruct (ncb);
  200566. typedef struct _ASTAT_
  200567. {
  200568. ADAPTER_STATUS adapt;
  200569. NAME_BUFFER NameBuff [30];
  200570. } ASTAT;
  200571. ASTAT astat;
  200572. zerostruct (astat);
  200573. LANA_ENUM enums;
  200574. zerostruct (enums);
  200575. ncb.ncb_command = NCBENUM;
  200576. ncb.ncb_buffer = (unsigned char*) &enums;
  200577. ncb.ncb_length = sizeof (LANA_ENUM);
  200578. NetbiosCall (&ncb);
  200579. for (int i = 0; i < enums.length; ++i)
  200580. {
  200581. zerostruct (ncb);
  200582. ncb.ncb_command = NCBRESET;
  200583. ncb.ncb_lana_num = enums.lana[i];
  200584. if (NetbiosCall (&ncb) == 0)
  200585. {
  200586. zerostruct (ncb);
  200587. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  200588. ncb.ncb_command = NCBASTAT;
  200589. ncb.ncb_lana_num = enums.lana[i];
  200590. ncb.ncb_buffer = (unsigned char*) &astat;
  200591. ncb.ncb_length = sizeof (ASTAT);
  200592. if (NetbiosCall (&ncb) == 0)
  200593. {
  200594. if (astat.adapt.adapter_type == 0xfe)
  200595. {
  200596. uint64 mac = 0;
  200597. for (int i = 6; --i >= 0;)
  200598. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  200599. if (numFound < maxNum && mac != 0)
  200600. addresses [numFound++] = mac;
  200601. }
  200602. }
  200603. }
  200604. }
  200605. }
  200606. return numFound;
  200607. }
  200608. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  200609. {
  200610. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  200611. if (numFound == 0)
  200612. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  200613. return numFound;
  200614. }
  200615. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  200616. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  200617. const String& emailSubject,
  200618. const String& bodyText,
  200619. const StringArray& filesToAttach)
  200620. {
  200621. HMODULE h = LoadLibraryA ("MAPI32.dll");
  200622. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  200623. bool ok = false;
  200624. if (mapiSendMail != 0)
  200625. {
  200626. MapiMessage message;
  200627. zerostruct (message);
  200628. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  200629. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  200630. MapiRecipDesc recip;
  200631. zerostruct (recip);
  200632. recip.ulRecipClass = MAPI_TO;
  200633. String targetEmailAddress_ (targetEmailAddress);
  200634. if (targetEmailAddress_.isEmpty())
  200635. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  200636. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress_;
  200637. message.nRecipCount = 1;
  200638. message.lpRecips = &recip;
  200639. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  200640. mb.fillWith (0);
  200641. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  200642. message.nFileCount = filesToAttach.size();
  200643. message.lpFiles = files;
  200644. for (int i = 0; i < filesToAttach.size(); ++i)
  200645. {
  200646. files[i].nPosition = (ULONG) -1;
  200647. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  200648. }
  200649. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  200650. }
  200651. FreeLibrary (h);
  200652. return ok;
  200653. }
  200654. #endif
  200655. /********* End of inlined file: juce_win32_Network.cpp *********/
  200656. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  200657. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200658. // compiled on its own).
  200659. #if JUCE_INCLUDED_FILE
  200660. static HKEY findKeyForPath (String name,
  200661. const bool createForWriting,
  200662. String& valueName) throw()
  200663. {
  200664. HKEY rootKey = 0;
  200665. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  200666. rootKey = HKEY_CURRENT_USER;
  200667. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  200668. rootKey = HKEY_LOCAL_MACHINE;
  200669. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  200670. rootKey = HKEY_CLASSES_ROOT;
  200671. if (rootKey != 0)
  200672. {
  200673. name = name.substring (name.indexOfChar (T('\\')) + 1);
  200674. const int lastSlash = name.lastIndexOfChar (T('\\'));
  200675. valueName = name.substring (lastSlash + 1);
  200676. name = name.substring (0, lastSlash);
  200677. HKEY key;
  200678. DWORD result;
  200679. if (createForWriting)
  200680. {
  200681. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  200682. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  200683. return key;
  200684. }
  200685. else
  200686. {
  200687. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  200688. return key;
  200689. }
  200690. }
  200691. return 0;
  200692. }
  200693. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  200694. const String& defaultValue)
  200695. {
  200696. String valueName, s;
  200697. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200698. if (k != 0)
  200699. {
  200700. WCHAR buffer [2048];
  200701. unsigned long bufferSize = sizeof (buffer);
  200702. DWORD type = REG_SZ;
  200703. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  200704. s = buffer;
  200705. else
  200706. s = defaultValue;
  200707. RegCloseKey (k);
  200708. }
  200709. return s;
  200710. }
  200711. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  200712. const String& value)
  200713. {
  200714. String valueName;
  200715. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200716. if (k != 0)
  200717. {
  200718. RegSetValueEx (k, valueName, 0, REG_SZ,
  200719. (const BYTE*) (const WCHAR*) value,
  200720. sizeof (WCHAR) * (value.length() + 1));
  200721. RegCloseKey (k);
  200722. }
  200723. }
  200724. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  200725. {
  200726. bool exists = false;
  200727. String valueName;
  200728. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200729. if (k != 0)
  200730. {
  200731. unsigned char buffer [2048];
  200732. unsigned long bufferSize = sizeof (buffer);
  200733. DWORD type = 0;
  200734. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  200735. exists = true;
  200736. RegCloseKey (k);
  200737. }
  200738. return exists;
  200739. }
  200740. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  200741. {
  200742. String valueName;
  200743. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200744. if (k != 0)
  200745. {
  200746. RegDeleteValue (k, valueName);
  200747. RegCloseKey (k);
  200748. }
  200749. }
  200750. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  200751. {
  200752. String valueName;
  200753. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  200754. if (k != 0)
  200755. {
  200756. RegDeleteKey (k, valueName);
  200757. RegCloseKey (k);
  200758. }
  200759. }
  200760. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  200761. const String& symbolicDescription,
  200762. const String& fullDescription,
  200763. const File& targetExecutable,
  200764. int iconResourceNumber)
  200765. {
  200766. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  200767. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  200768. if (iconResourceNumber != 0)
  200769. setRegistryValue (key + "\\DefaultIcon\\",
  200770. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  200771. setRegistryValue (key + "\\", fullDescription);
  200772. setRegistryValue (key + "\\shell\\open\\command\\",
  200773. targetExecutable.getFullPathName() + " %1");
  200774. }
  200775. bool juce_IsRunningInWine() throw()
  200776. {
  200777. HKEY key;
  200778. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  200779. {
  200780. RegCloseKey (key);
  200781. return true;
  200782. }
  200783. return false;
  200784. }
  200785. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  200786. {
  200787. String s (::GetCommandLineW());
  200788. StringArray tokens;
  200789. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  200790. return tokens.joinIntoString (T(" "), 1);
  200791. }
  200792. static void* currentModuleHandle = 0;
  200793. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  200794. {
  200795. if (currentModuleHandle == 0)
  200796. currentModuleHandle = GetModuleHandle (0);
  200797. return currentModuleHandle;
  200798. }
  200799. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  200800. {
  200801. currentModuleHandle = newHandle;
  200802. }
  200803. void PlatformUtilities::fpuReset()
  200804. {
  200805. #if JUCE_MSVC
  200806. _clearfp();
  200807. #endif
  200808. }
  200809. void PlatformUtilities::beep()
  200810. {
  200811. MessageBeep (MB_OK);
  200812. }
  200813. #endif
  200814. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  200815. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200816. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  200817. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200818. // compiled on its own).
  200819. #if JUCE_INCLUDED_FILE
  200820. static const unsigned int specialId = WM_APP + 0x4400;
  200821. static const unsigned int broadcastId = WM_APP + 0x4403;
  200822. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  200823. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  200824. HWND juce_messageWindowHandle = 0;
  200825. extern long improbableWindowNumber; // defined in windowing.cpp
  200826. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  200827. const UINT message,
  200828. const WPARAM wParam,
  200829. const LPARAM lParam) throw()
  200830. {
  200831. JUCE_TRY
  200832. {
  200833. if (h == juce_messageWindowHandle)
  200834. {
  200835. if (message == specialCallbackId)
  200836. {
  200837. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  200838. return (LRESULT) (*func) ((void*) lParam);
  200839. }
  200840. else if (message == specialId)
  200841. {
  200842. // these are trapped early in the dispatch call, but must also be checked
  200843. // here in case there are windows modal dialog boxes doing their own
  200844. // dispatch loop and not calling our version
  200845. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  200846. return 0;
  200847. }
  200848. else if (message == broadcastId)
  200849. {
  200850. String* const messageString = (String*) lParam;
  200851. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  200852. delete messageString;
  200853. return 0;
  200854. }
  200855. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  200856. {
  200857. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  200858. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  200859. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  200860. return 0;
  200861. }
  200862. }
  200863. }
  200864. JUCE_CATCH_EXCEPTION
  200865. return DefWindowProc (h, message, wParam, lParam);
  200866. }
  200867. static bool isEventBlockedByModalComps (MSG& m)
  200868. {
  200869. if (Component::getNumCurrentlyModalComponents() == 0
  200870. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  200871. return false;
  200872. switch (m.message)
  200873. {
  200874. case WM_MOUSEMOVE:
  200875. case WM_NCMOUSEMOVE:
  200876. case 0x020A: /* WM_MOUSEWHEEL */
  200877. case 0x020E: /* WM_MOUSEHWHEEL */
  200878. case WM_KEYUP:
  200879. case WM_SYSKEYUP:
  200880. case WM_CHAR:
  200881. case WM_APPCOMMAND:
  200882. case WM_LBUTTONUP:
  200883. case WM_MBUTTONUP:
  200884. case WM_RBUTTONUP:
  200885. case WM_MOUSEACTIVATE:
  200886. case WM_NCMOUSEHOVER:
  200887. case WM_MOUSEHOVER:
  200888. return true;
  200889. case WM_NCLBUTTONDOWN:
  200890. case WM_NCLBUTTONDBLCLK:
  200891. case WM_NCRBUTTONDOWN:
  200892. case WM_NCRBUTTONDBLCLK:
  200893. case WM_NCMBUTTONDOWN:
  200894. case WM_NCMBUTTONDBLCLK:
  200895. case WM_LBUTTONDOWN:
  200896. case WM_LBUTTONDBLCLK:
  200897. case WM_MBUTTONDOWN:
  200898. case WM_MBUTTONDBLCLK:
  200899. case WM_RBUTTONDOWN:
  200900. case WM_RBUTTONDBLCLK:
  200901. case WM_KEYDOWN:
  200902. case WM_SYSKEYDOWN:
  200903. {
  200904. Component* const modal = Component::getCurrentlyModalComponent (0);
  200905. if (modal != 0)
  200906. modal->inputAttemptWhenModal();
  200907. return true;
  200908. }
  200909. default:
  200910. break;
  200911. }
  200912. return false;
  200913. }
  200914. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  200915. {
  200916. MSG m;
  200917. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  200918. return false;
  200919. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  200920. {
  200921. if (m.message == specialId
  200922. && m.hwnd == juce_messageWindowHandle)
  200923. {
  200924. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  200925. }
  200926. else if (! isEventBlockedByModalComps (m))
  200927. {
  200928. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  200929. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  200930. {
  200931. // if it's someone else's window being clicked on, and the focus is
  200932. // currently on a juce window, pass the kb focus over..
  200933. HWND currentFocus = GetFocus();
  200934. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  200935. SetFocus (m.hwnd);
  200936. }
  200937. TranslateMessage (&m);
  200938. DispatchMessage (&m);
  200939. }
  200940. }
  200941. return true;
  200942. }
  200943. bool juce_postMessageToSystemQueue (void* message)
  200944. {
  200945. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  200946. }
  200947. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  200948. void* userData)
  200949. {
  200950. if (MessageManager::getInstance()->isThisTheMessageThread())
  200951. {
  200952. return (*callback) (userData);
  200953. }
  200954. else
  200955. {
  200956. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  200957. // deadlock because the message manager is blocked from running, and can't
  200958. // call your function..
  200959. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  200960. return (void*) SendMessage (juce_messageWindowHandle,
  200961. specialCallbackId,
  200962. (WPARAM) callback,
  200963. (LPARAM) userData);
  200964. }
  200965. }
  200966. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  200967. {
  200968. if (hwnd != juce_messageWindowHandle)
  200969. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  200970. return TRUE;
  200971. }
  200972. void MessageManager::broadcastMessage (const String& value) throw()
  200973. {
  200974. VoidArray windows;
  200975. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  200976. const String localCopy (value);
  200977. COPYDATASTRUCT data;
  200978. data.dwData = broadcastId;
  200979. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  200980. data.lpData = (void*) (const juce_wchar*) localCopy;
  200981. for (int i = windows.size(); --i >= 0;)
  200982. {
  200983. HWND hwnd = (HWND) windows.getUnchecked(i);
  200984. TCHAR windowName [64]; // no need to read longer strings than this
  200985. GetWindowText (hwnd, windowName, 64);
  200986. windowName [63] = 0;
  200987. if (String (windowName) == String (messageWindowName))
  200988. {
  200989. DWORD_PTR result;
  200990. SendMessageTimeout (hwnd, WM_COPYDATA,
  200991. (WPARAM) juce_messageWindowHandle,
  200992. (LPARAM) &data,
  200993. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  200994. 8000,
  200995. &result);
  200996. }
  200997. }
  200998. }
  200999. static const String getMessageWindowClassName()
  201000. {
  201001. // this name has to be different for each app/dll instance because otherwise
  201002. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201003. // window class).
  201004. static int number = 0;
  201005. if (number == 0)
  201006. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  201007. return T("JUCEcs_") + String (number);
  201008. }
  201009. void MessageManager::doPlatformSpecificInitialisation()
  201010. {
  201011. OleInitialize (0);
  201012. const String className (getMessageWindowClassName());
  201013. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201014. WNDCLASSEX wc;
  201015. zerostruct (wc);
  201016. wc.cbSize = sizeof (wc);
  201017. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  201018. wc.cbWndExtra = 4;
  201019. wc.hInstance = hmod;
  201020. wc.lpszClassName = className;
  201021. RegisterClassEx (&wc);
  201022. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  201023. messageWindowName,
  201024. 0, 0, 0, 0, 0, 0, 0,
  201025. hmod, 0);
  201026. }
  201027. void MessageManager::doPlatformSpecificShutdown()
  201028. {
  201029. DestroyWindow (juce_messageWindowHandle);
  201030. UnregisterClass (getMessageWindowClassName(), 0);
  201031. OleUninitialize();
  201032. }
  201033. #endif
  201034. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  201035. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  201036. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201037. // compiled on its own).
  201038. #if JUCE_INCLUDED_FILE
  201039. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  201040. // these are in the windows SDK, but need to be repeated here for GCC..
  201041. #ifndef GET_APPCOMMAND_LPARAM
  201042. #define FAPPCOMMAND_MASK 0xF000
  201043. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  201044. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  201045. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  201046. #define APPCOMMAND_MEDIA_STOP 13
  201047. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  201048. #define WM_APPCOMMAND 0x0319
  201049. #endif
  201050. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  201051. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  201052. extern bool juce_IsRunningInWine() throw();
  201053. #ifndef ULW_ALPHA
  201054. #define ULW_ALPHA 0x00000002
  201055. #endif
  201056. #ifndef AC_SRC_ALPHA
  201057. #define AC_SRC_ALPHA 0x01
  201058. #endif
  201059. #define DEBUG_REPAINT_TIMES 0
  201060. static HPALETTE palette = 0;
  201061. static bool createPaletteIfNeeded = true;
  201062. static bool shouldDeactivateTitleBar = true;
  201063. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  201064. #define WM_TRAYNOTIFY WM_USER + 100
  201065. using ::abs;
  201066. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  201067. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  201068. bool Desktop::canUseSemiTransparentWindows() throw()
  201069. {
  201070. if (updateLayeredWindow == 0)
  201071. {
  201072. if (! juce_IsRunningInWine())
  201073. {
  201074. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  201075. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  201076. }
  201077. }
  201078. return updateLayeredWindow != 0;
  201079. }
  201080. #undef DefWindowProc
  201081. #define DefWindowProc DefWindowProcW
  201082. const int extendedKeyModifier = 0x10000;
  201083. const int KeyPress::spaceKey = VK_SPACE;
  201084. const int KeyPress::returnKey = VK_RETURN;
  201085. const int KeyPress::escapeKey = VK_ESCAPE;
  201086. const int KeyPress::backspaceKey = VK_BACK;
  201087. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  201088. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  201089. const int KeyPress::tabKey = VK_TAB;
  201090. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  201091. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  201092. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  201093. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  201094. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  201095. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  201096. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  201097. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  201098. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  201099. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  201100. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  201101. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  201102. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  201103. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  201104. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  201105. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  201106. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  201107. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  201108. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  201109. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  201110. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  201111. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  201112. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  201113. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  201114. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  201115. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  201116. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  201117. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  201118. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  201119. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  201120. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  201121. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  201122. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  201123. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  201124. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  201125. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  201126. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  201127. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  201128. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  201129. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  201130. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  201131. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  201132. const int KeyPress::playKey = 0x30000;
  201133. const int KeyPress::stopKey = 0x30001;
  201134. const int KeyPress::fastForwardKey = 0x30002;
  201135. const int KeyPress::rewindKey = 0x30003;
  201136. class WindowsBitmapImage : public Image
  201137. {
  201138. public:
  201139. HBITMAP hBitmap;
  201140. BITMAPV4HEADER bitmapInfo;
  201141. HDC hdc;
  201142. unsigned char* bitmapData;
  201143. WindowsBitmapImage (const PixelFormat format_,
  201144. const int w, const int h, const bool clearImage)
  201145. : Image (format_, w, h)
  201146. {
  201147. jassert (format_ == RGB || format_ == ARGB);
  201148. pixelStride = (format_ == RGB) ? 3 : 4;
  201149. zerostruct (bitmapInfo);
  201150. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  201151. bitmapInfo.bV4Width = w;
  201152. bitmapInfo.bV4Height = h;
  201153. bitmapInfo.bV4Planes = 1;
  201154. bitmapInfo.bV4CSType = 1;
  201155. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  201156. if (format_ == ARGB)
  201157. {
  201158. bitmapInfo.bV4AlphaMask = 0xff000000;
  201159. bitmapInfo.bV4RedMask = 0xff0000;
  201160. bitmapInfo.bV4GreenMask = 0xff00;
  201161. bitmapInfo.bV4BlueMask = 0xff;
  201162. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  201163. }
  201164. else
  201165. {
  201166. bitmapInfo.bV4V4Compression = BI_RGB;
  201167. }
  201168. lineStride = -((w * pixelStride + 3) & ~3);
  201169. HDC dc = GetDC (0);
  201170. hdc = CreateCompatibleDC (dc);
  201171. ReleaseDC (0, dc);
  201172. SetMapMode (hdc, MM_TEXT);
  201173. hBitmap = CreateDIBSection (hdc,
  201174. (BITMAPINFO*) &(bitmapInfo),
  201175. DIB_RGB_COLORS,
  201176. (void**) &bitmapData,
  201177. 0, 0);
  201178. SelectObject (hdc, hBitmap);
  201179. if (format_ == ARGB && clearImage)
  201180. zeromem (bitmapData, abs (h * lineStride));
  201181. imageData = bitmapData - (lineStride * (h - 1));
  201182. }
  201183. ~WindowsBitmapImage()
  201184. {
  201185. DeleteDC (hdc);
  201186. DeleteObject (hBitmap);
  201187. imageData = 0; // to stop the base class freeing this
  201188. }
  201189. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  201190. const int x, const int y,
  201191. const RectangleList& maskedRegion) throw()
  201192. {
  201193. static HDRAWDIB hdd = 0;
  201194. static bool needToCreateDrawDib = true;
  201195. if (needToCreateDrawDib)
  201196. {
  201197. needToCreateDrawDib = false;
  201198. HDC dc = GetDC (0);
  201199. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201200. ReleaseDC (0, dc);
  201201. // only open if we're not palettised
  201202. if (n > 8)
  201203. hdd = DrawDibOpen();
  201204. }
  201205. if (createPaletteIfNeeded)
  201206. {
  201207. HDC dc = GetDC (0);
  201208. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201209. ReleaseDC (0, dc);
  201210. if (n <= 8)
  201211. palette = CreateHalftonePalette (dc);
  201212. createPaletteIfNeeded = false;
  201213. }
  201214. if (palette != 0)
  201215. {
  201216. SelectPalette (dc, palette, FALSE);
  201217. RealizePalette (dc);
  201218. SetStretchBltMode (dc, HALFTONE);
  201219. }
  201220. SetMapMode (dc, MM_TEXT);
  201221. if (transparent)
  201222. {
  201223. POINT p, pos;
  201224. SIZE size;
  201225. RECT windowBounds;
  201226. GetWindowRect (hwnd, &windowBounds);
  201227. p.x = -x;
  201228. p.y = -y;
  201229. pos.x = windowBounds.left;
  201230. pos.y = windowBounds.top;
  201231. size.cx = windowBounds.right - windowBounds.left;
  201232. size.cy = windowBounds.bottom - windowBounds.top;
  201233. BLENDFUNCTION bf;
  201234. bf.AlphaFormat = AC_SRC_ALPHA;
  201235. bf.BlendFlags = 0;
  201236. bf.BlendOp = AC_SRC_OVER;
  201237. bf.SourceConstantAlpha = 0xff;
  201238. if (! maskedRegion.isEmpty())
  201239. {
  201240. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201241. {
  201242. const Rectangle& r = *i.getRectangle();
  201243. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201244. }
  201245. }
  201246. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  201247. }
  201248. else
  201249. {
  201250. int savedDC = 0;
  201251. if (! maskedRegion.isEmpty())
  201252. {
  201253. savedDC = SaveDC (dc);
  201254. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201255. {
  201256. const Rectangle& r = *i.getRectangle();
  201257. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201258. }
  201259. }
  201260. const int w = getWidth();
  201261. const int h = getHeight();
  201262. if (hdd == 0)
  201263. {
  201264. StretchDIBits (dc,
  201265. x, y, w, h,
  201266. 0, 0, w, h,
  201267. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  201268. DIB_RGB_COLORS, SRCCOPY);
  201269. }
  201270. else
  201271. {
  201272. DrawDibDraw (hdd, dc, x, y, -1, -1,
  201273. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  201274. 0, 0, w, h, 0);
  201275. }
  201276. if (! maskedRegion.isEmpty())
  201277. RestoreDC (dc, savedDC);
  201278. }
  201279. }
  201280. juce_UseDebuggingNewOperator
  201281. private:
  201282. WindowsBitmapImage (const WindowsBitmapImage&);
  201283. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  201284. };
  201285. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  201286. static int currentModifiers = 0;
  201287. static int modifiersAtLastCallback = 0;
  201288. static void updateKeyModifiers() throw()
  201289. {
  201290. currentModifiers &= ~(ModifierKeys::shiftModifier
  201291. | ModifierKeys::ctrlModifier
  201292. | ModifierKeys::altModifier);
  201293. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  201294. currentModifiers |= ModifierKeys::shiftModifier;
  201295. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  201296. currentModifiers |= ModifierKeys::ctrlModifier;
  201297. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  201298. currentModifiers |= ModifierKeys::altModifier;
  201299. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  201300. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  201301. }
  201302. void ModifierKeys::updateCurrentModifiers() throw()
  201303. {
  201304. currentModifierFlags = currentModifiers;
  201305. }
  201306. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  201307. {
  201308. SHORT k = (SHORT) keyCode;
  201309. if ((keyCode & extendedKeyModifier) == 0
  201310. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  201311. k += (SHORT) T('A') - (SHORT) T('a');
  201312. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  201313. (SHORT) '+', VK_OEM_PLUS,
  201314. (SHORT) '-', VK_OEM_MINUS,
  201315. (SHORT) '.', VK_OEM_PERIOD,
  201316. (SHORT) ';', VK_OEM_1,
  201317. (SHORT) ':', VK_OEM_1,
  201318. (SHORT) '/', VK_OEM_2,
  201319. (SHORT) '?', VK_OEM_2,
  201320. (SHORT) '[', VK_OEM_4,
  201321. (SHORT) ']', VK_OEM_6 };
  201322. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  201323. if (k == translatedValues [i])
  201324. k = translatedValues [i + 1];
  201325. return (GetKeyState (k) & 0x8000) != 0;
  201326. }
  201327. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  201328. {
  201329. updateKeyModifiers();
  201330. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201331. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  201332. currentModifiers |= ModifierKeys::leftButtonModifier;
  201333. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  201334. currentModifiers |= ModifierKeys::rightButtonModifier;
  201335. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  201336. currentModifiers |= ModifierKeys::middleButtonModifier;
  201337. return ModifierKeys (currentModifiers);
  201338. }
  201339. static int64 getMouseEventTime() throw()
  201340. {
  201341. static int64 eventTimeOffset = 0;
  201342. static DWORD lastMessageTime = 0;
  201343. const DWORD thisMessageTime = GetMessageTime();
  201344. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  201345. {
  201346. lastMessageTime = thisMessageTime;
  201347. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  201348. }
  201349. return eventTimeOffset + thisMessageTime;
  201350. }
  201351. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  201352. {
  201353. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  201354. return callback (userData);
  201355. else
  201356. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  201357. }
  201358. class Win32ComponentPeer : public ComponentPeer
  201359. {
  201360. public:
  201361. Win32ComponentPeer (Component* const component,
  201362. const int windowStyleFlags)
  201363. : ComponentPeer (component, windowStyleFlags),
  201364. dontRepaint (false),
  201365. fullScreen (false),
  201366. isDragging (false),
  201367. isMouseOver (false),
  201368. hasCreatedCaret (false),
  201369. currentWindowIcon (0),
  201370. taskBarIcon (0),
  201371. dropTarget (0)
  201372. {
  201373. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  201374. setTitle (component->getName());
  201375. if ((windowStyleFlags & windowHasDropShadow) != 0
  201376. && Desktop::canUseSemiTransparentWindows())
  201377. {
  201378. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  201379. if (shadower != 0)
  201380. shadower->setOwner (component);
  201381. }
  201382. else
  201383. {
  201384. shadower = 0;
  201385. }
  201386. }
  201387. ~Win32ComponentPeer()
  201388. {
  201389. setTaskBarIcon (0);
  201390. deleteAndZero (shadower);
  201391. // do this before the next bit to avoid messages arriving for this window
  201392. // before it's destroyed
  201393. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  201394. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  201395. if (currentWindowIcon != 0)
  201396. DestroyIcon (currentWindowIcon);
  201397. if (dropTarget != 0)
  201398. {
  201399. dropTarget->Release();
  201400. dropTarget = 0;
  201401. }
  201402. }
  201403. void* getNativeHandle() const
  201404. {
  201405. return (void*) hwnd;
  201406. }
  201407. void setVisible (bool shouldBeVisible)
  201408. {
  201409. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  201410. if (shouldBeVisible)
  201411. InvalidateRect (hwnd, 0, 0);
  201412. else
  201413. lastPaintTime = 0;
  201414. }
  201415. void setTitle (const String& title)
  201416. {
  201417. SetWindowText (hwnd, title);
  201418. }
  201419. void setPosition (int x, int y)
  201420. {
  201421. offsetWithinParent (x, y);
  201422. SetWindowPos (hwnd, 0,
  201423. x - windowBorder.getLeft(),
  201424. y - windowBorder.getTop(),
  201425. 0, 0,
  201426. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201427. }
  201428. void repaintNowIfTransparent()
  201429. {
  201430. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  201431. handlePaintMessage();
  201432. }
  201433. void updateBorderSize()
  201434. {
  201435. WINDOWINFO info;
  201436. info.cbSize = sizeof (info);
  201437. if (GetWindowInfo (hwnd, &info))
  201438. {
  201439. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  201440. info.rcClient.left - info.rcWindow.left,
  201441. info.rcWindow.bottom - info.rcClient.bottom,
  201442. info.rcWindow.right - info.rcClient.right);
  201443. }
  201444. }
  201445. void setSize (int w, int h)
  201446. {
  201447. SetWindowPos (hwnd, 0, 0, 0,
  201448. w + windowBorder.getLeftAndRight(),
  201449. h + windowBorder.getTopAndBottom(),
  201450. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201451. updateBorderSize();
  201452. repaintNowIfTransparent();
  201453. }
  201454. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  201455. {
  201456. fullScreen = isNowFullScreen;
  201457. offsetWithinParent (x, y);
  201458. SetWindowPos (hwnd, 0,
  201459. x - windowBorder.getLeft(),
  201460. y - windowBorder.getTop(),
  201461. w + windowBorder.getLeftAndRight(),
  201462. h + windowBorder.getTopAndBottom(),
  201463. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201464. updateBorderSize();
  201465. repaintNowIfTransparent();
  201466. }
  201467. void getBounds (int& x, int& y, int& w, int& h) const
  201468. {
  201469. RECT r;
  201470. GetWindowRect (hwnd, &r);
  201471. x = r.left;
  201472. y = r.top;
  201473. w = r.right - x;
  201474. h = r.bottom - y;
  201475. HWND parentH = GetParent (hwnd);
  201476. if (parentH != 0)
  201477. {
  201478. GetWindowRect (parentH, &r);
  201479. x -= r.left;
  201480. y -= r.top;
  201481. }
  201482. x += windowBorder.getLeft();
  201483. y += windowBorder.getTop();
  201484. w -= windowBorder.getLeftAndRight();
  201485. h -= windowBorder.getTopAndBottom();
  201486. }
  201487. int getScreenX() const
  201488. {
  201489. RECT r;
  201490. GetWindowRect (hwnd, &r);
  201491. return r.left + windowBorder.getLeft();
  201492. }
  201493. int getScreenY() const
  201494. {
  201495. RECT r;
  201496. GetWindowRect (hwnd, &r);
  201497. return r.top + windowBorder.getTop();
  201498. }
  201499. void relativePositionToGlobal (int& x, int& y)
  201500. {
  201501. RECT r;
  201502. GetWindowRect (hwnd, &r);
  201503. x += r.left + windowBorder.getLeft();
  201504. y += r.top + windowBorder.getTop();
  201505. }
  201506. void globalPositionToRelative (int& x, int& y)
  201507. {
  201508. RECT r;
  201509. GetWindowRect (hwnd, &r);
  201510. x -= r.left + windowBorder.getLeft();
  201511. y -= r.top + windowBorder.getTop();
  201512. }
  201513. void setMinimised (bool shouldBeMinimised)
  201514. {
  201515. if (shouldBeMinimised != isMinimised())
  201516. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  201517. }
  201518. bool isMinimised() const
  201519. {
  201520. WINDOWPLACEMENT wp;
  201521. wp.length = sizeof (WINDOWPLACEMENT);
  201522. GetWindowPlacement (hwnd, &wp);
  201523. return wp.showCmd == SW_SHOWMINIMIZED;
  201524. }
  201525. void setFullScreen (bool shouldBeFullScreen)
  201526. {
  201527. setMinimised (false);
  201528. if (fullScreen != shouldBeFullScreen)
  201529. {
  201530. fullScreen = shouldBeFullScreen;
  201531. const ComponentDeletionWatcher deletionChecker (component);
  201532. if (! fullScreen)
  201533. {
  201534. const Rectangle boundsCopy (lastNonFullscreenBounds);
  201535. if (hasTitleBar())
  201536. ShowWindow (hwnd, SW_SHOWNORMAL);
  201537. if (! boundsCopy.isEmpty())
  201538. {
  201539. setBounds (boundsCopy.getX(),
  201540. boundsCopy.getY(),
  201541. boundsCopy.getWidth(),
  201542. boundsCopy.getHeight(),
  201543. false);
  201544. }
  201545. }
  201546. else
  201547. {
  201548. if (hasTitleBar())
  201549. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  201550. else
  201551. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  201552. }
  201553. if (! deletionChecker.hasBeenDeleted())
  201554. handleMovedOrResized();
  201555. }
  201556. }
  201557. bool isFullScreen() const
  201558. {
  201559. if (! hasTitleBar())
  201560. return fullScreen;
  201561. WINDOWPLACEMENT wp;
  201562. wp.length = sizeof (wp);
  201563. GetWindowPlacement (hwnd, &wp);
  201564. return wp.showCmd == SW_SHOWMAXIMIZED;
  201565. }
  201566. bool contains (int x, int y, bool trueIfInAChildWindow) const
  201567. {
  201568. RECT r;
  201569. GetWindowRect (hwnd, &r);
  201570. POINT p;
  201571. p.x = x + r.left + windowBorder.getLeft();
  201572. p.y = y + r.top + windowBorder.getTop();
  201573. HWND w = WindowFromPoint (p);
  201574. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  201575. }
  201576. const BorderSize getFrameSize() const
  201577. {
  201578. return windowBorder;
  201579. }
  201580. bool setAlwaysOnTop (bool alwaysOnTop)
  201581. {
  201582. const bool oldDeactivate = shouldDeactivateTitleBar;
  201583. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201584. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  201585. 0, 0, 0, 0,
  201586. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201587. shouldDeactivateTitleBar = oldDeactivate;
  201588. if (shadower != 0)
  201589. shadower->componentBroughtToFront (*component);
  201590. return true;
  201591. }
  201592. void toFront (bool makeActive)
  201593. {
  201594. setMinimised (false);
  201595. const bool oldDeactivate = shouldDeactivateTitleBar;
  201596. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201597. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  201598. : &toFrontCallback2,
  201599. (void*) hwnd);
  201600. shouldDeactivateTitleBar = oldDeactivate;
  201601. if (! makeActive)
  201602. {
  201603. // in this case a broughttofront call won't have occured, so do it now..
  201604. handleBroughtToFront();
  201605. }
  201606. }
  201607. void toBehind (ComponentPeer* other)
  201608. {
  201609. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  201610. jassert (otherPeer != 0); // wrong type of window?
  201611. if (otherPeer != 0)
  201612. {
  201613. setMinimised (false);
  201614. // must be careful not to try to put a topmost window behind a normal one, or win32
  201615. // promotes the normal one to be topmost!
  201616. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  201617. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  201618. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201619. else if (otherPeer->getComponent()->isAlwaysOnTop())
  201620. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  201621. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201622. }
  201623. }
  201624. bool isFocused() const
  201625. {
  201626. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  201627. }
  201628. void grabFocus()
  201629. {
  201630. const bool oldDeactivate = shouldDeactivateTitleBar;
  201631. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201632. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  201633. shouldDeactivateTitleBar = oldDeactivate;
  201634. }
  201635. void textInputRequired (int /*x*/, int /*y*/)
  201636. {
  201637. if (! hasCreatedCaret)
  201638. {
  201639. hasCreatedCaret = true;
  201640. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  201641. }
  201642. ShowCaret (hwnd);
  201643. SetCaretPos (0, 0);
  201644. }
  201645. void repaint (int x, int y, int w, int h)
  201646. {
  201647. const RECT r = { x, y, x + w, y + h };
  201648. InvalidateRect (hwnd, &r, FALSE);
  201649. }
  201650. void performAnyPendingRepaintsNow()
  201651. {
  201652. MSG m;
  201653. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  201654. DispatchMessage (&m);
  201655. }
  201656. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  201657. {
  201658. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  201659. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  201660. return 0;
  201661. }
  201662. void setTaskBarIcon (const Image* const image)
  201663. {
  201664. if (image != 0)
  201665. {
  201666. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  201667. if (taskBarIcon == 0)
  201668. {
  201669. taskBarIcon = new NOTIFYICONDATA();
  201670. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  201671. taskBarIcon->hWnd = (HWND) hwnd;
  201672. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  201673. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  201674. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  201675. taskBarIcon->hIcon = hicon;
  201676. taskBarIcon->szTip[0] = 0;
  201677. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  201678. }
  201679. else
  201680. {
  201681. HICON oldIcon = taskBarIcon->hIcon;
  201682. taskBarIcon->hIcon = hicon;
  201683. taskBarIcon->uFlags = NIF_ICON;
  201684. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201685. DestroyIcon (oldIcon);
  201686. }
  201687. DestroyIcon (hicon);
  201688. }
  201689. else if (taskBarIcon != 0)
  201690. {
  201691. taskBarIcon->uFlags = 0;
  201692. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  201693. DestroyIcon (taskBarIcon->hIcon);
  201694. deleteAndZero (taskBarIcon);
  201695. }
  201696. }
  201697. void setTaskBarIconToolTip (const String& toolTip) const
  201698. {
  201699. if (taskBarIcon != 0)
  201700. {
  201701. taskBarIcon->uFlags = NIF_TIP;
  201702. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  201703. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201704. }
  201705. }
  201706. bool isInside (HWND h) const
  201707. {
  201708. return GetAncestor (hwnd, GA_ROOT) == h;
  201709. }
  201710. juce_UseDebuggingNewOperator
  201711. bool dontRepaint;
  201712. private:
  201713. HWND hwnd;
  201714. DropShadower* shadower;
  201715. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  201716. BorderSize windowBorder;
  201717. HICON currentWindowIcon;
  201718. NOTIFYICONDATA* taskBarIcon;
  201719. IDropTarget* dropTarget;
  201720. class TemporaryImage : public Timer
  201721. {
  201722. public:
  201723. TemporaryImage()
  201724. : image (0)
  201725. {
  201726. }
  201727. ~TemporaryImage()
  201728. {
  201729. delete image;
  201730. }
  201731. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  201732. {
  201733. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  201734. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  201735. {
  201736. delete image;
  201737. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  201738. }
  201739. startTimer (3000);
  201740. return image;
  201741. }
  201742. void timerCallback()
  201743. {
  201744. stopTimer();
  201745. deleteAndZero (image);
  201746. }
  201747. private:
  201748. WindowsBitmapImage* image;
  201749. TemporaryImage (const TemporaryImage&);
  201750. const TemporaryImage& operator= (const TemporaryImage&);
  201751. };
  201752. TemporaryImage offscreenImageGenerator;
  201753. class WindowClassHolder : public DeletedAtShutdown
  201754. {
  201755. public:
  201756. WindowClassHolder()
  201757. : windowClassName ("JUCE_")
  201758. {
  201759. // this name has to be different for each app/dll instance because otherwise
  201760. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201761. // window class).
  201762. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  201763. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201764. TCHAR moduleFile [1024];
  201765. moduleFile[0] = 0;
  201766. GetModuleFileName (moduleHandle, moduleFile, 1024);
  201767. WORD iconNum = 0;
  201768. WNDCLASSEX wcex;
  201769. wcex.cbSize = sizeof (wcex);
  201770. wcex.style = CS_OWNDC;
  201771. wcex.lpfnWndProc = (WNDPROC) windowProc;
  201772. wcex.lpszClassName = windowClassName;
  201773. wcex.cbClsExtra = 0;
  201774. wcex.cbWndExtra = 32;
  201775. wcex.hInstance = moduleHandle;
  201776. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201777. iconNum = 1;
  201778. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201779. wcex.hCursor = 0;
  201780. wcex.hbrBackground = 0;
  201781. wcex.lpszMenuName = 0;
  201782. RegisterClassEx (&wcex);
  201783. }
  201784. ~WindowClassHolder()
  201785. {
  201786. if (ComponentPeer::getNumPeers() == 0)
  201787. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  201788. clearSingletonInstance();
  201789. }
  201790. String windowClassName;
  201791. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  201792. };
  201793. static void* createWindowCallback (void* userData)
  201794. {
  201795. ((Win32ComponentPeer*) userData)->createWindow();
  201796. return 0;
  201797. }
  201798. void createWindow()
  201799. {
  201800. DWORD exstyle = WS_EX_ACCEPTFILES;
  201801. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  201802. if (hasTitleBar())
  201803. {
  201804. type |= WS_OVERLAPPED;
  201805. exstyle |= WS_EX_APPWINDOW;
  201806. if ((styleFlags & windowHasCloseButton) != 0)
  201807. {
  201808. type |= WS_SYSMENU;
  201809. }
  201810. else
  201811. {
  201812. // annoyingly, windows won't let you have a min/max button without a close button
  201813. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  201814. }
  201815. if ((styleFlags & windowIsResizable) != 0)
  201816. type |= WS_THICKFRAME;
  201817. }
  201818. else
  201819. {
  201820. type |= WS_POPUP | WS_SYSMENU;
  201821. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  201822. exstyle |= WS_EX_TOOLWINDOW;
  201823. else
  201824. exstyle |= WS_EX_APPWINDOW;
  201825. }
  201826. if ((styleFlags & windowHasMinimiseButton) != 0)
  201827. type |= WS_MINIMIZEBOX;
  201828. if ((styleFlags & windowHasMaximiseButton) != 0)
  201829. type |= WS_MAXIMIZEBOX;
  201830. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  201831. exstyle |= WS_EX_TRANSPARENT;
  201832. if ((styleFlags & windowIsSemiTransparent) != 0
  201833. && Desktop::canUseSemiTransparentWindows())
  201834. exstyle |= WS_EX_LAYERED;
  201835. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  201836. if (hwnd != 0)
  201837. {
  201838. SetWindowLongPtr (hwnd, 0, 0);
  201839. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  201840. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  201841. if (dropTarget == 0)
  201842. dropTarget = new JuceDropTarget (this);
  201843. RegisterDragDrop (hwnd, dropTarget);
  201844. updateBorderSize();
  201845. // Calling this function here is (for some reason) necessary to make Windows
  201846. // correctly enable the menu items that we specify in the wm_initmenu message.
  201847. GetSystemMenu (hwnd, false);
  201848. }
  201849. else
  201850. {
  201851. jassertfalse
  201852. }
  201853. }
  201854. static void* destroyWindowCallback (void* handle)
  201855. {
  201856. RevokeDragDrop ((HWND) handle);
  201857. DestroyWindow ((HWND) handle);
  201858. return 0;
  201859. }
  201860. static void* toFrontCallback1 (void* h)
  201861. {
  201862. SetForegroundWindow ((HWND) h);
  201863. return 0;
  201864. }
  201865. static void* toFrontCallback2 (void* h)
  201866. {
  201867. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201868. return 0;
  201869. }
  201870. static void* setFocusCallback (void* h)
  201871. {
  201872. SetFocus ((HWND) h);
  201873. return 0;
  201874. }
  201875. static void* getFocusCallback (void*)
  201876. {
  201877. return (void*) GetFocus();
  201878. }
  201879. void offsetWithinParent (int& x, int& y) const
  201880. {
  201881. if (isTransparent())
  201882. {
  201883. HWND parentHwnd = GetParent (hwnd);
  201884. if (parentHwnd != 0)
  201885. {
  201886. RECT parentRect;
  201887. GetWindowRect (parentHwnd, &parentRect);
  201888. x += parentRect.left;
  201889. y += parentRect.top;
  201890. }
  201891. }
  201892. }
  201893. bool isTransparent() const
  201894. {
  201895. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  201896. }
  201897. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  201898. void setIcon (const Image& newIcon)
  201899. {
  201900. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  201901. if (hicon != 0)
  201902. {
  201903. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  201904. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  201905. if (currentWindowIcon != 0)
  201906. DestroyIcon (currentWindowIcon);
  201907. currentWindowIcon = hicon;
  201908. }
  201909. }
  201910. void handlePaintMessage()
  201911. {
  201912. #if DEBUG_REPAINT_TIMES
  201913. const double paintStart = Time::getMillisecondCounterHiRes();
  201914. #endif
  201915. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  201916. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  201917. PAINTSTRUCT paintStruct;
  201918. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  201919. // message and become re-entrant, but that's OK
  201920. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  201921. // corrupt the image it's using to paint into, so do a check here.
  201922. static bool reentrant = false;
  201923. if (reentrant)
  201924. {
  201925. DeleteObject (rgn);
  201926. EndPaint (hwnd, &paintStruct);
  201927. return;
  201928. }
  201929. reentrant = true;
  201930. // this is the rectangle to update..
  201931. int x = paintStruct.rcPaint.left;
  201932. int y = paintStruct.rcPaint.top;
  201933. int w = paintStruct.rcPaint.right - x;
  201934. int h = paintStruct.rcPaint.bottom - y;
  201935. const bool transparent = isTransparent();
  201936. if (transparent)
  201937. {
  201938. // it's not possible to have a transparent window with a title bar at the moment!
  201939. jassert (! hasTitleBar());
  201940. RECT r;
  201941. GetWindowRect (hwnd, &r);
  201942. x = y = 0;
  201943. w = r.right - r.left;
  201944. h = r.bottom - r.top;
  201945. }
  201946. if (w > 0 && h > 0)
  201947. {
  201948. clearMaskedRegion();
  201949. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  201950. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  201951. RectangleList* const contextClip = context.getRawClipRegion();
  201952. contextClip->clear();
  201953. context.setOrigin (-x, -y);
  201954. bool needToPaintAll = true;
  201955. if (regionType == COMPLEXREGION && ! transparent)
  201956. {
  201957. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  201958. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  201959. DeleteObject (clipRgn);
  201960. char rgnData [8192];
  201961. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  201962. if (res > 0 && res <= sizeof (rgnData))
  201963. {
  201964. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  201965. if (hdr->iType == RDH_RECTANGLES
  201966. && hdr->rcBound.right - hdr->rcBound.left >= w
  201967. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  201968. {
  201969. needToPaintAll = false;
  201970. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  201971. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  201972. while (--num >= 0)
  201973. {
  201974. // (need to move this one pixel to the left because of a win32 bug)
  201975. const int cx = jmax (x, rects->left - 1);
  201976. const int cy = rects->top;
  201977. const int cw = rects->right - cx;
  201978. const int ch = rects->bottom - rects->top;
  201979. if (cx + cw - x <= w && cy + ch - y <= h)
  201980. {
  201981. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  201982. }
  201983. else
  201984. {
  201985. needToPaintAll = true;
  201986. break;
  201987. }
  201988. ++rects;
  201989. }
  201990. }
  201991. }
  201992. }
  201993. if (needToPaintAll)
  201994. {
  201995. contextClip->clear();
  201996. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  201997. }
  201998. if (transparent)
  201999. {
  202000. RectangleList::Iterator i (*contextClip);
  202001. while (i.next())
  202002. {
  202003. const Rectangle& r = *i.getRectangle();
  202004. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  202005. }
  202006. }
  202007. // if the component's not opaque, this won't draw properly unless the platform can support this
  202008. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  202009. updateCurrentModifiers();
  202010. handlePaint (context);
  202011. if (! dontRepaint)
  202012. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  202013. }
  202014. DeleteObject (rgn);
  202015. EndPaint (hwnd, &paintStruct);
  202016. reentrant = false;
  202017. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  202018. _fpreset(); // because some graphics cards can unmask FP exceptions
  202019. #endif
  202020. lastPaintTime = Time::getMillisecondCounter();
  202021. #if DEBUG_REPAINT_TIMES
  202022. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  202023. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  202024. #endif
  202025. }
  202026. void doMouseMove (const int x, const int y)
  202027. {
  202028. static uint32 lastMouseTime = 0;
  202029. // this can be set to throttle the mouse-messages to less than a
  202030. // certain number per second, as things can get unresponsive
  202031. // if each drag or move callback has to do a lot of work.
  202032. const int maxMouseMovesPerSecond = 60;
  202033. const int64 mouseEventTime = getMouseEventTime();
  202034. if (! isMouseOver)
  202035. {
  202036. isMouseOver = true;
  202037. TRACKMOUSEEVENT tme;
  202038. tme.cbSize = sizeof (tme);
  202039. tme.dwFlags = TME_LEAVE;
  202040. tme.hwndTrack = hwnd;
  202041. tme.dwHoverTime = 0;
  202042. if (! TrackMouseEvent (&tme))
  202043. {
  202044. jassertfalse;
  202045. }
  202046. updateKeyModifiers();
  202047. handleMouseEnter (x, y, mouseEventTime);
  202048. }
  202049. else if (! isDragging)
  202050. {
  202051. if (((unsigned int) x) < (unsigned int) component->getWidth()
  202052. && ((unsigned int) y) < (unsigned int) component->getHeight())
  202053. {
  202054. RECT r;
  202055. GetWindowRect (hwnd, &r);
  202056. POINT p;
  202057. p.x = x + r.left + windowBorder.getLeft();
  202058. p.y = y + r.top + windowBorder.getTop();
  202059. if (WindowFromPoint (p) == hwnd)
  202060. {
  202061. const uint32 now = Time::getMillisecondCounter();
  202062. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  202063. {
  202064. lastMouseTime = now;
  202065. handleMouseMove (x, y, mouseEventTime);
  202066. }
  202067. }
  202068. }
  202069. }
  202070. else
  202071. {
  202072. const uint32 now = Time::getMillisecondCounter();
  202073. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  202074. {
  202075. lastMouseTime = now;
  202076. handleMouseDrag (x, y, mouseEventTime);
  202077. }
  202078. }
  202079. }
  202080. void doMouseDown (const int x, const int y, const WPARAM wParam)
  202081. {
  202082. if (GetCapture() != hwnd)
  202083. SetCapture (hwnd);
  202084. doMouseMove (x, y);
  202085. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  202086. if ((wParam & MK_LBUTTON) != 0)
  202087. currentModifiers |= ModifierKeys::leftButtonModifier;
  202088. if ((wParam & MK_RBUTTON) != 0)
  202089. currentModifiers |= ModifierKeys::rightButtonModifier;
  202090. if ((wParam & MK_MBUTTON) != 0)
  202091. currentModifiers |= ModifierKeys::middleButtonModifier;
  202092. updateKeyModifiers();
  202093. isDragging = true;
  202094. handleMouseDown (x, y, getMouseEventTime());
  202095. }
  202096. void doMouseUp (const int x, const int y, const WPARAM wParam)
  202097. {
  202098. int numButtons = 0;
  202099. if ((wParam & MK_LBUTTON) != 0)
  202100. ++numButtons;
  202101. if ((wParam & MK_RBUTTON) != 0)
  202102. ++numButtons;
  202103. if ((wParam & MK_MBUTTON) != 0)
  202104. ++numButtons;
  202105. const int oldModifiers = currentModifiers;
  202106. // update the currentmodifiers only after the callback, so the callback
  202107. // knows which button was released.
  202108. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  202109. if ((wParam & MK_LBUTTON) != 0)
  202110. currentModifiers |= ModifierKeys::leftButtonModifier;
  202111. if ((wParam & MK_RBUTTON) != 0)
  202112. currentModifiers |= ModifierKeys::rightButtonModifier;
  202113. if ((wParam & MK_MBUTTON) != 0)
  202114. currentModifiers |= ModifierKeys::middleButtonModifier;
  202115. updateKeyModifiers();
  202116. isDragging = false;
  202117. // release the mouse capture if the user's not still got a button down
  202118. if (numButtons == 0 && hwnd == GetCapture())
  202119. ReleaseCapture();
  202120. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  202121. }
  202122. void doCaptureChanged()
  202123. {
  202124. if (isDragging)
  202125. {
  202126. RECT wr;
  202127. GetWindowRect (hwnd, &wr);
  202128. const DWORD mp = GetMessagePos();
  202129. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202130. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202131. (WPARAM) getMouseEventTime());
  202132. }
  202133. }
  202134. void doMouseExit()
  202135. {
  202136. if (isMouseOver)
  202137. {
  202138. isMouseOver = false;
  202139. RECT wr;
  202140. GetWindowRect (hwnd, &wr);
  202141. const DWORD mp = GetMessagePos();
  202142. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202143. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202144. getMouseEventTime());
  202145. }
  202146. }
  202147. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  202148. {
  202149. updateKeyModifiers();
  202150. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  202151. handleMouseWheel (isVertical ? 0 : amount,
  202152. isVertical ? amount : 0,
  202153. getMouseEventTime());
  202154. }
  202155. void sendModifierKeyChangeIfNeeded()
  202156. {
  202157. if (modifiersAtLastCallback != currentModifiers)
  202158. {
  202159. modifiersAtLastCallback = currentModifiers;
  202160. handleModifierKeysChange();
  202161. }
  202162. }
  202163. bool doKeyUp (const WPARAM key)
  202164. {
  202165. updateKeyModifiers();
  202166. switch (key)
  202167. {
  202168. case VK_SHIFT:
  202169. case VK_CONTROL:
  202170. case VK_MENU:
  202171. case VK_CAPITAL:
  202172. case VK_LWIN:
  202173. case VK_RWIN:
  202174. case VK_APPS:
  202175. case VK_NUMLOCK:
  202176. case VK_SCROLL:
  202177. case VK_LSHIFT:
  202178. case VK_RSHIFT:
  202179. case VK_LCONTROL:
  202180. case VK_LMENU:
  202181. case VK_RCONTROL:
  202182. case VK_RMENU:
  202183. sendModifierKeyChangeIfNeeded();
  202184. }
  202185. return handleKeyUpOrDown (false)
  202186. || Component::getCurrentlyModalComponent() != 0;
  202187. }
  202188. bool doKeyDown (const WPARAM key)
  202189. {
  202190. updateKeyModifiers();
  202191. bool used = false;
  202192. switch (key)
  202193. {
  202194. case VK_SHIFT:
  202195. case VK_LSHIFT:
  202196. case VK_RSHIFT:
  202197. case VK_CONTROL:
  202198. case VK_LCONTROL:
  202199. case VK_RCONTROL:
  202200. case VK_MENU:
  202201. case VK_LMENU:
  202202. case VK_RMENU:
  202203. case VK_LWIN:
  202204. case VK_RWIN:
  202205. case VK_CAPITAL:
  202206. case VK_NUMLOCK:
  202207. case VK_SCROLL:
  202208. case VK_APPS:
  202209. sendModifierKeyChangeIfNeeded();
  202210. break;
  202211. case VK_LEFT:
  202212. case VK_RIGHT:
  202213. case VK_UP:
  202214. case VK_DOWN:
  202215. case VK_PRIOR:
  202216. case VK_NEXT:
  202217. case VK_HOME:
  202218. case VK_END:
  202219. case VK_DELETE:
  202220. case VK_INSERT:
  202221. case VK_F1:
  202222. case VK_F2:
  202223. case VK_F3:
  202224. case VK_F4:
  202225. case VK_F5:
  202226. case VK_F6:
  202227. case VK_F7:
  202228. case VK_F8:
  202229. case VK_F9:
  202230. case VK_F10:
  202231. case VK_F11:
  202232. case VK_F12:
  202233. case VK_F13:
  202234. case VK_F14:
  202235. case VK_F15:
  202236. case VK_F16:
  202237. used = handleKeyUpOrDown (true);
  202238. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  202239. break;
  202240. case VK_ADD:
  202241. case VK_SUBTRACT:
  202242. case VK_MULTIPLY:
  202243. case VK_DIVIDE:
  202244. case VK_SEPARATOR:
  202245. case VK_DECIMAL:
  202246. used = handleKeyUpOrDown (true);
  202247. break;
  202248. default:
  202249. used = handleKeyUpOrDown (true);
  202250. {
  202251. MSG msg;
  202252. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  202253. {
  202254. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  202255. // manually generate the key-press event that matches this key-down.
  202256. const UINT keyChar = MapVirtualKey (key, 2);
  202257. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  202258. }
  202259. }
  202260. break;
  202261. }
  202262. if (Component::getCurrentlyModalComponent() != 0)
  202263. used = true;
  202264. return used;
  202265. }
  202266. bool doKeyChar (int key, const LPARAM flags)
  202267. {
  202268. updateKeyModifiers();
  202269. juce_wchar textChar = (juce_wchar) key;
  202270. const int virtualScanCode = (flags >> 16) & 0xff;
  202271. if (key >= '0' && key <= '9')
  202272. {
  202273. switch (virtualScanCode) // check for a numeric keypad scan-code
  202274. {
  202275. case 0x52:
  202276. case 0x4f:
  202277. case 0x50:
  202278. case 0x51:
  202279. case 0x4b:
  202280. case 0x4c:
  202281. case 0x4d:
  202282. case 0x47:
  202283. case 0x48:
  202284. case 0x49:
  202285. key = (key - '0') + KeyPress::numberPad0;
  202286. break;
  202287. default:
  202288. break;
  202289. }
  202290. }
  202291. else
  202292. {
  202293. // convert the scan code to an unmodified character code..
  202294. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  202295. UINT keyChar = MapVirtualKey (virtualKey, 2);
  202296. keyChar = LOWORD (keyChar);
  202297. if (keyChar != 0)
  202298. key = (int) keyChar;
  202299. // avoid sending junk text characters for some control-key combinations
  202300. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  202301. textChar = 0;
  202302. }
  202303. return handleKeyPress (key, textChar);
  202304. }
  202305. bool doAppCommand (const LPARAM lParam)
  202306. {
  202307. int key = 0;
  202308. switch (GET_APPCOMMAND_LPARAM (lParam))
  202309. {
  202310. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  202311. key = KeyPress::playKey;
  202312. break;
  202313. case APPCOMMAND_MEDIA_STOP:
  202314. key = KeyPress::stopKey;
  202315. break;
  202316. case APPCOMMAND_MEDIA_NEXTTRACK:
  202317. key = KeyPress::fastForwardKey;
  202318. break;
  202319. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  202320. key = KeyPress::rewindKey;
  202321. break;
  202322. }
  202323. if (key != 0)
  202324. {
  202325. updateKeyModifiers();
  202326. if (hwnd == GetActiveWindow())
  202327. {
  202328. handleKeyPress (key, 0);
  202329. return true;
  202330. }
  202331. }
  202332. return false;
  202333. }
  202334. class JuceDropTarget : public IDropTarget
  202335. {
  202336. public:
  202337. JuceDropTarget (Win32ComponentPeer* const owner_)
  202338. : owner (owner_),
  202339. refCount (1)
  202340. {
  202341. }
  202342. virtual ~JuceDropTarget()
  202343. {
  202344. jassert (refCount == 0);
  202345. }
  202346. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202347. {
  202348. if (id == IID_IUnknown || id == IID_IDropTarget)
  202349. {
  202350. AddRef();
  202351. *result = this;
  202352. return S_OK;
  202353. }
  202354. *result = 0;
  202355. return E_NOINTERFACE;
  202356. }
  202357. ULONG __stdcall AddRef() { return ++refCount; }
  202358. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202359. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202360. {
  202361. updateFileList (pDataObject);
  202362. int x = mousePos.x, y = mousePos.y;
  202363. owner->globalPositionToRelative (x, y);
  202364. owner->handleFileDragMove (files, x, y);
  202365. *pdwEffect = DROPEFFECT_COPY;
  202366. return S_OK;
  202367. }
  202368. HRESULT __stdcall DragLeave()
  202369. {
  202370. owner->handleFileDragExit (files);
  202371. return S_OK;
  202372. }
  202373. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202374. {
  202375. int x = mousePos.x, y = mousePos.y;
  202376. owner->globalPositionToRelative (x, y);
  202377. owner->handleFileDragMove (files, x, y);
  202378. *pdwEffect = DROPEFFECT_COPY;
  202379. return S_OK;
  202380. }
  202381. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202382. {
  202383. updateFileList (pDataObject);
  202384. int x = mousePos.x, y = mousePos.y;
  202385. owner->globalPositionToRelative (x, y);
  202386. owner->handleFileDragDrop (files, x, y);
  202387. *pdwEffect = DROPEFFECT_COPY;
  202388. return S_OK;
  202389. }
  202390. private:
  202391. Win32ComponentPeer* const owner;
  202392. int refCount;
  202393. StringArray files;
  202394. void updateFileList (IDataObject* const pDataObject)
  202395. {
  202396. files.clear();
  202397. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202398. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202399. if (pDataObject->GetData (&format, &medium) == S_OK)
  202400. {
  202401. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  202402. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  202403. unsigned int i = 0;
  202404. if (pDropFiles->fWide)
  202405. {
  202406. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  202407. for (;;)
  202408. {
  202409. unsigned int len = 0;
  202410. while (i + len < totalLen && fname [i + len] != 0)
  202411. ++len;
  202412. if (len == 0)
  202413. break;
  202414. files.add (String (fname + i, len));
  202415. i += len + 1;
  202416. }
  202417. }
  202418. else
  202419. {
  202420. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  202421. for (;;)
  202422. {
  202423. unsigned int len = 0;
  202424. while (i + len < totalLen && fname [i + len] != 0)
  202425. ++len;
  202426. if (len == 0)
  202427. break;
  202428. files.add (String (fname + i, len));
  202429. i += len + 1;
  202430. }
  202431. }
  202432. GlobalUnlock (medium.hGlobal);
  202433. }
  202434. }
  202435. JuceDropTarget (const JuceDropTarget&);
  202436. const JuceDropTarget& operator= (const JuceDropTarget&);
  202437. };
  202438. void doSettingChange()
  202439. {
  202440. Desktop::getInstance().refreshMonitorSizes();
  202441. if (fullScreen && ! isMinimised())
  202442. {
  202443. const Rectangle r (component->getParentMonitorArea());
  202444. SetWindowPos (hwnd, 0,
  202445. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  202446. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  202447. }
  202448. }
  202449. public:
  202450. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202451. {
  202452. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  202453. if (peer != 0)
  202454. return peer->peerWindowProc (h, message, wParam, lParam);
  202455. return DefWindowProc (h, message, wParam, lParam);
  202456. }
  202457. private:
  202458. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202459. {
  202460. {
  202461. if (isValidPeer (this))
  202462. {
  202463. switch (message)
  202464. {
  202465. case WM_NCHITTEST:
  202466. if (hasTitleBar())
  202467. break;
  202468. return HTCLIENT;
  202469. case WM_PAINT:
  202470. handlePaintMessage();
  202471. return 0;
  202472. case WM_NCPAINT:
  202473. if (wParam != 1)
  202474. handlePaintMessage();
  202475. if (hasTitleBar())
  202476. break;
  202477. return 0;
  202478. case WM_ERASEBKGND:
  202479. case WM_NCCALCSIZE:
  202480. if (hasTitleBar())
  202481. break;
  202482. return 1;
  202483. case WM_MOUSEMOVE:
  202484. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  202485. return 0;
  202486. case WM_MOUSELEAVE:
  202487. doMouseExit();
  202488. return 0;
  202489. case WM_LBUTTONDOWN:
  202490. case WM_MBUTTONDOWN:
  202491. case WM_RBUTTONDOWN:
  202492. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202493. return 0;
  202494. case WM_LBUTTONUP:
  202495. case WM_MBUTTONUP:
  202496. case WM_RBUTTONUP:
  202497. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202498. return 0;
  202499. case WM_CAPTURECHANGED:
  202500. doCaptureChanged();
  202501. return 0;
  202502. case WM_NCMOUSEMOVE:
  202503. if (hasTitleBar())
  202504. break;
  202505. return 0;
  202506. case 0x020A: /* WM_MOUSEWHEEL */
  202507. doMouseWheel (wParam, true);
  202508. return 0;
  202509. case 0x020E: /* WM_MOUSEHWHEEL */
  202510. doMouseWheel (wParam, false);
  202511. return 0;
  202512. case WM_WINDOWPOSCHANGING:
  202513. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  202514. {
  202515. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  202516. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  202517. {
  202518. if (constrainer != 0)
  202519. {
  202520. const Rectangle current (component->getX() - windowBorder.getLeft(),
  202521. component->getY() - windowBorder.getTop(),
  202522. component->getWidth() + windowBorder.getLeftAndRight(),
  202523. component->getHeight() + windowBorder.getTopAndBottom());
  202524. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  202525. current,
  202526. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  202527. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  202528. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  202529. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  202530. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  202531. }
  202532. }
  202533. }
  202534. return 0;
  202535. case WM_WINDOWPOSCHANGED:
  202536. handleMovedOrResized();
  202537. if (dontRepaint)
  202538. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  202539. else
  202540. return 0;
  202541. case WM_KEYDOWN:
  202542. case WM_SYSKEYDOWN:
  202543. if (doKeyDown (wParam))
  202544. return 0;
  202545. break;
  202546. case WM_KEYUP:
  202547. case WM_SYSKEYUP:
  202548. if (doKeyUp (wParam))
  202549. return 0;
  202550. break;
  202551. case WM_CHAR:
  202552. if (doKeyChar ((int) wParam, lParam))
  202553. return 0;
  202554. break;
  202555. case WM_APPCOMMAND:
  202556. if (doAppCommand (lParam))
  202557. return TRUE;
  202558. break;
  202559. case WM_SETFOCUS:
  202560. updateKeyModifiers();
  202561. handleFocusGain();
  202562. break;
  202563. case WM_KILLFOCUS:
  202564. if (hasCreatedCaret)
  202565. {
  202566. hasCreatedCaret = false;
  202567. DestroyCaret();
  202568. }
  202569. handleFocusLoss();
  202570. break;
  202571. case WM_ACTIVATEAPP:
  202572. // Windows does weird things to process priority when you swap apps,
  202573. // so this forces an update when the app is brought to the front
  202574. if (wParam != FALSE)
  202575. juce_repeatLastProcessPriority();
  202576. else
  202577. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  202578. juce_CheckCurrentlyFocusedTopLevelWindow();
  202579. modifiersAtLastCallback = -1;
  202580. return 0;
  202581. case WM_ACTIVATE:
  202582. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  202583. {
  202584. modifiersAtLastCallback = -1;
  202585. updateKeyModifiers();
  202586. if (isMinimised())
  202587. {
  202588. component->repaint();
  202589. handleMovedOrResized();
  202590. if (! isValidMessageListener())
  202591. return 0;
  202592. }
  202593. if (LOWORD (wParam) == WA_CLICKACTIVE
  202594. && component->isCurrentlyBlockedByAnotherModalComponent())
  202595. {
  202596. int mx, my;
  202597. component->getMouseXYRelative (mx, my);
  202598. Component* const underMouse = component->getComponentAt (mx, my);
  202599. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  202600. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  202601. return 0;
  202602. }
  202603. handleBroughtToFront();
  202604. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202605. Component::getCurrentlyModalComponent()->toFront (true);
  202606. return 0;
  202607. }
  202608. break;
  202609. case WM_NCACTIVATE:
  202610. // while a temporary window is being shown, prevent Windows from deactivating the
  202611. // title bars of our main windows.
  202612. if (wParam == 0 && ! shouldDeactivateTitleBar)
  202613. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  202614. break;
  202615. case WM_MOUSEACTIVATE:
  202616. if (! component->getMouseClickGrabsKeyboardFocus())
  202617. return MA_NOACTIVATE;
  202618. break;
  202619. case WM_SHOWWINDOW:
  202620. if (wParam != 0)
  202621. handleBroughtToFront();
  202622. break;
  202623. case WM_CLOSE:
  202624. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  202625. handleUserClosingWindow();
  202626. return 0;
  202627. case WM_QUIT:
  202628. if (JUCEApplication::getInstance() != 0)
  202629. JUCEApplication::getInstance()->systemRequestedQuit();
  202630. return 0;
  202631. case WM_QUERYENDSESSION:
  202632. if (JUCEApplication::getInstance() != 0)
  202633. {
  202634. JUCEApplication::getInstance()->systemRequestedQuit();
  202635. return MessageManager::getInstance()->hasStopMessageBeenSent();
  202636. }
  202637. return TRUE;
  202638. case WM_TRAYNOTIFY:
  202639. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202640. {
  202641. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  202642. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202643. {
  202644. Component* const current = Component::getCurrentlyModalComponent();
  202645. if (current != 0)
  202646. current->inputAttemptWhenModal();
  202647. }
  202648. }
  202649. else
  202650. {
  202651. const int oldModifiers = currentModifiers;
  202652. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  202653. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  202654. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  202655. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  202656. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  202657. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  202658. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  202659. {
  202660. SetFocus (hwnd);
  202661. SetForegroundWindow (hwnd);
  202662. component->mouseDown (e);
  202663. }
  202664. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  202665. {
  202666. e.mods = ModifierKeys (oldModifiers);
  202667. component->mouseUp (e);
  202668. }
  202669. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202670. {
  202671. e.mods = ModifierKeys (oldModifiers);
  202672. component->mouseDoubleClick (e);
  202673. }
  202674. else if (lParam == WM_MOUSEMOVE)
  202675. {
  202676. component->mouseMove (e);
  202677. }
  202678. }
  202679. break;
  202680. case WM_SYNCPAINT:
  202681. return 0;
  202682. case WM_PALETTECHANGED:
  202683. InvalidateRect (h, 0, 0);
  202684. break;
  202685. case WM_DISPLAYCHANGE:
  202686. InvalidateRect (h, 0, 0);
  202687. createPaletteIfNeeded = true;
  202688. // intentional fall-through...
  202689. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  202690. doSettingChange();
  202691. break;
  202692. case WM_INITMENU:
  202693. if (! hasTitleBar())
  202694. {
  202695. if (isFullScreen())
  202696. {
  202697. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  202698. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  202699. }
  202700. else if (! isMinimised())
  202701. {
  202702. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  202703. }
  202704. }
  202705. break;
  202706. case WM_SYSCOMMAND:
  202707. switch (wParam & 0xfff0)
  202708. {
  202709. case SC_CLOSE:
  202710. if (sendInputAttemptWhenModalMessage())
  202711. return 0;
  202712. if (hasTitleBar())
  202713. {
  202714. PostMessage (h, WM_CLOSE, 0, 0);
  202715. return 0;
  202716. }
  202717. break;
  202718. case SC_KEYMENU:
  202719. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  202720. // obscure situations that can arise if a modal loop is started from an alt-key
  202721. // keypress).
  202722. if (hasTitleBar() && h == GetCapture())
  202723. ReleaseCapture();
  202724. break;
  202725. case SC_MAXIMIZE:
  202726. if (sendInputAttemptWhenModalMessage())
  202727. return 0;
  202728. setFullScreen (true);
  202729. return 0;
  202730. case SC_MINIMIZE:
  202731. if (sendInputAttemptWhenModalMessage())
  202732. return 0;
  202733. if (! hasTitleBar())
  202734. {
  202735. setMinimised (true);
  202736. return 0;
  202737. }
  202738. break;
  202739. case SC_RESTORE:
  202740. if (sendInputAttemptWhenModalMessage())
  202741. return 0;
  202742. if (hasTitleBar())
  202743. {
  202744. if (isFullScreen())
  202745. {
  202746. setFullScreen (false);
  202747. return 0;
  202748. }
  202749. }
  202750. else
  202751. {
  202752. if (isMinimised())
  202753. setMinimised (false);
  202754. else if (isFullScreen())
  202755. setFullScreen (false);
  202756. return 0;
  202757. }
  202758. break;
  202759. }
  202760. break;
  202761. case WM_NCLBUTTONDOWN:
  202762. case WM_NCRBUTTONDOWN:
  202763. case WM_NCMBUTTONDOWN:
  202764. sendInputAttemptWhenModalMessage();
  202765. break;
  202766. //case WM_IME_STARTCOMPOSITION;
  202767. // return 0;
  202768. case WM_GETDLGCODE:
  202769. return DLGC_WANTALLKEYS;
  202770. default:
  202771. break;
  202772. }
  202773. }
  202774. }
  202775. // (the message manager lock exits before calling this, to avoid deadlocks if
  202776. // this calls into non-juce windows)
  202777. return DefWindowProc (h, message, wParam, lParam);
  202778. }
  202779. bool sendInputAttemptWhenModalMessage()
  202780. {
  202781. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202782. {
  202783. Component* const current = Component::getCurrentlyModalComponent();
  202784. if (current != 0)
  202785. current->inputAttemptWhenModal();
  202786. return true;
  202787. }
  202788. return false;
  202789. }
  202790. Win32ComponentPeer (const Win32ComponentPeer&);
  202791. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  202792. };
  202793. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  202794. {
  202795. return new Win32ComponentPeer (this, styleFlags);
  202796. }
  202797. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  202798. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  202799. {
  202800. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202801. if (wp != 0)
  202802. wp->setTaskBarIcon (&newImage);
  202803. }
  202804. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  202805. {
  202806. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202807. if (wp != 0)
  202808. wp->setTaskBarIconToolTip (tooltip);
  202809. }
  202810. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  202811. {
  202812. DWORD val = GetWindowLong (h, styleType);
  202813. if (bitIsSet)
  202814. val |= feature;
  202815. else
  202816. val &= ~feature;
  202817. SetWindowLongPtr (h, styleType, val);
  202818. SetWindowPos (h, 0, 0, 0, 0, 0,
  202819. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  202820. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  202821. }
  202822. bool Process::isForegroundProcess() throw()
  202823. {
  202824. HWND fg = GetForegroundWindow();
  202825. if (fg == 0)
  202826. return true;
  202827. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  202828. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  202829. // have to see if any of our windows are children of the foreground window
  202830. fg = GetAncestor (fg, GA_ROOT);
  202831. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  202832. {
  202833. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  202834. if (wp != 0 && wp->isInside (fg))
  202835. return true;
  202836. }
  202837. return false;
  202838. }
  202839. bool AlertWindow::showNativeDialogBox (const String& title,
  202840. const String& bodyText,
  202841. bool isOkCancel)
  202842. {
  202843. return MessageBox (0, bodyText, title,
  202844. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  202845. : MB_OK)) == IDOK;
  202846. }
  202847. void Desktop::getMousePosition (int& x, int& y) throw()
  202848. {
  202849. POINT mousePos;
  202850. GetCursorPos (&mousePos);
  202851. x = mousePos.x;
  202852. y = mousePos.y;
  202853. }
  202854. void Desktop::setMousePosition (int x, int y) throw()
  202855. {
  202856. SetCursorPos (x, y);
  202857. }
  202858. class ScreenSaverDefeater : public Timer,
  202859. public DeletedAtShutdown
  202860. {
  202861. public:
  202862. ScreenSaverDefeater() throw()
  202863. {
  202864. startTimer (10000);
  202865. timerCallback();
  202866. }
  202867. ~ScreenSaverDefeater() {}
  202868. void timerCallback()
  202869. {
  202870. if (Process::isForegroundProcess())
  202871. {
  202872. // simulate a shift key getting pressed..
  202873. INPUT input[2];
  202874. input[0].type = INPUT_KEYBOARD;
  202875. input[0].ki.wVk = VK_SHIFT;
  202876. input[0].ki.dwFlags = 0;
  202877. input[0].ki.dwExtraInfo = 0;
  202878. input[1].type = INPUT_KEYBOARD;
  202879. input[1].ki.wVk = VK_SHIFT;
  202880. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  202881. input[1].ki.dwExtraInfo = 0;
  202882. SendInput (2, input, sizeof (INPUT));
  202883. }
  202884. }
  202885. };
  202886. static ScreenSaverDefeater* screenSaverDefeater = 0;
  202887. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202888. {
  202889. if (isEnabled)
  202890. {
  202891. deleteAndZero (screenSaverDefeater);
  202892. }
  202893. else if (screenSaverDefeater == 0)
  202894. {
  202895. screenSaverDefeater = new ScreenSaverDefeater();
  202896. }
  202897. }
  202898. bool Desktop::isScreenSaverEnabled() throw()
  202899. {
  202900. return screenSaverDefeater == 0;
  202901. }
  202902. /* (The code below is the "correct" way to disable the screen saver, but it
  202903. completely fails on winXP when the saver is password-protected...)
  202904. static bool juce_screenSaverEnabled = true;
  202905. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202906. {
  202907. juce_screenSaverEnabled = isEnabled;
  202908. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  202909. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  202910. }
  202911. bool Desktop::isScreenSaverEnabled() throw()
  202912. {
  202913. return juce_screenSaverEnabled;
  202914. }
  202915. */
  202916. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  202917. {
  202918. if (enableOrDisable)
  202919. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  202920. }
  202921. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  202922. {
  202923. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  202924. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  202925. return TRUE;
  202926. }
  202927. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  202928. {
  202929. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  202930. // make sure the first in the list is the main monitor
  202931. for (int i = 1; i < monitorCoords.size(); ++i)
  202932. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  202933. monitorCoords.swap (i, 0);
  202934. if (monitorCoords.size() == 0)
  202935. {
  202936. RECT r;
  202937. GetWindowRect (GetDesktopWindow(), &r);
  202938. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  202939. }
  202940. if (clipToWorkArea)
  202941. {
  202942. // clip the main monitor to the active non-taskbar area
  202943. RECT r;
  202944. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  202945. Rectangle& screen = monitorCoords.getReference (0);
  202946. screen.setPosition (jmax (screen.getX(), r.left),
  202947. jmax (screen.getY(), r.top));
  202948. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  202949. jmin (screen.getBottom(), r.bottom) - screen.getY());
  202950. }
  202951. }
  202952. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  202953. {
  202954. Image* im = 0;
  202955. if (bitmap != 0)
  202956. {
  202957. BITMAP bm;
  202958. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  202959. && bm.bmWidth > 0 && bm.bmHeight > 0)
  202960. {
  202961. HDC tempDC = GetDC (0);
  202962. HDC dc = CreateCompatibleDC (tempDC);
  202963. ReleaseDC (0, tempDC);
  202964. SelectObject (dc, bitmap);
  202965. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  202966. for (int y = bm.bmHeight; --y >= 0;)
  202967. {
  202968. for (int x = bm.bmWidth; --x >= 0;)
  202969. {
  202970. COLORREF col = GetPixel (dc, x, y);
  202971. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  202972. (uint8) GetGValue (col),
  202973. (uint8) GetBValue (col)));
  202974. }
  202975. }
  202976. DeleteDC (dc);
  202977. }
  202978. }
  202979. return im;
  202980. }
  202981. static Image* createImageFromHICON (HICON icon) throw()
  202982. {
  202983. ICONINFO info;
  202984. if (GetIconInfo (icon, &info))
  202985. {
  202986. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  202987. if (mask == 0)
  202988. return 0;
  202989. Image* const image = createImageFromHBITMAP (info.hbmColor);
  202990. if (image == 0)
  202991. return mask;
  202992. for (int y = image->getHeight(); --y >= 0;)
  202993. {
  202994. for (int x = image->getWidth(); --x >= 0;)
  202995. {
  202996. const float brightness = mask->getPixelAt (x, y).getBrightness();
  202997. if (brightness > 0.0f)
  202998. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  202999. }
  203000. }
  203001. delete mask;
  203002. return image;
  203003. }
  203004. return 0;
  203005. }
  203006. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  203007. {
  203008. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  203009. ICONINFO info;
  203010. info.fIcon = isIcon;
  203011. info.xHotspot = hotspotX;
  203012. info.yHotspot = hotspotY;
  203013. info.hbmMask = mask;
  203014. HICON hi = 0;
  203015. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  203016. {
  203017. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  203018. Graphics g (bitmap);
  203019. g.drawImageAt (&image, 0, 0);
  203020. info.hbmColor = bitmap.hBitmap;
  203021. hi = CreateIconIndirect (&info);
  203022. }
  203023. else
  203024. {
  203025. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  203026. HDC colDC = CreateCompatibleDC (GetDC (0));
  203027. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  203028. SelectObject (colDC, colour);
  203029. SelectObject (alphaDC, mask);
  203030. for (int y = image.getHeight(); --y >= 0;)
  203031. {
  203032. for (int x = image.getWidth(); --x >= 0;)
  203033. {
  203034. const Colour c (image.getPixelAt (x, y));
  203035. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  203036. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  203037. }
  203038. }
  203039. DeleteDC (colDC);
  203040. DeleteDC (alphaDC);
  203041. info.hbmColor = colour;
  203042. hi = CreateIconIndirect (&info);
  203043. DeleteObject (colour);
  203044. }
  203045. DeleteObject (mask);
  203046. return hi;
  203047. }
  203048. Image* juce_createIconForFile (const File& file)
  203049. {
  203050. Image* image = 0;
  203051. TCHAR filename [1024];
  203052. file.getFullPathName().copyToBuffer (filename, 1023);
  203053. WORD iconNum = 0;
  203054. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  203055. filename, &iconNum);
  203056. if (icon != 0)
  203057. {
  203058. image = createImageFromHICON (icon);
  203059. DestroyIcon (icon);
  203060. }
  203061. return image;
  203062. }
  203063. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  203064. {
  203065. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  203066. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  203067. const Image* im = &image;
  203068. Image* newIm = 0;
  203069. if (image.getWidth() > maxW || image.getHeight() > maxH)
  203070. {
  203071. im = newIm = image.createCopy (maxW, maxH);
  203072. hotspotX = (hotspotX * maxW) / image.getWidth();
  203073. hotspotY = (hotspotY * maxH) / image.getHeight();
  203074. }
  203075. void* cursorH = 0;
  203076. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  203077. if (os == SystemStats::WinXP)
  203078. {
  203079. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  203080. }
  203081. else
  203082. {
  203083. const int stride = (maxW + 7) >> 3;
  203084. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  203085. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  203086. int index = 0;
  203087. for (int y = 0; y < maxH; ++y)
  203088. {
  203089. for (int x = 0; x < maxW; ++x)
  203090. {
  203091. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  203092. const Colour pixelColour (im->getPixelAt (x, y));
  203093. if (pixelColour.getAlpha() < 127)
  203094. andPlane [index + (x >> 3)] |= bit;
  203095. else if (pixelColour.getBrightness() >= 0.5f)
  203096. xorPlane [index + (x >> 3)] |= bit;
  203097. }
  203098. index += stride;
  203099. }
  203100. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  203101. juce_free (andPlane);
  203102. juce_free (xorPlane);
  203103. }
  203104. delete newIm;
  203105. return cursorH;
  203106. }
  203107. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  203108. {
  203109. if (cursorHandle != 0 && ! isStandard)
  203110. DestroyCursor ((HCURSOR) cursorHandle);
  203111. }
  203112. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  203113. {
  203114. LPCTSTR cursorName = IDC_ARROW;
  203115. switch (type)
  203116. {
  203117. case MouseCursor::NormalCursor:
  203118. cursorName = IDC_ARROW;
  203119. break;
  203120. case MouseCursor::NoCursor:
  203121. return 0;
  203122. case MouseCursor::DraggingHandCursor:
  203123. {
  203124. static void* dragHandCursor = 0;
  203125. if (dragHandCursor == 0)
  203126. {
  203127. static const unsigned char dragHandData[] =
  203128. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  203129. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39, 132,117,151,116,132,146,248,60,209,138,
  203130. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  203131. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  203132. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  203133. delete image;
  203134. }
  203135. return dragHandCursor;
  203136. }
  203137. case MouseCursor::WaitCursor:
  203138. cursorName = IDC_WAIT;
  203139. break;
  203140. case MouseCursor::IBeamCursor:
  203141. cursorName = IDC_IBEAM;
  203142. break;
  203143. case MouseCursor::PointingHandCursor:
  203144. cursorName = MAKEINTRESOURCE(32649);
  203145. break;
  203146. case MouseCursor::LeftRightResizeCursor:
  203147. case MouseCursor::LeftEdgeResizeCursor:
  203148. case MouseCursor::RightEdgeResizeCursor:
  203149. cursorName = IDC_SIZEWE;
  203150. break;
  203151. case MouseCursor::UpDownResizeCursor:
  203152. case MouseCursor::TopEdgeResizeCursor:
  203153. case MouseCursor::BottomEdgeResizeCursor:
  203154. cursorName = IDC_SIZENS;
  203155. break;
  203156. case MouseCursor::TopLeftCornerResizeCursor:
  203157. case MouseCursor::BottomRightCornerResizeCursor:
  203158. cursorName = IDC_SIZENWSE;
  203159. break;
  203160. case MouseCursor::TopRightCornerResizeCursor:
  203161. case MouseCursor::BottomLeftCornerResizeCursor:
  203162. cursorName = IDC_SIZENESW;
  203163. break;
  203164. case MouseCursor::UpDownLeftRightResizeCursor:
  203165. cursorName = IDC_SIZEALL;
  203166. break;
  203167. case MouseCursor::CrosshairCursor:
  203168. cursorName = IDC_CROSS;
  203169. break;
  203170. case MouseCursor::CopyingCursor:
  203171. // can't seem to find one of these in the win32 list..
  203172. break;
  203173. }
  203174. HCURSOR cursorH = LoadCursor (0, cursorName);
  203175. if (cursorH == 0)
  203176. cursorH = LoadCursor (0, IDC_ARROW);
  203177. return (void*) cursorH;
  203178. }
  203179. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  203180. {
  203181. SetCursor ((HCURSOR) getHandle());
  203182. }
  203183. void MouseCursor::showInAllWindows() const throw()
  203184. {
  203185. showInWindow (0);
  203186. }
  203187. class JuceDropSource : public IDropSource
  203188. {
  203189. int refCount;
  203190. public:
  203191. JuceDropSource()
  203192. : refCount (1)
  203193. {
  203194. }
  203195. virtual ~JuceDropSource()
  203196. {
  203197. jassert (refCount == 0);
  203198. }
  203199. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203200. {
  203201. if (id == IID_IUnknown || id == IID_IDropSource)
  203202. {
  203203. AddRef();
  203204. *result = this;
  203205. return S_OK;
  203206. }
  203207. *result = 0;
  203208. return E_NOINTERFACE;
  203209. }
  203210. ULONG __stdcall AddRef() { return ++refCount; }
  203211. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203212. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  203213. {
  203214. if (escapePressed)
  203215. return DRAGDROP_S_CANCEL;
  203216. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  203217. return DRAGDROP_S_DROP;
  203218. return S_OK;
  203219. }
  203220. HRESULT __stdcall GiveFeedback (DWORD)
  203221. {
  203222. return DRAGDROP_S_USEDEFAULTCURSORS;
  203223. }
  203224. };
  203225. class JuceEnumFormatEtc : public IEnumFORMATETC
  203226. {
  203227. public:
  203228. JuceEnumFormatEtc (const FORMATETC* const format_)
  203229. : refCount (1),
  203230. format (format_),
  203231. index (0)
  203232. {
  203233. }
  203234. virtual ~JuceEnumFormatEtc()
  203235. {
  203236. jassert (refCount == 0);
  203237. }
  203238. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203239. {
  203240. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  203241. {
  203242. AddRef();
  203243. *result = this;
  203244. return S_OK;
  203245. }
  203246. *result = 0;
  203247. return E_NOINTERFACE;
  203248. }
  203249. ULONG __stdcall AddRef() { return ++refCount; }
  203250. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203251. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  203252. {
  203253. if (result == 0)
  203254. return E_POINTER;
  203255. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  203256. newOne->index = index;
  203257. *result = newOne;
  203258. return S_OK;
  203259. }
  203260. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  203261. {
  203262. if (pceltFetched != 0)
  203263. *pceltFetched = 0;
  203264. else if (celt != 1)
  203265. return S_FALSE;
  203266. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  203267. {
  203268. copyFormatEtc (lpFormatEtc [0], *format);
  203269. ++index;
  203270. if (pceltFetched != 0)
  203271. *pceltFetched = 1;
  203272. return S_OK;
  203273. }
  203274. return S_FALSE;
  203275. }
  203276. HRESULT __stdcall Skip (ULONG celt)
  203277. {
  203278. if (index + (int) celt >= 1)
  203279. return S_FALSE;
  203280. index += celt;
  203281. return S_OK;
  203282. }
  203283. HRESULT __stdcall Reset()
  203284. {
  203285. index = 0;
  203286. return S_OK;
  203287. }
  203288. private:
  203289. int refCount;
  203290. const FORMATETC* const format;
  203291. int index;
  203292. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  203293. {
  203294. dest = source;
  203295. if (source.ptd != 0)
  203296. {
  203297. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  203298. *(dest.ptd) = *(source.ptd);
  203299. }
  203300. }
  203301. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  203302. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  203303. };
  203304. class JuceDataObject : public IDataObject
  203305. {
  203306. JuceDropSource* const dropSource;
  203307. const FORMATETC* const format;
  203308. const STGMEDIUM* const medium;
  203309. int refCount;
  203310. JuceDataObject (const JuceDataObject&);
  203311. const JuceDataObject& operator= (const JuceDataObject&);
  203312. public:
  203313. JuceDataObject (JuceDropSource* const dropSource_,
  203314. const FORMATETC* const format_,
  203315. const STGMEDIUM* const medium_)
  203316. : dropSource (dropSource_),
  203317. format (format_),
  203318. medium (medium_),
  203319. refCount (1)
  203320. {
  203321. }
  203322. virtual ~JuceDataObject()
  203323. {
  203324. jassert (refCount == 0);
  203325. }
  203326. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203327. {
  203328. if (id == IID_IUnknown || id == IID_IDataObject)
  203329. {
  203330. AddRef();
  203331. *result = this;
  203332. return S_OK;
  203333. }
  203334. *result = 0;
  203335. return E_NOINTERFACE;
  203336. }
  203337. ULONG __stdcall AddRef() { return ++refCount; }
  203338. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203339. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  203340. {
  203341. if (pFormatEtc->tymed == format->tymed
  203342. && pFormatEtc->cfFormat == format->cfFormat
  203343. && pFormatEtc->dwAspect == format->dwAspect)
  203344. {
  203345. pMedium->tymed = format->tymed;
  203346. pMedium->pUnkForRelease = 0;
  203347. if (format->tymed == TYMED_HGLOBAL)
  203348. {
  203349. const SIZE_T len = GlobalSize (medium->hGlobal);
  203350. void* const src = GlobalLock (medium->hGlobal);
  203351. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  203352. memcpy (dst, src, len);
  203353. GlobalUnlock (medium->hGlobal);
  203354. pMedium->hGlobal = dst;
  203355. return S_OK;
  203356. }
  203357. }
  203358. return DV_E_FORMATETC;
  203359. }
  203360. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  203361. {
  203362. if (f == 0)
  203363. return E_INVALIDARG;
  203364. if (f->tymed == format->tymed
  203365. && f->cfFormat == format->cfFormat
  203366. && f->dwAspect == format->dwAspect)
  203367. return S_OK;
  203368. return DV_E_FORMATETC;
  203369. }
  203370. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  203371. {
  203372. pFormatEtcOut->ptd = 0;
  203373. return E_NOTIMPL;
  203374. }
  203375. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  203376. {
  203377. if (result == 0)
  203378. return E_POINTER;
  203379. if (direction == DATADIR_GET)
  203380. {
  203381. *result = new JuceEnumFormatEtc (format);
  203382. return S_OK;
  203383. }
  203384. *result = 0;
  203385. return E_NOTIMPL;
  203386. }
  203387. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  203388. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  203389. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  203390. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  203391. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  203392. };
  203393. static HDROP createHDrop (const StringArray& fileNames) throw()
  203394. {
  203395. int totalChars = 0;
  203396. for (int i = fileNames.size(); --i >= 0;)
  203397. totalChars += fileNames[i].length() + 1;
  203398. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  203399. sizeof (DROPFILES)
  203400. + sizeof (WCHAR) * (totalChars + 2));
  203401. if (hDrop != 0)
  203402. {
  203403. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  203404. pDropFiles->pFiles = sizeof (DROPFILES);
  203405. pDropFiles->fWide = true;
  203406. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  203407. for (int i = 0; i < fileNames.size(); ++i)
  203408. {
  203409. fileNames[i].copyToBuffer (fname, 2048);
  203410. fname += fileNames[i].length() + 1;
  203411. }
  203412. *fname = 0;
  203413. GlobalUnlock (hDrop);
  203414. }
  203415. return hDrop;
  203416. }
  203417. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  203418. {
  203419. JuceDropSource* const source = new JuceDropSource();
  203420. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  203421. DWORD effect;
  203422. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  203423. data->Release();
  203424. source->Release();
  203425. return res == DRAGDROP_S_DROP;
  203426. }
  203427. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  203428. {
  203429. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203430. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203431. medium.hGlobal = createHDrop (files);
  203432. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  203433. : DROPEFFECT_COPY);
  203434. }
  203435. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  203436. {
  203437. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203438. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203439. const int numChars = text.length();
  203440. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  203441. char* d = (char*) GlobalLock (medium.hGlobal);
  203442. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  203443. format.cfFormat = CF_UNICODETEXT;
  203444. GlobalUnlock (medium.hGlobal);
  203445. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  203446. }
  203447. #endif
  203448. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  203449. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  203450. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203451. // compiled on its own).
  203452. #if JUCE_INCLUDED_FILE
  203453. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  203454. NEWTEXTMETRICEXW*,
  203455. int type,
  203456. LPARAM lParam)
  203457. {
  203458. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203459. {
  203460. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203461. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  203462. }
  203463. return 1;
  203464. }
  203465. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  203466. NEWTEXTMETRICEXW*,
  203467. int type,
  203468. LPARAM lParam)
  203469. {
  203470. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203471. {
  203472. LOGFONTW lf;
  203473. zerostruct (lf);
  203474. lf.lfWeight = FW_DONTCARE;
  203475. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203476. lf.lfQuality = DEFAULT_QUALITY;
  203477. lf.lfCharSet = DEFAULT_CHARSET;
  203478. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203479. lf.lfPitchAndFamily = FF_DONTCARE;
  203480. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203481. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  203482. HDC dc = CreateCompatibleDC (0);
  203483. EnumFontFamiliesEx (dc, &lf,
  203484. (FONTENUMPROCW) &wfontEnum2,
  203485. lParam, 0);
  203486. DeleteDC (dc);
  203487. }
  203488. return 1;
  203489. }
  203490. const StringArray Font::findAllTypefaceNames() throw()
  203491. {
  203492. StringArray results;
  203493. HDC dc = CreateCompatibleDC (0);
  203494. {
  203495. LOGFONTW lf;
  203496. zerostruct (lf);
  203497. lf.lfWeight = FW_DONTCARE;
  203498. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203499. lf.lfQuality = DEFAULT_QUALITY;
  203500. lf.lfCharSet = DEFAULT_CHARSET;
  203501. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203502. lf.lfPitchAndFamily = FF_DONTCARE;
  203503. lf.lfFaceName[0] = 0;
  203504. EnumFontFamiliesEx (dc, &lf,
  203505. (FONTENUMPROCW) &wfontEnum1,
  203506. (LPARAM) &results, 0);
  203507. }
  203508. DeleteDC (dc);
  203509. results.sort (true);
  203510. return results;
  203511. }
  203512. extern bool juce_IsRunningInWine() throw();
  203513. void Typeface::getDefaultFontNames (String& defaultSans,
  203514. String& defaultSerif,
  203515. String& defaultFixed) throw()
  203516. {
  203517. if (juce_IsRunningInWine())
  203518. {
  203519. // If we're running in Wine, then use fonts that might be available on Linux..
  203520. defaultSans = "Bitstream Vera Sans";
  203521. defaultSerif = "Bitstream Vera Serif";
  203522. defaultFixed = "Bitstream Vera Sans Mono";
  203523. }
  203524. else
  203525. {
  203526. defaultSans = "Verdana";
  203527. defaultSerif = "Times";
  203528. defaultFixed = "Lucida Console";
  203529. }
  203530. }
  203531. class FontDCHolder : private DeletedAtShutdown
  203532. {
  203533. HDC dc;
  203534. String fontName;
  203535. KERNINGPAIR* kps;
  203536. int numKPs;
  203537. bool bold, italic;
  203538. int size;
  203539. FontDCHolder (const FontDCHolder&);
  203540. const FontDCHolder& operator= (const FontDCHolder&);
  203541. public:
  203542. HFONT fontH;
  203543. FontDCHolder() throw()
  203544. : dc (0),
  203545. kps (0),
  203546. numKPs (0),
  203547. bold (false),
  203548. italic (false),
  203549. size (0)
  203550. {
  203551. }
  203552. ~FontDCHolder() throw()
  203553. {
  203554. if (dc != 0)
  203555. {
  203556. DeleteDC (dc);
  203557. DeleteObject (fontH);
  203558. juce_free (kps);
  203559. }
  203560. clearSingletonInstance();
  203561. }
  203562. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  203563. HDC loadFont (const String& fontName_,
  203564. const bool bold_,
  203565. const bool italic_,
  203566. const int size_) throw()
  203567. {
  203568. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  203569. {
  203570. fontName = fontName_;
  203571. bold = bold_;
  203572. italic = italic_;
  203573. size = size_;
  203574. if (dc != 0)
  203575. {
  203576. DeleteDC (dc);
  203577. DeleteObject (fontH);
  203578. juce_free (kps);
  203579. kps = 0;
  203580. }
  203581. fontH = 0;
  203582. dc = CreateCompatibleDC (0);
  203583. SetMapperFlags (dc, 0);
  203584. SetMapMode (dc, MM_TEXT);
  203585. LOGFONTW lfw;
  203586. zerostruct (lfw);
  203587. lfw.lfCharSet = DEFAULT_CHARSET;
  203588. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203589. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203590. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  203591. lfw.lfQuality = PROOF_QUALITY;
  203592. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  203593. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  203594. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  203595. lfw.lfHeight = size > 0 ? size : -256;
  203596. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  203597. if (standardSizedFont != 0)
  203598. {
  203599. if (SelectObject (dc, standardSizedFont) != 0)
  203600. {
  203601. fontH = standardSizedFont;
  203602. if (size == 0)
  203603. {
  203604. OUTLINETEXTMETRIC otm;
  203605. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  203606. {
  203607. lfw.lfHeight = -(int) otm.otmEMSquare;
  203608. fontH = CreateFontIndirect (&lfw);
  203609. SelectObject (dc, fontH);
  203610. DeleteObject (standardSizedFont);
  203611. }
  203612. }
  203613. }
  203614. else
  203615. {
  203616. jassertfalse
  203617. }
  203618. }
  203619. else
  203620. {
  203621. jassertfalse
  203622. }
  203623. }
  203624. return dc;
  203625. }
  203626. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  203627. {
  203628. if (kps == 0)
  203629. {
  203630. numKPs = GetKerningPairs (dc, 0, 0);
  203631. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  203632. GetKerningPairs (dc, numKPs, kps);
  203633. }
  203634. numKPs_ = numKPs;
  203635. return kps;
  203636. }
  203637. };
  203638. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  203639. static bool addGlyphToTypeface (HDC dc,
  203640. juce_wchar character,
  203641. Typeface& dest,
  203642. bool addKerning)
  203643. {
  203644. Path destShape;
  203645. GLYPHMETRICS gm;
  203646. float height;
  203647. BOOL ok = false;
  203648. {
  203649. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203650. WORD index = 0;
  203651. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203652. && index == 0xffff)
  203653. {
  203654. return false;
  203655. }
  203656. }
  203657. TEXTMETRIC tm;
  203658. ok = GetTextMetrics (dc, &tm);
  203659. height = (float) tm.tmHeight;
  203660. if (! ok)
  203661. {
  203662. dest.addGlyph (character, destShape, 0);
  203663. return true;
  203664. }
  203665. const float scaleX = 1.0f / height;
  203666. const float scaleY = -1.0f / height;
  203667. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203668. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203669. &gm, 0, 0, &identityMatrix);
  203670. if (bufSize > 0)
  203671. {
  203672. char* const data = (char*) juce_malloc (bufSize);
  203673. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203674. bufSize, data, &identityMatrix);
  203675. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203676. while ((char*) pheader < data + bufSize)
  203677. {
  203678. #define remapX(v) (scaleX * (v).x.value)
  203679. #define remapY(v) (scaleY * (v).y.value)
  203680. float x = remapX (pheader->pfxStart);
  203681. float y = remapY (pheader->pfxStart);
  203682. destShape.startNewSubPath (x, y);
  203683. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203684. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203685. while ((const char*) curve < curveEnd)
  203686. {
  203687. if (curve->wType == TT_PRIM_LINE)
  203688. {
  203689. for (int i = 0; i < curve->cpfx; ++i)
  203690. {
  203691. x = remapX (curve->apfx [i]);
  203692. y = remapY (curve->apfx [i]);
  203693. destShape.lineTo (x, y);
  203694. }
  203695. }
  203696. else if (curve->wType == TT_PRIM_QSPLINE)
  203697. {
  203698. for (int i = 0; i < curve->cpfx - 1; ++i)
  203699. {
  203700. const float x2 = remapX (curve->apfx [i]);
  203701. const float y2 = remapY (curve->apfx [i]);
  203702. float x3, y3;
  203703. if (i < curve->cpfx - 2)
  203704. {
  203705. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203706. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203707. }
  203708. else
  203709. {
  203710. x3 = remapX (curve->apfx [i + 1]);
  203711. y3 = remapY (curve->apfx [i + 1]);
  203712. }
  203713. destShape.quadraticTo (x2, y2, x3, y3);
  203714. x = x3;
  203715. y = y3;
  203716. }
  203717. }
  203718. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203719. }
  203720. pheader = (const TTPOLYGONHEADER*) curve;
  203721. destShape.closeSubPath();
  203722. }
  203723. juce_free (data);
  203724. }
  203725. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203726. if (addKerning)
  203727. {
  203728. int numKPs;
  203729. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203730. for (int i = 0; i < numKPs; ++i)
  203731. {
  203732. if (kps[i].wFirst == character)
  203733. {
  203734. dest.addKerningPair (kps[i].wFirst,
  203735. kps[i].wSecond,
  203736. kps[i].iKernAmount / height);
  203737. }
  203738. }
  203739. }
  203740. return true;
  203741. }
  203742. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203743. {
  203744. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203745. return addGlyphToTypeface (dc, character, *this, true);
  203746. }
  203747. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203748. {
  203749. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203750. int bufSize;
  203751. GLYPHMETRICS gm;
  203752. const UINT format = GGO_GRAY2_BITMAP;
  203753. const int shift = 6;
  203754. if (wGetGlyphOutlineW != 0)
  203755. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203756. else
  203757. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203758. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203759. if (bufSize > 0)
  203760. {
  203761. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203762. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203763. uint8* const data = (uint8*) juce_calloc (bufSize);
  203764. if (wGetGlyphOutlineW != 0)
  203765. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203766. else
  203767. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203768. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203769. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203770. {
  203771. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203772. {
  203773. const int level = data [x + y * stride] << shift;
  203774. if (level > 0)
  203775. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203776. }
  203777. }
  203778. juce_free (data);
  203779. }
  203780. return im;
  203781. }*/
  203782. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203783. bool bold,
  203784. bool italic,
  203785. bool addAllGlyphsToFont) throw()
  203786. {
  203787. clear();
  203788. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203789. float height;
  203790. int firstChar, lastChar;
  203791. {
  203792. TEXTMETRIC tm;
  203793. GetTextMetrics (dc, &tm);
  203794. height = (float) tm.tmHeight;
  203795. firstChar = tm.tmFirstChar;
  203796. lastChar = tm.tmLastChar;
  203797. setAscent (tm.tmAscent / height);
  203798. setDefaultCharacter (tm.tmDefaultChar);
  203799. }
  203800. setName (fontName);
  203801. setBold (bold);
  203802. setItalic (italic);
  203803. if (addAllGlyphsToFont)
  203804. {
  203805. for (int character = firstChar; character <= lastChar; ++character)
  203806. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203807. int numKPs;
  203808. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203809. for (int i = 0; i < numKPs; ++i)
  203810. {
  203811. addKerningPair (kps[i].wFirst,
  203812. kps[i].wSecond,
  203813. kps[i].iKernAmount / height);
  203814. }
  203815. }
  203816. }
  203817. #endif
  203818. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203819. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203820. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203821. // compiled on its own).
  203822. #if JUCE_INCLUDED_FILE
  203823. static const void* defaultDirPath = 0;
  203824. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203825. static Component* currentExtraFileWin = 0;
  203826. static bool areThereAnyAlwaysOnTopWindows()
  203827. {
  203828. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203829. {
  203830. Component* c = Desktop::getInstance().getComponent (i);
  203831. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203832. return true;
  203833. }
  203834. return false;
  203835. }
  203836. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203837. {
  203838. if (msg == BFFM_INITIALIZED)
  203839. {
  203840. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203841. }
  203842. else if (msg == BFFM_VALIDATEFAILEDW)
  203843. {
  203844. returnedString = (LPCWSTR) lParam;
  203845. }
  203846. else if (msg == BFFM_VALIDATEFAILEDA)
  203847. {
  203848. returnedString = (const char*) lParam;
  203849. }
  203850. return 0;
  203851. }
  203852. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  203853. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203854. {
  203855. if (currentExtraFileWin != 0)
  203856. {
  203857. if (uiMsg == WM_INITDIALOG)
  203858. {
  203859. HWND dialogH = GetParent (hdlg);
  203860. jassert (dialogH != 0);
  203861. if (dialogH == 0)
  203862. dialogH = hdlg;
  203863. RECT r, cr;
  203864. GetWindowRect (dialogH, &r);
  203865. GetClientRect (dialogH, &cr);
  203866. SetWindowPos (dialogH, 0,
  203867. r.left, r.top,
  203868. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203869. jmax (150, r.bottom - r.top),
  203870. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203871. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203872. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203873. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203874. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203875. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203876. }
  203877. else if (uiMsg == WM_NOTIFY)
  203878. {
  203879. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203880. if (ofn->hdr.code == CDN_SELCHANGE)
  203881. {
  203882. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203883. if (comp != 0)
  203884. {
  203885. TCHAR path [MAX_PATH * 2];
  203886. path[0] = 0;
  203887. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203888. const String fn ((const WCHAR*) path);
  203889. comp->selectedFileChanged (File (fn));
  203890. }
  203891. }
  203892. }
  203893. }
  203894. return 0;
  203895. }
  203896. class FPComponentHolder : public Component
  203897. {
  203898. public:
  203899. FPComponentHolder()
  203900. {
  203901. setVisible (true);
  203902. setOpaque (true);
  203903. }
  203904. ~FPComponentHolder()
  203905. {
  203906. }
  203907. void paint (Graphics& g)
  203908. {
  203909. g.fillAll (Colours::lightgrey);
  203910. }
  203911. private:
  203912. FPComponentHolder (const FPComponentHolder&);
  203913. const FPComponentHolder& operator= (const FPComponentHolder&);
  203914. };
  203915. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203916. const String& title,
  203917. const File& currentFileOrDirectory,
  203918. const String& filter,
  203919. bool selectsDirectory,
  203920. bool isSaveDialogue,
  203921. bool warnAboutOverwritingExistingFiles,
  203922. bool selectMultipleFiles,
  203923. FilePreviewComponent* extraInfoComponent)
  203924. {
  203925. const int numCharsAvailable = 32768;
  203926. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203927. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203928. int fnameIdx = 0;
  203929. JUCE_TRY
  203930. {
  203931. // use a modal window as the parent for this dialog box
  203932. // to block input from other app windows
  203933. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203934. Component w (String::empty);
  203935. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203936. mainMon.getY() + mainMon.getHeight() / 4,
  203937. 0, 0);
  203938. w.setOpaque (true);
  203939. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203940. w.addToDesktop (0);
  203941. if (extraInfoComponent == 0)
  203942. w.enterModalState();
  203943. String initialDir;
  203944. if (currentFileOrDirectory.isDirectory())
  203945. {
  203946. initialDir = currentFileOrDirectory.getFullPathName();
  203947. }
  203948. else
  203949. {
  203950. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203951. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203952. }
  203953. if (currentExtraFileWin->isValidComponent())
  203954. {
  203955. jassertfalse
  203956. return;
  203957. }
  203958. if (selectsDirectory)
  203959. {
  203960. LPITEMIDLIST list = 0;
  203961. filenameSpace.fillWith (0);
  203962. {
  203963. BROWSEINFO bi;
  203964. zerostruct (bi);
  203965. bi.hwndOwner = (HWND) w.getWindowHandle();
  203966. bi.pszDisplayName = fname;
  203967. bi.lpszTitle = title;
  203968. bi.lpfn = browseCallbackProc;
  203969. #ifdef BIF_USENEWUI
  203970. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203971. #else
  203972. bi.ulFlags = 0x50;
  203973. #endif
  203974. defaultDirPath = (const WCHAR*) initialDir;
  203975. list = SHBrowseForFolder (&bi);
  203976. if (! SHGetPathFromIDListW (list, fname))
  203977. {
  203978. fname[0] = 0;
  203979. returnedString = String::empty;
  203980. }
  203981. }
  203982. LPMALLOC al;
  203983. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203984. al->Free (list);
  203985. defaultDirPath = 0;
  203986. if (returnedString.isNotEmpty())
  203987. {
  203988. const String stringFName (fname);
  203989. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203990. returnedString = String::empty;
  203991. return;
  203992. }
  203993. }
  203994. else
  203995. {
  203996. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203997. if (warnAboutOverwritingExistingFiles)
  203998. flags |= OFN_OVERWRITEPROMPT;
  203999. if (selectMultipleFiles)
  204000. flags |= OFN_ALLOWMULTISELECT;
  204001. if (extraInfoComponent != 0)
  204002. {
  204003. flags |= OFN_ENABLEHOOK;
  204004. currentExtraFileWin = new FPComponentHolder();
  204005. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204006. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204007. extraInfoComponent->getHeight());
  204008. currentExtraFileWin->addToDesktop (0);
  204009. currentExtraFileWin->enterModalState();
  204010. }
  204011. {
  204012. WCHAR filters [1024];
  204013. zeromem (filters, sizeof (filters));
  204014. filter.copyToBuffer (filters, 1024);
  204015. filter.copyToBuffer (filters + filter.length() + 1,
  204016. 1022 - filter.length());
  204017. OPENFILENAMEW of;
  204018. zerostruct (of);
  204019. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204020. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204021. #else
  204022. of.lStructSize = sizeof (of);
  204023. #endif
  204024. of.hwndOwner = (HWND) w.getWindowHandle();
  204025. of.lpstrFilter = filters;
  204026. of.nFilterIndex = 1;
  204027. of.lpstrFile = fname;
  204028. of.nMaxFile = numCharsAvailable;
  204029. of.lpstrInitialDir = initialDir;
  204030. of.lpstrTitle = title;
  204031. of.Flags = flags;
  204032. if (extraInfoComponent != 0)
  204033. of.lpfnHook = &openCallback;
  204034. if (isSaveDialogue)
  204035. {
  204036. if (! GetSaveFileName (&of))
  204037. fname[0] = 0;
  204038. else
  204039. fnameIdx = of.nFileOffset;
  204040. }
  204041. else
  204042. {
  204043. if (! GetOpenFileName (&of))
  204044. fname[0] = 0;
  204045. else
  204046. fnameIdx = of.nFileOffset;
  204047. }
  204048. }
  204049. }
  204050. }
  204051. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204052. catch (...)
  204053. {
  204054. fname[0] = 0;
  204055. }
  204056. #endif
  204057. deleteAndZero (currentExtraFileWin);
  204058. const WCHAR* const files = fname;
  204059. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204060. {
  204061. const WCHAR* filename = files + fnameIdx;
  204062. while (*filename != 0)
  204063. {
  204064. const String filepath (String (files) + T("\\") + String (filename));
  204065. results.add (new File (filepath));
  204066. filename += CharacterFunctions::length (filename) + 1;
  204067. }
  204068. }
  204069. else if (files[0] != 0)
  204070. {
  204071. results.add (new File (files));
  204072. }
  204073. }
  204074. #endif
  204075. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  204076. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  204077. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204078. // compiled on its own).
  204079. #if JUCE_INCLUDED_FILE
  204080. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  204081. {
  204082. if (OpenClipboard (0) != 0)
  204083. {
  204084. if (EmptyClipboard() != 0)
  204085. {
  204086. const int len = text.length();
  204087. if (len > 0)
  204088. {
  204089. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  204090. (len + 1) * sizeof (wchar_t));
  204091. if (bufH != 0)
  204092. {
  204093. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  204094. text.copyToBuffer (data, len);
  204095. GlobalUnlock (bufH);
  204096. SetClipboardData (CF_UNICODETEXT, bufH);
  204097. }
  204098. }
  204099. }
  204100. CloseClipboard();
  204101. }
  204102. }
  204103. const String SystemClipboard::getTextFromClipboard() throw()
  204104. {
  204105. String result;
  204106. if (OpenClipboard (0) != 0)
  204107. {
  204108. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  204109. if (bufH != 0)
  204110. {
  204111. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  204112. if (data != 0)
  204113. {
  204114. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  204115. GlobalUnlock (bufH);
  204116. }
  204117. }
  204118. CloseClipboard();
  204119. }
  204120. return result;
  204121. }
  204122. #endif
  204123. /********* End of inlined file: juce_win32_Misc.cpp *********/
  204124. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  204125. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204126. // compiled on its own).
  204127. #if JUCE_INCLUDED_FILE
  204128. class JuceIStorage : public IStorage
  204129. {
  204130. int refCount;
  204131. public:
  204132. JuceIStorage() : refCount (1) {}
  204133. virtual ~JuceIStorage()
  204134. {
  204135. jassert (refCount == 0);
  204136. }
  204137. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204138. {
  204139. if (id == IID_IUnknown || id == IID_IStorage)
  204140. {
  204141. AddRef();
  204142. *result = this;
  204143. return S_OK;
  204144. }
  204145. *result = 0;
  204146. return E_NOINTERFACE;
  204147. }
  204148. ULONG __stdcall AddRef() { return ++refCount; }
  204149. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204150. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204151. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204152. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  204153. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  204154. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  204155. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  204156. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  204157. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  204158. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  204159. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  204160. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  204161. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  204162. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  204163. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  204164. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  204165. juce_UseDebuggingNewOperator
  204166. };
  204167. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  204168. {
  204169. int refCount;
  204170. HWND window;
  204171. public:
  204172. JuceOleInPlaceFrame (HWND window_)
  204173. : refCount (1),
  204174. window (window_)
  204175. {
  204176. }
  204177. virtual ~JuceOleInPlaceFrame()
  204178. {
  204179. jassert (refCount == 0);
  204180. }
  204181. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204182. {
  204183. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  204184. {
  204185. AddRef();
  204186. *result = this;
  204187. return S_OK;
  204188. }
  204189. *result = 0;
  204190. return E_NOINTERFACE;
  204191. }
  204192. ULONG __stdcall AddRef() { return ++refCount; }
  204193. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204194. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204195. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204196. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  204197. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204198. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204199. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  204200. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  204201. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  204202. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  204203. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  204204. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  204205. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  204206. juce_UseDebuggingNewOperator
  204207. };
  204208. class JuceIOleInPlaceSite : public IOleInPlaceSite
  204209. {
  204210. int refCount;
  204211. HWND window;
  204212. JuceOleInPlaceFrame* frame;
  204213. public:
  204214. JuceIOleInPlaceSite (HWND window_)
  204215. : refCount (1),
  204216. window (window_)
  204217. {
  204218. frame = new JuceOleInPlaceFrame (window);
  204219. }
  204220. virtual ~JuceIOleInPlaceSite()
  204221. {
  204222. jassert (refCount == 0);
  204223. frame->Release();
  204224. }
  204225. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204226. {
  204227. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  204228. {
  204229. AddRef();
  204230. *result = this;
  204231. return S_OK;
  204232. }
  204233. *result = 0;
  204234. return E_NOINTERFACE;
  204235. }
  204236. ULONG __stdcall AddRef() { return ++refCount; }
  204237. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204238. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204239. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204240. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  204241. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  204242. HRESULT __stdcall OnUIActivate() { return S_OK; }
  204243. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  204244. {
  204245. frame->AddRef();
  204246. *lplpFrame = frame;
  204247. *lplpDoc = 0;
  204248. lpFrameInfo->fMDIApp = FALSE;
  204249. lpFrameInfo->hwndFrame = window;
  204250. lpFrameInfo->haccel = 0;
  204251. lpFrameInfo->cAccelEntries = 0;
  204252. return S_OK;
  204253. }
  204254. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  204255. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  204256. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  204257. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  204258. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  204259. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  204260. juce_UseDebuggingNewOperator
  204261. };
  204262. class JuceIOleClientSite : public IOleClientSite
  204263. {
  204264. int refCount;
  204265. JuceIOleInPlaceSite* inplaceSite;
  204266. public:
  204267. JuceIOleClientSite (HWND window)
  204268. : refCount (1)
  204269. {
  204270. inplaceSite = new JuceIOleInPlaceSite (window);
  204271. }
  204272. virtual ~JuceIOleClientSite()
  204273. {
  204274. jassert (refCount == 0);
  204275. inplaceSite->Release();
  204276. }
  204277. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204278. {
  204279. if (id == IID_IUnknown || id == IID_IOleClientSite)
  204280. {
  204281. AddRef();
  204282. *result = this;
  204283. return S_OK;
  204284. }
  204285. else if (id == IID_IOleInPlaceSite)
  204286. {
  204287. inplaceSite->AddRef();
  204288. *result = inplaceSite;
  204289. return S_OK;
  204290. }
  204291. *result = 0;
  204292. return E_NOINTERFACE;
  204293. }
  204294. ULONG __stdcall AddRef() { return ++refCount; }
  204295. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204296. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  204297. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  204298. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  204299. HRESULT __stdcall ShowObject() { return S_OK; }
  204300. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  204301. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  204302. juce_UseDebuggingNewOperator
  204303. };
  204304. class ActiveXControlData : public ComponentMovementWatcher
  204305. {
  204306. ActiveXControlComponent* const owner;
  204307. bool wasShowing;
  204308. public:
  204309. HWND controlHWND;
  204310. IStorage* storage;
  204311. IOleClientSite* clientSite;
  204312. IOleObject* control;
  204313. ActiveXControlData (HWND hwnd,
  204314. ActiveXControlComponent* const owner_)
  204315. : ComponentMovementWatcher (owner_),
  204316. owner (owner_),
  204317. wasShowing (owner_ != 0 && owner_->isShowing()),
  204318. controlHWND (0),
  204319. storage (new JuceIStorage()),
  204320. clientSite (new JuceIOleClientSite (hwnd)),
  204321. control (0)
  204322. {
  204323. }
  204324. ~ActiveXControlData()
  204325. {
  204326. if (control != 0)
  204327. {
  204328. control->Close (OLECLOSE_NOSAVE);
  204329. control->Release();
  204330. }
  204331. clientSite->Release();
  204332. storage->Release();
  204333. }
  204334. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  204335. {
  204336. Component* const topComp = owner->getTopLevelComponent();
  204337. if (topComp->getPeer() != 0)
  204338. {
  204339. int x = 0, y = 0;
  204340. owner->relativePositionToOtherComponent (topComp, x, y);
  204341. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  204342. }
  204343. }
  204344. void componentPeerChanged()
  204345. {
  204346. const bool isShowingNow = owner->isShowing();
  204347. if (wasShowing != isShowingNow)
  204348. {
  204349. wasShowing = isShowingNow;
  204350. owner->setControlVisible (isShowingNow);
  204351. }
  204352. componentMovedOrResized (true, true);
  204353. }
  204354. void componentVisibilityChanged (Component&)
  204355. {
  204356. componentPeerChanged();
  204357. }
  204358. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  204359. {
  204360. return ((ActiveXControlData*) ax->control) != 0
  204361. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  204362. }
  204363. };
  204364. static VoidArray activeXComps;
  204365. static HWND getHWND (const ActiveXControlComponent* const component)
  204366. {
  204367. HWND hwnd = 0;
  204368. const IID iid = IID_IOleWindow;
  204369. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  204370. if (window != 0)
  204371. {
  204372. window->GetWindow (&hwnd);
  204373. window->Release();
  204374. }
  204375. return hwnd;
  204376. }
  204377. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  204378. {
  204379. RECT activeXRect, peerRect;
  204380. GetWindowRect (hwnd, &activeXRect);
  204381. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  204382. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  204383. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  204384. const int64 mouseEventTime = getMouseEventTime();
  204385. const int oldModifiers = currentModifiers;
  204386. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  204387. switch (message)
  204388. {
  204389. case WM_MOUSEMOVE:
  204390. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  204391. peer->handleMouseDrag (mx, my, mouseEventTime);
  204392. else
  204393. peer->handleMouseMove (mx, my, mouseEventTime);
  204394. break;
  204395. case WM_LBUTTONDOWN:
  204396. case WM_MBUTTONDOWN:
  204397. case WM_RBUTTONDOWN:
  204398. peer->handleMouseDown (mx, my, mouseEventTime);
  204399. break;
  204400. case WM_LBUTTONUP:
  204401. case WM_MBUTTONUP:
  204402. case WM_RBUTTONUP:
  204403. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  204404. break;
  204405. default:
  204406. break;
  204407. }
  204408. }
  204409. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  204410. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  204411. {
  204412. for (int i = activeXComps.size(); --i >= 0;)
  204413. {
  204414. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  204415. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  204416. {
  204417. switch (message)
  204418. {
  204419. case WM_MOUSEMOVE:
  204420. case WM_LBUTTONDOWN:
  204421. case WM_MBUTTONDOWN:
  204422. case WM_RBUTTONDOWN:
  204423. case WM_LBUTTONUP:
  204424. case WM_MBUTTONUP:
  204425. case WM_RBUTTONUP:
  204426. case WM_LBUTTONDBLCLK:
  204427. case WM_MBUTTONDBLCLK:
  204428. case WM_RBUTTONDBLCLK:
  204429. if (ax->isShowing())
  204430. {
  204431. ComponentPeer* const peer = ax->getPeer();
  204432. if (peer != 0)
  204433. {
  204434. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  204435. if (! ax->areMouseEventsAllowed())
  204436. return 0;
  204437. }
  204438. }
  204439. break;
  204440. default:
  204441. break;
  204442. }
  204443. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  204444. }
  204445. }
  204446. return DefWindowProc (hwnd, message, wParam, lParam);
  204447. }
  204448. ActiveXControlComponent::ActiveXControlComponent()
  204449. : originalWndProc (0),
  204450. control (0),
  204451. mouseEventsAllowed (true)
  204452. {
  204453. activeXComps.add (this);
  204454. }
  204455. ActiveXControlComponent::~ActiveXControlComponent()
  204456. {
  204457. deleteControl();
  204458. activeXComps.removeValue (this);
  204459. }
  204460. void ActiveXControlComponent::paint (Graphics& g)
  204461. {
  204462. if (control == 0)
  204463. g.fillAll (Colours::lightgrey);
  204464. }
  204465. bool ActiveXControlComponent::createControl (const void* controlIID)
  204466. {
  204467. deleteControl();
  204468. ComponentPeer* const peer = getPeer();
  204469. // the component must have already been added to a real window when you call this!
  204470. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  204471. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  204472. {
  204473. int x = 0, y = 0;
  204474. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  204475. HWND hwnd = (HWND) peer->getNativeHandle();
  204476. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  204477. HRESULT hr;
  204478. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  204479. info->clientSite, info->storage,
  204480. (void**) &(info->control))) == S_OK)
  204481. {
  204482. info->control->SetHostNames (L"Juce", 0);
  204483. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  204484. {
  204485. RECT rect;
  204486. rect.left = x;
  204487. rect.top = y;
  204488. rect.right = x + getWidth();
  204489. rect.bottom = y + getHeight();
  204490. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  204491. {
  204492. control = info;
  204493. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  204494. info->controlHWND = getHWND (this);
  204495. if (info->controlHWND != 0)
  204496. {
  204497. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  204498. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  204499. }
  204500. return true;
  204501. }
  204502. }
  204503. }
  204504. delete info;
  204505. }
  204506. return false;
  204507. }
  204508. void ActiveXControlComponent::deleteControl()
  204509. {
  204510. ActiveXControlData* const info = (ActiveXControlData*) control;
  204511. if (info != 0)
  204512. {
  204513. delete info;
  204514. control = 0;
  204515. originalWndProc = 0;
  204516. }
  204517. }
  204518. void* ActiveXControlComponent::queryInterface (const void* iid) const
  204519. {
  204520. ActiveXControlData* const info = (ActiveXControlData*) control;
  204521. void* result = 0;
  204522. if (info != 0 && info->control != 0
  204523. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  204524. return result;
  204525. return 0;
  204526. }
  204527. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  204528. {
  204529. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204530. if (hwnd != 0)
  204531. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  204532. }
  204533. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  204534. {
  204535. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204536. if (hwnd != 0)
  204537. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204538. }
  204539. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  204540. {
  204541. mouseEventsAllowed = eventsCanReachControl;
  204542. }
  204543. #endif
  204544. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  204545. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204546. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204547. // compiled on its own).
  204548. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  204549. using namespace QTOLibrary;
  204550. using namespace QTOControlLib;
  204551. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  204552. static bool isQTAvailable = false;
  204553. struct QTMovieCompInternal
  204554. {
  204555. QTMovieCompInternal()
  204556. : dataHandle (0)
  204557. {
  204558. }
  204559. ~QTMovieCompInternal()
  204560. {
  204561. clearHandle();
  204562. }
  204563. IQTControlPtr qtControlInternal;
  204564. IQTMoviePtr qtMovieInternal;
  204565. Handle dataHandle;
  204566. void clearHandle()
  204567. {
  204568. if (dataHandle != 0)
  204569. {
  204570. DisposeHandle (dataHandle);
  204571. dataHandle = 0;
  204572. }
  204573. }
  204574. };
  204575. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  204576. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  204577. QuickTimeMovieComponent::QuickTimeMovieComponent()
  204578. : movieLoaded (false),
  204579. controllerVisible (true)
  204580. {
  204581. internal = new QTMovieCompInternal();
  204582. setMouseEventsAllowed (false);
  204583. }
  204584. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  204585. {
  204586. closeMovie();
  204587. qtControl = 0;
  204588. deleteControl();
  204589. delete internal;
  204590. internal = 0;
  204591. }
  204592. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  204593. {
  204594. if (! isQTAvailable)
  204595. {
  204596. isQTAvailable = (InitializeQTML (0) == noErr)
  204597. && (EnterMovies() == noErr);
  204598. }
  204599. return isQTAvailable;
  204600. }
  204601. void QuickTimeMovieComponent::createControlIfNeeded()
  204602. {
  204603. if (isShowing() && ! isControlCreated())
  204604. {
  204605. const IID qtIID = __uuidof (QTControl);
  204606. if (createControl (&qtIID))
  204607. {
  204608. const IID qtInterfaceIID = __uuidof (IQTControl);
  204609. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  204610. if (qtControl != 0)
  204611. {
  204612. qtControl->Release(); // it has one ref too many at this point
  204613. qtControl->QuickTimeInitialize();
  204614. qtControl->PutSizing (qtMovieFitsControl);
  204615. if (movieFile != File::nonexistent)
  204616. loadMovie (movieFile, controllerVisible);
  204617. }
  204618. }
  204619. }
  204620. }
  204621. bool QuickTimeMovieComponent::isControlCreated() const
  204622. {
  204623. return isControlOpen();
  204624. }
  204625. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  204626. const bool isControllerVisible)
  204627. {
  204628. movieFile = File::nonexistent;
  204629. movieLoaded = false;
  204630. qtMovie = 0;
  204631. controllerVisible = isControllerVisible;
  204632. createControlIfNeeded();
  204633. if (isControlCreated())
  204634. {
  204635. if (qtControl != 0)
  204636. {
  204637. qtControl->Put_MovieHandle (0);
  204638. ((QTMovieCompInternal*) internal)->clearHandle();
  204639. Movie movie;
  204640. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  204641. {
  204642. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  204643. qtMovie = qtControl->GetMovie();
  204644. if (qtMovie != 0)
  204645. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  204646. : qtMovieControllerTypeNone);
  204647. }
  204648. if (movie == 0)
  204649. ((QTMovieCompInternal*) internal)->clearHandle();
  204650. }
  204651. movieLoaded = (qtMovie != 0);
  204652. }
  204653. else
  204654. {
  204655. // You're trying to open a movie when the control hasn't yet been created, probably because
  204656. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  204657. jassertfalse
  204658. }
  204659. delete movieStream;
  204660. return movieLoaded;
  204661. }
  204662. void QuickTimeMovieComponent::closeMovie()
  204663. {
  204664. stop();
  204665. movieFile = File::nonexistent;
  204666. movieLoaded = false;
  204667. qtMovie = 0;
  204668. if (qtControl != 0)
  204669. qtControl->Put_MovieHandle (0);
  204670. ((QTMovieCompInternal*) internal)->clearHandle();
  204671. }
  204672. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  204673. {
  204674. return movieFile;
  204675. }
  204676. bool QuickTimeMovieComponent::isMovieOpen() const
  204677. {
  204678. return movieLoaded;
  204679. }
  204680. double QuickTimeMovieComponent::getMovieDuration() const
  204681. {
  204682. if (qtMovie != 0)
  204683. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  204684. return 0.0;
  204685. }
  204686. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  204687. {
  204688. if (qtMovie != 0)
  204689. {
  204690. struct QTRECT r = qtMovie->GetNaturalRect();
  204691. width = r.right - r.left;
  204692. height = r.bottom - r.top;
  204693. }
  204694. else
  204695. {
  204696. width = height = 0;
  204697. }
  204698. }
  204699. void QuickTimeMovieComponent::play()
  204700. {
  204701. if (qtMovie != 0)
  204702. qtMovie->Play();
  204703. }
  204704. void QuickTimeMovieComponent::stop()
  204705. {
  204706. if (qtMovie != 0)
  204707. qtMovie->Stop();
  204708. }
  204709. bool QuickTimeMovieComponent::isPlaying() const
  204710. {
  204711. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  204712. }
  204713. void QuickTimeMovieComponent::setPosition (const double seconds)
  204714. {
  204715. if (qtMovie != 0)
  204716. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  204717. }
  204718. double QuickTimeMovieComponent::getPosition() const
  204719. {
  204720. if (qtMovie != 0)
  204721. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  204722. return 0.0;
  204723. }
  204724. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  204725. {
  204726. if (qtMovie != 0)
  204727. qtMovie->PutRate (newSpeed);
  204728. }
  204729. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  204730. {
  204731. if (qtMovie != 0)
  204732. {
  204733. qtMovie->PutAudioVolume (newVolume);
  204734. qtMovie->PutAudioMute (newVolume <= 0);
  204735. }
  204736. }
  204737. float QuickTimeMovieComponent::getMovieVolume() const
  204738. {
  204739. if (qtMovie != 0)
  204740. return qtMovie->GetAudioVolume();
  204741. return 0.0f;
  204742. }
  204743. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  204744. {
  204745. if (qtMovie != 0)
  204746. qtMovie->PutLoop (shouldLoop);
  204747. }
  204748. bool QuickTimeMovieComponent::isLooping() const
  204749. {
  204750. return qtMovie != 0 && qtMovie->GetLoop();
  204751. }
  204752. bool QuickTimeMovieComponent::isControllerVisible() const
  204753. {
  204754. return controllerVisible;
  204755. }
  204756. void QuickTimeMovieComponent::parentHierarchyChanged()
  204757. {
  204758. createControlIfNeeded();
  204759. QTCompBaseClass::parentHierarchyChanged();
  204760. }
  204761. void QuickTimeMovieComponent::visibilityChanged()
  204762. {
  204763. createControlIfNeeded();
  204764. QTCompBaseClass::visibilityChanged();
  204765. }
  204766. void QuickTimeMovieComponent::paint (Graphics& g)
  204767. {
  204768. if (! isControlCreated())
  204769. g.fillAll (Colours::black);
  204770. }
  204771. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  204772. {
  204773. Handle dataRef = 0;
  204774. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  204775. if (err == noErr)
  204776. {
  204777. Str255 suffix;
  204778. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  204779. StringPtr name = suffix;
  204780. err = PtrAndHand (name, dataRef, name[0] + 1);
  204781. if (err == noErr)
  204782. {
  204783. long atoms[3];
  204784. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  204785. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  204786. atoms[2] = EndianU32_NtoB (MovieFileType);
  204787. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  204788. if (err == noErr)
  204789. return dataRef;
  204790. }
  204791. DisposeHandle (dataRef);
  204792. }
  204793. return 0;
  204794. }
  204795. static CFStringRef juceStringToCFString (const String& s)
  204796. {
  204797. const int len = s.length();
  204798. const juce_wchar* const t = (const juce_wchar*) s;
  204799. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  204800. for (int i = 0; i <= len; ++i)
  204801. temp[i] = t[i];
  204802. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  204803. juce_free (temp);
  204804. return result;
  204805. }
  204806. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  204807. {
  204808. Boolean trueBool = true;
  204809. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204810. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  204811. props[prop].propValueSize = sizeof (trueBool);
  204812. props[prop].propValueAddress = &trueBool;
  204813. ++prop;
  204814. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204815. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  204816. props[prop].propValueSize = sizeof (trueBool);
  204817. props[prop].propValueAddress = &trueBool;
  204818. ++prop;
  204819. Boolean isActive = true;
  204820. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  204821. props[prop].propID = kQTNewMoviePropertyID_Active;
  204822. props[prop].propValueSize = sizeof (isActive);
  204823. props[prop].propValueAddress = &isActive;
  204824. ++prop;
  204825. MacSetPort (0);
  204826. jassert (prop <= 5);
  204827. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  204828. return err == noErr;
  204829. }
  204830. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  204831. {
  204832. if (input == 0)
  204833. return false;
  204834. dataHandle = 0;
  204835. bool ok = false;
  204836. QTNewMoviePropertyElement props[5];
  204837. zeromem (props, sizeof (props));
  204838. int prop = 0;
  204839. DataReferenceRecord dr;
  204840. props[prop].propClass = kQTPropertyClass_DataLocation;
  204841. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  204842. props[prop].propValueSize = sizeof (dr);
  204843. props[prop].propValueAddress = (void*) &dr;
  204844. ++prop;
  204845. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  204846. if (fin != 0)
  204847. {
  204848. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  204849. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  204850. &dr.dataRef, &dr.dataRefType);
  204851. ok = openMovie (props, prop, movie);
  204852. DisposeHandle (dr.dataRef);
  204853. CFRelease (filePath);
  204854. }
  204855. else
  204856. {
  204857. // sanity-check because this currently needs to load the whole stream into memory..
  204858. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  204859. dataHandle = NewHandle ((Size) input->getTotalLength());
  204860. HLock (dataHandle);
  204861. // read the entire stream into memory - this is a pain, but can't get it to work
  204862. // properly using a custom callback to supply the data.
  204863. input->read (*dataHandle, (int) input->getTotalLength());
  204864. HUnlock (dataHandle);
  204865. // different types to get QT to try. (We should really be a bit smarter here by
  204866. // working out in advance which one the stream contains, rather than just trying
  204867. // each one)
  204868. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  204869. "\04.avi", "\04.m4a" };
  204870. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  204871. {
  204872. /* // this fails for some bizarre reason - it can be bodged to work with
  204873. // movies, but can't seem to do it for other file types..
  204874. QTNewMovieUserProcRecord procInfo;
  204875. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  204876. procInfo.getMovieUserProcRefcon = this;
  204877. procInfo.defaultDataRef.dataRef = dataRef;
  204878. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  204879. props[prop].propClass = kQTPropertyClass_DataLocation;
  204880. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  204881. props[prop].propValueSize = sizeof (procInfo);
  204882. props[prop].propValueAddress = (void*) &procInfo;
  204883. ++prop; */
  204884. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  204885. dr.dataRefType = HandleDataHandlerSubType;
  204886. ok = openMovie (props, prop, movie);
  204887. DisposeHandle (dr.dataRef);
  204888. }
  204889. }
  204890. return ok;
  204891. }
  204892. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  204893. const bool isControllerVisible)
  204894. {
  204895. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  204896. movieFile = movieFile_;
  204897. return ok;
  204898. }
  204899. void QuickTimeMovieComponent::goToStart()
  204900. {
  204901. setPosition (0.0);
  204902. }
  204903. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  204904. const RectanglePlacement& placement)
  204905. {
  204906. int normalWidth, normalHeight;
  204907. getMovieNormalSize (normalWidth, normalHeight);
  204908. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  204909. {
  204910. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  204911. placement.applyTo (x, y, w, h,
  204912. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  204913. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  204914. if (w > 0 && h > 0)
  204915. {
  204916. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  204917. roundDoubleToInt (w), roundDoubleToInt (h));
  204918. }
  204919. }
  204920. else
  204921. {
  204922. setBounds (spaceToFitWithin);
  204923. }
  204924. }
  204925. #endif
  204926. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204927. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204928. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204929. // compiled on its own).
  204930. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  204931. class WebBrowserComponentInternal : public ActiveXControlComponent
  204932. {
  204933. public:
  204934. WebBrowserComponentInternal()
  204935. : browser (0),
  204936. connectionPoint (0),
  204937. adviseCookie (0)
  204938. {
  204939. }
  204940. ~WebBrowserComponentInternal()
  204941. {
  204942. if (connectionPoint != 0)
  204943. connectionPoint->Unadvise (adviseCookie);
  204944. if (browser != 0)
  204945. browser->Release();
  204946. }
  204947. void createBrowser()
  204948. {
  204949. createControl (&CLSID_WebBrowser);
  204950. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204951. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204952. if (connectionPointContainer != 0)
  204953. {
  204954. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204955. &connectionPoint);
  204956. if (connectionPoint != 0)
  204957. {
  204958. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204959. jassert (owner != 0);
  204960. EventHandler* handler = new EventHandler (owner);
  204961. connectionPoint->Advise (handler, &adviseCookie);
  204962. }
  204963. }
  204964. }
  204965. void goToURL (const String& url,
  204966. const StringArray* headers,
  204967. const MemoryBlock* postData)
  204968. {
  204969. if (browser != 0)
  204970. {
  204971. LPSAFEARRAY sa = 0;
  204972. _variant_t flags, frame, postDataVar, headersVar;
  204973. if (headers != 0)
  204974. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204975. if (postData != 0 && postData->getSize() > 0)
  204976. {
  204977. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204978. if (sa != 0)
  204979. {
  204980. void* data = 0;
  204981. SafeArrayAccessData (sa, &data);
  204982. jassert (data != 0);
  204983. if (data != 0)
  204984. {
  204985. postData->copyTo (data, 0, postData->getSize());
  204986. SafeArrayUnaccessData (sa);
  204987. VARIANT postDataVar2;
  204988. VariantInit (&postDataVar2);
  204989. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204990. V_ARRAY (&postDataVar2) = sa;
  204991. postDataVar = postDataVar2;
  204992. }
  204993. }
  204994. }
  204995. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204996. &flags, &frame,
  204997. &postDataVar, &headersVar);
  204998. if (sa != 0)
  204999. SafeArrayDestroy (sa);
  205000. }
  205001. }
  205002. IWebBrowser2* browser;
  205003. juce_UseDebuggingNewOperator
  205004. private:
  205005. IConnectionPoint* connectionPoint;
  205006. DWORD adviseCookie;
  205007. class EventHandler : public IDispatch,
  205008. public ComponentMovementWatcher
  205009. {
  205010. public:
  205011. EventHandler (WebBrowserComponent* owner_)
  205012. : ComponentMovementWatcher (owner_),
  205013. owner (owner_),
  205014. refCount (0)
  205015. {
  205016. }
  205017. ~EventHandler()
  205018. {
  205019. }
  205020. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  205021. {
  205022. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  205023. {
  205024. AddRef();
  205025. *result = this;
  205026. return S_OK;
  205027. }
  205028. *result = 0;
  205029. return E_NOINTERFACE;
  205030. }
  205031. ULONG __stdcall AddRef() { return ++refCount; }
  205032. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  205033. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205034. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205035. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205036. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205037. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205038. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205039. UINT __RPC_FAR* /*puArgErr*/)
  205040. {
  205041. switch (dispIdMember)
  205042. {
  205043. case DISPID_BEFORENAVIGATE2:
  205044. {
  205045. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205046. String url;
  205047. if ((vurl->vt & VT_BYREF) != 0)
  205048. url = *vurl->pbstrVal;
  205049. else
  205050. url = vurl->bstrVal;
  205051. *pDispParams->rgvarg->pboolVal
  205052. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205053. : VARIANT_TRUE;
  205054. return S_OK;
  205055. }
  205056. default:
  205057. break;
  205058. }
  205059. return E_NOTIMPL;
  205060. }
  205061. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  205062. void componentPeerChanged() {}
  205063. void componentVisibilityChanged (Component&)
  205064. {
  205065. owner->visibilityChanged();
  205066. }
  205067. juce_UseDebuggingNewOperator
  205068. private:
  205069. WebBrowserComponent* const owner;
  205070. int refCount;
  205071. EventHandler (const EventHandler&);
  205072. const EventHandler& operator= (const EventHandler&);
  205073. };
  205074. };
  205075. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  205076. : browser (0),
  205077. blankPageShown (false),
  205078. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  205079. {
  205080. setOpaque (true);
  205081. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205082. }
  205083. WebBrowserComponent::~WebBrowserComponent()
  205084. {
  205085. delete browser;
  205086. }
  205087. void WebBrowserComponent::goToURL (const String& url,
  205088. const StringArray* headers,
  205089. const MemoryBlock* postData)
  205090. {
  205091. lastURL = url;
  205092. lastHeaders.clear();
  205093. if (headers != 0)
  205094. lastHeaders = *headers;
  205095. lastPostData.setSize (0);
  205096. if (postData != 0)
  205097. lastPostData = *postData;
  205098. blankPageShown = false;
  205099. browser->goToURL (url, headers, postData);
  205100. }
  205101. void WebBrowserComponent::stop()
  205102. {
  205103. if (browser->browser != 0)
  205104. browser->browser->Stop();
  205105. }
  205106. void WebBrowserComponent::goBack()
  205107. {
  205108. lastURL = String::empty;
  205109. blankPageShown = false;
  205110. if (browser->browser != 0)
  205111. browser->browser->GoBack();
  205112. }
  205113. void WebBrowserComponent::goForward()
  205114. {
  205115. lastURL = String::empty;
  205116. if (browser->browser != 0)
  205117. browser->browser->GoForward();
  205118. }
  205119. void WebBrowserComponent::refresh()
  205120. {
  205121. if (browser->browser != 0)
  205122. browser->browser->Refresh();
  205123. }
  205124. void WebBrowserComponent::paint (Graphics& g)
  205125. {
  205126. if (browser->browser == 0)
  205127. g.fillAll (Colours::white);
  205128. }
  205129. void WebBrowserComponent::checkWindowAssociation()
  205130. {
  205131. if (isShowing())
  205132. {
  205133. if (browser->browser == 0 && getPeer() != 0)
  205134. {
  205135. browser->createBrowser();
  205136. reloadLastURL();
  205137. }
  205138. else
  205139. {
  205140. if (blankPageShown)
  205141. goBack();
  205142. }
  205143. }
  205144. else
  205145. {
  205146. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  205147. {
  205148. // when the component becomes invisible, some stuff like flash
  205149. // carries on playing audio, so we need to force it onto a blank
  205150. // page to avoid this..
  205151. blankPageShown = true;
  205152. browser->goToURL ("about:blank", 0, 0);
  205153. }
  205154. }
  205155. }
  205156. void WebBrowserComponent::reloadLastURL()
  205157. {
  205158. if (lastURL.isNotEmpty())
  205159. {
  205160. goToURL (lastURL, &lastHeaders, &lastPostData);
  205161. lastURL = String::empty;
  205162. }
  205163. }
  205164. void WebBrowserComponent::parentHierarchyChanged()
  205165. {
  205166. checkWindowAssociation();
  205167. }
  205168. void WebBrowserComponent::resized()
  205169. {
  205170. browser->setSize (getWidth(), getHeight());
  205171. }
  205172. void WebBrowserComponent::visibilityChanged()
  205173. {
  205174. checkWindowAssociation();
  205175. }
  205176. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205177. {
  205178. return true;
  205179. }
  205180. #endif
  205181. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205182. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205183. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205184. // compiled on its own).
  205185. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  205186. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  205187. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  205188. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  205189. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  205190. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  205191. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  205192. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  205193. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  205194. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  205195. #define WGL_ACCELERATION_ARB 0x2003
  205196. #define WGL_SWAP_METHOD_ARB 0x2007
  205197. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  205198. #define WGL_PIXEL_TYPE_ARB 0x2013
  205199. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  205200. #define WGL_COLOR_BITS_ARB 0x2014
  205201. #define WGL_RED_BITS_ARB 0x2015
  205202. #define WGL_GREEN_BITS_ARB 0x2017
  205203. #define WGL_BLUE_BITS_ARB 0x2019
  205204. #define WGL_ALPHA_BITS_ARB 0x201B
  205205. #define WGL_DEPTH_BITS_ARB 0x2022
  205206. #define WGL_STENCIL_BITS_ARB 0x2023
  205207. #define WGL_FULL_ACCELERATION_ARB 0x2027
  205208. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  205209. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  205210. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  205211. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  205212. #define WGL_STEREO_ARB 0x2012
  205213. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  205214. #define WGL_SAMPLES_ARB 0x2042
  205215. #define WGL_TYPE_RGBA_ARB 0x202B
  205216. static void getWglExtensions (HDC dc, StringArray& result) throw()
  205217. {
  205218. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  205219. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  205220. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  205221. else
  205222. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  205223. }
  205224. class WindowedGLContext : public OpenGLContext
  205225. {
  205226. public:
  205227. WindowedGLContext (Component* const component_,
  205228. HGLRC contextToShareWith,
  205229. const OpenGLPixelFormat& pixelFormat)
  205230. : renderContext (0),
  205231. nativeWindow (0),
  205232. dc (0),
  205233. component (component_)
  205234. {
  205235. jassert (component != 0);
  205236. createNativeWindow();
  205237. // Use a default pixel format that should be supported everywhere
  205238. PIXELFORMATDESCRIPTOR pfd;
  205239. zerostruct (pfd);
  205240. pfd.nSize = sizeof (pfd);
  205241. pfd.nVersion = 1;
  205242. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  205243. pfd.iPixelType = PFD_TYPE_RGBA;
  205244. pfd.cColorBits = 24;
  205245. pfd.cDepthBits = 16;
  205246. const int format = ChoosePixelFormat (dc, &pfd);
  205247. if (format != 0)
  205248. SetPixelFormat (dc, format, &pfd);
  205249. renderContext = wglCreateContext (dc);
  205250. makeActive();
  205251. setPixelFormat (pixelFormat);
  205252. if (contextToShareWith != 0 && renderContext != 0)
  205253. wglShareLists (contextToShareWith, renderContext);
  205254. }
  205255. ~WindowedGLContext()
  205256. {
  205257. makeInactive();
  205258. wglDeleteContext (renderContext);
  205259. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205260. delete nativeWindow;
  205261. }
  205262. bool makeActive() const throw()
  205263. {
  205264. jassert (renderContext != 0);
  205265. return wglMakeCurrent (dc, renderContext) != 0;
  205266. }
  205267. bool makeInactive() const throw()
  205268. {
  205269. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  205270. }
  205271. bool isActive() const throw()
  205272. {
  205273. return wglGetCurrentContext() == renderContext;
  205274. }
  205275. const OpenGLPixelFormat getPixelFormat() const
  205276. {
  205277. OpenGLPixelFormat pf;
  205278. makeActive();
  205279. StringArray availableExtensions;
  205280. getWglExtensions (dc, availableExtensions);
  205281. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  205282. return pf;
  205283. }
  205284. void* getRawContext() const throw()
  205285. {
  205286. return renderContext;
  205287. }
  205288. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  205289. {
  205290. makeActive();
  205291. PIXELFORMATDESCRIPTOR pfd;
  205292. zerostruct (pfd);
  205293. pfd.nSize = sizeof (pfd);
  205294. pfd.nVersion = 1;
  205295. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  205296. pfd.iPixelType = PFD_TYPE_RGBA;
  205297. pfd.iLayerType = PFD_MAIN_PLANE;
  205298. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  205299. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  205300. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  205301. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  205302. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  205303. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  205304. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  205305. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  205306. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  205307. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  205308. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  205309. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  205310. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  205311. int format = 0;
  205312. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  205313. StringArray availableExtensions;
  205314. getWglExtensions (dc, availableExtensions);
  205315. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205316. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  205317. {
  205318. int attributes[64];
  205319. int n = 0;
  205320. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  205321. attributes[n++] = GL_TRUE;
  205322. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  205323. attributes[n++] = GL_TRUE;
  205324. attributes[n++] = WGL_ACCELERATION_ARB;
  205325. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  205326. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  205327. attributes[n++] = GL_TRUE;
  205328. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  205329. attributes[n++] = WGL_TYPE_RGBA_ARB;
  205330. attributes[n++] = WGL_COLOR_BITS_ARB;
  205331. attributes[n++] = pfd.cColorBits;
  205332. attributes[n++] = WGL_RED_BITS_ARB;
  205333. attributes[n++] = pixelFormat.redBits;
  205334. attributes[n++] = WGL_GREEN_BITS_ARB;
  205335. attributes[n++] = pixelFormat.greenBits;
  205336. attributes[n++] = WGL_BLUE_BITS_ARB;
  205337. attributes[n++] = pixelFormat.blueBits;
  205338. attributes[n++] = WGL_ALPHA_BITS_ARB;
  205339. attributes[n++] = pixelFormat.alphaBits;
  205340. attributes[n++] = WGL_DEPTH_BITS_ARB;
  205341. attributes[n++] = pixelFormat.depthBufferBits;
  205342. if (pixelFormat.stencilBufferBits > 0)
  205343. {
  205344. attributes[n++] = WGL_STENCIL_BITS_ARB;
  205345. attributes[n++] = pixelFormat.stencilBufferBits;
  205346. }
  205347. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  205348. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  205349. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  205350. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  205351. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  205352. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  205353. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205354. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  205355. if (availableExtensions.contains ("WGL_ARB_multisample")
  205356. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  205357. {
  205358. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  205359. attributes[n++] = 1;
  205360. attributes[n++] = WGL_SAMPLES_ARB;
  205361. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  205362. }
  205363. attributes[n++] = 0;
  205364. UINT formatsCount;
  205365. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  205366. (void) ok;
  205367. jassert (ok);
  205368. }
  205369. else
  205370. {
  205371. format = ChoosePixelFormat (dc, &pfd);
  205372. }
  205373. if (format != 0)
  205374. {
  205375. makeInactive();
  205376. // win32 can't change the pixel format of a window, so need to delete the
  205377. // old one and create a new one..
  205378. jassert (nativeWindow != 0);
  205379. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205380. delete nativeWindow;
  205381. createNativeWindow();
  205382. if (SetPixelFormat (dc, format, &pfd))
  205383. {
  205384. wglDeleteContext (renderContext);
  205385. renderContext = wglCreateContext (dc);
  205386. jassert (renderContext != 0);
  205387. return renderContext != 0;
  205388. }
  205389. }
  205390. return false;
  205391. }
  205392. void updateWindowPosition (int x, int y, int w, int h, int)
  205393. {
  205394. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  205395. x, y, w, h,
  205396. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205397. }
  205398. void repaint()
  205399. {
  205400. int x, y, w, h;
  205401. nativeWindow->getBounds (x, y, w, h);
  205402. nativeWindow->repaint (0, 0, w, h);
  205403. }
  205404. void swapBuffers()
  205405. {
  205406. SwapBuffers (dc);
  205407. }
  205408. bool setSwapInterval (const int numFramesPerSwap)
  205409. {
  205410. makeActive();
  205411. StringArray availableExtensions;
  205412. getWglExtensions (dc, availableExtensions);
  205413. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  205414. return availableExtensions.contains ("WGL_EXT_swap_control")
  205415. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  205416. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  205417. }
  205418. int getSwapInterval() const
  205419. {
  205420. makeActive();
  205421. StringArray availableExtensions;
  205422. getWglExtensions (dc, availableExtensions);
  205423. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  205424. if (availableExtensions.contains ("WGL_EXT_swap_control")
  205425. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  205426. return wglGetSwapIntervalEXT();
  205427. return 0;
  205428. }
  205429. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  205430. {
  205431. jassert (isActive());
  205432. StringArray availableExtensions;
  205433. getWglExtensions (dc, availableExtensions);
  205434. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205435. int numTypes = 0;
  205436. if (availableExtensions.contains("WGL_ARB_pixel_format")
  205437. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205438. {
  205439. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  205440. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  205441. jassertfalse
  205442. }
  205443. else
  205444. {
  205445. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  205446. }
  205447. OpenGLPixelFormat pf;
  205448. for (int i = 0; i < numTypes; ++i)
  205449. {
  205450. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  205451. {
  205452. bool alreadyListed = false;
  205453. for (int j = results.size(); --j >= 0;)
  205454. if (pf == *results.getUnchecked(j))
  205455. alreadyListed = true;
  205456. if (! alreadyListed)
  205457. results.add (new OpenGLPixelFormat (pf));
  205458. }
  205459. }
  205460. }
  205461. void* getNativeWindowHandle() const
  205462. {
  205463. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  205464. }
  205465. juce_UseDebuggingNewOperator
  205466. HGLRC renderContext;
  205467. private:
  205468. Win32ComponentPeer* nativeWindow;
  205469. Component* const component;
  205470. HDC dc;
  205471. void createNativeWindow()
  205472. {
  205473. nativeWindow = new Win32ComponentPeer (component, 0);
  205474. nativeWindow->dontRepaint = true;
  205475. nativeWindow->setVisible (true);
  205476. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  205477. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  205478. if (peer != 0)
  205479. {
  205480. SetParent (hwnd, (HWND) peer->getNativeHandle());
  205481. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  205482. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  205483. }
  205484. dc = GetDC (hwnd);
  205485. }
  205486. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  205487. OpenGLPixelFormat& result,
  205488. const StringArray& availableExtensions) const throw()
  205489. {
  205490. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205491. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205492. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205493. {
  205494. int attributes[32];
  205495. int numAttributes = 0;
  205496. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  205497. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  205498. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  205499. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  205500. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  205501. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  205502. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  205503. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  205504. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  205505. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  205506. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  205507. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  205508. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  205509. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  205510. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205511. if (availableExtensions.contains ("WGL_ARB_multisample"))
  205512. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  205513. int values[32];
  205514. zeromem (values, sizeof (values));
  205515. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  205516. {
  205517. int n = 0;
  205518. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  205519. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  205520. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  205521. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  205522. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  205523. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  205524. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  205525. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  205526. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  205527. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  205528. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  205529. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  205530. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  205531. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  205532. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  205533. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  205534. return isValidFormat;
  205535. }
  205536. else
  205537. {
  205538. jassertfalse
  205539. }
  205540. }
  205541. else
  205542. {
  205543. PIXELFORMATDESCRIPTOR pfd;
  205544. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  205545. {
  205546. result.redBits = pfd.cRedBits;
  205547. result.greenBits = pfd.cGreenBits;
  205548. result.blueBits = pfd.cBlueBits;
  205549. result.alphaBits = pfd.cAlphaBits;
  205550. result.depthBufferBits = pfd.cDepthBits;
  205551. result.stencilBufferBits = pfd.cStencilBits;
  205552. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  205553. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  205554. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  205555. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  205556. result.fullSceneAntiAliasingNumSamples = 0;
  205557. return true;
  205558. }
  205559. else
  205560. {
  205561. jassertfalse
  205562. }
  205563. }
  205564. return false;
  205565. }
  205566. WindowedGLContext (const WindowedGLContext&);
  205567. const WindowedGLContext& operator= (const WindowedGLContext&);
  205568. };
  205569. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  205570. const OpenGLPixelFormat& pixelFormat,
  205571. const OpenGLContext* const contextToShareWith)
  205572. {
  205573. WindowedGLContext* c = new WindowedGLContext (component,
  205574. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  205575. pixelFormat);
  205576. if (c->renderContext == 0)
  205577. deleteAndZero (c);
  205578. return c;
  205579. }
  205580. void* OpenGLComponent::getNativeWindowHandle() const
  205581. {
  205582. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  205583. }
  205584. void juce_glViewport (const int w, const int h)
  205585. {
  205586. glViewport (0, 0, w, h);
  205587. }
  205588. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  205589. OwnedArray <OpenGLPixelFormat>& results)
  205590. {
  205591. Component tempComp;
  205592. {
  205593. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  205594. wc.makeActive();
  205595. wc.findAlternativeOpenGLPixelFormats (results);
  205596. }
  205597. }
  205598. #endif
  205599. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205600. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  205601. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205602. // compiled on its own).
  205603. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  205604. //***************************************************************************
  205605. // %%% TARGET STATUS VALUES %%%
  205606. //***************************************************************************
  205607. #define STATUS_GOOD 0x00 // Status Good
  205608. #define STATUS_CHKCOND 0x02 // Check Condition
  205609. #define STATUS_CONDMET 0x04 // Condition Met
  205610. #define STATUS_BUSY 0x08 // Busy
  205611. #define STATUS_INTERM 0x10 // Intermediate
  205612. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  205613. #define STATUS_RESCONF 0x18 // Reservation conflict
  205614. #define STATUS_COMTERM 0x22 // Command Terminated
  205615. #define STATUS_QFULL 0x28 // Queue full
  205616. //***************************************************************************
  205617. // %%% SCSI MISCELLANEOUS EQUATES %%%
  205618. //***************************************************************************
  205619. #define MAXLUN 7 // Maximum Logical Unit Id
  205620. #define MAXTARG 7 // Maximum Target Id
  205621. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  205622. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  205623. //***************************************************************************
  205624. // %%% Commands for all Device Types %%%
  205625. //***************************************************************************
  205626. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  205627. #define SCSI_COMPARE 0x39 // Compare (O)
  205628. #define SCSI_COPY 0x18 // Copy (O)
  205629. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  205630. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  205631. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  205632. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  205633. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  205634. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  205635. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  205636. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  205637. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  205638. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  205639. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  205640. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  205641. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  205642. //***************************************************************************
  205643. // %%% Commands Unique to Direct Access Devices %%%
  205644. //***************************************************************************
  205645. #define SCSI_COMPARE 0x39 // Compare (O)
  205646. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  205647. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  205648. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  205649. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  205650. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  205651. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  205652. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  205653. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  205654. #define SCSI_READ_LONG 0x3E // Read Long (O)
  205655. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  205656. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  205657. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  205658. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  205659. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  205660. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  205661. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  205662. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  205663. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  205664. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  205665. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  205666. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  205667. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  205668. #define SCSI_VERIFY 0x2F // Verify (O)
  205669. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  205670. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  205671. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  205672. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  205673. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  205674. //***************************************************************************
  205675. // %%% Commands Unique to Sequential Access Devices %%%
  205676. //***************************************************************************
  205677. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  205678. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  205679. #define SCSI_LOCATE 0x2B // Locate (O)
  205680. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  205681. #define SCSI_READ_POS 0x34 // Read Position (O)
  205682. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  205683. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  205684. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  205685. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  205686. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  205687. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  205688. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  205689. //***************************************************************************
  205690. // %%% Commands Unique to Printer Devices %%%
  205691. //***************************************************************************
  205692. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  205693. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  205694. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  205695. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  205696. //***************************************************************************
  205697. // %%% Commands Unique to Processor Devices %%%
  205698. //***************************************************************************
  205699. #define SCSI_RECEIVE 0x08 // Receive (O)
  205700. #define SCSI_SEND 0x0A // Send (O)
  205701. //***************************************************************************
  205702. // %%% Commands Unique to Write-Once Devices %%%
  205703. //***************************************************************************
  205704. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  205705. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  205706. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  205707. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  205708. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  205709. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  205710. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  205711. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  205712. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  205713. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  205714. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  205715. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  205716. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  205717. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  205718. //***************************************************************************
  205719. // %%% Commands Unique to CD-ROM Devices %%%
  205720. //***************************************************************************
  205721. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  205722. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  205723. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  205724. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  205725. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  205726. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  205727. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  205728. #define SCSI_READHEADER 0x44 // Read Header (O)
  205729. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  205730. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  205731. //***************************************************************************
  205732. // %%% Commands Unique to Scanner Devices %%%
  205733. //***************************************************************************
  205734. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  205735. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  205736. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  205737. #define SCSI_SCAN 0x1B // Scan (O)
  205738. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  205739. //***************************************************************************
  205740. // %%% Commands Unique to Optical Memory Devices %%%
  205741. //***************************************************************************
  205742. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  205743. //***************************************************************************
  205744. // %%% Commands Unique to Medium Changer Devices %%%
  205745. //***************************************************************************
  205746. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  205747. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  205748. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  205749. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  205750. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  205751. //***************************************************************************
  205752. // %%% Commands Unique to Communication Devices %%%
  205753. //***************************************************************************
  205754. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  205755. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  205756. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  205757. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  205758. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  205759. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  205760. //***************************************************************************
  205761. // %%% Request Sense Data Format %%%
  205762. //***************************************************************************
  205763. typedef struct {
  205764. BYTE ErrorCode; // Error Code (70H or 71H)
  205765. BYTE SegmentNum; // Number of current segment descriptor
  205766. BYTE SenseKey; // Sense Key(See bit definitions too)
  205767. BYTE InfoByte0; // Information MSB
  205768. BYTE InfoByte1; // Information MID
  205769. BYTE InfoByte2; // Information MID
  205770. BYTE InfoByte3; // Information LSB
  205771. BYTE AddSenLen; // Additional Sense Length
  205772. BYTE ComSpecInf0; // Command Specific Information MSB
  205773. BYTE ComSpecInf1; // Command Specific Information MID
  205774. BYTE ComSpecInf2; // Command Specific Information MID
  205775. BYTE ComSpecInf3; // Command Specific Information LSB
  205776. BYTE AddSenseCode; // Additional Sense Code
  205777. BYTE AddSenQual; // Additional Sense Code Qualifier
  205778. BYTE FieldRepUCode; // Field Replaceable Unit Code
  205779. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  205780. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  205781. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  205782. BYTE AddSenseBytes; // Additional Sense Bytes
  205783. } SENSE_DATA_FMT;
  205784. //***************************************************************************
  205785. // %%% REQUEST SENSE ERROR CODE %%%
  205786. //***************************************************************************
  205787. #define SERROR_CURRENT 0x70 // Current Errors
  205788. #define SERROR_DEFERED 0x71 // Deferred Errors
  205789. //***************************************************************************
  205790. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  205791. //***************************************************************************
  205792. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  205793. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  205794. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  205795. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  205796. //***************************************************************************
  205797. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  205798. //***************************************************************************
  205799. #define KEY_NOSENSE 0x00 // No Sense
  205800. #define KEY_RECERROR 0x01 // Recovered Error
  205801. #define KEY_NOTREADY 0x02 // Not Ready
  205802. #define KEY_MEDIUMERR 0x03 // Medium Error
  205803. #define KEY_HARDERROR 0x04 // Hardware Error
  205804. #define KEY_ILLGLREQ 0x05 // Illegal Request
  205805. #define KEY_UNITATT 0x06 // Unit Attention
  205806. #define KEY_DATAPROT 0x07 // Data Protect
  205807. #define KEY_BLANKCHK 0x08 // Blank Check
  205808. #define KEY_VENDSPEC 0x09 // Vendor Specific
  205809. #define KEY_COPYABORT 0x0A // Copy Abort
  205810. #define KEY_EQUAL 0x0C // Equal (Search)
  205811. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  205812. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  205813. #define KEY_RESERVED 0x0F // Reserved
  205814. //***************************************************************************
  205815. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  205816. //***************************************************************************
  205817. #define DTYPE_DASD 0x00 // Disk Device
  205818. #define DTYPE_SEQD 0x01 // Tape Device
  205819. #define DTYPE_PRNT 0x02 // Printer
  205820. #define DTYPE_PROC 0x03 // Processor
  205821. #define DTYPE_WORM 0x04 // Write-once read-multiple
  205822. #define DTYPE_CROM 0x05 // CD-ROM device
  205823. #define DTYPE_SCAN 0x06 // Scanner device
  205824. #define DTYPE_OPTI 0x07 // Optical memory device
  205825. #define DTYPE_JUKE 0x08 // Medium Changer device
  205826. #define DTYPE_COMM 0x09 // Communications device
  205827. #define DTYPE_RESL 0x0A // Reserved (low)
  205828. #define DTYPE_RESH 0x1E // Reserved (high)
  205829. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  205830. //***************************************************************************
  205831. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  205832. //***************************************************************************
  205833. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  205834. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  205835. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  205836. #define ANSI_RESLO 0x3 // Reserved (low)
  205837. #define ANSI_RESHI 0x7 // Reserved (high)
  205838. typedef struct
  205839. {
  205840. USHORT Length;
  205841. UCHAR ScsiStatus;
  205842. UCHAR PathId;
  205843. UCHAR TargetId;
  205844. UCHAR Lun;
  205845. UCHAR CdbLength;
  205846. UCHAR SenseInfoLength;
  205847. UCHAR DataIn;
  205848. ULONG DataTransferLength;
  205849. ULONG TimeOutValue;
  205850. ULONG DataBufferOffset;
  205851. ULONG SenseInfoOffset;
  205852. UCHAR Cdb[16];
  205853. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  205854. typedef struct
  205855. {
  205856. USHORT Length;
  205857. UCHAR ScsiStatus;
  205858. UCHAR PathId;
  205859. UCHAR TargetId;
  205860. UCHAR Lun;
  205861. UCHAR CdbLength;
  205862. UCHAR SenseInfoLength;
  205863. UCHAR DataIn;
  205864. ULONG DataTransferLength;
  205865. ULONG TimeOutValue;
  205866. PVOID DataBuffer;
  205867. ULONG SenseInfoOffset;
  205868. UCHAR Cdb[16];
  205869. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  205870. typedef struct
  205871. {
  205872. SCSI_PASS_THROUGH_DIRECT spt;
  205873. ULONG Filler;
  205874. UCHAR ucSenseBuf[32];
  205875. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  205876. typedef struct
  205877. {
  205878. ULONG Length;
  205879. UCHAR PortNumber;
  205880. UCHAR PathId;
  205881. UCHAR TargetId;
  205882. UCHAR Lun;
  205883. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  205884. #define METHOD_BUFFERED 0
  205885. #define METHOD_IN_DIRECT 1
  205886. #define METHOD_OUT_DIRECT 2
  205887. #define METHOD_NEITHER 3
  205888. #define FILE_ANY_ACCESS 0
  205889. #ifndef FILE_READ_ACCESS
  205890. #define FILE_READ_ACCESS (0x0001)
  205891. #endif
  205892. #ifndef FILE_WRITE_ACCESS
  205893. #define FILE_WRITE_ACCESS (0x0002)
  205894. #endif
  205895. #define IOCTL_SCSI_BASE 0x00000004
  205896. #define SCSI_IOCTL_DATA_OUT 0
  205897. #define SCSI_IOCTL_DATA_IN 1
  205898. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  205899. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  205900. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  205901. )
  205902. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205903. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  205904. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205905. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  205906. #define SENSE_LEN 14
  205907. #define SRB_DIR_SCSI 0x00
  205908. #define SRB_POSTING 0x01
  205909. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  205910. #define SRB_DIR_IN 0x08
  205911. #define SRB_DIR_OUT 0x10
  205912. #define SRB_EVENT_NOTIFY 0x40
  205913. #define RESIDUAL_COUNT_SUPPORTED 0x02
  205914. #define MAX_SRB_TIMEOUT 1080001u
  205915. #define DEFAULT_SRB_TIMEOUT 1080001u
  205916. #define SC_HA_INQUIRY 0x00
  205917. #define SC_GET_DEV_TYPE 0x01
  205918. #define SC_EXEC_SCSI_CMD 0x02
  205919. #define SC_ABORT_SRB 0x03
  205920. #define SC_RESET_DEV 0x04
  205921. #define SC_SET_HA_PARMS 0x05
  205922. #define SC_GET_DISK_INFO 0x06
  205923. #define SC_RESCAN_SCSI_BUS 0x07
  205924. #define SC_GETSET_TIMEOUTS 0x08
  205925. #define SS_PENDING 0x00
  205926. #define SS_COMP 0x01
  205927. #define SS_ABORTED 0x02
  205928. #define SS_ABORT_FAIL 0x03
  205929. #define SS_ERR 0x04
  205930. #define SS_INVALID_CMD 0x80
  205931. #define SS_INVALID_HA 0x81
  205932. #define SS_NO_DEVICE 0x82
  205933. #define SS_INVALID_SRB 0xE0
  205934. #define SS_OLD_MANAGER 0xE1
  205935. #define SS_BUFFER_ALIGN 0xE1
  205936. #define SS_ILLEGAL_MODE 0xE2
  205937. #define SS_NO_ASPI 0xE3
  205938. #define SS_FAILED_INIT 0xE4
  205939. #define SS_ASPI_IS_BUSY 0xE5
  205940. #define SS_BUFFER_TO_BIG 0xE6
  205941. #define SS_BUFFER_TOO_BIG 0xE6
  205942. #define SS_MISMATCHED_COMPONENTS 0xE7
  205943. #define SS_NO_ADAPTERS 0xE8
  205944. #define SS_INSUFFICIENT_RESOURCES 0xE9
  205945. #define SS_ASPI_IS_SHUTDOWN 0xEA
  205946. #define SS_BAD_INSTALL 0xEB
  205947. #define HASTAT_OK 0x00
  205948. #define HASTAT_SEL_TO 0x11
  205949. #define HASTAT_DO_DU 0x12
  205950. #define HASTAT_BUS_FREE 0x13
  205951. #define HASTAT_PHASE_ERR 0x14
  205952. #define HASTAT_TIMEOUT 0x09
  205953. #define HASTAT_COMMAND_TIMEOUT 0x0B
  205954. #define HASTAT_MESSAGE_REJECT 0x0D
  205955. #define HASTAT_BUS_RESET 0x0E
  205956. #define HASTAT_PARITY_ERROR 0x0F
  205957. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  205958. #define PACKED
  205959. #pragma pack(1)
  205960. typedef struct
  205961. {
  205962. BYTE SRB_Cmd;
  205963. BYTE SRB_Status;
  205964. BYTE SRB_HaID;
  205965. BYTE SRB_Flags;
  205966. DWORD SRB_Hdr_Rsvd;
  205967. BYTE HA_Count;
  205968. BYTE HA_SCSI_ID;
  205969. BYTE HA_ManagerId[16];
  205970. BYTE HA_Identifier[16];
  205971. BYTE HA_Unique[16];
  205972. WORD HA_Rsvd1;
  205973. BYTE pad[20];
  205974. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  205975. typedef struct
  205976. {
  205977. BYTE SRB_Cmd;
  205978. BYTE SRB_Status;
  205979. BYTE SRB_HaID;
  205980. BYTE SRB_Flags;
  205981. DWORD SRB_Hdr_Rsvd;
  205982. BYTE SRB_Target;
  205983. BYTE SRB_Lun;
  205984. BYTE SRB_DeviceType;
  205985. BYTE SRB_Rsvd1;
  205986. BYTE pad[68];
  205987. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  205988. typedef struct
  205989. {
  205990. BYTE SRB_Cmd;
  205991. BYTE SRB_Status;
  205992. BYTE SRB_HaID;
  205993. BYTE SRB_Flags;
  205994. DWORD SRB_Hdr_Rsvd;
  205995. BYTE SRB_Target;
  205996. BYTE SRB_Lun;
  205997. WORD SRB_Rsvd1;
  205998. DWORD SRB_BufLen;
  205999. BYTE FAR *SRB_BufPointer;
  206000. BYTE SRB_SenseLen;
  206001. BYTE SRB_CDBLen;
  206002. BYTE SRB_HaStat;
  206003. BYTE SRB_TargStat;
  206004. VOID FAR *SRB_PostProc;
  206005. BYTE SRB_Rsvd2[20];
  206006. BYTE CDBByte[16];
  206007. BYTE SenseArea[SENSE_LEN+2];
  206008. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  206009. typedef struct
  206010. {
  206011. BYTE SRB_Cmd;
  206012. BYTE SRB_Status;
  206013. BYTE SRB_HaId;
  206014. BYTE SRB_Flags;
  206015. DWORD SRB_Hdr_Rsvd;
  206016. } PACKED SRB, *PSRB, FAR *LPSRB;
  206017. #pragma pack()
  206018. struct CDDeviceInfo
  206019. {
  206020. char vendor[9];
  206021. char productId[17];
  206022. char rev[5];
  206023. char vendorSpec[21];
  206024. BYTE ha;
  206025. BYTE tgt;
  206026. BYTE lun;
  206027. char scsiDriveLetter; // will be 0 if not using scsi
  206028. };
  206029. class CDReadBuffer
  206030. {
  206031. public:
  206032. int startFrame;
  206033. int numFrames;
  206034. int dataStartOffset;
  206035. int dataLength;
  206036. BYTE* buffer;
  206037. int bufferSize;
  206038. int index;
  206039. bool wantsIndex;
  206040. CDReadBuffer (const int numberOfFrames)
  206041. : startFrame (0),
  206042. numFrames (0),
  206043. dataStartOffset (0),
  206044. dataLength (0),
  206045. index (0),
  206046. wantsIndex (false)
  206047. {
  206048. bufferSize = 2352 * numberOfFrames;
  206049. buffer = (BYTE*) malloc (bufferSize);
  206050. }
  206051. ~CDReadBuffer()
  206052. {
  206053. free (buffer);
  206054. }
  206055. bool isZero() const
  206056. {
  206057. BYTE* p = buffer + dataStartOffset;
  206058. for (int i = dataLength; --i >= 0;)
  206059. if (*p++ != 0)
  206060. return false;
  206061. return true;
  206062. }
  206063. };
  206064. class CDDeviceHandle;
  206065. class CDController
  206066. {
  206067. public:
  206068. CDController();
  206069. virtual ~CDController();
  206070. virtual bool read (CDReadBuffer* t) = 0;
  206071. virtual void shutDown();
  206072. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  206073. int getLastIndex();
  206074. public:
  206075. bool initialised;
  206076. CDDeviceHandle* deviceInfo;
  206077. int framesToCheck, framesOverlap;
  206078. void prepare (SRB_ExecSCSICmd& s);
  206079. void perform (SRB_ExecSCSICmd& s);
  206080. void setPaused (bool paused);
  206081. };
  206082. #pragma pack(1)
  206083. struct TOCTRACK
  206084. {
  206085. BYTE rsvd;
  206086. BYTE ADR;
  206087. BYTE trackNumber;
  206088. BYTE rsvd2;
  206089. BYTE addr[4];
  206090. };
  206091. struct TOC
  206092. {
  206093. WORD tocLen;
  206094. BYTE firstTrack;
  206095. BYTE lastTrack;
  206096. TOCTRACK tracks[100];
  206097. };
  206098. #pragma pack()
  206099. enum
  206100. {
  206101. READTYPE_ANY = 0,
  206102. READTYPE_ATAPI1 = 1,
  206103. READTYPE_ATAPI2 = 2,
  206104. READTYPE_READ6 = 3,
  206105. READTYPE_READ10 = 4,
  206106. READTYPE_READ_D8 = 5,
  206107. READTYPE_READ_D4 = 6,
  206108. READTYPE_READ_D4_1 = 7,
  206109. READTYPE_READ10_2 = 8
  206110. };
  206111. class CDDeviceHandle
  206112. {
  206113. public:
  206114. CDDeviceHandle (const CDDeviceInfo* const device)
  206115. : scsiHandle (0),
  206116. readType (READTYPE_ANY),
  206117. controller (0)
  206118. {
  206119. memcpy (&info, device, sizeof (info));
  206120. }
  206121. ~CDDeviceHandle()
  206122. {
  206123. if (controller != 0)
  206124. {
  206125. controller->shutDown();
  206126. delete controller;
  206127. }
  206128. if (scsiHandle != 0)
  206129. CloseHandle (scsiHandle);
  206130. }
  206131. bool readTOC (TOC* lpToc, bool useMSF);
  206132. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  206133. void openDrawer (bool shouldBeOpen);
  206134. CDDeviceInfo info;
  206135. HANDLE scsiHandle;
  206136. BYTE readType;
  206137. private:
  206138. CDController* controller;
  206139. bool testController (const int readType,
  206140. CDController* const newController,
  206141. CDReadBuffer* const bufferToUse);
  206142. };
  206143. DWORD (*fGetASPI32SupportInfo)(void);
  206144. DWORD (*fSendASPI32Command)(LPSRB);
  206145. static HINSTANCE winAspiLib = 0;
  206146. static bool usingScsi = false;
  206147. static bool initialised = false;
  206148. static bool InitialiseCDRipper()
  206149. {
  206150. if (! initialised)
  206151. {
  206152. initialised = true;
  206153. OSVERSIONINFO info;
  206154. info.dwOSVersionInfoSize = sizeof (info);
  206155. GetVersionEx (&info);
  206156. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  206157. if (! usingScsi)
  206158. {
  206159. fGetASPI32SupportInfo = 0;
  206160. fSendASPI32Command = 0;
  206161. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  206162. if (winAspiLib != 0)
  206163. {
  206164. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  206165. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  206166. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  206167. return false;
  206168. }
  206169. else
  206170. {
  206171. usingScsi = true;
  206172. }
  206173. }
  206174. }
  206175. return true;
  206176. }
  206177. static void DeinitialiseCDRipper()
  206178. {
  206179. if (winAspiLib != 0)
  206180. {
  206181. fGetASPI32SupportInfo = 0;
  206182. fSendASPI32Command = 0;
  206183. FreeLibrary (winAspiLib);
  206184. winAspiLib = 0;
  206185. }
  206186. initialised = false;
  206187. }
  206188. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  206189. {
  206190. TCHAR devicePath[8];
  206191. devicePath[0] = '\\';
  206192. devicePath[1] = '\\';
  206193. devicePath[2] = '.';
  206194. devicePath[3] = '\\';
  206195. devicePath[4] = driveLetter;
  206196. devicePath[5] = ':';
  206197. devicePath[6] = 0;
  206198. OSVERSIONINFO info;
  206199. info.dwOSVersionInfoSize = sizeof (info);
  206200. GetVersionEx (&info);
  206201. DWORD flags = GENERIC_READ;
  206202. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  206203. flags = GENERIC_READ | GENERIC_WRITE;
  206204. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206205. if (h == INVALID_HANDLE_VALUE)
  206206. {
  206207. flags ^= GENERIC_WRITE;
  206208. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206209. }
  206210. return h;
  206211. }
  206212. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  206213. const char driveLetter,
  206214. HANDLE& deviceHandle,
  206215. const bool retryOnFailure = true)
  206216. {
  206217. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  206218. zerostruct (s);
  206219. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  206220. s.spt.CdbLength = srb->SRB_CDBLen;
  206221. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  206222. ? SCSI_IOCTL_DATA_IN
  206223. : ((srb->SRB_Flags & SRB_DIR_OUT)
  206224. ? SCSI_IOCTL_DATA_OUT
  206225. : SCSI_IOCTL_DATA_UNSPECIFIED));
  206226. s.spt.DataTransferLength = srb->SRB_BufLen;
  206227. s.spt.TimeOutValue = 5;
  206228. s.spt.DataBuffer = srb->SRB_BufPointer;
  206229. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206230. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  206231. srb->SRB_Status = SS_ERR;
  206232. srb->SRB_TargStat = 0x0004;
  206233. DWORD bytesReturned = 0;
  206234. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206235. &s, sizeof (s),
  206236. &s, sizeof (s),
  206237. &bytesReturned, 0) != 0)
  206238. {
  206239. srb->SRB_Status = SS_COMP;
  206240. }
  206241. else if (retryOnFailure)
  206242. {
  206243. const DWORD error = GetLastError();
  206244. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  206245. {
  206246. if (error != ERROR_INVALID_HANDLE)
  206247. CloseHandle (deviceHandle);
  206248. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  206249. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  206250. }
  206251. }
  206252. return srb->SRB_Status;
  206253. }
  206254. // Controller types..
  206255. class ControllerType1 : public CDController
  206256. {
  206257. public:
  206258. ControllerType1() {}
  206259. ~ControllerType1() {}
  206260. bool read (CDReadBuffer* rb)
  206261. {
  206262. if (rb->numFrames * 2352 > rb->bufferSize)
  206263. return false;
  206264. SRB_ExecSCSICmd s;
  206265. prepare (s);
  206266. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206267. s.SRB_BufLen = rb->bufferSize;
  206268. s.SRB_BufPointer = rb->buffer;
  206269. s.SRB_CDBLen = 12;
  206270. s.CDBByte[0] = 0xBE;
  206271. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206272. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206273. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206274. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206275. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  206276. perform (s);
  206277. if (s.SRB_Status != SS_COMP)
  206278. return false;
  206279. rb->dataLength = rb->numFrames * 2352;
  206280. rb->dataStartOffset = 0;
  206281. return true;
  206282. }
  206283. };
  206284. class ControllerType2 : public CDController
  206285. {
  206286. public:
  206287. ControllerType2() {}
  206288. ~ControllerType2() {}
  206289. void shutDown()
  206290. {
  206291. if (initialised)
  206292. {
  206293. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  206294. SRB_ExecSCSICmd s;
  206295. prepare (s);
  206296. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  206297. s.SRB_BufLen = 0x0C;
  206298. s.SRB_BufPointer = bufPointer;
  206299. s.SRB_CDBLen = 6;
  206300. s.CDBByte[0] = 0x15;
  206301. s.CDBByte[4] = 0x0C;
  206302. perform (s);
  206303. }
  206304. }
  206305. bool init()
  206306. {
  206307. SRB_ExecSCSICmd s;
  206308. s.SRB_Status = SS_ERR;
  206309. if (deviceInfo->readType == READTYPE_READ10_2)
  206310. {
  206311. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  206312. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  206313. for (int i = 0; i < 2; ++i)
  206314. {
  206315. prepare (s);
  206316. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206317. s.SRB_BufLen = 0x14;
  206318. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  206319. s.SRB_CDBLen = 6;
  206320. s.CDBByte[0] = 0x15;
  206321. s.CDBByte[1] = 0x10;
  206322. s.CDBByte[4] = 0x14;
  206323. perform (s);
  206324. if (s.SRB_Status != SS_COMP)
  206325. return false;
  206326. }
  206327. }
  206328. else
  206329. {
  206330. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  206331. prepare (s);
  206332. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206333. s.SRB_BufLen = 0x0C;
  206334. s.SRB_BufPointer = bufPointer;
  206335. s.SRB_CDBLen = 6;
  206336. s.CDBByte[0] = 0x15;
  206337. s.CDBByte[4] = 0x0C;
  206338. perform (s);
  206339. }
  206340. return s.SRB_Status == SS_COMP;
  206341. }
  206342. bool read (CDReadBuffer* rb)
  206343. {
  206344. if (rb->numFrames * 2352 > rb->bufferSize)
  206345. return false;
  206346. if (!initialised)
  206347. {
  206348. initialised = init();
  206349. if (!initialised)
  206350. return false;
  206351. }
  206352. SRB_ExecSCSICmd s;
  206353. prepare (s);
  206354. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206355. s.SRB_BufLen = rb->bufferSize;
  206356. s.SRB_BufPointer = rb->buffer;
  206357. s.SRB_CDBLen = 10;
  206358. s.CDBByte[0] = 0x28;
  206359. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206360. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206361. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206362. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206363. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206364. perform (s);
  206365. if (s.SRB_Status != SS_COMP)
  206366. return false;
  206367. rb->dataLength = rb->numFrames * 2352;
  206368. rb->dataStartOffset = 0;
  206369. return true;
  206370. }
  206371. };
  206372. class ControllerType3 : public CDController
  206373. {
  206374. public:
  206375. ControllerType3() {}
  206376. ~ControllerType3() {}
  206377. bool read (CDReadBuffer* rb)
  206378. {
  206379. if (rb->numFrames * 2352 > rb->bufferSize)
  206380. return false;
  206381. if (!initialised)
  206382. {
  206383. setPaused (false);
  206384. initialised = true;
  206385. }
  206386. SRB_ExecSCSICmd s;
  206387. prepare (s);
  206388. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206389. s.SRB_BufLen = rb->numFrames * 2352;
  206390. s.SRB_BufPointer = rb->buffer;
  206391. s.SRB_CDBLen = 12;
  206392. s.CDBByte[0] = 0xD8;
  206393. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206394. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206395. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206396. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  206397. perform (s);
  206398. if (s.SRB_Status != SS_COMP)
  206399. return false;
  206400. rb->dataLength = rb->numFrames * 2352;
  206401. rb->dataStartOffset = 0;
  206402. return true;
  206403. }
  206404. };
  206405. class ControllerType4 : public CDController
  206406. {
  206407. public:
  206408. ControllerType4() {}
  206409. ~ControllerType4() {}
  206410. bool selectD4Mode()
  206411. {
  206412. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  206413. SRB_ExecSCSICmd s;
  206414. prepare (s);
  206415. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206416. s.SRB_CDBLen = 6;
  206417. s.SRB_BufLen = 12;
  206418. s.SRB_BufPointer = bufPointer;
  206419. s.CDBByte[0] = 0x15;
  206420. s.CDBByte[1] = 0x10;
  206421. s.CDBByte[4] = 0x08;
  206422. perform (s);
  206423. return s.SRB_Status == SS_COMP;
  206424. }
  206425. bool read (CDReadBuffer* rb)
  206426. {
  206427. if (rb->numFrames * 2352 > rb->bufferSize)
  206428. return false;
  206429. if (!initialised)
  206430. {
  206431. setPaused (true);
  206432. if (deviceInfo->readType == READTYPE_READ_D4_1)
  206433. selectD4Mode();
  206434. initialised = true;
  206435. }
  206436. SRB_ExecSCSICmd s;
  206437. prepare (s);
  206438. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206439. s.SRB_BufLen = rb->bufferSize;
  206440. s.SRB_BufPointer = rb->buffer;
  206441. s.SRB_CDBLen = 10;
  206442. s.CDBByte[0] = 0xD4;
  206443. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206444. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206445. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206446. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206447. perform (s);
  206448. if (s.SRB_Status != SS_COMP)
  206449. return false;
  206450. rb->dataLength = rb->numFrames * 2352;
  206451. rb->dataStartOffset = 0;
  206452. return true;
  206453. }
  206454. };
  206455. CDController::CDController() : initialised (false)
  206456. {
  206457. }
  206458. CDController::~CDController()
  206459. {
  206460. }
  206461. void CDController::prepare (SRB_ExecSCSICmd& s)
  206462. {
  206463. zerostruct (s);
  206464. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206465. s.SRB_HaID = deviceInfo->info.ha;
  206466. s.SRB_Target = deviceInfo->info.tgt;
  206467. s.SRB_Lun = deviceInfo->info.lun;
  206468. s.SRB_SenseLen = SENSE_LEN;
  206469. }
  206470. void CDController::perform (SRB_ExecSCSICmd& s)
  206471. {
  206472. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206473. s.SRB_PostProc = (void*)event;
  206474. ResetEvent (event);
  206475. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  206476. deviceInfo->info.scsiDriveLetter,
  206477. deviceInfo->scsiHandle)
  206478. : fSendASPI32Command ((LPSRB)&s);
  206479. if (status == SS_PENDING)
  206480. WaitForSingleObject (event, 4000);
  206481. CloseHandle (event);
  206482. }
  206483. void CDController::setPaused (bool paused)
  206484. {
  206485. SRB_ExecSCSICmd s;
  206486. prepare (s);
  206487. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206488. s.SRB_CDBLen = 10;
  206489. s.CDBByte[0] = 0x4B;
  206490. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  206491. perform (s);
  206492. }
  206493. void CDController::shutDown()
  206494. {
  206495. }
  206496. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  206497. {
  206498. if (overlapBuffer != 0)
  206499. {
  206500. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  206501. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  206502. if (doJitter
  206503. && overlapBuffer->startFrame > 0
  206504. && overlapBuffer->numFrames > 0
  206505. && overlapBuffer->dataLength > 0)
  206506. {
  206507. const int numFrames = rb->numFrames;
  206508. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  206509. {
  206510. rb->startFrame -= framesOverlap;
  206511. if (framesToCheck < framesOverlap
  206512. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  206513. rb->numFrames += framesOverlap;
  206514. }
  206515. else
  206516. {
  206517. overlapBuffer->dataLength = 0;
  206518. overlapBuffer->startFrame = 0;
  206519. overlapBuffer->numFrames = 0;
  206520. }
  206521. }
  206522. if (! read (rb))
  206523. return false;
  206524. if (doJitter)
  206525. {
  206526. const int checkLen = framesToCheck * 2352;
  206527. const int maxToCheck = rb->dataLength - checkLen;
  206528. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  206529. return true;
  206530. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  206531. bool found = false;
  206532. for (int i = 0; i < maxToCheck; ++i)
  206533. {
  206534. if (!memcmp (p, rb->buffer + i, checkLen))
  206535. {
  206536. i += checkLen;
  206537. rb->dataStartOffset = i;
  206538. rb->dataLength -= i;
  206539. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  206540. found = true;
  206541. break;
  206542. }
  206543. }
  206544. rb->numFrames = rb->dataLength / 2352;
  206545. rb->dataLength = 2352 * rb->numFrames;
  206546. if (!found)
  206547. return false;
  206548. }
  206549. if (canDoJitter)
  206550. {
  206551. memcpy (overlapBuffer->buffer,
  206552. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  206553. 2352 * framesToCheck);
  206554. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  206555. overlapBuffer->numFrames = framesToCheck;
  206556. overlapBuffer->dataLength = 2352 * framesToCheck;
  206557. overlapBuffer->dataStartOffset = 0;
  206558. }
  206559. else
  206560. {
  206561. overlapBuffer->startFrame = 0;
  206562. overlapBuffer->numFrames = 0;
  206563. overlapBuffer->dataLength = 0;
  206564. }
  206565. return true;
  206566. }
  206567. else
  206568. {
  206569. return read (rb);
  206570. }
  206571. }
  206572. int CDController::getLastIndex()
  206573. {
  206574. char qdata[100];
  206575. SRB_ExecSCSICmd s;
  206576. prepare (s);
  206577. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206578. s.SRB_BufLen = sizeof (qdata);
  206579. s.SRB_BufPointer = (BYTE*)qdata;
  206580. s.SRB_CDBLen = 12;
  206581. s.CDBByte[0] = 0x42;
  206582. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206583. s.CDBByte[2] = 64;
  206584. s.CDBByte[3] = 1; // get current position
  206585. s.CDBByte[7] = 0;
  206586. s.CDBByte[8] = (BYTE)sizeof (qdata);
  206587. perform (s);
  206588. if (s.SRB_Status == SS_COMP)
  206589. return qdata[7];
  206590. return 0;
  206591. }
  206592. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  206593. {
  206594. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206595. SRB_ExecSCSICmd s;
  206596. zerostruct (s);
  206597. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206598. s.SRB_HaID = info.ha;
  206599. s.SRB_Target = info.tgt;
  206600. s.SRB_Lun = info.lun;
  206601. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206602. s.SRB_BufLen = 0x324;
  206603. s.SRB_BufPointer = (BYTE*)lpToc;
  206604. s.SRB_SenseLen = 0x0E;
  206605. s.SRB_CDBLen = 0x0A;
  206606. s.SRB_PostProc = (void*)event;
  206607. s.CDBByte[0] = 0x43;
  206608. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  206609. s.CDBByte[7] = 0x03;
  206610. s.CDBByte[8] = 0x24;
  206611. ResetEvent (event);
  206612. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206613. : fSendASPI32Command ((LPSRB)&s);
  206614. if (status == SS_PENDING)
  206615. WaitForSingleObject (event, 4000);
  206616. CloseHandle (event);
  206617. return (s.SRB_Status == SS_COMP);
  206618. }
  206619. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  206620. CDReadBuffer* const overlapBuffer)
  206621. {
  206622. if (controller == 0)
  206623. {
  206624. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  206625. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  206626. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  206627. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  206628. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  206629. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  206630. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  206631. }
  206632. buffer->index = 0;
  206633. if ((controller != 0)
  206634. && controller->readAudio (buffer, overlapBuffer))
  206635. {
  206636. if (buffer->wantsIndex)
  206637. buffer->index = controller->getLastIndex();
  206638. return true;
  206639. }
  206640. return false;
  206641. }
  206642. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  206643. {
  206644. if (shouldBeOpen)
  206645. {
  206646. if (controller != 0)
  206647. {
  206648. controller->shutDown();
  206649. delete controller;
  206650. controller = 0;
  206651. }
  206652. if (scsiHandle != 0)
  206653. {
  206654. CloseHandle (scsiHandle);
  206655. scsiHandle = 0;
  206656. }
  206657. }
  206658. SRB_ExecSCSICmd s;
  206659. zerostruct (s);
  206660. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206661. s.SRB_HaID = info.ha;
  206662. s.SRB_Target = info.tgt;
  206663. s.SRB_Lun = info.lun;
  206664. s.SRB_SenseLen = SENSE_LEN;
  206665. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206666. s.SRB_BufLen = 0;
  206667. s.SRB_BufPointer = 0;
  206668. s.SRB_CDBLen = 12;
  206669. s.CDBByte[0] = 0x1b;
  206670. s.CDBByte[1] = (BYTE)(info.lun << 5);
  206671. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  206672. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206673. s.SRB_PostProc = (void*)event;
  206674. ResetEvent (event);
  206675. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206676. : fSendASPI32Command ((LPSRB)&s);
  206677. if (status == SS_PENDING)
  206678. WaitForSingleObject (event, 4000);
  206679. CloseHandle (event);
  206680. }
  206681. bool CDDeviceHandle::testController (const int type,
  206682. CDController* const newController,
  206683. CDReadBuffer* const rb)
  206684. {
  206685. controller = newController;
  206686. readType = (BYTE)type;
  206687. controller->deviceInfo = this;
  206688. controller->framesToCheck = 1;
  206689. controller->framesOverlap = 3;
  206690. bool passed = false;
  206691. memset (rb->buffer, 0xcd, rb->bufferSize);
  206692. if (controller->read (rb))
  206693. {
  206694. passed = true;
  206695. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  206696. int wrong = 0;
  206697. for (int i = rb->dataLength / 4; --i >= 0;)
  206698. {
  206699. if (*p++ == (int) 0xcdcdcdcd)
  206700. {
  206701. if (++wrong == 4)
  206702. {
  206703. passed = false;
  206704. break;
  206705. }
  206706. }
  206707. else
  206708. {
  206709. wrong = 0;
  206710. }
  206711. }
  206712. }
  206713. if (! passed)
  206714. {
  206715. controller->shutDown();
  206716. delete controller;
  206717. controller = 0;
  206718. }
  206719. return passed;
  206720. }
  206721. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  206722. {
  206723. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206724. const int bufSize = 128;
  206725. BYTE buffer[bufSize];
  206726. zeromem (buffer, bufSize);
  206727. SRB_ExecSCSICmd s;
  206728. zerostruct (s);
  206729. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206730. s.SRB_HaID = ha;
  206731. s.SRB_Target = tgt;
  206732. s.SRB_Lun = lun;
  206733. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206734. s.SRB_BufLen = bufSize;
  206735. s.SRB_BufPointer = buffer;
  206736. s.SRB_SenseLen = SENSE_LEN;
  206737. s.SRB_CDBLen = 6;
  206738. s.SRB_PostProc = (void*)event;
  206739. s.CDBByte[0] = SCSI_INQUIRY;
  206740. s.CDBByte[4] = 100;
  206741. ResetEvent (event);
  206742. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  206743. WaitForSingleObject (event, 4000);
  206744. CloseHandle (event);
  206745. if (s.SRB_Status == SS_COMP)
  206746. {
  206747. memcpy (dev->vendor, &buffer[8], 8);
  206748. memcpy (dev->productId, &buffer[16], 16);
  206749. memcpy (dev->rev, &buffer[32], 4);
  206750. memcpy (dev->vendorSpec, &buffer[36], 20);
  206751. }
  206752. }
  206753. static int FindCDDevices (CDDeviceInfo* const list,
  206754. int maxItems)
  206755. {
  206756. int count = 0;
  206757. if (usingScsi)
  206758. {
  206759. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  206760. {
  206761. TCHAR drivePath[8];
  206762. drivePath[0] = driveLetter;
  206763. drivePath[1] = ':';
  206764. drivePath[2] = '\\';
  206765. drivePath[3] = 0;
  206766. if (GetDriveType (drivePath) == DRIVE_CDROM)
  206767. {
  206768. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  206769. if (h != INVALID_HANDLE_VALUE)
  206770. {
  206771. BYTE buffer[100], passThroughStruct[1024];
  206772. zeromem (buffer, sizeof (buffer));
  206773. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206774. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  206775. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  206776. p->spt.CdbLength = 6;
  206777. p->spt.SenseInfoLength = 24;
  206778. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  206779. p->spt.DataTransferLength = 100;
  206780. p->spt.TimeOutValue = 2;
  206781. p->spt.DataBuffer = buffer;
  206782. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206783. p->spt.Cdb[0] = 0x12;
  206784. p->spt.Cdb[4] = 100;
  206785. DWORD bytesReturned = 0;
  206786. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206787. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206788. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206789. &bytesReturned, 0) != 0)
  206790. {
  206791. zeromem (&list[count], sizeof (CDDeviceInfo));
  206792. list[count].scsiDriveLetter = driveLetter;
  206793. memcpy (list[count].vendor, &buffer[8], 8);
  206794. memcpy (list[count].productId, &buffer[16], 16);
  206795. memcpy (list[count].rev, &buffer[32], 4);
  206796. memcpy (list[count].vendorSpec, &buffer[36], 20);
  206797. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206798. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  206799. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  206800. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  206801. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  206802. &bytesReturned, 0) != 0)
  206803. {
  206804. list[count].ha = scsiAddr->PortNumber;
  206805. list[count].tgt = scsiAddr->TargetId;
  206806. list[count].lun = scsiAddr->Lun;
  206807. ++count;
  206808. }
  206809. }
  206810. CloseHandle (h);
  206811. }
  206812. }
  206813. }
  206814. }
  206815. else
  206816. {
  206817. const DWORD d = fGetASPI32SupportInfo();
  206818. BYTE status = HIBYTE (LOWORD (d));
  206819. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  206820. return 0;
  206821. const int numAdapters = LOBYTE (LOWORD (d));
  206822. for (BYTE ha = 0; ha < numAdapters; ++ha)
  206823. {
  206824. SRB_HAInquiry s;
  206825. zerostruct (s);
  206826. s.SRB_Cmd = SC_HA_INQUIRY;
  206827. s.SRB_HaID = ha;
  206828. fSendASPI32Command ((LPSRB)&s);
  206829. if (s.SRB_Status == SS_COMP)
  206830. {
  206831. maxItems = (int)s.HA_Unique[3];
  206832. if (maxItems == 0)
  206833. maxItems = 8;
  206834. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  206835. {
  206836. for (BYTE lun = 0; lun < 8; ++lun)
  206837. {
  206838. SRB_GDEVBlock sb;
  206839. zerostruct (sb);
  206840. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  206841. sb.SRB_HaID = ha;
  206842. sb.SRB_Target = tgt;
  206843. sb.SRB_Lun = lun;
  206844. fSendASPI32Command ((LPSRB) &sb);
  206845. if (sb.SRB_Status == SS_COMP
  206846. && sb.SRB_DeviceType == DTYPE_CROM)
  206847. {
  206848. zeromem (&list[count], sizeof (CDDeviceInfo));
  206849. list[count].ha = ha;
  206850. list[count].tgt = tgt;
  206851. list[count].lun = lun;
  206852. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  206853. ++count;
  206854. }
  206855. }
  206856. }
  206857. }
  206858. }
  206859. }
  206860. return count;
  206861. }
  206862. static int ripperUsers = 0;
  206863. static bool initialisedOk = false;
  206864. class DeinitialiseTimer : private Timer,
  206865. private DeletedAtShutdown
  206866. {
  206867. DeinitialiseTimer (const DeinitialiseTimer&);
  206868. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  206869. public:
  206870. DeinitialiseTimer()
  206871. {
  206872. startTimer (4000);
  206873. }
  206874. ~DeinitialiseTimer()
  206875. {
  206876. if (--ripperUsers == 0)
  206877. DeinitialiseCDRipper();
  206878. }
  206879. void timerCallback()
  206880. {
  206881. delete this;
  206882. }
  206883. juce_UseDebuggingNewOperator
  206884. };
  206885. static void incUserCount()
  206886. {
  206887. if (ripperUsers++ == 0)
  206888. initialisedOk = InitialiseCDRipper();
  206889. }
  206890. static void decUserCount()
  206891. {
  206892. new DeinitialiseTimer();
  206893. }
  206894. struct CDDeviceWrapper
  206895. {
  206896. CDDeviceHandle* cdH;
  206897. CDReadBuffer* overlapBuffer;
  206898. bool jitter;
  206899. };
  206900. static int getAddressOf (const TOCTRACK* const t)
  206901. {
  206902. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  206903. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  206904. }
  206905. static int getMSFAddressOf (const TOCTRACK* const t)
  206906. {
  206907. return 60 * t->addr[1] + t->addr[2];
  206908. }
  206909. static const int samplesPerFrame = 44100 / 75;
  206910. static const int bytesPerFrame = samplesPerFrame * 4;
  206911. const StringArray AudioCDReader::getAvailableCDNames()
  206912. {
  206913. StringArray results;
  206914. incUserCount();
  206915. if (initialisedOk)
  206916. {
  206917. CDDeviceInfo list[8];
  206918. const int num = FindCDDevices (list, 8);
  206919. decUserCount();
  206920. for (int i = 0; i < num; ++i)
  206921. {
  206922. String s;
  206923. if (list[i].scsiDriveLetter > 0)
  206924. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  206925. s << String (list[i].vendor).trim()
  206926. << T(" ") << String (list[i].productId).trim()
  206927. << T(" ") << String (list[i].rev).trim();
  206928. results.add (s);
  206929. }
  206930. }
  206931. return results;
  206932. }
  206933. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  206934. {
  206935. SRB_GDEVBlock s;
  206936. zerostruct (s);
  206937. s.SRB_Cmd = SC_GET_DEV_TYPE;
  206938. s.SRB_HaID = device->ha;
  206939. s.SRB_Target = device->tgt;
  206940. s.SRB_Lun = device->lun;
  206941. if (usingScsi)
  206942. {
  206943. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  206944. if (h != INVALID_HANDLE_VALUE)
  206945. {
  206946. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  206947. cdh->scsiHandle = h;
  206948. return cdh;
  206949. }
  206950. }
  206951. else
  206952. {
  206953. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  206954. && s.SRB_DeviceType == DTYPE_CROM)
  206955. {
  206956. return new CDDeviceHandle (device);
  206957. }
  206958. }
  206959. return 0;
  206960. }
  206961. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  206962. {
  206963. incUserCount();
  206964. if (initialisedOk)
  206965. {
  206966. CDDeviceInfo list[8];
  206967. const int num = FindCDDevices (list, 8);
  206968. if (((unsigned int) deviceIndex) < (unsigned int) num)
  206969. {
  206970. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  206971. if (handle != 0)
  206972. {
  206973. CDDeviceWrapper* const d = new CDDeviceWrapper();
  206974. d->cdH = handle;
  206975. d->overlapBuffer = new CDReadBuffer(3);
  206976. return new AudioCDReader (d);
  206977. }
  206978. }
  206979. }
  206980. decUserCount();
  206981. return 0;
  206982. }
  206983. AudioCDReader::AudioCDReader (void* handle_)
  206984. : AudioFormatReader (0, T("CD Audio")),
  206985. handle (handle_),
  206986. indexingEnabled (false),
  206987. lastIndex (0),
  206988. firstFrameInBuffer (0),
  206989. samplesInBuffer (0)
  206990. {
  206991. jassert (handle_ != 0);
  206992. refreshTrackLengths();
  206993. sampleRate = 44100.0;
  206994. bitsPerSample = 16;
  206995. lengthInSamples = getPositionOfTrackStart (numTracks);
  206996. numChannels = 2;
  206997. usesFloatingPointData = false;
  206998. buffer.setSize (4 * bytesPerFrame, true);
  206999. }
  207000. AudioCDReader::~AudioCDReader()
  207001. {
  207002. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  207003. delete device->cdH;
  207004. delete device->overlapBuffer;
  207005. delete device;
  207006. decUserCount();
  207007. }
  207008. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  207009. int64 startSampleInFile, int numSamples)
  207010. {
  207011. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207012. bool ok = true;
  207013. while (numSamples > 0)
  207014. {
  207015. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  207016. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  207017. if (startSampleInFile >= bufferStartSample
  207018. && startSampleInFile < bufferEndSample)
  207019. {
  207020. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  207021. int* const l = destSamples[0] + startOffsetInDestBuffer;
  207022. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207023. const short* src = (const short*) buffer.getData();
  207024. src += 2 * (startSampleInFile - bufferStartSample);
  207025. for (int i = 0; i < toDo; ++i)
  207026. {
  207027. l[i] = src [i << 1] << 16;
  207028. if (r != 0)
  207029. r[i] = src [(i << 1) + 1] << 16;
  207030. }
  207031. startOffsetInDestBuffer += toDo;
  207032. startSampleInFile += toDo;
  207033. numSamples -= toDo;
  207034. }
  207035. else
  207036. {
  207037. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  207038. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  207039. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  207040. {
  207041. device->overlapBuffer->dataLength = 0;
  207042. device->overlapBuffer->startFrame = 0;
  207043. device->overlapBuffer->numFrames = 0;
  207044. device->jitter = false;
  207045. }
  207046. firstFrameInBuffer = frameNeeded;
  207047. lastIndex = 0;
  207048. CDReadBuffer readBuffer (framesInBuffer + 4);
  207049. readBuffer.wantsIndex = indexingEnabled;
  207050. int i;
  207051. for (i = 5; --i >= 0;)
  207052. {
  207053. readBuffer.startFrame = frameNeeded;
  207054. readBuffer.numFrames = framesInBuffer;
  207055. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  207056. break;
  207057. else
  207058. device->overlapBuffer->dataLength = 0;
  207059. }
  207060. if (i >= 0)
  207061. {
  207062. memcpy ((char*) buffer.getData(),
  207063. readBuffer.buffer + readBuffer.dataStartOffset,
  207064. readBuffer.dataLength);
  207065. samplesInBuffer = readBuffer.dataLength >> 2;
  207066. lastIndex = readBuffer.index;
  207067. }
  207068. else
  207069. {
  207070. int* l = destSamples[0] + startOffsetInDestBuffer;
  207071. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207072. while (--numSamples >= 0)
  207073. {
  207074. *l++ = 0;
  207075. if (r != 0)
  207076. *r++ = 0;
  207077. }
  207078. // sometimes the read fails for just the very last couple of blocks, so
  207079. // we'll ignore and errors in the last half-second of the disk..
  207080. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  207081. break;
  207082. }
  207083. }
  207084. }
  207085. return ok;
  207086. }
  207087. bool AudioCDReader::isCDStillPresent() const
  207088. {
  207089. TOC toc;
  207090. zerostruct (toc);
  207091. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  207092. }
  207093. int AudioCDReader::getNumTracks() const
  207094. {
  207095. return numTracks;
  207096. }
  207097. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  207098. {
  207099. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  207100. : 0;
  207101. }
  207102. void AudioCDReader::refreshTrackLengths()
  207103. {
  207104. zeromem (trackStarts, sizeof (trackStarts));
  207105. zeromem (audioTracks, sizeof (audioTracks));
  207106. TOC toc;
  207107. zerostruct (toc);
  207108. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  207109. {
  207110. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  207111. for (int i = 0; i <= numTracks; ++i)
  207112. {
  207113. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  207114. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  207115. }
  207116. }
  207117. else
  207118. {
  207119. numTracks = 0;
  207120. }
  207121. }
  207122. bool AudioCDReader::isTrackAudio (int trackNum) const
  207123. {
  207124. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  207125. : false;
  207126. }
  207127. void AudioCDReader::enableIndexScanning (bool b)
  207128. {
  207129. indexingEnabled = b;
  207130. }
  207131. int AudioCDReader::getLastIndex() const
  207132. {
  207133. return lastIndex;
  207134. }
  207135. const int framesPerIndexRead = 4;
  207136. int AudioCDReader::getIndexAt (int samplePos)
  207137. {
  207138. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207139. const int frameNeeded = samplePos / samplesPerFrame;
  207140. device->overlapBuffer->dataLength = 0;
  207141. device->overlapBuffer->startFrame = 0;
  207142. device->overlapBuffer->numFrames = 0;
  207143. device->jitter = false;
  207144. firstFrameInBuffer = 0;
  207145. lastIndex = 0;
  207146. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  207147. readBuffer.wantsIndex = true;
  207148. int i;
  207149. for (i = 5; --i >= 0;)
  207150. {
  207151. readBuffer.startFrame = frameNeeded;
  207152. readBuffer.numFrames = framesPerIndexRead;
  207153. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207154. break;
  207155. }
  207156. if (i >= 0)
  207157. return readBuffer.index;
  207158. return -1;
  207159. }
  207160. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  207161. {
  207162. Array <int> indexes;
  207163. const int trackStart = getPositionOfTrackStart (trackNumber);
  207164. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  207165. bool needToScan = true;
  207166. if (trackEnd - trackStart > 20 * 44100)
  207167. {
  207168. // check the end of the track for indexes before scanning the whole thing
  207169. needToScan = false;
  207170. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  207171. bool seenAnIndex = false;
  207172. while (pos <= trackEnd - samplesPerFrame)
  207173. {
  207174. const int index = getIndexAt (pos);
  207175. if (index == 0)
  207176. {
  207177. // lead-out, so skip back a bit if we've not found any indexes yet..
  207178. if (seenAnIndex)
  207179. break;
  207180. pos -= 44100 * 5;
  207181. if (pos < trackStart)
  207182. break;
  207183. }
  207184. else
  207185. {
  207186. if (index > 0)
  207187. seenAnIndex = true;
  207188. if (index > 1)
  207189. {
  207190. needToScan = true;
  207191. break;
  207192. }
  207193. pos += samplesPerFrame * framesPerIndexRead;
  207194. }
  207195. }
  207196. }
  207197. if (needToScan)
  207198. {
  207199. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207200. int pos = trackStart;
  207201. int last = -1;
  207202. while (pos < trackEnd - samplesPerFrame * 10)
  207203. {
  207204. const int frameNeeded = pos / samplesPerFrame;
  207205. device->overlapBuffer->dataLength = 0;
  207206. device->overlapBuffer->startFrame = 0;
  207207. device->overlapBuffer->numFrames = 0;
  207208. device->jitter = false;
  207209. firstFrameInBuffer = 0;
  207210. CDReadBuffer readBuffer (4);
  207211. readBuffer.wantsIndex = true;
  207212. int i;
  207213. for (i = 5; --i >= 0;)
  207214. {
  207215. readBuffer.startFrame = frameNeeded;
  207216. readBuffer.numFrames = framesPerIndexRead;
  207217. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207218. break;
  207219. }
  207220. if (i < 0)
  207221. break;
  207222. if (readBuffer.index > last && readBuffer.index > 1)
  207223. {
  207224. last = readBuffer.index;
  207225. indexes.add (pos);
  207226. }
  207227. pos += samplesPerFrame * framesPerIndexRead;
  207228. }
  207229. indexes.removeValue (trackStart);
  207230. }
  207231. return indexes;
  207232. }
  207233. int AudioCDReader::getCDDBId()
  207234. {
  207235. refreshTrackLengths();
  207236. if (numTracks > 0)
  207237. {
  207238. TOC toc;
  207239. zerostruct (toc);
  207240. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  207241. {
  207242. int n = 0;
  207243. for (int i = numTracks; --i >= 0;)
  207244. {
  207245. int j = getMSFAddressOf (&toc.tracks[i]);
  207246. while (j > 0)
  207247. {
  207248. n += (j % 10);
  207249. j /= 10;
  207250. }
  207251. }
  207252. if (n != 0)
  207253. {
  207254. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  207255. - getMSFAddressOf (&toc.tracks[0]);
  207256. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  207257. }
  207258. }
  207259. }
  207260. return 0;
  207261. }
  207262. void AudioCDReader::ejectDisk()
  207263. {
  207264. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  207265. }
  207266. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  207267. {
  207268. CoInitialize (0);
  207269. IDiscMaster* dm;
  207270. IDiscRecorder* result = 0;
  207271. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  207272. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  207273. IID_IDiscMaster,
  207274. (void**) &dm)))
  207275. {
  207276. if (SUCCEEDED (dm->Open()))
  207277. {
  207278. IEnumDiscRecorders* drEnum = 0;
  207279. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  207280. {
  207281. IDiscRecorder* dr = 0;
  207282. DWORD dummy;
  207283. int index = 0;
  207284. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  207285. {
  207286. if (indexToOpen == index)
  207287. {
  207288. result = dr;
  207289. break;
  207290. }
  207291. else if (list != 0)
  207292. {
  207293. BSTR path;
  207294. if (SUCCEEDED (dr->GetPath (&path)))
  207295. list->add ((const WCHAR*) path);
  207296. }
  207297. ++index;
  207298. dr->Release();
  207299. }
  207300. drEnum->Release();
  207301. }
  207302. /*if (redbookFormat != 0)
  207303. {
  207304. IEnumDiscMasterFormats* mfEnum;
  207305. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  207306. {
  207307. IID formatIID;
  207308. DWORD dummy;
  207309. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  207310. {
  207311. }
  207312. mfEnum->Release();
  207313. }
  207314. redbookFormat
  207315. }*/
  207316. if (master == 0)
  207317. dm->Close();
  207318. }
  207319. if (master != 0)
  207320. *master = dm;
  207321. else
  207322. dm->Release();
  207323. }
  207324. return result;
  207325. }
  207326. const StringArray AudioCDBurner::findAvailableDevices()
  207327. {
  207328. StringArray devs;
  207329. enumCDBurners (&devs, -1, 0);
  207330. return devs;
  207331. }
  207332. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  207333. {
  207334. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  207335. if (b->internal == 0)
  207336. deleteAndZero (b);
  207337. return b;
  207338. }
  207339. class CDBurnerInfo : public IDiscMasterProgressEvents
  207340. {
  207341. public:
  207342. CDBurnerInfo()
  207343. : refCount (1),
  207344. progress (0),
  207345. shouldCancel (false),
  207346. listener (0)
  207347. {
  207348. }
  207349. ~CDBurnerInfo()
  207350. {
  207351. }
  207352. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207353. {
  207354. if (result == 0)
  207355. return E_POINTER;
  207356. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  207357. {
  207358. AddRef();
  207359. *result = this;
  207360. return S_OK;
  207361. }
  207362. *result = 0;
  207363. return E_NOINTERFACE;
  207364. }
  207365. ULONG __stdcall AddRef() { return ++refCount; }
  207366. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207367. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  207368. {
  207369. if (listener != 0 && ! shouldCancel)
  207370. shouldCancel = listener->audioCDBurnProgress (progress);
  207371. *pbCancel = shouldCancel;
  207372. return S_OK;
  207373. }
  207374. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  207375. {
  207376. progress = nCompleted / (float) nTotal;
  207377. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  207378. return E_NOTIMPL;
  207379. }
  207380. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  207381. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  207382. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  207383. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207384. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207385. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207386. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207387. IDiscMaster* discMaster;
  207388. IDiscRecorder* discRecorder;
  207389. IRedbookDiscMaster* redbook;
  207390. AudioCDBurner::BurnProgressListener* listener;
  207391. float progress;
  207392. bool shouldCancel;
  207393. private:
  207394. int refCount;
  207395. };
  207396. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  207397. : internal (0)
  207398. {
  207399. IDiscMaster* discMaster;
  207400. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  207401. if (dr != 0)
  207402. {
  207403. IRedbookDiscMaster* redbook;
  207404. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  207405. hr = discMaster->SetActiveDiscRecorder (dr);
  207406. CDBurnerInfo* const info = new CDBurnerInfo();
  207407. internal = info;
  207408. info->discMaster = discMaster;
  207409. info->discRecorder = dr;
  207410. info->redbook = redbook;
  207411. }
  207412. }
  207413. AudioCDBurner::~AudioCDBurner()
  207414. {
  207415. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207416. if (info != 0)
  207417. {
  207418. info->discRecorder->Close();
  207419. info->redbook->Release();
  207420. info->discRecorder->Release();
  207421. info->discMaster->Release();
  207422. info->Release();
  207423. }
  207424. }
  207425. bool AudioCDBurner::isDiskPresent() const
  207426. {
  207427. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207428. HRESULT hr = info->discRecorder->OpenExclusive();
  207429. long type, flags;
  207430. hr = info->discRecorder->QueryMediaType (&type, &flags);
  207431. info->discRecorder->Close();
  207432. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  207433. }
  207434. int AudioCDBurner::getNumAvailableAudioBlocks() const
  207435. {
  207436. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207437. long blocksFree = 0;
  207438. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  207439. return blocksFree;
  207440. }
  207441. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  207442. const bool ejectDiscAfterwards,
  207443. const bool performFakeBurnForTesting)
  207444. {
  207445. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207446. info->listener = listener;
  207447. info->progress = 0;
  207448. info->shouldCancel = false;
  207449. UINT_PTR cookie;
  207450. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  207451. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  207452. ejectDiscAfterwards);
  207453. String error;
  207454. if (hr != S_OK)
  207455. {
  207456. const char* e = "Couldn't open or write to the CD device";
  207457. if (hr == IMAPI_E_USERABORT)
  207458. e = "User cancelled the write operation";
  207459. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  207460. e = "No Disk present";
  207461. error = e;
  207462. }
  207463. info->discMaster->ProgressUnadvise (cookie);
  207464. info->listener = 0;
  207465. return error;
  207466. }
  207467. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  207468. {
  207469. if (source == 0)
  207470. return false;
  207471. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207472. long bytesPerBlock;
  207473. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  207474. const int samplesPerBlock = bytesPerBlock / 4;
  207475. bool ok = true;
  207476. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  207477. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  207478. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  207479. int samplesDone = 0;
  207480. source->prepareToPlay (samplesPerBlock, 44100.0);
  207481. while (ok)
  207482. {
  207483. {
  207484. AudioSourceChannelInfo info;
  207485. info.buffer = &sourceBuffer;
  207486. info.numSamples = samplesPerBlock;
  207487. info.startSample = 0;
  207488. sourceBuffer.clear();
  207489. source->getNextAudioBlock (info);
  207490. }
  207491. zeromem (buffer, bytesPerBlock);
  207492. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  207493. buffer, samplesPerBlock, 4);
  207494. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  207495. buffer + 2, samplesPerBlock, 4);
  207496. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  207497. if (hr != S_OK)
  207498. ok = false;
  207499. samplesDone += samplesPerBlock;
  207500. if (samplesDone >= numSamples)
  207501. break;
  207502. }
  207503. juce_free (buffer);
  207504. hr = info->redbook->CloseAudioTrack();
  207505. delete source;
  207506. return ok && hr == S_OK;
  207507. }
  207508. #endif
  207509. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  207510. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  207511. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207512. // compiled on its own).
  207513. #if JUCE_INCLUDED_FILE
  207514. static const int midiBufferSize = 1024 * 10;
  207515. static const int numInHeaders = 32;
  207516. static const int inBufferSize = 256;
  207517. static Array <void*, CriticalSection> activeMidiThreads;
  207518. using ::free;
  207519. class MidiInThread : public Thread
  207520. {
  207521. public:
  207522. MidiInThread (MidiInput* const input_,
  207523. MidiInputCallback* const callback_)
  207524. : Thread ("Juce Midi"),
  207525. hIn (0),
  207526. input (input_),
  207527. callback (callback_),
  207528. isStarted (false),
  207529. startTime (0),
  207530. pendingLength(0)
  207531. {
  207532. for (int i = numInHeaders; --i >= 0;)
  207533. {
  207534. zeromem (&hdr[i], sizeof (MIDIHDR));
  207535. hdr[i].lpData = inData[i];
  207536. hdr[i].dwBufferLength = inBufferSize;
  207537. }
  207538. };
  207539. ~MidiInThread()
  207540. {
  207541. stop();
  207542. if (hIn != 0)
  207543. {
  207544. int count = 5;
  207545. while (--count >= 0)
  207546. {
  207547. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  207548. break;
  207549. Sleep (20);
  207550. }
  207551. }
  207552. }
  207553. void handle (const uint32 message, const uint32 timeStamp) throw()
  207554. {
  207555. const int byte = message & 0xff;
  207556. if (byte < 0x80)
  207557. return;
  207558. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  207559. const double time = timeStampToTime (timeStamp);
  207560. lock.enter();
  207561. if (pendingLength < midiBufferSize - 12)
  207562. {
  207563. char* const p = pending + pendingLength;
  207564. *(double*) p = time;
  207565. *(uint32*) (p + 8) = numBytes;
  207566. *(uint32*) (p + 12) = message;
  207567. pendingLength += 12 + numBytes;
  207568. }
  207569. else
  207570. {
  207571. jassertfalse // midi buffer overflow! You might need to increase the size..
  207572. }
  207573. lock.exit();
  207574. notify();
  207575. }
  207576. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  207577. {
  207578. const int num = hdr->dwBytesRecorded;
  207579. if (num > 0)
  207580. {
  207581. const double time = timeStampToTime (timeStamp);
  207582. lock.enter();
  207583. if (pendingLength < midiBufferSize - (8 + num))
  207584. {
  207585. char* const p = pending + pendingLength;
  207586. *(double*) p = time;
  207587. *(uint32*) (p + 8) = num;
  207588. memcpy (p + 12, hdr->lpData, num);
  207589. pendingLength += 12 + num;
  207590. }
  207591. else
  207592. {
  207593. jassertfalse // midi buffer overflow! You might need to increase the size..
  207594. }
  207595. lock.exit();
  207596. notify();
  207597. }
  207598. }
  207599. void writeBlock (const int i) throw()
  207600. {
  207601. hdr[i].dwBytesRecorded = 0;
  207602. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207603. jassert (res == MMSYSERR_NOERROR);
  207604. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  207605. jassert (res == MMSYSERR_NOERROR);
  207606. }
  207607. void run()
  207608. {
  207609. MemoryBlock pendingCopy (64);
  207610. while (! threadShouldExit())
  207611. {
  207612. for (int i = 0; i < numInHeaders; ++i)
  207613. {
  207614. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207615. {
  207616. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207617. (void) res;
  207618. jassert (res == MMSYSERR_NOERROR);
  207619. writeBlock (i);
  207620. }
  207621. }
  207622. lock.enter();
  207623. int len = pendingLength;
  207624. if (len > 0)
  207625. {
  207626. pendingCopy.ensureSize (len);
  207627. pendingCopy.copyFrom (pending, 0, len);
  207628. pendingLength = 0;
  207629. }
  207630. lock.exit();
  207631. //xxx needs to figure out if blocks are broken up or not
  207632. if (len == 0)
  207633. {
  207634. wait (500);
  207635. }
  207636. else
  207637. {
  207638. const char* p = (const char*) pendingCopy.getData();
  207639. while (len > 0)
  207640. {
  207641. const double time = *(const double*) p;
  207642. const int messageLen = *(const int*) (p + 8);
  207643. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  207644. callback->handleIncomingMidiMessage (input, message);
  207645. p += 12 + messageLen;
  207646. len -= 12 + messageLen;
  207647. }
  207648. }
  207649. }
  207650. }
  207651. void start() throw()
  207652. {
  207653. jassert (hIn != 0);
  207654. if (hIn != 0 && ! isStarted)
  207655. {
  207656. stop();
  207657. activeMidiThreads.addIfNotAlreadyThere (this);
  207658. int i;
  207659. for (i = 0; i < numInHeaders; ++i)
  207660. writeBlock (i);
  207661. startTime = Time::getMillisecondCounter();
  207662. MMRESULT res = midiInStart (hIn);
  207663. jassert (res == MMSYSERR_NOERROR);
  207664. if (res == MMSYSERR_NOERROR)
  207665. {
  207666. isStarted = true;
  207667. pendingLength = 0;
  207668. startThread (6);
  207669. }
  207670. }
  207671. }
  207672. void stop() throw()
  207673. {
  207674. if (isStarted)
  207675. {
  207676. stopThread (5000);
  207677. midiInReset (hIn);
  207678. midiInStop (hIn);
  207679. activeMidiThreads.removeValue (this);
  207680. lock.enter();
  207681. lock.exit();
  207682. for (int i = numInHeaders; --i >= 0;)
  207683. {
  207684. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207685. {
  207686. int c = 10;
  207687. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  207688. Sleep (20);
  207689. jassert (c >= 0);
  207690. }
  207691. }
  207692. isStarted = false;
  207693. pendingLength = 0;
  207694. }
  207695. }
  207696. juce_UseDebuggingNewOperator
  207697. HMIDIIN hIn;
  207698. private:
  207699. MidiInput* input;
  207700. MidiInputCallback* callback;
  207701. bool isStarted;
  207702. uint32 startTime;
  207703. CriticalSection lock;
  207704. MIDIHDR hdr [numInHeaders];
  207705. char inData [numInHeaders] [inBufferSize];
  207706. int pendingLength;
  207707. char pending [midiBufferSize];
  207708. double timeStampToTime (uint32 timeStamp) throw()
  207709. {
  207710. timeStamp += startTime;
  207711. const uint32 now = Time::getMillisecondCounter();
  207712. if (timeStamp > now)
  207713. {
  207714. if (timeStamp > now + 2)
  207715. --startTime;
  207716. timeStamp = now;
  207717. }
  207718. return 0.001 * timeStamp;
  207719. }
  207720. MidiInThread (const MidiInThread&);
  207721. const MidiInThread& operator= (const MidiInThread&);
  207722. };
  207723. static void CALLBACK midiInCallback (HMIDIIN,
  207724. UINT uMsg,
  207725. DWORD_PTR dwInstance,
  207726. DWORD_PTR midiMessage,
  207727. DWORD_PTR timeStamp)
  207728. {
  207729. MidiInThread* const thread = (MidiInThread*) dwInstance;
  207730. if (thread != 0 && activeMidiThreads.contains (thread))
  207731. {
  207732. if (uMsg == MIM_DATA)
  207733. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  207734. else if (uMsg == MIM_LONGDATA)
  207735. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  207736. }
  207737. }
  207738. const StringArray MidiInput::getDevices()
  207739. {
  207740. StringArray s;
  207741. const int num = midiInGetNumDevs();
  207742. for (int i = 0; i < num; ++i)
  207743. {
  207744. MIDIINCAPS mc;
  207745. zerostruct (mc);
  207746. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207747. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207748. }
  207749. return s;
  207750. }
  207751. int MidiInput::getDefaultDeviceIndex()
  207752. {
  207753. return 0;
  207754. }
  207755. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  207756. {
  207757. if (callback == 0)
  207758. return 0;
  207759. UINT deviceId = MIDI_MAPPER;
  207760. int n = 0;
  207761. String name;
  207762. const int num = midiInGetNumDevs();
  207763. for (int i = 0; i < num; ++i)
  207764. {
  207765. MIDIINCAPS mc;
  207766. zerostruct (mc);
  207767. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207768. {
  207769. if (index == n)
  207770. {
  207771. deviceId = i;
  207772. name = String (mc.szPname, sizeof (mc.szPname));
  207773. break;
  207774. }
  207775. ++n;
  207776. }
  207777. }
  207778. MidiInput* const in = new MidiInput (name);
  207779. MidiInThread* const thread = new MidiInThread (in, callback);
  207780. HMIDIIN h;
  207781. HRESULT err = midiInOpen (&h, deviceId,
  207782. (DWORD_PTR) &midiInCallback,
  207783. (DWORD_PTR) thread,
  207784. CALLBACK_FUNCTION);
  207785. if (err == MMSYSERR_NOERROR)
  207786. {
  207787. thread->hIn = h;
  207788. in->internal = (void*) thread;
  207789. return in;
  207790. }
  207791. else
  207792. {
  207793. delete in;
  207794. delete thread;
  207795. return 0;
  207796. }
  207797. }
  207798. MidiInput::MidiInput (const String& name_)
  207799. : name (name_),
  207800. internal (0)
  207801. {
  207802. }
  207803. MidiInput::~MidiInput()
  207804. {
  207805. if (internal != 0)
  207806. {
  207807. MidiInThread* const thread = (MidiInThread*) internal;
  207808. delete thread;
  207809. }
  207810. }
  207811. void MidiInput::start()
  207812. {
  207813. ((MidiInThread*) internal)->start();
  207814. }
  207815. void MidiInput::stop()
  207816. {
  207817. ((MidiInThread*) internal)->stop();
  207818. }
  207819. struct MidiOutHandle
  207820. {
  207821. int refCount;
  207822. UINT deviceId;
  207823. HMIDIOUT handle;
  207824. juce_UseDebuggingNewOperator
  207825. };
  207826. static VoidArray handles (4);
  207827. const StringArray MidiOutput::getDevices()
  207828. {
  207829. StringArray s;
  207830. const int num = midiOutGetNumDevs();
  207831. for (int i = 0; i < num; ++i)
  207832. {
  207833. MIDIOUTCAPS mc;
  207834. zerostruct (mc);
  207835. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207836. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207837. }
  207838. return s;
  207839. }
  207840. int MidiOutput::getDefaultDeviceIndex()
  207841. {
  207842. const int num = midiOutGetNumDevs();
  207843. int n = 0;
  207844. for (int i = 0; i < num; ++i)
  207845. {
  207846. MIDIOUTCAPS mc;
  207847. zerostruct (mc);
  207848. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207849. {
  207850. if ((mc.wTechnology & MOD_MAPPER) != 0)
  207851. return n;
  207852. ++n;
  207853. }
  207854. }
  207855. return 0;
  207856. }
  207857. MidiOutput* MidiOutput::openDevice (int index)
  207858. {
  207859. UINT deviceId = MIDI_MAPPER;
  207860. const int num = midiOutGetNumDevs();
  207861. int i, n = 0;
  207862. for (i = 0; i < num; ++i)
  207863. {
  207864. MIDIOUTCAPS mc;
  207865. zerostruct (mc);
  207866. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207867. {
  207868. // use the microsoft sw synth as a default - best not to allow deviceId
  207869. // to be MIDI_MAPPER, or else device sharing breaks
  207870. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  207871. deviceId = i;
  207872. if (index == n)
  207873. {
  207874. deviceId = i;
  207875. break;
  207876. }
  207877. ++n;
  207878. }
  207879. }
  207880. for (i = handles.size(); --i >= 0;)
  207881. {
  207882. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  207883. if (han != 0 && han->deviceId == deviceId)
  207884. {
  207885. han->refCount++;
  207886. MidiOutput* const out = new MidiOutput();
  207887. out->internal = (void*) han;
  207888. return out;
  207889. }
  207890. }
  207891. for (i = 4; --i >= 0;)
  207892. {
  207893. HMIDIOUT h = 0;
  207894. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  207895. if (res == MMSYSERR_NOERROR)
  207896. {
  207897. MidiOutHandle* const han = new MidiOutHandle();
  207898. han->deviceId = deviceId;
  207899. han->refCount = 1;
  207900. han->handle = h;
  207901. handles.add (han);
  207902. MidiOutput* const out = new MidiOutput();
  207903. out->internal = (void*) han;
  207904. return out;
  207905. }
  207906. else if (res == MMSYSERR_ALLOCATED)
  207907. {
  207908. Sleep (100);
  207909. }
  207910. else
  207911. {
  207912. break;
  207913. }
  207914. }
  207915. return 0;
  207916. }
  207917. MidiOutput::~MidiOutput()
  207918. {
  207919. MidiOutHandle* const h = (MidiOutHandle*) internal;
  207920. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  207921. {
  207922. midiOutClose (h->handle);
  207923. handles.removeValue ((void*) h);
  207924. delete h;
  207925. }
  207926. }
  207927. void MidiOutput::reset()
  207928. {
  207929. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  207930. midiOutReset (h->handle);
  207931. }
  207932. bool MidiOutput::getVolume (float& leftVol,
  207933. float& rightVol)
  207934. {
  207935. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207936. DWORD n;
  207937. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  207938. {
  207939. const unsigned short* const nn = (const unsigned short*) &n;
  207940. rightVol = nn[0] / (float) 0xffff;
  207941. leftVol = nn[1] / (float) 0xffff;
  207942. return true;
  207943. }
  207944. else
  207945. {
  207946. rightVol = leftVol = 1.0f;
  207947. return false;
  207948. }
  207949. }
  207950. void MidiOutput::setVolume (float leftVol,
  207951. float rightVol)
  207952. {
  207953. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  207954. DWORD n;
  207955. unsigned short* const nn = (unsigned short*) &n;
  207956. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  207957. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  207958. midiOutSetVolume (handle->handle, n);
  207959. }
  207960. void MidiOutput::sendMessageNow (const MidiMessage& message)
  207961. {
  207962. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207963. if (message.getRawDataSize() > 3
  207964. || message.isSysEx())
  207965. {
  207966. MIDIHDR h;
  207967. zerostruct (h);
  207968. h.lpData = (char*) message.getRawData();
  207969. h.dwBufferLength = message.getRawDataSize();
  207970. h.dwBytesRecorded = message.getRawDataSize();
  207971. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  207972. {
  207973. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  207974. if (res == MMSYSERR_NOERROR)
  207975. {
  207976. while ((h.dwFlags & MHDR_DONE) == 0)
  207977. Sleep (1);
  207978. int count = 500; // 1 sec timeout
  207979. while (--count >= 0)
  207980. {
  207981. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  207982. if (res == MIDIERR_STILLPLAYING)
  207983. Sleep (2);
  207984. else
  207985. break;
  207986. }
  207987. }
  207988. }
  207989. }
  207990. else
  207991. {
  207992. midiOutShortMsg (handle->handle,
  207993. *(unsigned int*) message.getRawData());
  207994. }
  207995. }
  207996. #endif
  207997. /********* End of inlined file: juce_win32_Midi.cpp *********/
  207998. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  207999. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208000. // compiled on its own).
  208001. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  208002. #undef WINDOWS
  208003. // #define ASIO_DEBUGGING
  208004. #ifdef ASIO_DEBUGGING
  208005. #define log(a) { Logger::writeToLog (a); DBG (a) }
  208006. #else
  208007. #define log(a) {}
  208008. #endif
  208009. #ifdef ASIO_DEBUGGING
  208010. static void logError (const String& context, long error)
  208011. {
  208012. String err ("unknown error");
  208013. if (error == ASE_NotPresent)
  208014. err = "Not Present";
  208015. else if (error == ASE_HWMalfunction)
  208016. err = "Hardware Malfunction";
  208017. else if (error == ASE_InvalidParameter)
  208018. err = "Invalid Parameter";
  208019. else if (error == ASE_InvalidMode)
  208020. err = "Invalid Mode";
  208021. else if (error == ASE_SPNotAdvancing)
  208022. err = "Sample position not advancing";
  208023. else if (error == ASE_NoClock)
  208024. err = "No Clock";
  208025. else if (error == ASE_NoMemory)
  208026. err = "Out of memory";
  208027. log (T("!!error: ") + context + T(" - ") + err);
  208028. }
  208029. #else
  208030. #define logError(a, b) {}
  208031. #endif
  208032. class ASIOAudioIODevice;
  208033. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  208034. static const int maxASIOChannels = 160;
  208035. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  208036. private Timer
  208037. {
  208038. public:
  208039. Component ourWindow;
  208040. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  208041. const String& optionalDllForDirectLoading_)
  208042. : AudioIODevice (name_, T("ASIO")),
  208043. asioObject (0),
  208044. classId (classId_),
  208045. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  208046. currentBitDepth (16),
  208047. currentSampleRate (0),
  208048. tempBuffer (0),
  208049. isOpen_ (false),
  208050. isStarted (false),
  208051. postOutput (true),
  208052. insideControlPanelModalLoop (false),
  208053. shouldUsePreferredSize (false)
  208054. {
  208055. name = name_;
  208056. ourWindow.addToDesktop (0);
  208057. windowHandle = ourWindow.getWindowHandle();
  208058. jassert (currentASIODev [slotNumber] == 0);
  208059. currentASIODev [slotNumber] = this;
  208060. openDevice();
  208061. }
  208062. ~ASIOAudioIODevice()
  208063. {
  208064. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  208065. if (currentASIODev[i] == this)
  208066. currentASIODev[i] = 0;
  208067. close();
  208068. log ("ASIO - exiting");
  208069. removeCurrentDriver();
  208070. juce_free (tempBuffer);
  208071. }
  208072. void updateSampleRates()
  208073. {
  208074. // find a list of sample rates..
  208075. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  208076. sampleRates.clear();
  208077. if (asioObject != 0)
  208078. {
  208079. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  208080. {
  208081. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  208082. if (err == 0)
  208083. {
  208084. sampleRates.add ((int) possibleSampleRates[index]);
  208085. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  208086. }
  208087. else if (err != ASE_NoClock)
  208088. {
  208089. logError (T("CanSampleRate"), err);
  208090. }
  208091. }
  208092. if (sampleRates.size() == 0)
  208093. {
  208094. double cr = 0;
  208095. const long err = asioObject->getSampleRate (&cr);
  208096. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  208097. if (err == 0)
  208098. sampleRates.add ((int) cr);
  208099. }
  208100. }
  208101. }
  208102. const StringArray getOutputChannelNames()
  208103. {
  208104. return outputChannelNames;
  208105. }
  208106. const StringArray getInputChannelNames()
  208107. {
  208108. return inputChannelNames;
  208109. }
  208110. int getNumSampleRates()
  208111. {
  208112. return sampleRates.size();
  208113. }
  208114. double getSampleRate (int index)
  208115. {
  208116. return sampleRates [index];
  208117. }
  208118. int getNumBufferSizesAvailable()
  208119. {
  208120. return bufferSizes.size();
  208121. }
  208122. int getBufferSizeSamples (int index)
  208123. {
  208124. return bufferSizes [index];
  208125. }
  208126. int getDefaultBufferSize()
  208127. {
  208128. return preferredSize;
  208129. }
  208130. const String open (const BitArray& inputChannels,
  208131. const BitArray& outputChannels,
  208132. double sr,
  208133. int bufferSizeSamples)
  208134. {
  208135. close();
  208136. currentCallback = 0;
  208137. if (bufferSizeSamples <= 0)
  208138. shouldUsePreferredSize = true;
  208139. if (asioObject == 0 || ! isASIOOpen)
  208140. {
  208141. log ("Warning: device not open");
  208142. const String err (openDevice());
  208143. if (asioObject == 0 || ! isASIOOpen)
  208144. return err;
  208145. }
  208146. isStarted = false;
  208147. bufferIndex = -1;
  208148. long err = 0;
  208149. long newPreferredSize = 0;
  208150. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  208151. minSize = 0;
  208152. maxSize = 0;
  208153. newPreferredSize = 0;
  208154. granularity = 0;
  208155. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  208156. {
  208157. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  208158. shouldUsePreferredSize = true;
  208159. preferredSize = newPreferredSize;
  208160. }
  208161. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  208162. // dynamic changes to the buffer size...
  208163. shouldUsePreferredSize = shouldUsePreferredSize
  208164. || getName().containsIgnoreCase (T("Digidesign"));
  208165. if (shouldUsePreferredSize)
  208166. {
  208167. log ("Using preferred size for buffer..");
  208168. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208169. {
  208170. bufferSizeSamples = preferredSize;
  208171. }
  208172. else
  208173. {
  208174. bufferSizeSamples = 1024;
  208175. logError ("GetBufferSize1", err);
  208176. }
  208177. shouldUsePreferredSize = false;
  208178. }
  208179. int sampleRate = roundDoubleToInt (sr);
  208180. currentSampleRate = sampleRate;
  208181. currentBlockSizeSamples = bufferSizeSamples;
  208182. currentChansOut.clear();
  208183. currentChansIn.clear();
  208184. zeromem (inBuffers, sizeof (inBuffers));
  208185. zeromem (outBuffers, sizeof (outBuffers));
  208186. updateSampleRates();
  208187. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  208188. sampleRate = sampleRates[0];
  208189. jassert (sampleRate != 0);
  208190. if (sampleRate == 0)
  208191. sampleRate = 44100;
  208192. long numSources = 32;
  208193. ASIOClockSource clocks[32];
  208194. zeromem (clocks, sizeof (clocks));
  208195. asioObject->getClockSources (clocks, &numSources);
  208196. bool isSourceSet = false;
  208197. // careful not to remove this loop because it does more than just logging!
  208198. int i;
  208199. for (i = 0; i < numSources; ++i)
  208200. {
  208201. String s ("clock: ");
  208202. s += clocks[i].name;
  208203. if (clocks[i].isCurrentSource)
  208204. {
  208205. isSourceSet = true;
  208206. s << " (cur)";
  208207. }
  208208. log (s);
  208209. }
  208210. if (numSources > 1 && ! isSourceSet)
  208211. {
  208212. log ("setting clock source");
  208213. asioObject->setClockSource (clocks[0].index);
  208214. Thread::sleep (20);
  208215. }
  208216. else
  208217. {
  208218. if (numSources == 0)
  208219. {
  208220. log ("ASIO - no clock sources!");
  208221. }
  208222. }
  208223. double cr = 0;
  208224. err = asioObject->getSampleRate (&cr);
  208225. if (err == 0)
  208226. {
  208227. currentSampleRate = cr;
  208228. }
  208229. else
  208230. {
  208231. logError ("GetSampleRate", err);
  208232. currentSampleRate = 0;
  208233. }
  208234. error = String::empty;
  208235. needToReset = false;
  208236. isReSync = false;
  208237. err = 0;
  208238. bool buffersCreated = false;
  208239. if (currentSampleRate != sampleRate)
  208240. {
  208241. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  208242. err = asioObject->setSampleRate (sampleRate);
  208243. if (err == ASE_NoClock && numSources > 0)
  208244. {
  208245. log ("trying to set a clock source..");
  208246. Thread::sleep (10);
  208247. err = asioObject->setClockSource (clocks[0].index);
  208248. if (err != 0)
  208249. {
  208250. logError ("SetClock", err);
  208251. }
  208252. Thread::sleep (10);
  208253. err = asioObject->setSampleRate (sampleRate);
  208254. }
  208255. }
  208256. if (err == 0)
  208257. {
  208258. currentSampleRate = sampleRate;
  208259. if (needToReset)
  208260. {
  208261. if (isReSync)
  208262. {
  208263. log ("Resync request");
  208264. }
  208265. log ("! Resetting ASIO after sample rate change");
  208266. removeCurrentDriver();
  208267. loadDriver();
  208268. const String error (initDriver());
  208269. if (error.isNotEmpty())
  208270. {
  208271. log (T("ASIOInit: ") + error);
  208272. }
  208273. needToReset = false;
  208274. isReSync = false;
  208275. }
  208276. numActiveInputChans = 0;
  208277. numActiveOutputChans = 0;
  208278. ASIOBufferInfo* info = bufferInfos;
  208279. int i;
  208280. for (i = 0; i < totalNumInputChans; ++i)
  208281. {
  208282. if (inputChannels[i])
  208283. {
  208284. currentChansIn.setBit (i);
  208285. info->isInput = 1;
  208286. info->channelNum = i;
  208287. info->buffers[0] = info->buffers[1] = 0;
  208288. ++info;
  208289. ++numActiveInputChans;
  208290. }
  208291. }
  208292. for (i = 0; i < totalNumOutputChans; ++i)
  208293. {
  208294. if (outputChannels[i])
  208295. {
  208296. currentChansOut.setBit (i);
  208297. info->isInput = 0;
  208298. info->channelNum = i;
  208299. info->buffers[0] = info->buffers[1] = 0;
  208300. ++info;
  208301. ++numActiveOutputChans;
  208302. }
  208303. }
  208304. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  208305. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208306. if (currentASIODev[0] == this)
  208307. {
  208308. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208309. callbacks.asioMessage = &asioMessagesCallback0;
  208310. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208311. }
  208312. else if (currentASIODev[1] == this)
  208313. {
  208314. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208315. callbacks.asioMessage = &asioMessagesCallback1;
  208316. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208317. }
  208318. else if (currentASIODev[2] == this)
  208319. {
  208320. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208321. callbacks.asioMessage = &asioMessagesCallback2;
  208322. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208323. }
  208324. else
  208325. {
  208326. jassertfalse
  208327. }
  208328. log ("disposing buffers");
  208329. err = asioObject->disposeBuffers();
  208330. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  208331. err = asioObject->createBuffers (bufferInfos,
  208332. totalBuffers,
  208333. currentBlockSizeSamples,
  208334. &callbacks);
  208335. if (err != 0)
  208336. {
  208337. currentBlockSizeSamples = preferredSize;
  208338. logError ("create buffers 2", err);
  208339. asioObject->disposeBuffers();
  208340. err = asioObject->createBuffers (bufferInfos,
  208341. totalBuffers,
  208342. currentBlockSizeSamples,
  208343. &callbacks);
  208344. }
  208345. if (err == 0)
  208346. {
  208347. buffersCreated = true;
  208348. juce_free (tempBuffer);
  208349. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  208350. int n = 0;
  208351. Array <int> types;
  208352. currentBitDepth = 16;
  208353. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  208354. {
  208355. if (inputChannels[i])
  208356. {
  208357. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  208358. ASIOChannelInfo channelInfo;
  208359. zerostruct (channelInfo);
  208360. channelInfo.channel = i;
  208361. channelInfo.isInput = 1;
  208362. asioObject->getChannelInfo (&channelInfo);
  208363. types.addIfNotAlreadyThere (channelInfo.type);
  208364. typeToFormatParameters (channelInfo.type,
  208365. inputChannelBitDepths[n],
  208366. inputChannelBytesPerSample[n],
  208367. inputChannelIsFloat[n],
  208368. inputChannelLittleEndian[n]);
  208369. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  208370. ++n;
  208371. }
  208372. }
  208373. jassert (numActiveInputChans == n);
  208374. n = 0;
  208375. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  208376. {
  208377. if (outputChannels[i])
  208378. {
  208379. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  208380. ASIOChannelInfo channelInfo;
  208381. zerostruct (channelInfo);
  208382. channelInfo.channel = i;
  208383. channelInfo.isInput = 0;
  208384. asioObject->getChannelInfo (&channelInfo);
  208385. types.addIfNotAlreadyThere (channelInfo.type);
  208386. typeToFormatParameters (channelInfo.type,
  208387. outputChannelBitDepths[n],
  208388. outputChannelBytesPerSample[n],
  208389. outputChannelIsFloat[n],
  208390. outputChannelLittleEndian[n]);
  208391. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  208392. ++n;
  208393. }
  208394. }
  208395. jassert (numActiveOutputChans == n);
  208396. for (i = types.size(); --i >= 0;)
  208397. {
  208398. log (T("channel format: ") + String (types[i]));
  208399. }
  208400. jassert (n <= totalBuffers);
  208401. for (i = 0; i < numActiveOutputChans; ++i)
  208402. {
  208403. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  208404. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  208405. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  208406. {
  208407. log ("!! Null buffers");
  208408. }
  208409. else
  208410. {
  208411. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  208412. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  208413. }
  208414. }
  208415. inputLatency = outputLatency = 0;
  208416. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208417. {
  208418. log ("ASIO - no latencies");
  208419. }
  208420. else
  208421. {
  208422. log (T("ASIO latencies: ")
  208423. + String ((int) outputLatency)
  208424. + T(", ")
  208425. + String ((int) inputLatency));
  208426. }
  208427. isOpen_ = true;
  208428. log ("starting ASIO");
  208429. calledback = false;
  208430. err = asioObject->start();
  208431. if (err != 0)
  208432. {
  208433. isOpen_ = false;
  208434. log ("ASIO - stop on failure");
  208435. Thread::sleep (10);
  208436. asioObject->stop();
  208437. error = "Can't start device";
  208438. Thread::sleep (10);
  208439. }
  208440. else
  208441. {
  208442. int count = 300;
  208443. while (--count > 0 && ! calledback)
  208444. Thread::sleep (10);
  208445. isStarted = true;
  208446. if (! calledback)
  208447. {
  208448. error = "Device didn't start correctly";
  208449. log ("ASIO didn't callback - stopping..");
  208450. asioObject->stop();
  208451. }
  208452. }
  208453. }
  208454. else
  208455. {
  208456. error = "Can't create i/o buffers";
  208457. }
  208458. }
  208459. else
  208460. {
  208461. error = "Can't set sample rate: ";
  208462. error << sampleRate;
  208463. }
  208464. if (error.isNotEmpty())
  208465. {
  208466. logError (error, err);
  208467. if (asioObject != 0 && buffersCreated)
  208468. asioObject->disposeBuffers();
  208469. Thread::sleep (20);
  208470. isStarted = false;
  208471. isOpen_ = false;
  208472. close();
  208473. }
  208474. needToReset = false;
  208475. isReSync = false;
  208476. return error;
  208477. }
  208478. void close()
  208479. {
  208480. error = String::empty;
  208481. stopTimer();
  208482. stop();
  208483. if (isASIOOpen && isOpen_)
  208484. {
  208485. const ScopedLock sl (callbackLock);
  208486. isOpen_ = false;
  208487. isStarted = false;
  208488. needToReset = false;
  208489. isReSync = false;
  208490. log ("ASIO - stopping");
  208491. if (asioObject != 0)
  208492. {
  208493. Thread::sleep (20);
  208494. asioObject->stop();
  208495. Thread::sleep (10);
  208496. asioObject->disposeBuffers();
  208497. }
  208498. Thread::sleep (10);
  208499. }
  208500. }
  208501. bool isOpen()
  208502. {
  208503. return isOpen_ || insideControlPanelModalLoop;
  208504. }
  208505. int getCurrentBufferSizeSamples()
  208506. {
  208507. return currentBlockSizeSamples;
  208508. }
  208509. double getCurrentSampleRate()
  208510. {
  208511. return currentSampleRate;
  208512. }
  208513. const BitArray getActiveOutputChannels() const
  208514. {
  208515. return currentChansOut;
  208516. }
  208517. const BitArray getActiveInputChannels() const
  208518. {
  208519. return currentChansIn;
  208520. }
  208521. int getCurrentBitDepth()
  208522. {
  208523. return currentBitDepth;
  208524. }
  208525. int getOutputLatencyInSamples()
  208526. {
  208527. return outputLatency + currentBlockSizeSamples / 4;
  208528. }
  208529. int getInputLatencyInSamples()
  208530. {
  208531. return inputLatency + currentBlockSizeSamples / 4;
  208532. }
  208533. void start (AudioIODeviceCallback* callback)
  208534. {
  208535. if (callback != 0)
  208536. {
  208537. callback->audioDeviceAboutToStart (this);
  208538. const ScopedLock sl (callbackLock);
  208539. currentCallback = callback;
  208540. }
  208541. }
  208542. void stop()
  208543. {
  208544. AudioIODeviceCallback* const lastCallback = currentCallback;
  208545. {
  208546. const ScopedLock sl (callbackLock);
  208547. currentCallback = 0;
  208548. }
  208549. if (lastCallback != 0)
  208550. lastCallback->audioDeviceStopped();
  208551. }
  208552. bool isPlaying()
  208553. {
  208554. return isASIOOpen && (currentCallback != 0);
  208555. }
  208556. const String getLastError()
  208557. {
  208558. return error;
  208559. }
  208560. bool hasControlPanel() const
  208561. {
  208562. return true;
  208563. }
  208564. bool showControlPanel()
  208565. {
  208566. log ("ASIO - showing control panel");
  208567. Component modalWindow (String::empty);
  208568. modalWindow.setOpaque (true);
  208569. modalWindow.addToDesktop (0);
  208570. modalWindow.enterModalState();
  208571. bool done = false;
  208572. JUCE_TRY
  208573. {
  208574. // are there are devices that need to be closed before showing their control panel?
  208575. // close();
  208576. insideControlPanelModalLoop = true;
  208577. const uint32 started = Time::getMillisecondCounter();
  208578. if (asioObject != 0)
  208579. {
  208580. asioObject->controlPanel();
  208581. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  208582. log (T("spent: ") + String (spent));
  208583. if (spent > 300)
  208584. {
  208585. shouldUsePreferredSize = true;
  208586. done = true;
  208587. }
  208588. }
  208589. }
  208590. JUCE_CATCH_ALL
  208591. insideControlPanelModalLoop = false;
  208592. return done;
  208593. }
  208594. void resetRequest() throw()
  208595. {
  208596. needToReset = true;
  208597. }
  208598. void resyncRequest() throw()
  208599. {
  208600. needToReset = true;
  208601. isReSync = true;
  208602. }
  208603. void timerCallback()
  208604. {
  208605. if (! insideControlPanelModalLoop)
  208606. {
  208607. stopTimer();
  208608. // used to cause a reset
  208609. log ("! ASIO restart request!");
  208610. if (isOpen_)
  208611. {
  208612. AudioIODeviceCallback* const oldCallback = currentCallback;
  208613. close();
  208614. open (BitArray (currentChansIn), BitArray (currentChansOut),
  208615. currentSampleRate, currentBlockSizeSamples);
  208616. if (oldCallback != 0)
  208617. start (oldCallback);
  208618. }
  208619. }
  208620. else
  208621. {
  208622. startTimer (100);
  208623. }
  208624. }
  208625. juce_UseDebuggingNewOperator
  208626. private:
  208627. IASIO* volatile asioObject;
  208628. ASIOCallbacks callbacks;
  208629. void* windowHandle;
  208630. CLSID classId;
  208631. const String optionalDllForDirectLoading;
  208632. String error;
  208633. long totalNumInputChans, totalNumOutputChans;
  208634. StringArray inputChannelNames, outputChannelNames;
  208635. Array<int> sampleRates, bufferSizes;
  208636. long inputLatency, outputLatency;
  208637. long minSize, maxSize, preferredSize, granularity;
  208638. int volatile currentBlockSizeSamples;
  208639. int volatile currentBitDepth;
  208640. double volatile currentSampleRate;
  208641. BitArray currentChansOut, currentChansIn;
  208642. AudioIODeviceCallback* volatile currentCallback;
  208643. CriticalSection callbackLock;
  208644. ASIOBufferInfo bufferInfos [maxASIOChannels];
  208645. float* inBuffers [maxASIOChannels];
  208646. float* outBuffers [maxASIOChannels];
  208647. int inputChannelBitDepths [maxASIOChannels];
  208648. int outputChannelBitDepths [maxASIOChannels];
  208649. int inputChannelBytesPerSample [maxASIOChannels];
  208650. int outputChannelBytesPerSample [maxASIOChannels];
  208651. bool inputChannelIsFloat [maxASIOChannels];
  208652. bool outputChannelIsFloat [maxASIOChannels];
  208653. bool inputChannelLittleEndian [maxASIOChannels];
  208654. bool outputChannelLittleEndian [maxASIOChannels];
  208655. WaitableEvent event1;
  208656. float* tempBuffer;
  208657. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  208658. bool isOpen_, isStarted;
  208659. bool volatile isASIOOpen;
  208660. bool volatile calledback;
  208661. bool volatile littleEndian, postOutput, needToReset, isReSync;
  208662. bool volatile insideControlPanelModalLoop;
  208663. bool volatile shouldUsePreferredSize;
  208664. void removeCurrentDriver()
  208665. {
  208666. if (asioObject != 0)
  208667. {
  208668. asioObject->Release();
  208669. asioObject = 0;
  208670. }
  208671. }
  208672. bool loadDriver()
  208673. {
  208674. removeCurrentDriver();
  208675. JUCE_TRY
  208676. {
  208677. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  208678. classId, (void**) &asioObject) == S_OK)
  208679. {
  208680. return true;
  208681. }
  208682. // If a class isn't registered but we have a path for it, we can fallback to
  208683. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  208684. if (optionalDllForDirectLoading.isNotEmpty())
  208685. {
  208686. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  208687. if (h != 0)
  208688. {
  208689. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  208690. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  208691. if (dllGetClassObject != 0)
  208692. {
  208693. IClassFactory* classFactory = 0;
  208694. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  208695. if (classFactory != 0)
  208696. {
  208697. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  208698. classFactory->Release();
  208699. }
  208700. return asioObject != 0;
  208701. }
  208702. }
  208703. }
  208704. }
  208705. JUCE_CATCH_ALL
  208706. asioObject = 0;
  208707. return false;
  208708. }
  208709. const String initDriver()
  208710. {
  208711. if (asioObject != 0)
  208712. {
  208713. char buffer [256];
  208714. zeromem (buffer, sizeof (buffer));
  208715. if (! asioObject->init (windowHandle))
  208716. {
  208717. asioObject->getErrorMessage (buffer);
  208718. return String (buffer, sizeof (buffer) - 1);
  208719. }
  208720. // just in case any daft drivers expect this to be called..
  208721. asioObject->getDriverName (buffer);
  208722. return String::empty;
  208723. }
  208724. return "No Driver";
  208725. }
  208726. const String openDevice()
  208727. {
  208728. // use this in case the driver starts opening dialog boxes..
  208729. Component modalWindow (String::empty);
  208730. modalWindow.setOpaque (true);
  208731. modalWindow.addToDesktop (0);
  208732. modalWindow.enterModalState();
  208733. // open the device and get its info..
  208734. log (T("opening ASIO device: ") + getName());
  208735. needToReset = false;
  208736. isReSync = false;
  208737. outputChannelNames.clear();
  208738. inputChannelNames.clear();
  208739. bufferSizes.clear();
  208740. sampleRates.clear();
  208741. isASIOOpen = false;
  208742. isOpen_ = false;
  208743. totalNumInputChans = 0;
  208744. totalNumOutputChans = 0;
  208745. numActiveInputChans = 0;
  208746. numActiveOutputChans = 0;
  208747. currentCallback = 0;
  208748. error = String::empty;
  208749. if (getName().isEmpty())
  208750. return error;
  208751. long err = 0;
  208752. if (loadDriver())
  208753. {
  208754. if ((error = initDriver()).isEmpty())
  208755. {
  208756. numActiveInputChans = 0;
  208757. numActiveOutputChans = 0;
  208758. totalNumInputChans = 0;
  208759. totalNumOutputChans = 0;
  208760. if (asioObject != 0
  208761. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  208762. {
  208763. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  208764. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208765. {
  208766. // find a list of buffer sizes..
  208767. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  208768. if (granularity >= 0)
  208769. {
  208770. granularity = jmax (1, (int) granularity);
  208771. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  208772. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  208773. }
  208774. else if (granularity < 0)
  208775. {
  208776. for (int i = 0; i < 18; ++i)
  208777. {
  208778. const int s = (1 << i);
  208779. if (s >= minSize && s <= maxSize)
  208780. bufferSizes.add (s);
  208781. }
  208782. }
  208783. if (! bufferSizes.contains (preferredSize))
  208784. bufferSizes.insert (0, preferredSize);
  208785. double currentRate = 0;
  208786. asioObject->getSampleRate (&currentRate);
  208787. if (currentRate <= 0.0 || currentRate > 192001.0)
  208788. {
  208789. log ("setting sample rate");
  208790. err = asioObject->setSampleRate (44100.0);
  208791. if (err != 0)
  208792. {
  208793. logError ("setting sample rate", err);
  208794. }
  208795. asioObject->getSampleRate (&currentRate);
  208796. }
  208797. currentSampleRate = currentRate;
  208798. postOutput = (asioObject->outputReady() == 0);
  208799. if (postOutput)
  208800. {
  208801. log ("ASIO outputReady = ok");
  208802. }
  208803. updateSampleRates();
  208804. // ..because cubase does it at this point
  208805. inputLatency = outputLatency = 0;
  208806. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208807. {
  208808. log ("ASIO - no latencies");
  208809. }
  208810. log (String ("latencies: ")
  208811. + String ((int) inputLatency)
  208812. + T(", ") + String ((int) outputLatency));
  208813. // create some dummy buffers now.. because cubase does..
  208814. numActiveInputChans = 0;
  208815. numActiveOutputChans = 0;
  208816. ASIOBufferInfo* info = bufferInfos;
  208817. int i, numChans = 0;
  208818. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  208819. {
  208820. info->isInput = 1;
  208821. info->channelNum = i;
  208822. info->buffers[0] = info->buffers[1] = 0;
  208823. ++info;
  208824. ++numChans;
  208825. }
  208826. const int outputBufferIndex = numChans;
  208827. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  208828. {
  208829. info->isInput = 0;
  208830. info->channelNum = i;
  208831. info->buffers[0] = info->buffers[1] = 0;
  208832. ++info;
  208833. ++numChans;
  208834. }
  208835. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208836. if (currentASIODev[0] == this)
  208837. {
  208838. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208839. callbacks.asioMessage = &asioMessagesCallback0;
  208840. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208841. }
  208842. else if (currentASIODev[1] == this)
  208843. {
  208844. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208845. callbacks.asioMessage = &asioMessagesCallback1;
  208846. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208847. }
  208848. else if (currentASIODev[2] == this)
  208849. {
  208850. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208851. callbacks.asioMessage = &asioMessagesCallback2;
  208852. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208853. }
  208854. else
  208855. {
  208856. jassertfalse
  208857. }
  208858. log (T("creating buffers (dummy): ") + String (numChans)
  208859. + T(", ") + String ((int) preferredSize));
  208860. if (preferredSize > 0)
  208861. {
  208862. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  208863. if (err != 0)
  208864. {
  208865. logError ("dummy buffers", err);
  208866. }
  208867. }
  208868. long newInps = 0, newOuts = 0;
  208869. asioObject->getChannels (&newInps, &newOuts);
  208870. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  208871. {
  208872. totalNumInputChans = newInps;
  208873. totalNumOutputChans = newOuts;
  208874. log (String ((int) totalNumInputChans) + T(" in; ")
  208875. + String ((int) totalNumOutputChans) + T(" out"));
  208876. }
  208877. updateSampleRates();
  208878. ASIOChannelInfo channelInfo;
  208879. channelInfo.type = 0;
  208880. for (i = 0; i < totalNumInputChans; ++i)
  208881. {
  208882. zerostruct (channelInfo);
  208883. channelInfo.channel = i;
  208884. channelInfo.isInput = 1;
  208885. asioObject->getChannelInfo (&channelInfo);
  208886. inputChannelNames.add (String (channelInfo.name));
  208887. }
  208888. for (i = 0; i < totalNumOutputChans; ++i)
  208889. {
  208890. zerostruct (channelInfo);
  208891. channelInfo.channel = i;
  208892. channelInfo.isInput = 0;
  208893. asioObject->getChannelInfo (&channelInfo);
  208894. outputChannelNames.add (String (channelInfo.name));
  208895. typeToFormatParameters (channelInfo.type,
  208896. outputChannelBitDepths[i],
  208897. outputChannelBytesPerSample[i],
  208898. outputChannelIsFloat[i],
  208899. outputChannelLittleEndian[i]);
  208900. if (i < 2)
  208901. {
  208902. // clear the channels that are used with the dummy stuff
  208903. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  208904. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  208905. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  208906. }
  208907. }
  208908. outputChannelNames.trim();
  208909. inputChannelNames.trim();
  208910. outputChannelNames.appendNumbersToDuplicates (false, true);
  208911. inputChannelNames.appendNumbersToDuplicates (false, true);
  208912. // start and stop because cubase does it..
  208913. asioObject->getLatencies (&inputLatency, &outputLatency);
  208914. if ((err = asioObject->start()) != 0)
  208915. {
  208916. // ignore an error here, as it might start later after setting other stuff up
  208917. logError ("ASIO start", err);
  208918. }
  208919. Thread::sleep (100);
  208920. asioObject->stop();
  208921. }
  208922. else
  208923. {
  208924. error = "Can't detect buffer sizes";
  208925. }
  208926. }
  208927. else
  208928. {
  208929. error = "Can't detect asio channels";
  208930. }
  208931. }
  208932. }
  208933. else
  208934. {
  208935. error = "No such device";
  208936. }
  208937. if (error.isNotEmpty())
  208938. {
  208939. logError (error, err);
  208940. if (asioObject != 0)
  208941. asioObject->disposeBuffers();
  208942. removeCurrentDriver();
  208943. isASIOOpen = false;
  208944. }
  208945. else
  208946. {
  208947. isASIOOpen = true;
  208948. log ("ASIO device open");
  208949. }
  208950. isOpen_ = false;
  208951. needToReset = false;
  208952. isReSync = false;
  208953. return error;
  208954. }
  208955. void callback (const long index) throw()
  208956. {
  208957. if (isStarted)
  208958. {
  208959. bufferIndex = index;
  208960. processBuffer();
  208961. }
  208962. else
  208963. {
  208964. if (postOutput && (asioObject != 0))
  208965. asioObject->outputReady();
  208966. }
  208967. calledback = true;
  208968. }
  208969. void processBuffer() throw()
  208970. {
  208971. const ASIOBufferInfo* const infos = bufferInfos;
  208972. const int bi = bufferIndex;
  208973. const ScopedLock sl (callbackLock);
  208974. if (needToReset)
  208975. {
  208976. needToReset = false;
  208977. if (isReSync)
  208978. {
  208979. log ("! ASIO resync");
  208980. isReSync = false;
  208981. }
  208982. else
  208983. {
  208984. startTimer (20);
  208985. }
  208986. }
  208987. if (bi >= 0)
  208988. {
  208989. const int samps = currentBlockSizeSamples;
  208990. if (currentCallback != 0)
  208991. {
  208992. int i;
  208993. for (i = 0; i < numActiveInputChans; ++i)
  208994. {
  208995. float* const dst = inBuffers[i];
  208996. jassert (dst != 0);
  208997. const char* const src = (const char*) (infos[i].buffers[bi]);
  208998. if (inputChannelIsFloat[i])
  208999. {
  209000. memcpy (dst, src, samps * sizeof (float));
  209001. }
  209002. else
  209003. {
  209004. jassert (dst == tempBuffer + (samps * i));
  209005. switch (inputChannelBitDepths[i])
  209006. {
  209007. case 16:
  209008. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  209009. samps, inputChannelLittleEndian[i]);
  209010. break;
  209011. case 24:
  209012. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  209013. samps, inputChannelLittleEndian[i]);
  209014. break;
  209015. case 32:
  209016. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  209017. samps, inputChannelLittleEndian[i]);
  209018. break;
  209019. case 64:
  209020. jassertfalse
  209021. break;
  209022. }
  209023. }
  209024. }
  209025. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  209026. numActiveInputChans,
  209027. outBuffers,
  209028. numActiveOutputChans,
  209029. samps);
  209030. for (i = 0; i < numActiveOutputChans; ++i)
  209031. {
  209032. float* const src = outBuffers[i];
  209033. jassert (src != 0);
  209034. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  209035. if (outputChannelIsFloat[i])
  209036. {
  209037. memcpy (dst, src, samps * sizeof (float));
  209038. }
  209039. else
  209040. {
  209041. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  209042. switch (outputChannelBitDepths[i])
  209043. {
  209044. case 16:
  209045. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  209046. samps, outputChannelLittleEndian[i]);
  209047. break;
  209048. case 24:
  209049. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  209050. samps, outputChannelLittleEndian[i]);
  209051. break;
  209052. case 32:
  209053. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  209054. samps, outputChannelLittleEndian[i]);
  209055. break;
  209056. case 64:
  209057. jassertfalse
  209058. break;
  209059. }
  209060. }
  209061. }
  209062. }
  209063. else
  209064. {
  209065. for (int i = 0; i < numActiveOutputChans; ++i)
  209066. {
  209067. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  209068. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  209069. }
  209070. }
  209071. }
  209072. if (postOutput)
  209073. asioObject->outputReady();
  209074. }
  209075. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  209076. {
  209077. if (currentASIODev[0] != 0)
  209078. currentASIODev[0]->callback (index);
  209079. return 0;
  209080. }
  209081. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  209082. {
  209083. if (currentASIODev[1] != 0)
  209084. currentASIODev[1]->callback (index);
  209085. return 0;
  209086. }
  209087. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  209088. {
  209089. if (currentASIODev[2] != 0)
  209090. currentASIODev[2]->callback (index);
  209091. return 0;
  209092. }
  209093. static void bufferSwitchCallback0 (long index, long) throw()
  209094. {
  209095. if (currentASIODev[0] != 0)
  209096. currentASIODev[0]->callback (index);
  209097. }
  209098. static void bufferSwitchCallback1 (long index, long) throw()
  209099. {
  209100. if (currentASIODev[1] != 0)
  209101. currentASIODev[1]->callback (index);
  209102. }
  209103. static void bufferSwitchCallback2 (long index, long) throw()
  209104. {
  209105. if (currentASIODev[2] != 0)
  209106. currentASIODev[2]->callback (index);
  209107. }
  209108. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  209109. {
  209110. return asioMessagesCallback (selector, value, 0);
  209111. }
  209112. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  209113. {
  209114. return asioMessagesCallback (selector, value, 1);
  209115. }
  209116. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  209117. {
  209118. return asioMessagesCallback (selector, value, 2);
  209119. }
  209120. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  209121. {
  209122. switch (selector)
  209123. {
  209124. case kAsioSelectorSupported:
  209125. if (value == kAsioResetRequest
  209126. || value == kAsioEngineVersion
  209127. || value == kAsioResyncRequest
  209128. || value == kAsioLatenciesChanged
  209129. || value == kAsioSupportsInputMonitor)
  209130. return 1;
  209131. break;
  209132. case kAsioBufferSizeChange:
  209133. break;
  209134. case kAsioResetRequest:
  209135. if (currentASIODev[deviceIndex] != 0)
  209136. currentASIODev[deviceIndex]->resetRequest();
  209137. return 1;
  209138. case kAsioResyncRequest:
  209139. if (currentASIODev[deviceIndex] != 0)
  209140. currentASIODev[deviceIndex]->resyncRequest();
  209141. return 1;
  209142. case kAsioLatenciesChanged:
  209143. return 1;
  209144. case kAsioEngineVersion:
  209145. return 2;
  209146. case kAsioSupportsTimeInfo:
  209147. case kAsioSupportsTimeCode:
  209148. return 0;
  209149. }
  209150. return 0;
  209151. }
  209152. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  209153. {
  209154. }
  209155. static void convertInt16ToFloat (const char* src,
  209156. float* dest,
  209157. const int srcStrideBytes,
  209158. int numSamples,
  209159. const bool littleEndian) throw()
  209160. {
  209161. const double g = 1.0 / 32768.0;
  209162. if (littleEndian)
  209163. {
  209164. while (--numSamples >= 0)
  209165. {
  209166. *dest++ = (float) (g * (short) littleEndianShort (src));
  209167. src += srcStrideBytes;
  209168. }
  209169. }
  209170. else
  209171. {
  209172. while (--numSamples >= 0)
  209173. {
  209174. *dest++ = (float) (g * (short) bigEndianShort (src));
  209175. src += srcStrideBytes;
  209176. }
  209177. }
  209178. }
  209179. static void convertFloatToInt16 (const float* src,
  209180. char* dest,
  209181. const int dstStrideBytes,
  209182. int numSamples,
  209183. const bool littleEndian) throw()
  209184. {
  209185. const double maxVal = (double) 0x7fff;
  209186. if (littleEndian)
  209187. {
  209188. while (--numSamples >= 0)
  209189. {
  209190. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209191. dest += dstStrideBytes;
  209192. }
  209193. }
  209194. else
  209195. {
  209196. while (--numSamples >= 0)
  209197. {
  209198. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209199. dest += dstStrideBytes;
  209200. }
  209201. }
  209202. }
  209203. static void convertInt24ToFloat (const char* src,
  209204. float* dest,
  209205. const int srcStrideBytes,
  209206. int numSamples,
  209207. const bool littleEndian) throw()
  209208. {
  209209. const double g = 1.0 / 0x7fffff;
  209210. if (littleEndian)
  209211. {
  209212. while (--numSamples >= 0)
  209213. {
  209214. *dest++ = (float) (g * littleEndian24Bit (src));
  209215. src += srcStrideBytes;
  209216. }
  209217. }
  209218. else
  209219. {
  209220. while (--numSamples >= 0)
  209221. {
  209222. *dest++ = (float) (g * bigEndian24Bit (src));
  209223. src += srcStrideBytes;
  209224. }
  209225. }
  209226. }
  209227. static void convertFloatToInt24 (const float* src,
  209228. char* dest,
  209229. const int dstStrideBytes,
  209230. int numSamples,
  209231. const bool littleEndian) throw()
  209232. {
  209233. const double maxVal = (double) 0x7fffff;
  209234. if (littleEndian)
  209235. {
  209236. while (--numSamples >= 0)
  209237. {
  209238. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209239. dest += dstStrideBytes;
  209240. }
  209241. }
  209242. else
  209243. {
  209244. while (--numSamples >= 0)
  209245. {
  209246. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209247. dest += dstStrideBytes;
  209248. }
  209249. }
  209250. }
  209251. static void convertInt32ToFloat (const char* src,
  209252. float* dest,
  209253. const int srcStrideBytes,
  209254. int numSamples,
  209255. const bool littleEndian) throw()
  209256. {
  209257. const double g = 1.0 / 0x7fffffff;
  209258. if (littleEndian)
  209259. {
  209260. while (--numSamples >= 0)
  209261. {
  209262. *dest++ = (float) (g * (int) littleEndianInt (src));
  209263. src += srcStrideBytes;
  209264. }
  209265. }
  209266. else
  209267. {
  209268. while (--numSamples >= 0)
  209269. {
  209270. *dest++ = (float) (g * (int) bigEndianInt (src));
  209271. src += srcStrideBytes;
  209272. }
  209273. }
  209274. }
  209275. static void convertFloatToInt32 (const float* src,
  209276. char* dest,
  209277. const int dstStrideBytes,
  209278. int numSamples,
  209279. const bool littleEndian) throw()
  209280. {
  209281. const double maxVal = (double) 0x7fffffff;
  209282. if (littleEndian)
  209283. {
  209284. while (--numSamples >= 0)
  209285. {
  209286. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209287. dest += dstStrideBytes;
  209288. }
  209289. }
  209290. else
  209291. {
  209292. while (--numSamples >= 0)
  209293. {
  209294. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209295. dest += dstStrideBytes;
  209296. }
  209297. }
  209298. }
  209299. static void typeToFormatParameters (const long type,
  209300. int& bitDepth,
  209301. int& byteStride,
  209302. bool& formatIsFloat,
  209303. bool& littleEndian) throw()
  209304. {
  209305. bitDepth = 0;
  209306. littleEndian = false;
  209307. formatIsFloat = false;
  209308. switch (type)
  209309. {
  209310. case ASIOSTInt16MSB:
  209311. case ASIOSTInt16LSB:
  209312. case ASIOSTInt32MSB16:
  209313. case ASIOSTInt32LSB16:
  209314. bitDepth = 16; break;
  209315. case ASIOSTFloat32MSB:
  209316. case ASIOSTFloat32LSB:
  209317. formatIsFloat = true;
  209318. bitDepth = 32; break;
  209319. case ASIOSTInt32MSB:
  209320. case ASIOSTInt32LSB:
  209321. bitDepth = 32; break;
  209322. case ASIOSTInt24MSB:
  209323. case ASIOSTInt24LSB:
  209324. case ASIOSTInt32MSB24:
  209325. case ASIOSTInt32LSB24:
  209326. case ASIOSTInt32MSB18:
  209327. case ASIOSTInt32MSB20:
  209328. case ASIOSTInt32LSB18:
  209329. case ASIOSTInt32LSB20:
  209330. bitDepth = 24; break;
  209331. case ASIOSTFloat64MSB:
  209332. case ASIOSTFloat64LSB:
  209333. default:
  209334. bitDepth = 64;
  209335. break;
  209336. }
  209337. switch (type)
  209338. {
  209339. case ASIOSTInt16MSB:
  209340. case ASIOSTInt32MSB16:
  209341. case ASIOSTFloat32MSB:
  209342. case ASIOSTFloat64MSB:
  209343. case ASIOSTInt32MSB:
  209344. case ASIOSTInt32MSB18:
  209345. case ASIOSTInt32MSB20:
  209346. case ASIOSTInt32MSB24:
  209347. case ASIOSTInt24MSB:
  209348. littleEndian = false; break;
  209349. case ASIOSTInt16LSB:
  209350. case ASIOSTInt32LSB16:
  209351. case ASIOSTFloat32LSB:
  209352. case ASIOSTFloat64LSB:
  209353. case ASIOSTInt32LSB:
  209354. case ASIOSTInt32LSB18:
  209355. case ASIOSTInt32LSB20:
  209356. case ASIOSTInt32LSB24:
  209357. case ASIOSTInt24LSB:
  209358. littleEndian = true; break;
  209359. default:
  209360. break;
  209361. }
  209362. switch (type)
  209363. {
  209364. case ASIOSTInt16LSB:
  209365. case ASIOSTInt16MSB:
  209366. byteStride = 2; break;
  209367. case ASIOSTInt24LSB:
  209368. case ASIOSTInt24MSB:
  209369. byteStride = 3; break;
  209370. case ASIOSTInt32MSB16:
  209371. case ASIOSTInt32LSB16:
  209372. case ASIOSTInt32MSB:
  209373. case ASIOSTInt32MSB18:
  209374. case ASIOSTInt32MSB20:
  209375. case ASIOSTInt32MSB24:
  209376. case ASIOSTInt32LSB:
  209377. case ASIOSTInt32LSB18:
  209378. case ASIOSTInt32LSB20:
  209379. case ASIOSTInt32LSB24:
  209380. case ASIOSTFloat32LSB:
  209381. case ASIOSTFloat32MSB:
  209382. byteStride = 4; break;
  209383. case ASIOSTFloat64MSB:
  209384. case ASIOSTFloat64LSB:
  209385. byteStride = 8; break;
  209386. default:
  209387. break;
  209388. }
  209389. }
  209390. };
  209391. class ASIOAudioIODeviceType : public AudioIODeviceType
  209392. {
  209393. public:
  209394. ASIOAudioIODeviceType()
  209395. : AudioIODeviceType (T("ASIO")),
  209396. classIds (2),
  209397. hasScanned (false)
  209398. {
  209399. CoInitialize (0);
  209400. }
  209401. ~ASIOAudioIODeviceType()
  209402. {
  209403. }
  209404. void scanForDevices()
  209405. {
  209406. hasScanned = true;
  209407. deviceNames.clear();
  209408. classIds.clear();
  209409. HKEY hk = 0;
  209410. int index = 0;
  209411. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  209412. {
  209413. for (;;)
  209414. {
  209415. char name [256];
  209416. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  209417. {
  209418. addDriverInfo (name, hk);
  209419. }
  209420. else
  209421. {
  209422. break;
  209423. }
  209424. }
  209425. RegCloseKey (hk);
  209426. }
  209427. }
  209428. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  209429. {
  209430. jassert (hasScanned); // need to call scanForDevices() before doing this
  209431. return deviceNames;
  209432. }
  209433. int getDefaultDeviceIndex (const bool) const
  209434. {
  209435. jassert (hasScanned); // need to call scanForDevices() before doing this
  209436. for (int i = deviceNames.size(); --i >= 0;)
  209437. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  209438. return i; // asio4all is a safe choice for a default..
  209439. #if JUCE_DEBUG
  209440. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  209441. return 1; // (the digi m-box driver crashes the app when you run
  209442. // it in the debugger, which can be a bit annoying)
  209443. #endif
  209444. return 0;
  209445. }
  209446. static int findFreeSlot()
  209447. {
  209448. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209449. if (currentASIODev[i] == 0)
  209450. return i;
  209451. jassertfalse; // unfortunately you can only have a finite number
  209452. // of ASIO devices open at the same time..
  209453. return -1;
  209454. }
  209455. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  209456. {
  209457. jassert (hasScanned); // need to call scanForDevices() before doing this
  209458. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  209459. }
  209460. bool hasSeparateInputsAndOutputs() const { return false; }
  209461. AudioIODevice* createDevice (const String& outputDeviceName,
  209462. const String& inputDeviceName)
  209463. {
  209464. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  209465. (void) inputDeviceName;
  209466. jassert (hasScanned); // need to call scanForDevices() before doing this
  209467. const int index = deviceNames.indexOf (outputDeviceName);
  209468. if (index >= 0)
  209469. {
  209470. const int freeSlot = findFreeSlot();
  209471. if (freeSlot >= 0)
  209472. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  209473. }
  209474. return 0;
  209475. }
  209476. juce_UseDebuggingNewOperator
  209477. private:
  209478. StringArray deviceNames;
  209479. OwnedArray <CLSID> classIds;
  209480. bool hasScanned;
  209481. static bool checkClassIsOk (const String& classId)
  209482. {
  209483. HKEY hk = 0;
  209484. bool ok = false;
  209485. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  209486. {
  209487. int index = 0;
  209488. for (;;)
  209489. {
  209490. char buf [512];
  209491. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  209492. {
  209493. if (classId.equalsIgnoreCase (buf))
  209494. {
  209495. HKEY subKey, pathKey;
  209496. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209497. {
  209498. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  209499. {
  209500. char pathName [600];
  209501. DWORD dtype = REG_SZ;
  209502. DWORD dsize = sizeof (pathName);
  209503. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  209504. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  209505. {
  209506. OFSTRUCT of;
  209507. zerostruct (of);
  209508. of.cBytes = sizeof (of);
  209509. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  209510. }
  209511. RegCloseKey (pathKey);
  209512. }
  209513. RegCloseKey (subKey);
  209514. }
  209515. break;
  209516. }
  209517. }
  209518. else
  209519. {
  209520. break;
  209521. }
  209522. }
  209523. RegCloseKey (hk);
  209524. }
  209525. return ok;
  209526. }
  209527. void addDriverInfo (const String& keyName, HKEY hk)
  209528. {
  209529. HKEY subKey;
  209530. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209531. {
  209532. char buf [256];
  209533. DWORD dtype = REG_SZ;
  209534. DWORD dsize = sizeof (buf);
  209535. zeromem (buf, dsize);
  209536. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209537. {
  209538. if (dsize > 0 && checkClassIsOk (buf))
  209539. {
  209540. wchar_t classIdStr [130];
  209541. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  209542. String deviceName;
  209543. CLSID classId;
  209544. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  209545. {
  209546. dtype = REG_SZ;
  209547. dsize = sizeof (buf);
  209548. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209549. deviceName = buf;
  209550. else
  209551. deviceName = keyName;
  209552. log (T("found ") + deviceName);
  209553. deviceNames.add (deviceName);
  209554. classIds.add (new CLSID (classId));
  209555. }
  209556. }
  209557. RegCloseKey (subKey);
  209558. }
  209559. }
  209560. }
  209561. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  209562. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  209563. };
  209564. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  209565. {
  209566. return new ASIOAudioIODeviceType();
  209567. }
  209568. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  209569. void* guid,
  209570. const String& optionalDllForDirectLoading)
  209571. {
  209572. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  209573. if (freeSlot < 0)
  209574. return 0;
  209575. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  209576. }
  209577. #undef log
  209578. #endif
  209579. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  209580. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  209581. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209582. // compiled on its own).
  209583. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  209584. END_JUCE_NAMESPACE
  209585. extern "C"
  209586. {
  209587. // Declare just the minimum number of interfaces for the DSound objects that we need..
  209588. typedef struct typeDSBUFFERDESC
  209589. {
  209590. DWORD dwSize;
  209591. DWORD dwFlags;
  209592. DWORD dwBufferBytes;
  209593. DWORD dwReserved;
  209594. LPWAVEFORMATEX lpwfxFormat;
  209595. GUID guid3DAlgorithm;
  209596. } DSBUFFERDESC;
  209597. struct IDirectSoundBuffer;
  209598. #undef INTERFACE
  209599. #define INTERFACE IDirectSound
  209600. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  209601. {
  209602. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209603. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209604. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209605. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  209606. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209607. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  209608. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  209609. STDMETHOD(Compact) (THIS) PURE;
  209610. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  209611. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  209612. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209613. };
  209614. #undef INTERFACE
  209615. #define INTERFACE IDirectSoundBuffer
  209616. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  209617. {
  209618. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209619. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209620. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209621. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209622. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209623. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209624. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  209625. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  209626. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  209627. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209628. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  209629. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209630. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  209631. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  209632. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  209633. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  209634. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  209635. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  209636. STDMETHOD(Stop) (THIS) PURE;
  209637. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209638. STDMETHOD(Restore) (THIS) PURE;
  209639. };
  209640. typedef struct typeDSCBUFFERDESC
  209641. {
  209642. DWORD dwSize;
  209643. DWORD dwFlags;
  209644. DWORD dwBufferBytes;
  209645. DWORD dwReserved;
  209646. LPWAVEFORMATEX lpwfxFormat;
  209647. } DSCBUFFERDESC;
  209648. struct IDirectSoundCaptureBuffer;
  209649. #undef INTERFACE
  209650. #define INTERFACE IDirectSoundCapture
  209651. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  209652. {
  209653. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209654. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209655. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209656. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  209657. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209658. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209659. };
  209660. #undef INTERFACE
  209661. #define INTERFACE IDirectSoundCaptureBuffer
  209662. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  209663. {
  209664. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209665. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209666. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209667. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209668. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209669. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209670. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209671. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  209672. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209673. STDMETHOD(Start) (THIS_ DWORD) PURE;
  209674. STDMETHOD(Stop) (THIS) PURE;
  209675. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209676. };
  209677. };
  209678. BEGIN_JUCE_NAMESPACE
  209679. static const String getDSErrorMessage (HRESULT hr)
  209680. {
  209681. const char* result = 0;
  209682. switch (hr)
  209683. {
  209684. case MAKE_HRESULT(1, 0x878, 10):
  209685. result = "Device already allocated";
  209686. break;
  209687. case MAKE_HRESULT(1, 0x878, 30):
  209688. result = "Control unavailable";
  209689. break;
  209690. case E_INVALIDARG:
  209691. result = "Invalid parameter";
  209692. break;
  209693. case MAKE_HRESULT(1, 0x878, 50):
  209694. result = "Invalid call";
  209695. break;
  209696. case E_FAIL:
  209697. result = "Generic error";
  209698. break;
  209699. case MAKE_HRESULT(1, 0x878, 70):
  209700. result = "Priority level error";
  209701. break;
  209702. case E_OUTOFMEMORY:
  209703. result = "Out of memory";
  209704. break;
  209705. case MAKE_HRESULT(1, 0x878, 100):
  209706. result = "Bad format";
  209707. break;
  209708. case E_NOTIMPL:
  209709. result = "Unsupported function";
  209710. break;
  209711. case MAKE_HRESULT(1, 0x878, 120):
  209712. result = "No driver";
  209713. break;
  209714. case MAKE_HRESULT(1, 0x878, 130):
  209715. result = "Already initialised";
  209716. break;
  209717. case CLASS_E_NOAGGREGATION:
  209718. result = "No aggregation";
  209719. break;
  209720. case MAKE_HRESULT(1, 0x878, 150):
  209721. result = "Buffer lost";
  209722. break;
  209723. case MAKE_HRESULT(1, 0x878, 160):
  209724. result = "Another app has priority";
  209725. break;
  209726. case MAKE_HRESULT(1, 0x878, 170):
  209727. result = "Uninitialised";
  209728. break;
  209729. case E_NOINTERFACE:
  209730. result = "No interface";
  209731. break;
  209732. case S_OK:
  209733. result = "No error";
  209734. break;
  209735. default:
  209736. return "Unknown error: " + String ((int) hr);
  209737. }
  209738. return result;
  209739. }
  209740. #define DS_DEBUGGING 1
  209741. #ifdef DS_DEBUGGING
  209742. #define CATCH JUCE_CATCH_EXCEPTION
  209743. #undef log
  209744. #define log(a) Logger::writeToLog(a);
  209745. #undef logError
  209746. #define logError(a) logDSError(a, __LINE__);
  209747. static void logDSError (HRESULT hr, int lineNum)
  209748. {
  209749. if (hr != S_OK)
  209750. {
  209751. String error ("DS error at line ");
  209752. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  209753. log (error);
  209754. }
  209755. }
  209756. #else
  209757. #define CATCH JUCE_CATCH_ALL
  209758. #define log(a)
  209759. #define logError(a)
  209760. #endif
  209761. #define DSOUND_FUNCTION(functionName, params) \
  209762. typedef HRESULT (WINAPI *type##functionName) params; \
  209763. static type##functionName ds##functionName = 0;
  209764. #define DSOUND_FUNCTION_LOAD(functionName) \
  209765. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  209766. jassert (ds##functionName != 0);
  209767. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  209768. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  209769. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  209770. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  209771. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209772. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209773. static void initialiseDSoundFunctions()
  209774. {
  209775. if (dsDirectSoundCreate == 0)
  209776. {
  209777. HMODULE h = LoadLibraryA ("dsound.dll");
  209778. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  209779. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  209780. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  209781. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  209782. }
  209783. }
  209784. class DSoundInternalOutChannel
  209785. {
  209786. String name;
  209787. LPGUID guid;
  209788. int sampleRate, bufferSizeSamples;
  209789. float* leftBuffer;
  209790. float* rightBuffer;
  209791. IDirectSound* pDirectSound;
  209792. IDirectSoundBuffer* pOutputBuffer;
  209793. DWORD writeOffset;
  209794. int totalBytesPerBuffer;
  209795. int bytesPerBuffer;
  209796. unsigned int lastPlayCursor;
  209797. public:
  209798. int bitDepth;
  209799. bool doneFlag;
  209800. DSoundInternalOutChannel (const String& name_,
  209801. LPGUID guid_,
  209802. int rate,
  209803. int bufferSize,
  209804. float* left,
  209805. float* right)
  209806. : name (name_),
  209807. guid (guid_),
  209808. sampleRate (rate),
  209809. bufferSizeSamples (bufferSize),
  209810. leftBuffer (left),
  209811. rightBuffer (right),
  209812. pDirectSound (0),
  209813. pOutputBuffer (0),
  209814. bitDepth (16)
  209815. {
  209816. }
  209817. ~DSoundInternalOutChannel()
  209818. {
  209819. close();
  209820. }
  209821. void close()
  209822. {
  209823. HRESULT hr;
  209824. if (pOutputBuffer != 0)
  209825. {
  209826. JUCE_TRY
  209827. {
  209828. log (T("closing dsound out: ") + name);
  209829. hr = pOutputBuffer->Stop();
  209830. logError (hr);
  209831. }
  209832. CATCH
  209833. JUCE_TRY
  209834. {
  209835. hr = pOutputBuffer->Release();
  209836. logError (hr);
  209837. }
  209838. CATCH
  209839. pOutputBuffer = 0;
  209840. }
  209841. if (pDirectSound != 0)
  209842. {
  209843. JUCE_TRY
  209844. {
  209845. hr = pDirectSound->Release();
  209846. logError (hr);
  209847. }
  209848. CATCH
  209849. pDirectSound = 0;
  209850. }
  209851. }
  209852. const String open()
  209853. {
  209854. log (T("opening dsound out device: ") + name
  209855. + T(" rate=") + String (sampleRate)
  209856. + T(" bits=") + String (bitDepth)
  209857. + T(" buf=") + String (bufferSizeSamples));
  209858. pDirectSound = 0;
  209859. pOutputBuffer = 0;
  209860. writeOffset = 0;
  209861. String error;
  209862. HRESULT hr = E_NOINTERFACE;
  209863. if (dsDirectSoundCreate != 0)
  209864. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  209865. if (hr == S_OK)
  209866. {
  209867. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209868. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209869. const int numChannels = 2;
  209870. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  209871. logError (hr);
  209872. if (hr == S_OK)
  209873. {
  209874. IDirectSoundBuffer* pPrimaryBuffer;
  209875. DSBUFFERDESC primaryDesc;
  209876. zerostruct (primaryDesc);
  209877. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209878. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  209879. primaryDesc.dwBufferBytes = 0;
  209880. primaryDesc.lpwfxFormat = 0;
  209881. log ("opening dsound out step 2");
  209882. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  209883. logError (hr);
  209884. if (hr == S_OK)
  209885. {
  209886. WAVEFORMATEX wfFormat;
  209887. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209888. wfFormat.nChannels = (unsigned short) numChannels;
  209889. wfFormat.nSamplesPerSec = sampleRate;
  209890. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  209891. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  209892. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209893. wfFormat.cbSize = 0;
  209894. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  209895. logError (hr);
  209896. if (hr == S_OK)
  209897. {
  209898. DSBUFFERDESC secondaryDesc;
  209899. zerostruct (secondaryDesc);
  209900. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209901. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  209902. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  209903. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  209904. secondaryDesc.lpwfxFormat = &wfFormat;
  209905. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  209906. logError (hr);
  209907. if (hr == S_OK)
  209908. {
  209909. log ("opening dsound out step 3");
  209910. DWORD dwDataLen;
  209911. unsigned char* pDSBuffData;
  209912. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  209913. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  209914. logError (hr);
  209915. if (hr == S_OK)
  209916. {
  209917. zeromem (pDSBuffData, dwDataLen);
  209918. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  209919. if (hr == S_OK)
  209920. {
  209921. hr = pOutputBuffer->SetCurrentPosition (0);
  209922. if (hr == S_OK)
  209923. {
  209924. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  209925. if (hr == S_OK)
  209926. return String::empty;
  209927. }
  209928. }
  209929. }
  209930. }
  209931. }
  209932. }
  209933. }
  209934. }
  209935. error = getDSErrorMessage (hr);
  209936. close();
  209937. return error;
  209938. }
  209939. void synchronisePosition()
  209940. {
  209941. if (pOutputBuffer != 0)
  209942. {
  209943. DWORD playCursor;
  209944. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  209945. }
  209946. }
  209947. bool service()
  209948. {
  209949. if (pOutputBuffer == 0)
  209950. return true;
  209951. DWORD playCursor, writeCursor;
  209952. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  209953. if (hr != S_OK)
  209954. {
  209955. logError (hr);
  209956. jassertfalse
  209957. return true;
  209958. }
  209959. int playWriteGap = writeCursor - playCursor;
  209960. if (playWriteGap < 0)
  209961. playWriteGap += totalBytesPerBuffer;
  209962. int bytesEmpty = playCursor - writeOffset;
  209963. if (bytesEmpty < 0)
  209964. bytesEmpty += totalBytesPerBuffer;
  209965. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  209966. {
  209967. writeOffset = writeCursor;
  209968. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  209969. }
  209970. if (bytesEmpty >= bytesPerBuffer)
  209971. {
  209972. LPBYTE lpbuf1 = 0;
  209973. LPBYTE lpbuf2 = 0;
  209974. DWORD dwSize1 = 0;
  209975. DWORD dwSize2 = 0;
  209976. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  209977. bytesPerBuffer,
  209978. (void**) &lpbuf1, &dwSize1,
  209979. (void**) &lpbuf2, &dwSize2, 0);
  209980. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  209981. {
  209982. pOutputBuffer->Restore();
  209983. hr = pOutputBuffer->Lock (writeOffset,
  209984. bytesPerBuffer,
  209985. (void**) &lpbuf1, &dwSize1,
  209986. (void**) &lpbuf2, &dwSize2, 0);
  209987. }
  209988. if (hr == S_OK)
  209989. {
  209990. if (bitDepth == 16)
  209991. {
  209992. const float gainL = 32767.0f;
  209993. const float gainR = 32767.0f;
  209994. int* dest = (int*)lpbuf1;
  209995. const float* left = leftBuffer;
  209996. const float* right = rightBuffer;
  209997. int samples1 = dwSize1 >> 2;
  209998. int samples2 = dwSize2 >> 2;
  209999. if (left == 0)
  210000. {
  210001. while (--samples1 >= 0)
  210002. {
  210003. int r = roundFloatToInt (gainR * *right++);
  210004. if (r < -32768)
  210005. r = -32768;
  210006. else if (r > 32767)
  210007. r = 32767;
  210008. *dest++ = (r << 16);
  210009. }
  210010. dest = (int*)lpbuf2;
  210011. while (--samples2 >= 0)
  210012. {
  210013. int r = roundFloatToInt (gainR * *right++);
  210014. if (r < -32768)
  210015. r = -32768;
  210016. else if (r > 32767)
  210017. r = 32767;
  210018. *dest++ = (r << 16);
  210019. }
  210020. }
  210021. else if (right == 0)
  210022. {
  210023. while (--samples1 >= 0)
  210024. {
  210025. int l = roundFloatToInt (gainL * *left++);
  210026. if (l < -32768)
  210027. l = -32768;
  210028. else if (l > 32767)
  210029. l = 32767;
  210030. l &= 0xffff;
  210031. *dest++ = l;
  210032. }
  210033. dest = (int*)lpbuf2;
  210034. while (--samples2 >= 0)
  210035. {
  210036. int l = roundFloatToInt (gainL * *left++);
  210037. if (l < -32768)
  210038. l = -32768;
  210039. else if (l > 32767)
  210040. l = 32767;
  210041. l &= 0xffff;
  210042. *dest++ = l;
  210043. }
  210044. }
  210045. else
  210046. {
  210047. while (--samples1 >= 0)
  210048. {
  210049. int l = roundFloatToInt (gainL * *left++);
  210050. if (l < -32768)
  210051. l = -32768;
  210052. else if (l > 32767)
  210053. l = 32767;
  210054. l &= 0xffff;
  210055. int r = roundFloatToInt (gainR * *right++);
  210056. if (r < -32768)
  210057. r = -32768;
  210058. else if (r > 32767)
  210059. r = 32767;
  210060. *dest++ = (r << 16) | l;
  210061. }
  210062. dest = (int*)lpbuf2;
  210063. while (--samples2 >= 0)
  210064. {
  210065. int l = roundFloatToInt (gainL * *left++);
  210066. if (l < -32768)
  210067. l = -32768;
  210068. else if (l > 32767)
  210069. l = 32767;
  210070. l &= 0xffff;
  210071. int r = roundFloatToInt (gainR * *right++);
  210072. if (r < -32768)
  210073. r = -32768;
  210074. else if (r > 32767)
  210075. r = 32767;
  210076. *dest++ = (r << 16) | l;
  210077. }
  210078. }
  210079. }
  210080. else
  210081. {
  210082. jassertfalse
  210083. }
  210084. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  210085. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  210086. }
  210087. else
  210088. {
  210089. jassertfalse
  210090. logError (hr);
  210091. }
  210092. bytesEmpty -= bytesPerBuffer;
  210093. return true;
  210094. }
  210095. else
  210096. {
  210097. return false;
  210098. }
  210099. }
  210100. };
  210101. struct DSoundInternalInChannel
  210102. {
  210103. String name;
  210104. LPGUID guid;
  210105. int sampleRate, bufferSizeSamples;
  210106. float* leftBuffer;
  210107. float* rightBuffer;
  210108. IDirectSound* pDirectSound;
  210109. IDirectSoundCapture* pDirectSoundCapture;
  210110. IDirectSoundCaptureBuffer* pInputBuffer;
  210111. public:
  210112. unsigned int readOffset;
  210113. int bytesPerBuffer, totalBytesPerBuffer;
  210114. int bitDepth;
  210115. bool doneFlag;
  210116. DSoundInternalInChannel (const String& name_,
  210117. LPGUID guid_,
  210118. int rate,
  210119. int bufferSize,
  210120. float* left,
  210121. float* right)
  210122. : name (name_),
  210123. guid (guid_),
  210124. sampleRate (rate),
  210125. bufferSizeSamples (bufferSize),
  210126. leftBuffer (left),
  210127. rightBuffer (right),
  210128. pDirectSound (0),
  210129. pDirectSoundCapture (0),
  210130. pInputBuffer (0),
  210131. bitDepth (16)
  210132. {
  210133. }
  210134. ~DSoundInternalInChannel()
  210135. {
  210136. close();
  210137. }
  210138. void close()
  210139. {
  210140. HRESULT hr;
  210141. if (pInputBuffer != 0)
  210142. {
  210143. JUCE_TRY
  210144. {
  210145. log (T("closing dsound in: ") + name);
  210146. hr = pInputBuffer->Stop();
  210147. logError (hr);
  210148. }
  210149. CATCH
  210150. JUCE_TRY
  210151. {
  210152. hr = pInputBuffer->Release();
  210153. logError (hr);
  210154. }
  210155. CATCH
  210156. pInputBuffer = 0;
  210157. }
  210158. if (pDirectSoundCapture != 0)
  210159. {
  210160. JUCE_TRY
  210161. {
  210162. hr = pDirectSoundCapture->Release();
  210163. logError (hr);
  210164. }
  210165. CATCH
  210166. pDirectSoundCapture = 0;
  210167. }
  210168. if (pDirectSound != 0)
  210169. {
  210170. JUCE_TRY
  210171. {
  210172. hr = pDirectSound->Release();
  210173. logError (hr);
  210174. }
  210175. CATCH
  210176. pDirectSound = 0;
  210177. }
  210178. }
  210179. const String open()
  210180. {
  210181. log (T("opening dsound in device: ") + name
  210182. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  210183. pDirectSound = 0;
  210184. pDirectSoundCapture = 0;
  210185. pInputBuffer = 0;
  210186. readOffset = 0;
  210187. totalBytesPerBuffer = 0;
  210188. String error;
  210189. HRESULT hr = E_NOINTERFACE;
  210190. if (dsDirectSoundCaptureCreate != 0)
  210191. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  210192. logError (hr);
  210193. if (hr == S_OK)
  210194. {
  210195. const int numChannels = 2;
  210196. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210197. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210198. WAVEFORMATEX wfFormat;
  210199. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210200. wfFormat.nChannels = (unsigned short)numChannels;
  210201. wfFormat.nSamplesPerSec = sampleRate;
  210202. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  210203. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  210204. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210205. wfFormat.cbSize = 0;
  210206. DSCBUFFERDESC captureDesc;
  210207. zerostruct (captureDesc);
  210208. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  210209. captureDesc.dwFlags = 0;
  210210. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  210211. captureDesc.lpwfxFormat = &wfFormat;
  210212. log (T("opening dsound in step 2"));
  210213. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  210214. logError (hr);
  210215. if (hr == S_OK)
  210216. {
  210217. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  210218. logError (hr);
  210219. if (hr == S_OK)
  210220. return String::empty;
  210221. }
  210222. }
  210223. error = getDSErrorMessage (hr);
  210224. close();
  210225. return error;
  210226. }
  210227. void synchronisePosition()
  210228. {
  210229. if (pInputBuffer != 0)
  210230. {
  210231. DWORD capturePos;
  210232. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  210233. }
  210234. }
  210235. bool service()
  210236. {
  210237. if (pInputBuffer == 0)
  210238. return true;
  210239. DWORD capturePos, readPos;
  210240. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  210241. logError (hr);
  210242. if (hr != S_OK)
  210243. return true;
  210244. int bytesFilled = readPos - readOffset;
  210245. if (bytesFilled < 0)
  210246. bytesFilled += totalBytesPerBuffer;
  210247. if (bytesFilled >= bytesPerBuffer)
  210248. {
  210249. LPBYTE lpbuf1 = 0;
  210250. LPBYTE lpbuf2 = 0;
  210251. DWORD dwsize1 = 0;
  210252. DWORD dwsize2 = 0;
  210253. HRESULT hr = pInputBuffer->Lock (readOffset,
  210254. bytesPerBuffer,
  210255. (void**) &lpbuf1, &dwsize1,
  210256. (void**) &lpbuf2, &dwsize2, 0);
  210257. if (hr == S_OK)
  210258. {
  210259. if (bitDepth == 16)
  210260. {
  210261. const float g = 1.0f / 32768.0f;
  210262. float* destL = leftBuffer;
  210263. float* destR = rightBuffer;
  210264. int samples1 = dwsize1 >> 2;
  210265. int samples2 = dwsize2 >> 2;
  210266. const short* src = (const short*)lpbuf1;
  210267. if (destL == 0)
  210268. {
  210269. while (--samples1 >= 0)
  210270. {
  210271. ++src;
  210272. *destR++ = *src++ * g;
  210273. }
  210274. src = (const short*)lpbuf2;
  210275. while (--samples2 >= 0)
  210276. {
  210277. ++src;
  210278. *destR++ = *src++ * g;
  210279. }
  210280. }
  210281. else if (destR == 0)
  210282. {
  210283. while (--samples1 >= 0)
  210284. {
  210285. *destL++ = *src++ * g;
  210286. ++src;
  210287. }
  210288. src = (const short*)lpbuf2;
  210289. while (--samples2 >= 0)
  210290. {
  210291. *destL++ = *src++ * g;
  210292. ++src;
  210293. }
  210294. }
  210295. else
  210296. {
  210297. while (--samples1 >= 0)
  210298. {
  210299. *destL++ = *src++ * g;
  210300. *destR++ = *src++ * g;
  210301. }
  210302. src = (const short*)lpbuf2;
  210303. while (--samples2 >= 0)
  210304. {
  210305. *destL++ = *src++ * g;
  210306. *destR++ = *src++ * g;
  210307. }
  210308. }
  210309. }
  210310. else
  210311. {
  210312. jassertfalse
  210313. }
  210314. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  210315. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  210316. }
  210317. else
  210318. {
  210319. logError (hr);
  210320. jassertfalse
  210321. }
  210322. bytesFilled -= bytesPerBuffer;
  210323. return true;
  210324. }
  210325. else
  210326. {
  210327. return false;
  210328. }
  210329. }
  210330. };
  210331. class DSoundAudioIODevice : public AudioIODevice,
  210332. public Thread
  210333. {
  210334. public:
  210335. DSoundAudioIODevice (const String& deviceName,
  210336. const int outputDeviceIndex_,
  210337. const int inputDeviceIndex_)
  210338. : AudioIODevice (deviceName, "DirectSound"),
  210339. Thread ("Juce DSound"),
  210340. isOpen_ (false),
  210341. isStarted (false),
  210342. outputDeviceIndex (outputDeviceIndex_),
  210343. inputDeviceIndex (inputDeviceIndex_),
  210344. inChans (4),
  210345. outChans (4),
  210346. numInputBuffers (0),
  210347. numOutputBuffers (0),
  210348. totalSamplesOut (0),
  210349. sampleRate (0.0),
  210350. inputBuffers (0),
  210351. outputBuffers (0),
  210352. callback (0),
  210353. bufferSizeSamples (0)
  210354. {
  210355. if (outputDeviceIndex_ >= 0)
  210356. {
  210357. outChannels.add (TRANS("Left"));
  210358. outChannels.add (TRANS("Right"));
  210359. }
  210360. if (inputDeviceIndex_ >= 0)
  210361. {
  210362. inChannels.add (TRANS("Left"));
  210363. inChannels.add (TRANS("Right"));
  210364. }
  210365. }
  210366. ~DSoundAudioIODevice()
  210367. {
  210368. close();
  210369. }
  210370. const StringArray getOutputChannelNames()
  210371. {
  210372. return outChannels;
  210373. }
  210374. const StringArray getInputChannelNames()
  210375. {
  210376. return inChannels;
  210377. }
  210378. int getNumSampleRates()
  210379. {
  210380. return 4;
  210381. }
  210382. double getSampleRate (int index)
  210383. {
  210384. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210385. return samps [jlimit (0, 3, index)];
  210386. }
  210387. int getNumBufferSizesAvailable()
  210388. {
  210389. return 50;
  210390. }
  210391. int getBufferSizeSamples (int index)
  210392. {
  210393. int n = 64;
  210394. for (int i = 0; i < index; ++i)
  210395. n += (n < 512) ? 32
  210396. : ((n < 1024) ? 64
  210397. : ((n < 2048) ? 128 : 256));
  210398. return n;
  210399. }
  210400. int getDefaultBufferSize()
  210401. {
  210402. return 2560;
  210403. }
  210404. const String open (const BitArray& inputChannels,
  210405. const BitArray& outputChannels,
  210406. double sampleRate,
  210407. int bufferSizeSamples)
  210408. {
  210409. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  210410. isOpen_ = lastError.isEmpty();
  210411. return lastError;
  210412. }
  210413. void close()
  210414. {
  210415. stop();
  210416. if (isOpen_)
  210417. {
  210418. closeDevice();
  210419. isOpen_ = false;
  210420. }
  210421. }
  210422. bool isOpen()
  210423. {
  210424. return isOpen_ && isThreadRunning();
  210425. }
  210426. int getCurrentBufferSizeSamples()
  210427. {
  210428. return bufferSizeSamples;
  210429. }
  210430. double getCurrentSampleRate()
  210431. {
  210432. return sampleRate;
  210433. }
  210434. int getCurrentBitDepth()
  210435. {
  210436. int i, bits = 256;
  210437. for (i = inChans.size(); --i >= 0;)
  210438. bits = jmin (bits, inChans[i]->bitDepth);
  210439. for (i = outChans.size(); --i >= 0;)
  210440. bits = jmin (bits, outChans[i]->bitDepth);
  210441. if (bits > 32)
  210442. bits = 16;
  210443. return bits;
  210444. }
  210445. const BitArray getActiveOutputChannels() const
  210446. {
  210447. return enabledOutputs;
  210448. }
  210449. const BitArray getActiveInputChannels() const
  210450. {
  210451. return enabledInputs;
  210452. }
  210453. int getOutputLatencyInSamples()
  210454. {
  210455. return (int) (getCurrentBufferSizeSamples() * 1.5);
  210456. }
  210457. int getInputLatencyInSamples()
  210458. {
  210459. return getOutputLatencyInSamples();
  210460. }
  210461. void start (AudioIODeviceCallback* call)
  210462. {
  210463. if (isOpen_ && call != 0 && ! isStarted)
  210464. {
  210465. if (! isThreadRunning())
  210466. {
  210467. // something gone wrong and the thread's stopped..
  210468. isOpen_ = false;
  210469. return;
  210470. }
  210471. call->audioDeviceAboutToStart (this);
  210472. const ScopedLock sl (startStopLock);
  210473. callback = call;
  210474. isStarted = true;
  210475. }
  210476. }
  210477. void stop()
  210478. {
  210479. if (isStarted)
  210480. {
  210481. AudioIODeviceCallback* const callbackLocal = callback;
  210482. {
  210483. const ScopedLock sl (startStopLock);
  210484. isStarted = false;
  210485. }
  210486. if (callbackLocal != 0)
  210487. callbackLocal->audioDeviceStopped();
  210488. }
  210489. }
  210490. bool isPlaying()
  210491. {
  210492. return isStarted && isOpen_ && isThreadRunning();
  210493. }
  210494. const String getLastError()
  210495. {
  210496. return lastError;
  210497. }
  210498. juce_UseDebuggingNewOperator
  210499. StringArray inChannels, outChannels;
  210500. int outputDeviceIndex, inputDeviceIndex;
  210501. private:
  210502. bool isOpen_;
  210503. bool isStarted;
  210504. String lastError;
  210505. OwnedArray <DSoundInternalInChannel> inChans;
  210506. OwnedArray <DSoundInternalOutChannel> outChans;
  210507. WaitableEvent startEvent;
  210508. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  210509. int volatile totalSamplesOut;
  210510. int64 volatile lastBlockTime;
  210511. double sampleRate;
  210512. BitArray enabledInputs, enabledOutputs;
  210513. float** inputBuffers;
  210514. float** outputBuffers;
  210515. AudioIODeviceCallback* callback;
  210516. CriticalSection startStopLock;
  210517. DSoundAudioIODevice (const DSoundAudioIODevice&);
  210518. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  210519. const String openDevice (const BitArray& inputChannels,
  210520. const BitArray& outputChannels,
  210521. double sampleRate_,
  210522. int bufferSizeSamples_);
  210523. void closeDevice()
  210524. {
  210525. isStarted = false;
  210526. stopThread (5000);
  210527. inChans.clear();
  210528. outChans.clear();
  210529. int i;
  210530. for (i = 0; i < numInputBuffers; ++i)
  210531. juce_free (inputBuffers[i]);
  210532. delete[] inputBuffers;
  210533. inputBuffers = 0;
  210534. numInputBuffers = 0;
  210535. for (i = 0; i < numOutputBuffers; ++i)
  210536. juce_free (outputBuffers[i]);
  210537. delete[] outputBuffers;
  210538. outputBuffers = 0;
  210539. numOutputBuffers = 0;
  210540. }
  210541. void resync()
  210542. {
  210543. if (! threadShouldExit())
  210544. {
  210545. sleep (5);
  210546. int i;
  210547. for (i = 0; i < outChans.size(); ++i)
  210548. outChans.getUnchecked(i)->synchronisePosition();
  210549. for (i = 0; i < inChans.size(); ++i)
  210550. inChans.getUnchecked(i)->synchronisePosition();
  210551. }
  210552. }
  210553. public:
  210554. void run()
  210555. {
  210556. while (! threadShouldExit())
  210557. {
  210558. if (wait (100))
  210559. break;
  210560. }
  210561. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  210562. const int maxTimeMS = jmax (5, 3 * latencyMs);
  210563. while (! threadShouldExit())
  210564. {
  210565. int numToDo = 0;
  210566. uint32 startTime = Time::getMillisecondCounter();
  210567. int i;
  210568. for (i = inChans.size(); --i >= 0;)
  210569. {
  210570. inChans.getUnchecked(i)->doneFlag = false;
  210571. ++numToDo;
  210572. }
  210573. for (i = outChans.size(); --i >= 0;)
  210574. {
  210575. outChans.getUnchecked(i)->doneFlag = false;
  210576. ++numToDo;
  210577. }
  210578. if (numToDo > 0)
  210579. {
  210580. const int maxCount = 3;
  210581. int count = maxCount;
  210582. for (;;)
  210583. {
  210584. for (i = inChans.size(); --i >= 0;)
  210585. {
  210586. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  210587. if ((! in->doneFlag) && in->service())
  210588. {
  210589. in->doneFlag = true;
  210590. --numToDo;
  210591. }
  210592. }
  210593. for (i = outChans.size(); --i >= 0;)
  210594. {
  210595. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  210596. if ((! out->doneFlag) && out->service())
  210597. {
  210598. out->doneFlag = true;
  210599. --numToDo;
  210600. }
  210601. }
  210602. if (numToDo <= 0)
  210603. break;
  210604. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  210605. {
  210606. resync();
  210607. break;
  210608. }
  210609. if (--count <= 0)
  210610. {
  210611. Sleep (1);
  210612. count = maxCount;
  210613. }
  210614. if (threadShouldExit())
  210615. return;
  210616. }
  210617. }
  210618. else
  210619. {
  210620. sleep (1);
  210621. }
  210622. const ScopedLock sl (startStopLock);
  210623. if (isStarted)
  210624. {
  210625. JUCE_TRY
  210626. {
  210627. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  210628. numInputBuffers,
  210629. outputBuffers,
  210630. numOutputBuffers,
  210631. bufferSizeSamples);
  210632. }
  210633. JUCE_CATCH_EXCEPTION
  210634. totalSamplesOut += bufferSizeSamples;
  210635. }
  210636. else
  210637. {
  210638. for (i = 0; i < numOutputBuffers; ++i)
  210639. if (outputBuffers[i] != 0)
  210640. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  210641. totalSamplesOut = 0;
  210642. sleep (1);
  210643. }
  210644. }
  210645. }
  210646. };
  210647. class DSoundAudioIODeviceType : public AudioIODeviceType
  210648. {
  210649. public:
  210650. DSoundAudioIODeviceType()
  210651. : AudioIODeviceType (T("DirectSound")),
  210652. hasScanned (false)
  210653. {
  210654. initialiseDSoundFunctions();
  210655. }
  210656. ~DSoundAudioIODeviceType()
  210657. {
  210658. }
  210659. void scanForDevices()
  210660. {
  210661. hasScanned = true;
  210662. outputDeviceNames.clear();
  210663. outputGuids.clear();
  210664. inputDeviceNames.clear();
  210665. inputGuids.clear();
  210666. if (dsDirectSoundEnumerateW != 0)
  210667. {
  210668. dsDirectSoundEnumerateW (outputEnumProcW, this);
  210669. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  210670. }
  210671. }
  210672. const StringArray getDeviceNames (const bool wantInputNames) const
  210673. {
  210674. jassert (hasScanned); // need to call scanForDevices() before doing this
  210675. return wantInputNames ? inputDeviceNames
  210676. : outputDeviceNames;
  210677. }
  210678. int getDefaultDeviceIndex (const bool /*forInput*/) const
  210679. {
  210680. jassert (hasScanned); // need to call scanForDevices() before doing this
  210681. return 0;
  210682. }
  210683. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210684. {
  210685. jassert (hasScanned); // need to call scanForDevices() before doing this
  210686. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  210687. if (d == 0)
  210688. return -1;
  210689. return asInput ? d->inputDeviceIndex
  210690. : d->outputDeviceIndex;
  210691. }
  210692. bool hasSeparateInputsAndOutputs() const { return true; }
  210693. AudioIODevice* createDevice (const String& outputDeviceName,
  210694. const String& inputDeviceName)
  210695. {
  210696. jassert (hasScanned); // need to call scanForDevices() before doing this
  210697. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  210698. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  210699. if (outputIndex >= 0 || inputIndex >= 0)
  210700. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  210701. : inputDeviceName,
  210702. outputIndex, inputIndex);
  210703. return 0;
  210704. }
  210705. juce_UseDebuggingNewOperator
  210706. StringArray outputDeviceNames;
  210707. OwnedArray <GUID> outputGuids;
  210708. StringArray inputDeviceNames;
  210709. OwnedArray <GUID> inputGuids;
  210710. private:
  210711. bool hasScanned;
  210712. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  210713. {
  210714. desc = desc.trim();
  210715. if (desc.isNotEmpty())
  210716. {
  210717. const String origDesc (desc);
  210718. int n = 2;
  210719. while (outputDeviceNames.contains (desc))
  210720. desc = origDesc + T(" (") + String (n++) + T(")");
  210721. outputDeviceNames.add (desc);
  210722. if (lpGUID != 0)
  210723. outputGuids.add (new GUID (*lpGUID));
  210724. else
  210725. outputGuids.add (0);
  210726. }
  210727. return TRUE;
  210728. }
  210729. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210730. {
  210731. return ((DSoundAudioIODeviceType*) object)
  210732. ->outputEnumProc (lpGUID, String (description));
  210733. }
  210734. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210735. {
  210736. return ((DSoundAudioIODeviceType*) object)
  210737. ->outputEnumProc (lpGUID, String (description));
  210738. }
  210739. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  210740. {
  210741. desc = desc.trim();
  210742. if (desc.isNotEmpty())
  210743. {
  210744. const String origDesc (desc);
  210745. int n = 2;
  210746. while (inputDeviceNames.contains (desc))
  210747. desc = origDesc + T(" (") + String (n++) + T(")");
  210748. inputDeviceNames.add (desc);
  210749. if (lpGUID != 0)
  210750. inputGuids.add (new GUID (*lpGUID));
  210751. else
  210752. inputGuids.add (0);
  210753. }
  210754. return TRUE;
  210755. }
  210756. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210757. {
  210758. return ((DSoundAudioIODeviceType*) object)
  210759. ->inputEnumProc (lpGUID, String (description));
  210760. }
  210761. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210762. {
  210763. return ((DSoundAudioIODeviceType*) object)
  210764. ->inputEnumProc (lpGUID, String (description));
  210765. }
  210766. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  210767. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  210768. };
  210769. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  210770. const BitArray& outputChannels,
  210771. double sampleRate_,
  210772. int bufferSizeSamples_)
  210773. {
  210774. closeDevice();
  210775. totalSamplesOut = 0;
  210776. sampleRate = sampleRate_;
  210777. if (bufferSizeSamples_ <= 0)
  210778. bufferSizeSamples_ = 960; // use as a default size if none is set.
  210779. bufferSizeSamples = bufferSizeSamples_ & ~7;
  210780. DSoundAudioIODeviceType dlh;
  210781. dlh.scanForDevices();
  210782. enabledInputs = inputChannels;
  210783. enabledInputs.setRange (inChannels.size(),
  210784. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  210785. false);
  210786. numInputBuffers = enabledInputs.countNumberOfSetBits();
  210787. inputBuffers = new float* [numInputBuffers + 2];
  210788. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  210789. int i, numIns = 0;
  210790. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  210791. {
  210792. float* left = 0;
  210793. float* right = 0;
  210794. if (enabledInputs[i])
  210795. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210796. if (enabledInputs[i + 1])
  210797. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210798. if (left != 0 || right != 0)
  210799. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  210800. dlh.inputGuids [inputDeviceIndex],
  210801. (int) sampleRate, bufferSizeSamples,
  210802. left, right));
  210803. }
  210804. enabledOutputs = outputChannels;
  210805. enabledOutputs.setRange (outChannels.size(),
  210806. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  210807. false);
  210808. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  210809. outputBuffers = new float* [numOutputBuffers + 2];
  210810. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  210811. int numOuts = 0;
  210812. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  210813. {
  210814. float* left = 0;
  210815. float* right = 0;
  210816. if (enabledOutputs[i])
  210817. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210818. if (enabledOutputs[i + 1])
  210819. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210820. if (left != 0 || right != 0)
  210821. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  210822. dlh.outputGuids [outputDeviceIndex],
  210823. (int) sampleRate, bufferSizeSamples,
  210824. left, right));
  210825. }
  210826. String error;
  210827. // boost our priority while opening the devices to try to get better sync between them
  210828. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  210829. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  210830. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  210831. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  210832. for (i = 0; i < outChans.size(); ++i)
  210833. {
  210834. error = outChans[i]->open();
  210835. if (error.isNotEmpty())
  210836. {
  210837. error = T("Error opening ") + dlh.outputDeviceNames[i]
  210838. + T(": \"") + error + T("\"");
  210839. break;
  210840. }
  210841. }
  210842. if (error.isEmpty())
  210843. {
  210844. for (i = 0; i < inChans.size(); ++i)
  210845. {
  210846. error = inChans[i]->open();
  210847. if (error.isNotEmpty())
  210848. {
  210849. error = T("Error opening ") + dlh.inputDeviceNames[i]
  210850. + T(": \"") + error + T("\"");
  210851. break;
  210852. }
  210853. }
  210854. }
  210855. if (error.isEmpty())
  210856. {
  210857. totalSamplesOut = 0;
  210858. for (i = 0; i < outChans.size(); ++i)
  210859. outChans.getUnchecked(i)->synchronisePosition();
  210860. for (i = 0; i < inChans.size(); ++i)
  210861. inChans.getUnchecked(i)->synchronisePosition();
  210862. startThread (9);
  210863. sleep (10);
  210864. notify();
  210865. }
  210866. else
  210867. {
  210868. log (error);
  210869. }
  210870. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  210871. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  210872. return error;
  210873. }
  210874. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  210875. {
  210876. return new DSoundAudioIODeviceType();
  210877. }
  210878. #undef log
  210879. #endif
  210880. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  210881. /********* Start of inlined file: juce_win32_WASAPI.cpp *********/
  210882. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210883. // compiled on its own).
  210884. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  210885. #if 1
  210886. const String getAudioErrorDesc (HRESULT hr)
  210887. {
  210888. const char* e = 0;
  210889. switch (hr)
  210890. {
  210891. case E_POINTER: e = "E_POINTER"; break;
  210892. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  210893. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  210894. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  210895. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  210896. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  210897. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  210898. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  210899. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  210900. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  210901. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  210902. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  210903. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  210904. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  210905. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  210906. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  210907. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  210908. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  210909. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  210910. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  210911. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  210912. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  210913. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  210914. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  210915. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  210916. default: return String::toHexString ((int) hr);
  210917. }
  210918. return e;
  210919. }
  210920. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  210921. #define OK(a) wasapi_checkResult(a)
  210922. static bool wasapi_checkResult (HRESULT hr)
  210923. {
  210924. logFailure (hr);
  210925. return SUCCEEDED (hr);
  210926. }
  210927. #else
  210928. #define logFailure(hr) {}
  210929. #define OK(a) SUCCEEDED(a)
  210930. #endif
  210931. static const String wasapi_getDeviceID (IMMDevice* const device)
  210932. {
  210933. String s;
  210934. WCHAR* deviceId = 0;
  210935. if (OK (device->GetId (&deviceId)))
  210936. {
  210937. s = String (deviceId);
  210938. CoTaskMemFree (deviceId);
  210939. }
  210940. return s;
  210941. }
  210942. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  210943. {
  210944. EDataFlow flow = eRender;
  210945. ComSmartPtr <IMMEndpoint> endPoint;
  210946. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  210947. (void) OK (endPoint->GetDataFlow (&flow));
  210948. return flow;
  210949. }
  210950. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  210951. {
  210952. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  210953. }
  210954. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  210955. {
  210956. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  210957. : sizeof (WAVEFORMATEX));
  210958. }
  210959. class WASAPIDeviceBase
  210960. {
  210961. public:
  210962. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_)
  210963. : device (device_),
  210964. sampleRate (0),
  210965. numChannels (0),
  210966. actualNumChannels (0),
  210967. defaultSampleRate (0),
  210968. minBufferSize (0),
  210969. defaultBufferSize (0),
  210970. latencySamples (0)
  210971. {
  210972. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  210973. ComSmartPtr <IAudioClient> tempClient (createClient());
  210974. if (tempClient == 0)
  210975. return;
  210976. REFERENCE_TIME defaultPeriod, minPeriod;
  210977. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  210978. return;
  210979. WAVEFORMATEX* mixFormat = 0;
  210980. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  210981. return;
  210982. WAVEFORMATEXTENSIBLE format;
  210983. wasapi_copyWavFormat (format, mixFormat);
  210984. CoTaskMemFree (mixFormat);
  210985. actualNumChannels = numChannels = format.Format.nChannels;
  210986. defaultSampleRate = format.Format.nSamplesPerSec;
  210987. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  210988. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  210989. FloatElementComparator<double> comparator;
  210990. rates.addSorted (comparator, defaultSampleRate);
  210991. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210992. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  210993. {
  210994. if (ratesToTest[i] == defaultSampleRate)
  210995. continue;
  210996. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  210997. if (SUCCEEDED (tempClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, 0)))
  210998. if (! rates.contains (ratesToTest[i]))
  210999. rates.addSorted (comparator, ratesToTest[i]);
  211000. }
  211001. }
  211002. ~WASAPIDeviceBase()
  211003. {
  211004. device = 0;
  211005. CloseHandle (clientEvent);
  211006. }
  211007. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  211008. bool openClient (const double newSampleRate, const BitArray& newChannels)
  211009. {
  211010. sampleRate = newSampleRate;
  211011. channels = newChannels;
  211012. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  211013. numChannels = channels.getHighestBit() + 1;
  211014. if (numChannels == 0)
  211015. return true;
  211016. client = createClient();
  211017. if (client != 0
  211018. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  211019. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  211020. {
  211021. channelMaps.clear();
  211022. for (int i = 0; i <= channels.getHighestBit(); ++i)
  211023. if (channels[i])
  211024. channelMaps.add (i);
  211025. REFERENCE_TIME latency;
  211026. if (OK (client->GetStreamLatency (&latency)))
  211027. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  211028. (void) OK (client->GetBufferSize (&actualBufferSize));
  211029. return OK (client->SetEventHandle (clientEvent));
  211030. }
  211031. return false;
  211032. }
  211033. void closeClient()
  211034. {
  211035. if (client != 0)
  211036. client->Stop();
  211037. client = 0;
  211038. ResetEvent (clientEvent);
  211039. }
  211040. ComSmartPtr <IMMDevice> device;
  211041. ComSmartPtr <IAudioClient> client;
  211042. double sampleRate, defaultSampleRate;
  211043. int numChannels, actualNumChannels;
  211044. int minBufferSize, defaultBufferSize, latencySamples;
  211045. Array <double> rates;
  211046. HANDLE clientEvent;
  211047. BitArray channels;
  211048. AudioDataConverters::DataFormat dataFormat;
  211049. Array <int> channelMaps;
  211050. UINT32 actualBufferSize;
  211051. int bytesPerSample;
  211052. private:
  211053. const ComSmartPtr <IAudioClient> createClient()
  211054. {
  211055. ComSmartPtr <IAudioClient> client;
  211056. if (device != 0)
  211057. {
  211058. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  211059. logFailure (hr);
  211060. }
  211061. return client;
  211062. }
  211063. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  211064. {
  211065. WAVEFORMATEXTENSIBLE format;
  211066. zerostruct (format);
  211067. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  211068. {
  211069. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  211070. }
  211071. else
  211072. {
  211073. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  211074. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  211075. }
  211076. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  211077. format.Format.nChannels = (WORD) numChannels;
  211078. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  211079. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  211080. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  211081. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  211082. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  211083. switch (numChannels)
  211084. {
  211085. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  211086. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  211087. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211088. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211089. case 8: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
  211090. default: break;
  211091. }
  211092. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  211093. HRESULT hr = client->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, (WAVEFORMATEX**) &nearestFormat);
  211094. logFailure (hr);
  211095. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  211096. {
  211097. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  211098. hr = S_OK;
  211099. }
  211100. CoTaskMemFree (nearestFormat);
  211101. GUID session;
  211102. if (hr == S_OK
  211103. && OK (client->Initialize (AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  211104. 0, 0, (WAVEFORMATEX*) &format, &session)))
  211105. {
  211106. actualNumChannels = format.Format.nChannels;
  211107. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  211108. bytesPerSample = format.Format.wBitsPerSample / 8;
  211109. dataFormat = isFloat ? AudioDataConverters::float32LE
  211110. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  211111. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  211112. : AudioDataConverters::int16LE)));
  211113. return true;
  211114. }
  211115. return false;
  211116. }
  211117. };
  211118. class WASAPIInputDevice : public WASAPIDeviceBase
  211119. {
  211120. public:
  211121. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_)
  211122. : WASAPIDeviceBase (device_),
  211123. reservoir (1, 1)
  211124. {
  211125. }
  211126. ~WASAPIInputDevice()
  211127. {
  211128. close();
  211129. }
  211130. bool open (const double newSampleRate, const BitArray& newChannels)
  211131. {
  211132. reservoirSize = 0;
  211133. reservoirCapacity = 16384;
  211134. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  211135. return openClient (newSampleRate, newChannels)
  211136. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  211137. }
  211138. void close()
  211139. {
  211140. closeClient();
  211141. captureClient = 0;
  211142. reservoir.setSize (0);
  211143. }
  211144. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  211145. {
  211146. if (numChannels <= 0)
  211147. return;
  211148. int offset = 0;
  211149. while (bufferSize > 0)
  211150. {
  211151. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  211152. {
  211153. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  211154. for (int i = 0; i < numDestBuffers; ++i)
  211155. {
  211156. float* const dest = destBuffers[i] + offset;
  211157. const int srcChan = channelMaps.getUnchecked(i);
  211158. switch (dataFormat)
  211159. {
  211160. case AudioDataConverters::float32LE:
  211161. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211162. break;
  211163. case AudioDataConverters::int32LE:
  211164. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211165. break;
  211166. case AudioDataConverters::int24LE:
  211167. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211168. break;
  211169. case AudioDataConverters::int16LE:
  211170. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211171. break;
  211172. default: jassertfalse; break;
  211173. }
  211174. }
  211175. bufferSize -= samplesToDo;
  211176. offset += samplesToDo;
  211177. reservoirSize -= samplesToDo;
  211178. }
  211179. else
  211180. {
  211181. UINT32 packetLength = 0;
  211182. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  211183. break;
  211184. if (packetLength == 0)
  211185. {
  211186. if (thread.threadShouldExit())
  211187. break;
  211188. Thread::sleep (1);
  211189. continue;
  211190. }
  211191. uint8* inputData = 0;
  211192. UINT32 numSamplesAvailable;
  211193. DWORD flags;
  211194. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  211195. {
  211196. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  211197. for (int i = 0; i < numDestBuffers; ++i)
  211198. {
  211199. float* const dest = destBuffers[i] + offset;
  211200. const int srcChan = channelMaps.getUnchecked(i);
  211201. switch (dataFormat)
  211202. {
  211203. case AudioDataConverters::float32LE:
  211204. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211205. break;
  211206. case AudioDataConverters::int32LE:
  211207. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211208. break;
  211209. case AudioDataConverters::int24LE:
  211210. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211211. break;
  211212. case AudioDataConverters::int16LE:
  211213. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211214. break;
  211215. default: jassertfalse; break;
  211216. }
  211217. }
  211218. bufferSize -= samplesToDo;
  211219. offset += samplesToDo;
  211220. if (samplesToDo < numSamplesAvailable)
  211221. {
  211222. reservoirSize = jmin (numSamplesAvailable - samplesToDo, reservoirCapacity);
  211223. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  211224. bytesPerSample * actualNumChannels * reservoirSize);
  211225. }
  211226. captureClient->ReleaseBuffer (numSamplesAvailable);
  211227. }
  211228. }
  211229. }
  211230. }
  211231. ComSmartPtr <IAudioCaptureClient> captureClient;
  211232. MemoryBlock reservoir;
  211233. int reservoirSize, reservoirCapacity;
  211234. };
  211235. class WASAPIOutputDevice : public WASAPIDeviceBase
  211236. {
  211237. public:
  211238. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_)
  211239. : WASAPIDeviceBase (device_)
  211240. {
  211241. }
  211242. ~WASAPIOutputDevice()
  211243. {
  211244. close();
  211245. }
  211246. bool open (const double newSampleRate, const BitArray& newChannels)
  211247. {
  211248. return openClient (newSampleRate, newChannels)
  211249. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  211250. }
  211251. void close()
  211252. {
  211253. closeClient();
  211254. renderClient = 0;
  211255. }
  211256. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  211257. {
  211258. if (numChannels <= 0)
  211259. return;
  211260. int offset = 0;
  211261. while (bufferSize > 0)
  211262. {
  211263. UINT32 padding = 0;
  211264. if (! OK (client->GetCurrentPadding (&padding)))
  211265. return;
  211266. const int samplesToDo = jmin ((int) (actualBufferSize - padding), bufferSize);
  211267. if (samplesToDo <= 0)
  211268. {
  211269. if (thread.threadShouldExit())
  211270. break;
  211271. Thread::sleep (0);
  211272. continue;
  211273. }
  211274. uint8* outputData = 0;
  211275. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  211276. {
  211277. for (int i = 0; i < numSrcBuffers; ++i)
  211278. {
  211279. const float* const source = srcBuffers[i] + offset;
  211280. const int destChan = channelMaps.getUnchecked(i);
  211281. switch (dataFormat)
  211282. {
  211283. case AudioDataConverters::float32LE:
  211284. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211285. break;
  211286. case AudioDataConverters::int32LE:
  211287. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211288. break;
  211289. case AudioDataConverters::int24LE:
  211290. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  211291. break;
  211292. case AudioDataConverters::int16LE:
  211293. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  211294. break;
  211295. default: jassertfalse; break;
  211296. }
  211297. }
  211298. renderClient->ReleaseBuffer (samplesToDo, 0);
  211299. offset += samplesToDo;
  211300. bufferSize -= samplesToDo;
  211301. }
  211302. }
  211303. }
  211304. ComSmartPtr <IAudioRenderClient> renderClient;
  211305. };
  211306. class WASAPIAudioIODevice : public AudioIODevice,
  211307. public Thread
  211308. {
  211309. public:
  211310. WASAPIAudioIODevice (const String& deviceName,
  211311. const String& outputDeviceId_,
  211312. const String& inputDeviceId_)
  211313. : AudioIODevice (deviceName, "Windows Audio"),
  211314. Thread ("Juce WASAPI"),
  211315. isOpen_ (false),
  211316. isStarted (false),
  211317. outputDevice (0),
  211318. outputDeviceId (outputDeviceId_),
  211319. inputDevice (0),
  211320. inputDeviceId (inputDeviceId_),
  211321. currentBufferSizeSamples (0),
  211322. currentSampleRate (0),
  211323. callback (0)
  211324. {
  211325. }
  211326. ~WASAPIAudioIODevice()
  211327. {
  211328. close();
  211329. deleteAndZero (inputDevice);
  211330. deleteAndZero (outputDevice);
  211331. }
  211332. bool initialise()
  211333. {
  211334. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  211335. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  211336. latencyIn = latencyOut = 0;
  211337. Array <double> ratesIn, ratesOut;
  211338. if (createDevices())
  211339. {
  211340. jassert (inputDevice != 0 || outputDevice != 0);
  211341. if (inputDevice != 0 && outputDevice != 0)
  211342. {
  211343. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  211344. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  211345. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  211346. sampleRates = inputDevice->rates;
  211347. sampleRates.removeValuesNotIn (outputDevice->rates);
  211348. }
  211349. else
  211350. {
  211351. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  211352. defaultSampleRate = d->defaultSampleRate;
  211353. minBufferSize = d->minBufferSize;
  211354. defaultBufferSize = d->defaultBufferSize;
  211355. sampleRates = d->rates;
  211356. }
  211357. IntegerElementComparator<int> comparator;
  211358. bufferSizes.addSorted (comparator, defaultBufferSize);
  211359. if (minBufferSize != defaultBufferSize)
  211360. bufferSizes.addSorted (comparator, minBufferSize);
  211361. int n = 64;
  211362. for (int i = 0; i < 40; ++i)
  211363. {
  211364. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  211365. bufferSizes.addSorted (comparator, n);
  211366. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  211367. }
  211368. return true;
  211369. }
  211370. return false;
  211371. }
  211372. const StringArray getOutputChannelNames()
  211373. {
  211374. StringArray outChannels;
  211375. if (outputDevice != 0)
  211376. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  211377. outChannels.add ("Output channel " + String (i));
  211378. return outChannels;
  211379. }
  211380. const StringArray getInputChannelNames()
  211381. {
  211382. StringArray inChannels;
  211383. if (inputDevice != 0)
  211384. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  211385. inChannels.add ("Input channel " + String (i));
  211386. return inChannels;
  211387. }
  211388. int getNumSampleRates() { return sampleRates.size(); }
  211389. double getSampleRate (int index) { return sampleRates [index]; }
  211390. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211391. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211392. int getDefaultBufferSize() { return defaultBufferSize; }
  211393. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  211394. double getCurrentSampleRate() { return currentSampleRate; }
  211395. int getCurrentBitDepth() { return 32; }
  211396. int getOutputLatencyInSamples() { return latencyOut; }
  211397. int getInputLatencyInSamples() { return latencyIn; }
  211398. const BitArray getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BitArray(); }
  211399. const BitArray getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BitArray(); }
  211400. const String getLastError() { return lastError; }
  211401. const String open (const BitArray& inputChannels, const BitArray& outputChannels,
  211402. double sampleRate, int bufferSizeSamples)
  211403. {
  211404. close();
  211405. lastError = String::empty;
  211406. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  211407. {
  211408. lastError = "The input and output devices don't share a common sample rate!";
  211409. return lastError;
  211410. }
  211411. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  211412. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  211413. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  211414. {
  211415. lastError = "Couldn't open the input device!";
  211416. return lastError;
  211417. }
  211418. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  211419. {
  211420. close();
  211421. lastError = "Couldn't open the output device!";
  211422. return lastError;
  211423. }
  211424. if (inputDevice != 0)
  211425. ResetEvent (inputDevice->clientEvent);
  211426. if (outputDevice != 0)
  211427. ResetEvent (outputDevice->clientEvent);
  211428. startThread (8);
  211429. Thread::sleep (5);
  211430. if (inputDevice != 0 && inputDevice->client != 0)
  211431. {
  211432. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  211433. HRESULT hr = inputDevice->client->Start();
  211434. logFailure (hr); //xxx handle this
  211435. }
  211436. if (outputDevice != 0 && outputDevice->client != 0)
  211437. {
  211438. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  211439. HRESULT hr = outputDevice->client->Start();
  211440. logFailure (hr); //xxx handle this
  211441. }
  211442. isOpen_ = true;
  211443. return lastError;
  211444. }
  211445. void close()
  211446. {
  211447. stop();
  211448. if (inputDevice != 0)
  211449. SetEvent (inputDevice->clientEvent);
  211450. if (outputDevice != 0)
  211451. SetEvent (outputDevice->clientEvent);
  211452. stopThread (5000);
  211453. if (inputDevice != 0)
  211454. inputDevice->close();
  211455. if (outputDevice != 0)
  211456. outputDevice->close();
  211457. isOpen_ = false;
  211458. }
  211459. bool isOpen() { return isOpen_ && isThreadRunning(); }
  211460. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  211461. void start (AudioIODeviceCallback* call)
  211462. {
  211463. if (isOpen_ && call != 0 && ! isStarted)
  211464. {
  211465. if (! isThreadRunning())
  211466. {
  211467. // something's gone wrong and the thread's stopped..
  211468. isOpen_ = false;
  211469. return;
  211470. }
  211471. call->audioDeviceAboutToStart (this);
  211472. const ScopedLock sl (startStopLock);
  211473. callback = call;
  211474. isStarted = true;
  211475. }
  211476. }
  211477. void stop()
  211478. {
  211479. if (isStarted)
  211480. {
  211481. AudioIODeviceCallback* const callbackLocal = callback;
  211482. {
  211483. const ScopedLock sl (startStopLock);
  211484. isStarted = false;
  211485. }
  211486. if (callbackLocal != 0)
  211487. callbackLocal->audioDeviceStopped();
  211488. }
  211489. }
  211490. void run()
  211491. {
  211492. const int bufferSize = currentBufferSizeSamples;
  211493. HANDLE events[2];
  211494. int numEvents = 0;
  211495. if (inputDevice != 0)
  211496. events [numEvents++] = inputDevice->clientEvent;
  211497. if (outputDevice != 0)
  211498. events [numEvents++] = outputDevice->clientEvent;
  211499. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  211500. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  211501. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  211502. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  211503. float** const inputBuffers = ins.getArrayOfChannels();
  211504. float** const outputBuffers = outs.getArrayOfChannels();
  211505. ins.clear();
  211506. while (! threadShouldExit())
  211507. {
  211508. const DWORD result = WaitForMultipleObjects (numEvents, events, true, 1000);
  211509. if (result == WAIT_TIMEOUT)
  211510. continue;
  211511. if (threadShouldExit())
  211512. break;
  211513. if (inputDevice != 0)
  211514. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  211515. // Make the callback..
  211516. {
  211517. const ScopedLock sl (startStopLock);
  211518. if (isStarted)
  211519. {
  211520. JUCE_TRY
  211521. {
  211522. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  211523. numInputBuffers,
  211524. outputBuffers,
  211525. numOutputBuffers,
  211526. bufferSize);
  211527. }
  211528. JUCE_CATCH_EXCEPTION
  211529. }
  211530. else
  211531. {
  211532. outs.clear();
  211533. }
  211534. }
  211535. if (outputDevice != 0)
  211536. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  211537. }
  211538. }
  211539. juce_UseDebuggingNewOperator
  211540. String outputDeviceId, inputDeviceId;
  211541. String lastError;
  211542. private:
  211543. // Device stats...
  211544. WASAPIInputDevice* inputDevice;
  211545. WASAPIOutputDevice* outputDevice;
  211546. double defaultSampleRate;
  211547. int minBufferSize, defaultBufferSize;
  211548. int latencyIn, latencyOut;
  211549. Array <double> sampleRates;
  211550. Array <int> bufferSizes;
  211551. // Active state...
  211552. bool isOpen_, isStarted;
  211553. int currentBufferSizeSamples;
  211554. double currentSampleRate;
  211555. AudioIODeviceCallback* callback;
  211556. CriticalSection startStopLock;
  211557. bool createDevices()
  211558. {
  211559. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211560. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211561. return false;
  211562. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211563. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  211564. return false;
  211565. UINT32 numDevices = 0;
  211566. if (! OK (deviceCollection->GetCount (&numDevices)))
  211567. return false;
  211568. for (UINT32 i = 0; i < numDevices; ++i)
  211569. {
  211570. ComSmartPtr <IMMDevice> device;
  211571. if (! OK (deviceCollection->Item (i, &device)))
  211572. continue;
  211573. const String deviceId (wasapi_getDeviceID (device));
  211574. if (deviceId.isEmpty())
  211575. continue;
  211576. const EDataFlow flow = wasapi_getDataFlow (device);
  211577. if (deviceId == inputDeviceId && flow == eCapture)
  211578. inputDevice = new WASAPIInputDevice (device);
  211579. else if (deviceId == outputDeviceId && flow == eRender)
  211580. outputDevice = new WASAPIOutputDevice (device);
  211581. }
  211582. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  211583. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  211584. }
  211585. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  211586. const WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  211587. };
  211588. class WASAPIAudioIODeviceType : public AudioIODeviceType
  211589. {
  211590. public:
  211591. WASAPIAudioIODeviceType()
  211592. : AudioIODeviceType (T("Windows Audio")),
  211593. hasScanned (false)
  211594. {
  211595. }
  211596. ~WASAPIAudioIODeviceType()
  211597. {
  211598. }
  211599. void scanForDevices()
  211600. {
  211601. hasScanned = true;
  211602. outputDeviceNames.clear();
  211603. inputDeviceNames.clear();
  211604. outputDeviceIds.clear();
  211605. inputDeviceIds.clear();
  211606. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211607. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211608. return;
  211609. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  211610. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  211611. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211612. UINT32 numDevices = 0;
  211613. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  211614. && OK (deviceCollection->GetCount (&numDevices))))
  211615. return;
  211616. for (UINT32 i = 0; i < numDevices; ++i)
  211617. {
  211618. ComSmartPtr <IMMDevice> device;
  211619. if (! OK (deviceCollection->Item (i, &device)))
  211620. continue;
  211621. const String deviceId (wasapi_getDeviceID (device));
  211622. DWORD state = 0;
  211623. if (! OK (device->GetState (&state)))
  211624. continue;
  211625. if (state != DEVICE_STATE_ACTIVE)
  211626. continue;
  211627. String name;
  211628. {
  211629. ComSmartPtr <IPropertyStore> properties;
  211630. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  211631. continue;
  211632. PROPVARIANT value;
  211633. PropVariantInit (&value);
  211634. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  211635. name = value.pwszVal;
  211636. PropVariantClear (&value);
  211637. }
  211638. const EDataFlow flow = wasapi_getDataFlow (device);
  211639. if (flow == eRender)
  211640. {
  211641. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  211642. outputDeviceIds.insert (index, deviceId);
  211643. outputDeviceNames.insert (index, name);
  211644. }
  211645. else if (flow == eCapture)
  211646. {
  211647. const int index = (deviceId == defaultCapture) ? 0 : -1;
  211648. inputDeviceIds.insert (index, deviceId);
  211649. inputDeviceNames.insert (index, name);
  211650. }
  211651. }
  211652. inputDeviceNames.appendNumbersToDuplicates (false, false);
  211653. outputDeviceNames.appendNumbersToDuplicates (false, false);
  211654. }
  211655. const StringArray getDeviceNames (const bool wantInputNames) const
  211656. {
  211657. jassert (hasScanned); // need to call scanForDevices() before doing this
  211658. return wantInputNames ? inputDeviceNames
  211659. : outputDeviceNames;
  211660. }
  211661. int getDefaultDeviceIndex (const bool /*forInput*/) const
  211662. {
  211663. jassert (hasScanned); // need to call scanForDevices() before doing this
  211664. return 0;
  211665. }
  211666. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  211667. {
  211668. jassert (hasScanned); // need to call scanForDevices() before doing this
  211669. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  211670. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  211671. : outputDeviceIds.indexOf (d->outputDeviceId));
  211672. }
  211673. bool hasSeparateInputsAndOutputs() const { return true; }
  211674. AudioIODevice* createDevice (const String& outputDeviceName,
  211675. const String& inputDeviceName)
  211676. {
  211677. jassert (hasScanned); // need to call scanForDevices() before doing this
  211678. WASAPIAudioIODevice* d = 0;
  211679. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211680. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211681. if (outputIndex >= 0 || inputIndex >= 0)
  211682. {
  211683. d = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211684. : inputDeviceName,
  211685. outputDeviceIds [outputIndex],
  211686. inputDeviceIds [inputIndex]);
  211687. if (! d->initialise())
  211688. deleteAndZero (d);
  211689. }
  211690. return d;
  211691. }
  211692. juce_UseDebuggingNewOperator
  211693. StringArray outputDeviceNames, outputDeviceIds;
  211694. StringArray inputDeviceNames, inputDeviceIds;
  211695. private:
  211696. bool hasScanned;
  211697. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  211698. {
  211699. String s;
  211700. IMMDevice* dev = 0;
  211701. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  211702. eMultimedia, &dev)))
  211703. {
  211704. WCHAR* deviceId = 0;
  211705. if (OK (dev->GetId (&deviceId)))
  211706. {
  211707. s = String (deviceId);
  211708. CoTaskMemFree (deviceId);
  211709. }
  211710. dev->Release();
  211711. }
  211712. return s;
  211713. }
  211714. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  211715. const WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  211716. };
  211717. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  211718. {
  211719. return new WASAPIAudioIODeviceType();
  211720. }
  211721. #undef logFailure
  211722. #undef OK
  211723. #endif
  211724. /********* End of inlined file: juce_win32_WASAPI.cpp *********/
  211725. /********* Start of inlined file: juce_win32_CameraDevice.cpp *********/
  211726. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211727. // compiled on its own).
  211728. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  211729. class DShowCameraDeviceInteral : public ChangeBroadcaster
  211730. {
  211731. public:
  211732. DShowCameraDeviceInteral (CameraDevice* const owner_,
  211733. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  211734. const ComSmartPtr <IBaseFilter>& filter_,
  211735. int minWidth, int minHeight,
  211736. int maxWidth, int maxHeight)
  211737. : owner (owner_),
  211738. captureGraphBuilder (captureGraphBuilder_),
  211739. filter (filter_),
  211740. ok (false),
  211741. imageNeedsFlipping (false),
  211742. width (0),
  211743. height (0),
  211744. activeUsers (0),
  211745. recordNextFrameTime (false)
  211746. {
  211747. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph, CLSCTX_INPROC);
  211748. if (FAILED (hr))
  211749. return;
  211750. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  211751. if (FAILED (hr))
  211752. return;
  211753. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  211754. if (FAILED (hr))
  211755. return;
  211756. {
  211757. ComSmartPtr <IAMStreamConfig> streamConfig;
  211758. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE,
  211759. 0,
  211760. filter,
  211761. IID_IAMStreamConfig,
  211762. (void**) &streamConfig);
  211763. if (streamConfig != 0)
  211764. {
  211765. getVideoSizes (streamConfig);
  211766. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  211767. return;
  211768. }
  211769. }
  211770. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  211771. if (FAILED (hr))
  211772. return;
  211773. hr = smartTee.CoCreateInstance (CLSID_SmartTee, CLSCTX_INPROC_SERVER);
  211774. if (FAILED (hr))
  211775. return;
  211776. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  211777. if (FAILED (hr))
  211778. return;
  211779. if (! connectFilters (filter, smartTee))
  211780. return;
  211781. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  211782. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber, CLSCTX_INPROC_SERVER);
  211783. if (FAILED (hr))
  211784. return;
  211785. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  211786. if (FAILED (hr))
  211787. return;
  211788. AM_MEDIA_TYPE mt;
  211789. zerostruct (mt);
  211790. mt.majortype = MEDIATYPE_Video;
  211791. mt.subtype = MEDIASUBTYPE_RGB24;
  211792. mt.formattype = FORMAT_VideoInfo;
  211793. sampleGrabber->SetMediaType (&mt);
  211794. callback = new GrabberCallback (*this);
  211795. sampleGrabber->SetCallback (callback, 1);
  211796. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  211797. if (FAILED (hr))
  211798. return;
  211799. ComSmartPtr <IPin> grabberInputPin;
  211800. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  211801. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  211802. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  211803. return;
  211804. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  211805. if (FAILED (hr))
  211806. return;
  211807. zerostruct (mt);
  211808. hr = sampleGrabber->GetConnectedMediaType (&mt);
  211809. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  211810. width = pVih->bmiHeader.biWidth;
  211811. height = pVih->bmiHeader.biHeight;
  211812. ComSmartPtr <IBaseFilter> nullFilter;
  211813. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer, CLSCTX_INPROC_SERVER);
  211814. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  211815. if (connectFilters (sampleGrabberBase, nullFilter)
  211816. && addGraphToRot())
  211817. {
  211818. activeImage = new Image (Image::RGB, width, height, true);
  211819. loadingImage = new Image (Image::RGB, width, height, true);
  211820. ok = true;
  211821. }
  211822. }
  211823. ~DShowCameraDeviceInteral()
  211824. {
  211825. mediaControl->Stop();
  211826. removeGraphFromRot();
  211827. for (int i = viewerComps.size(); --i >= 0;)
  211828. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  211829. callback = 0;
  211830. graphBuilder = 0;
  211831. sampleGrabber = 0;
  211832. mediaControl = 0;
  211833. filter = 0;
  211834. captureGraphBuilder = 0;
  211835. smartTee = 0;
  211836. smartTeePreviewOutputPin = 0;
  211837. smartTeeCaptureOutputPin = 0;
  211838. mux = 0;
  211839. fileWriter = 0;
  211840. delete activeImage;
  211841. delete loadingImage;
  211842. }
  211843. void addUser()
  211844. {
  211845. if (ok && activeUsers++ == 0)
  211846. mediaControl->Run();
  211847. }
  211848. void removeUser()
  211849. {
  211850. if (ok && --activeUsers == 0)
  211851. mediaControl->Stop();
  211852. }
  211853. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  211854. {
  211855. if (recordNextFrameTime)
  211856. {
  211857. firstRecordedTime = Time::getCurrentTime();
  211858. recordNextFrameTime = false;
  211859. }
  211860. imageSwapLock.enter();
  211861. int ls, ps;
  211862. const int lineStride = width * 3;
  211863. uint8* const dest = loadingImage->lockPixelDataReadWrite (0, 0, width, height, ls, ps);
  211864. for (int i = 0; i < height; ++i)
  211865. memcpy (dest + ls * ((height - 1) - i),
  211866. buffer + lineStride * i,
  211867. lineStride);
  211868. loadingImage->releasePixelDataReadWrite (dest);
  211869. imageNeedsFlipping = true;
  211870. imageSwapLock.exit();
  211871. callListeners (*loadingImage);
  211872. sendChangeMessage (this);
  211873. }
  211874. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  211875. {
  211876. if (imageNeedsFlipping)
  211877. {
  211878. imageSwapLock.enter();
  211879. swapVariables (loadingImage, activeImage);
  211880. imageNeedsFlipping = false;
  211881. imageSwapLock.exit();
  211882. }
  211883. RectanglePlacement rp (RectanglePlacement::centred);
  211884. double dx = 0, dy = 0, dw = width, dh = height;
  211885. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  211886. const int rx = roundDoubleToInt (dx), ry = roundDoubleToInt (dy);
  211887. const int rw = roundDoubleToInt (dw), rh = roundDoubleToInt (dh);
  211888. g.saveState();
  211889. g.excludeClipRegion (rx, ry, rw, rh);
  211890. g.fillAll (Colours::black);
  211891. g.restoreState();
  211892. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  211893. }
  211894. bool createFileCaptureFilter (const File& file)
  211895. {
  211896. removeFileCaptureFilter();
  211897. file.deleteFile();
  211898. mediaControl->Stop();
  211899. firstRecordedTime = Time();
  211900. recordNextFrameTime = true;
  211901. HRESULT hr = mux.CoCreateInstance (CLSID_AviDest, CLSCTX_INPROC_SERVER);
  211902. if (SUCCEEDED (hr))
  211903. {
  211904. hr = graphBuilder->AddFilter (mux, _T("AVI Mux"));
  211905. if (SUCCEEDED (hr))
  211906. {
  211907. fileWriter.CoCreateInstance (CLSID_FileWriter, CLSCTX_INPROC_SERVER);
  211908. if (SUCCEEDED (hr))
  211909. {
  211910. ComSmartPtr <IFileSinkFilter> fileSink;
  211911. hr = fileWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  211912. if (SUCCEEDED (hr))
  211913. {
  211914. AM_MEDIA_TYPE mt;
  211915. zerostruct (mt);
  211916. mt.majortype = MEDIATYPE_Stream;
  211917. mt.subtype = MEDIASUBTYPE_Avi;
  211918. mt.formattype = FORMAT_VideoInfo;
  211919. hr = fileSink->SetFileName (file.getFullPathName(), &mt);
  211920. if (SUCCEEDED (hr))
  211921. {
  211922. hr = graphBuilder->AddFilter (fileWriter, _T("File Writer"));
  211923. if (SUCCEEDED (hr))
  211924. {
  211925. ComSmartPtr <IPin> muxInputPin, muxOutputPin, writerInput;
  211926. if (getPin (mux, PINDIR_INPUT, &muxInputPin)
  211927. && getPin (mux, PINDIR_OUTPUT, &muxOutputPin)
  211928. && getPin (fileWriter, PINDIR_INPUT, &writerInput))
  211929. {
  211930. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, muxInputPin);
  211931. if (SUCCEEDED (hr))
  211932. {
  211933. hr = graphBuilder->Connect (muxOutputPin, writerInput);
  211934. if (SUCCEEDED (hr))
  211935. {
  211936. if (ok && activeUsers > 0)
  211937. mediaControl->Run();
  211938. return true;
  211939. }
  211940. }
  211941. }
  211942. }
  211943. }
  211944. }
  211945. }
  211946. }
  211947. }
  211948. removeFileCaptureFilter();
  211949. if (ok && activeUsers > 0)
  211950. mediaControl->Run();
  211951. return false;
  211952. }
  211953. void removeFileCaptureFilter()
  211954. {
  211955. mediaControl->Stop();
  211956. if (mux != 0)
  211957. {
  211958. graphBuilder->RemoveFilter (mux);
  211959. mux = 0;
  211960. }
  211961. if (fileWriter != 0)
  211962. {
  211963. graphBuilder->RemoveFilter (fileWriter);
  211964. fileWriter = 0;
  211965. }
  211966. if (ok && activeUsers > 0)
  211967. mediaControl->Run();
  211968. }
  211969. void addListener (CameraImageListener* listenerToAdd)
  211970. {
  211971. const ScopedLock sl (listenerLock);
  211972. if (listeners.size() == 0)
  211973. addUser();
  211974. listeners.addIfNotAlreadyThere (listenerToAdd);
  211975. }
  211976. void removeListener (CameraImageListener* listenerToRemove)
  211977. {
  211978. const ScopedLock sl (listenerLock);
  211979. listeners.removeValue (listenerToRemove);
  211980. if (listeners.size() == 0)
  211981. removeUser();
  211982. }
  211983. void callListeners (Image& image)
  211984. {
  211985. const ScopedLock sl (listenerLock);
  211986. for (int i = listeners.size(); --i >= 0;)
  211987. {
  211988. CameraImageListener* l = (CameraImageListener*) listeners[i];
  211989. if (l != 0)
  211990. l->imageReceived (image);
  211991. }
  211992. }
  211993. class DShowCaptureViewerComp : public Component,
  211994. public ChangeListener
  211995. {
  211996. public:
  211997. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  211998. : owner (owner_)
  211999. {
  212000. setOpaque (true);
  212001. owner->addChangeListener (this);
  212002. owner->addUser();
  212003. owner->viewerComps.add (this);
  212004. setSize (owner_->width, owner_->height);
  212005. }
  212006. ~DShowCaptureViewerComp()
  212007. {
  212008. if (owner != 0)
  212009. {
  212010. owner->viewerComps.removeValue (this);
  212011. owner->removeUser();
  212012. owner->removeChangeListener (this);
  212013. }
  212014. }
  212015. void ownerDeleted()
  212016. {
  212017. owner = 0;
  212018. }
  212019. void paint (Graphics& g)
  212020. {
  212021. g.setColour (Colours::black);
  212022. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  212023. if (owner != 0)
  212024. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  212025. else
  212026. g.fillAll (Colours::black);
  212027. }
  212028. void changeListenerCallback (void*)
  212029. {
  212030. repaint();
  212031. }
  212032. private:
  212033. DShowCameraDeviceInteral* owner;
  212034. };
  212035. bool ok;
  212036. int width, height;
  212037. Time firstRecordedTime;
  212038. VoidArray viewerComps;
  212039. private:
  212040. CameraDevice* const owner;
  212041. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212042. ComSmartPtr <IBaseFilter> filter;
  212043. ComSmartPtr <IBaseFilter> smartTee;
  212044. ComSmartPtr <IGraphBuilder> graphBuilder;
  212045. ComSmartPtr <ISampleGrabber> sampleGrabber;
  212046. ComSmartPtr <IMediaControl> mediaControl;
  212047. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  212048. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  212049. ComSmartPtr <IBaseFilter> mux, fileWriter;
  212050. int activeUsers;
  212051. Array <int> widths, heights;
  212052. DWORD graphRegistrationID;
  212053. CriticalSection imageSwapLock;
  212054. bool imageNeedsFlipping;
  212055. Image* loadingImage;
  212056. Image* activeImage;
  212057. bool recordNextFrameTime;
  212058. void getVideoSizes (IAMStreamConfig* const streamConfig)
  212059. {
  212060. widths.clear();
  212061. heights.clear();
  212062. int count = 0, size = 0;
  212063. streamConfig->GetNumberOfCapabilities (&count, &size);
  212064. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212065. {
  212066. for (int i = 0; i < count; ++i)
  212067. {
  212068. VIDEO_STREAM_CONFIG_CAPS scc;
  212069. AM_MEDIA_TYPE* config;
  212070. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212071. if (SUCCEEDED (hr))
  212072. {
  212073. const int w = scc.InputSize.cx;
  212074. const int h = scc.InputSize.cy;
  212075. bool duplicate = false;
  212076. for (int j = widths.size(); --j >= 0;)
  212077. {
  212078. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  212079. {
  212080. duplicate = true;
  212081. break;
  212082. }
  212083. }
  212084. if (! duplicate)
  212085. {
  212086. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  212087. widths.add (w);
  212088. heights.add (h);
  212089. }
  212090. deleteMediaType (config);
  212091. }
  212092. }
  212093. }
  212094. }
  212095. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  212096. const int minWidth, const int minHeight,
  212097. const int maxWidth, const int maxHeight)
  212098. {
  212099. int count = 0, size = 0;
  212100. streamConfig->GetNumberOfCapabilities (&count, &size);
  212101. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212102. {
  212103. for (int i = 0; i < count; ++i)
  212104. {
  212105. VIDEO_STREAM_CONFIG_CAPS scc;
  212106. AM_MEDIA_TYPE* config;
  212107. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212108. if (SUCCEEDED (hr))
  212109. {
  212110. if (scc.InputSize.cx >= minWidth
  212111. && scc.InputSize.cy >= minHeight
  212112. && scc.InputSize.cx <= maxWidth
  212113. && scc.InputSize.cy <= maxHeight)
  212114. {
  212115. hr = streamConfig->SetFormat (config);
  212116. deleteMediaType (config);
  212117. return SUCCEEDED (hr);
  212118. }
  212119. deleteMediaType (config);
  212120. }
  212121. }
  212122. }
  212123. return false;
  212124. }
  212125. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  212126. {
  212127. ComSmartPtr <IEnumPins> enumerator;
  212128. ComSmartPtr <IPin> pin;
  212129. filter->EnumPins (&enumerator);
  212130. while (enumerator->Next (1, &pin, 0) == S_OK)
  212131. {
  212132. PIN_DIRECTION dir;
  212133. pin->QueryDirection (&dir);
  212134. if (wantedDirection == dir)
  212135. {
  212136. PIN_INFO info;
  212137. zerostruct (info);
  212138. pin->QueryPinInfo (&info);
  212139. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  212140. {
  212141. pin.p->AddRef();
  212142. *result = pin;
  212143. return true;
  212144. }
  212145. }
  212146. }
  212147. return false;
  212148. }
  212149. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  212150. {
  212151. ComSmartPtr <IPin> in, out;
  212152. return getPin (first, PINDIR_OUTPUT, &out)
  212153. && getPin (second, PINDIR_INPUT, &in)
  212154. && SUCCEEDED (graphBuilder->Connect (out, in));
  212155. }
  212156. bool addGraphToRot()
  212157. {
  212158. ComSmartPtr <IRunningObjectTable> rot;
  212159. if (FAILED (GetRunningObjectTable (0, &rot)))
  212160. return false;
  212161. ComSmartPtr <IMoniker> moniker;
  212162. WCHAR buffer[128];
  212163. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  212164. if (FAILED (hr))
  212165. return false;
  212166. graphRegistrationID = 0;
  212167. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  212168. }
  212169. void removeGraphFromRot()
  212170. {
  212171. ComSmartPtr <IRunningObjectTable> rot;
  212172. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  212173. rot->Revoke (graphRegistrationID);
  212174. }
  212175. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  212176. {
  212177. if (pmt->cbFormat != 0)
  212178. CoTaskMemFree ((PVOID) pmt->pbFormat);
  212179. if (pmt->pUnk != 0)
  212180. pmt->pUnk->Release();
  212181. CoTaskMemFree (pmt);
  212182. }
  212183. class GrabberCallback : public ISampleGrabberCB
  212184. {
  212185. public:
  212186. GrabberCallback (DShowCameraDeviceInteral& owner_)
  212187. : owner (owner_)
  212188. {
  212189. }
  212190. HRESULT __stdcall QueryInterface (REFIID id, void** result)
  212191. {
  212192. if (id == IID_IUnknown)
  212193. *result = dynamic_cast <IUnknown*> (this);
  212194. else if (id == IID_ISampleGrabberCB)
  212195. *result = dynamic_cast <ISampleGrabberCB*> (this);
  212196. else
  212197. {
  212198. *result = 0;
  212199. return E_NOINTERFACE;
  212200. }
  212201. AddRef();
  212202. return S_OK;
  212203. }
  212204. ULONG __stdcall AddRef() { return ++refCount; }
  212205. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  212206. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  212207. {
  212208. return E_FAIL;
  212209. }
  212210. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  212211. {
  212212. owner.handleFrame (time, buffer, bufferSize);
  212213. return S_OK;
  212214. }
  212215. private:
  212216. int refCount;
  212217. DShowCameraDeviceInteral& owner;
  212218. GrabberCallback (const GrabberCallback&);
  212219. const GrabberCallback& operator= (const GrabberCallback&);
  212220. };
  212221. ComSmartPtr <GrabberCallback> callback;
  212222. VoidArray listeners;
  212223. CriticalSection listenerLock;
  212224. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  212225. const DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  212226. };
  212227. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  212228. : name (name_)
  212229. {
  212230. isRecording = false;
  212231. }
  212232. CameraDevice::~CameraDevice()
  212233. {
  212234. stopRecording();
  212235. delete (DShowCameraDeviceInteral*) internal;
  212236. internal = 0;
  212237. }
  212238. Component* CameraDevice::createViewerComponent()
  212239. {
  212240. return new DShowCameraDeviceInteral::DShowCaptureViewerComp ((DShowCameraDeviceInteral*) internal);
  212241. }
  212242. const String CameraDevice::getFileExtension()
  212243. {
  212244. return ".avi";
  212245. }
  212246. void CameraDevice::startRecordingToFile (const File& file)
  212247. {
  212248. stopRecording();
  212249. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212250. d->addUser();
  212251. isRecording = d->createFileCaptureFilter (file);
  212252. }
  212253. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  212254. {
  212255. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212256. return d->firstRecordedTime;
  212257. }
  212258. void CameraDevice::stopRecording()
  212259. {
  212260. if (isRecording)
  212261. {
  212262. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212263. d->removeFileCaptureFilter();
  212264. d->removeUser();
  212265. isRecording = false;
  212266. }
  212267. }
  212268. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  212269. {
  212270. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212271. if (listenerToAdd != 0)
  212272. d->addListener (listenerToAdd);
  212273. }
  212274. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  212275. {
  212276. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212277. if (listenerToRemove != 0)
  212278. d->removeListener (listenerToRemove);
  212279. }
  212280. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  212281. const int deviceIndexToOpen,
  212282. String& name)
  212283. {
  212284. int index = 0;
  212285. ComSmartPtr <IBaseFilter> result;
  212286. ComSmartPtr <ICreateDevEnum> pDevEnum;
  212287. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum, CLSCTX_INPROC);
  212288. if (SUCCEEDED (hr))
  212289. {
  212290. ComSmartPtr <IEnumMoniker> enumerator;
  212291. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  212292. if (SUCCEEDED (hr) && enumerator != 0)
  212293. {
  212294. ComSmartPtr <IBaseFilter> captureFilter;
  212295. ComSmartPtr <IMoniker> moniker;
  212296. ULONG fetched;
  212297. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  212298. {
  212299. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  212300. if (SUCCEEDED (hr))
  212301. {
  212302. ComSmartPtr <IPropertyBag> propertyBag;
  212303. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  212304. if (SUCCEEDED (hr))
  212305. {
  212306. VARIANT var;
  212307. var.vt = VT_BSTR;
  212308. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  212309. propertyBag = 0;
  212310. if (SUCCEEDED (hr))
  212311. {
  212312. if (names != 0)
  212313. names->add (var.bstrVal);
  212314. if (index == deviceIndexToOpen)
  212315. {
  212316. name = var.bstrVal;
  212317. result = captureFilter;
  212318. captureFilter = 0;
  212319. break;
  212320. }
  212321. ++index;
  212322. }
  212323. moniker = 0;
  212324. }
  212325. captureFilter = 0;
  212326. }
  212327. }
  212328. }
  212329. }
  212330. return result;
  212331. }
  212332. const StringArray CameraDevice::getAvailableDevices()
  212333. {
  212334. StringArray devs;
  212335. String dummy;
  212336. enumerateCameras (&devs, -1, dummy);
  212337. return devs;
  212338. }
  212339. CameraDevice* CameraDevice::openDevice (int index,
  212340. int minWidth, int minHeight,
  212341. int maxWidth, int maxHeight)
  212342. {
  212343. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212344. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2, CLSCTX_INPROC);
  212345. if (SUCCEEDED (hr))
  212346. {
  212347. String name;
  212348. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  212349. if (filter != 0)
  212350. {
  212351. CameraDevice* const cam = new CameraDevice (name, index);
  212352. DShowCameraDeviceInteral* const intern
  212353. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  212354. minWidth, minHeight, maxWidth, maxHeight);
  212355. cam->internal = intern;
  212356. if (intern->ok)
  212357. return cam;
  212358. else
  212359. delete cam;
  212360. }
  212361. }
  212362. return 0;
  212363. }
  212364. #endif
  212365. /********* End of inlined file: juce_win32_CameraDevice.cpp *********/
  212366. #endif
  212367. // Auto-link the other win32 libs that are needed by library calls..
  212368. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  212369. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212370. // Auto-links to various win32 libs that are needed by library calls..
  212371. #pragma comment(lib, "kernel32.lib")
  212372. #pragma comment(lib, "user32.lib")
  212373. #pragma comment(lib, "shell32.lib")
  212374. #pragma comment(lib, "gdi32.lib")
  212375. #pragma comment(lib, "vfw32.lib")
  212376. #pragma comment(lib, "comdlg32.lib")
  212377. #pragma comment(lib, "winmm.lib")
  212378. #pragma comment(lib, "wininet.lib")
  212379. #pragma comment(lib, "ole32.lib")
  212380. #pragma comment(lib, "advapi32.lib")
  212381. #pragma comment(lib, "ws2_32.lib")
  212382. #pragma comment(lib, "comsupp.lib")
  212383. #pragma comment(lib, "version.lib")
  212384. #if JUCE_OPENGL
  212385. #pragma comment(lib, "OpenGL32.Lib")
  212386. #pragma comment(lib, "GlU32.Lib")
  212387. #endif
  212388. #if JUCE_QUICKTIME
  212389. #pragma comment (lib, "QTMLClient.lib")
  212390. #endif
  212391. #if JUCE_USE_CAMERA
  212392. #pragma comment (lib, "Strmiids.lib")
  212393. #endif
  212394. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212395. #endif
  212396. END_JUCE_NAMESPACE
  212397. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  212398. #endif
  212399. #if JUCE_LINUX
  212400. /********* Start of inlined file: juce_linux_NativeCode.cpp *********/
  212401. /*
  212402. This file wraps together all the mac-specific code, so that
  212403. we can include all the native headers just once, and compile all our
  212404. platform-specific stuff in one big lump, keeping it out of the way of
  212405. the rest of the codebase.
  212406. */
  212407. BEGIN_JUCE_NAMESPACE
  212408. /* Remove this macro if you're having problems compiling the cpu affinity
  212409. calls (the API for these has changed about quite a bit in various Linux
  212410. versions, and a lot of distros seem to ship with obsolete versions)
  212411. */
  212412. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  212413. #define SUPPORT_AFFINITIES 1
  212414. #endif
  212415. #define JUCE_INCLUDED_FILE 1
  212416. // Now include the actual code files..
  212417. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  212418. /*
  212419. This file contains posix routines that are common to both the Linux and Mac builds.
  212420. It gets included directly in the cpp files for these platforms.
  212421. */
  212422. CriticalSection::CriticalSection() throw()
  212423. {
  212424. pthread_mutexattr_t atts;
  212425. pthread_mutexattr_init (&atts);
  212426. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  212427. pthread_mutex_init (&internal, &atts);
  212428. }
  212429. CriticalSection::~CriticalSection() throw()
  212430. {
  212431. pthread_mutex_destroy (&internal);
  212432. }
  212433. void CriticalSection::enter() const throw()
  212434. {
  212435. pthread_mutex_lock (&internal);
  212436. }
  212437. bool CriticalSection::tryEnter() const throw()
  212438. {
  212439. return pthread_mutex_trylock (&internal) == 0;
  212440. }
  212441. void CriticalSection::exit() const throw()
  212442. {
  212443. pthread_mutex_unlock (&internal);
  212444. }
  212445. struct EventStruct
  212446. {
  212447. pthread_cond_t condition;
  212448. pthread_mutex_t mutex;
  212449. bool triggered;
  212450. };
  212451. WaitableEvent::WaitableEvent() throw()
  212452. {
  212453. EventStruct* const es = new EventStruct();
  212454. es->triggered = false;
  212455. pthread_cond_init (&es->condition, 0);
  212456. pthread_mutex_init (&es->mutex, 0);
  212457. internal = es;
  212458. }
  212459. WaitableEvent::~WaitableEvent() throw()
  212460. {
  212461. EventStruct* const es = (EventStruct*) internal;
  212462. pthread_cond_destroy (&es->condition);
  212463. pthread_mutex_destroy (&es->mutex);
  212464. delete es;
  212465. }
  212466. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  212467. {
  212468. EventStruct* const es = (EventStruct*) internal;
  212469. bool ok = true;
  212470. pthread_mutex_lock (&es->mutex);
  212471. if (timeOutMillisecs < 0)
  212472. {
  212473. while (! es->triggered)
  212474. pthread_cond_wait (&es->condition, &es->mutex);
  212475. }
  212476. else
  212477. {
  212478. while (! es->triggered)
  212479. {
  212480. struct timeval t;
  212481. gettimeofday (&t, 0);
  212482. struct timespec time;
  212483. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  212484. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  212485. if (time.tv_nsec >= 1000000000)
  212486. {
  212487. time.tv_nsec -= 1000000000;
  212488. time.tv_sec++;
  212489. }
  212490. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  212491. {
  212492. ok = false;
  212493. break;
  212494. }
  212495. }
  212496. }
  212497. es->triggered = false;
  212498. pthread_mutex_unlock (&es->mutex);
  212499. return ok;
  212500. }
  212501. void WaitableEvent::signal() const throw()
  212502. {
  212503. EventStruct* const es = (EventStruct*) internal;
  212504. pthread_mutex_lock (&es->mutex);
  212505. es->triggered = true;
  212506. pthread_cond_broadcast (&es->condition);
  212507. pthread_mutex_unlock (&es->mutex);
  212508. }
  212509. void WaitableEvent::reset() const throw()
  212510. {
  212511. EventStruct* const es = (EventStruct*) internal;
  212512. pthread_mutex_lock (&es->mutex);
  212513. es->triggered = false;
  212514. pthread_mutex_unlock (&es->mutex);
  212515. }
  212516. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  212517. {
  212518. struct timespec time;
  212519. time.tv_sec = millisecs / 1000;
  212520. time.tv_nsec = (millisecs % 1000) * 1000000;
  212521. nanosleep (&time, 0);
  212522. }
  212523. const tchar File::separator = T('/');
  212524. const tchar* File::separatorString = T("/");
  212525. bool juce_copyFile (const String& s, const String& d) throw();
  212526. static bool juce_stat (const String& fileName, struct stat& info) throw()
  212527. {
  212528. return fileName.isNotEmpty()
  212529. && (stat (fileName.toUTF8(), &info) == 0);
  212530. }
  212531. bool juce_isDirectory (const String& fileName) throw()
  212532. {
  212533. struct stat info;
  212534. return fileName.isEmpty()
  212535. || (juce_stat (fileName, info)
  212536. && ((info.st_mode & S_IFDIR) != 0));
  212537. }
  212538. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  212539. {
  212540. if (fileName.isEmpty())
  212541. return false;
  212542. const char* const fileNameUTF8 = fileName.toUTF8();
  212543. bool exists = access (fileNameUTF8, F_OK) == 0;
  212544. if (exists && dontCountDirectories)
  212545. {
  212546. struct stat info;
  212547. const int res = stat (fileNameUTF8, &info);
  212548. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  212549. exists = false;
  212550. }
  212551. return exists;
  212552. }
  212553. int64 juce_getFileSize (const String& fileName) throw()
  212554. {
  212555. struct stat info;
  212556. return juce_stat (fileName, info) ? info.st_size : 0;
  212557. }
  212558. bool juce_canWriteToFile (const String& fileName) throw()
  212559. {
  212560. return access (fileName.toUTF8(), W_OK) == 0;
  212561. }
  212562. bool juce_deleteFile (const String& fileName) throw()
  212563. {
  212564. if (juce_isDirectory (fileName))
  212565. return rmdir ((const char*) fileName.toUTF8()) == 0;
  212566. else
  212567. return remove ((const char*) fileName.toUTF8()) == 0;
  212568. }
  212569. bool juce_moveFile (const String& source, const String& dest) throw()
  212570. {
  212571. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  212572. return true;
  212573. if (juce_canWriteToFile (source)
  212574. && juce_copyFile (source, dest))
  212575. {
  212576. if (juce_deleteFile (source))
  212577. return true;
  212578. juce_deleteFile (dest);
  212579. }
  212580. return false;
  212581. }
  212582. void juce_createDirectory (const String& fileName) throw()
  212583. {
  212584. mkdir (fileName.toUTF8(), 0777);
  212585. }
  212586. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  212587. {
  212588. int flags = O_RDONLY;
  212589. if (forWriting)
  212590. {
  212591. if (juce_fileExists (fileName, false))
  212592. {
  212593. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  212594. if (f != -1)
  212595. lseek (f, 0, SEEK_END);
  212596. return (void*) f;
  212597. }
  212598. else
  212599. {
  212600. flags = O_RDWR + O_CREAT;
  212601. }
  212602. }
  212603. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  212604. }
  212605. void juce_fileClose (void* handle) throw()
  212606. {
  212607. if (handle != 0)
  212608. close ((int) (pointer_sized_int) handle);
  212609. }
  212610. int juce_fileRead (void* handle, void* buffer, int size) throw()
  212611. {
  212612. if (handle != 0)
  212613. return read ((int) (pointer_sized_int) handle, buffer, size);
  212614. return 0;
  212615. }
  212616. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  212617. {
  212618. if (handle != 0)
  212619. return write ((int) (pointer_sized_int) handle, buffer, size);
  212620. return 0;
  212621. }
  212622. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  212623. {
  212624. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  212625. return pos;
  212626. return -1;
  212627. }
  212628. int64 juce_fileGetPosition (void* handle) throw()
  212629. {
  212630. if (handle != 0)
  212631. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  212632. else
  212633. return -1;
  212634. }
  212635. void juce_fileFlush (void* handle) throw()
  212636. {
  212637. if (handle != 0)
  212638. fsync ((int) (pointer_sized_int) handle);
  212639. }
  212640. const File juce_getExecutableFile()
  212641. {
  212642. Dl_info exeInfo;
  212643. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  212644. return File (exeInfo.dli_fname);
  212645. }
  212646. // if this file doesn't exist, find a parent of it that does..
  212647. static bool doStatFS (const File* file, struct statfs& result) throw()
  212648. {
  212649. File f (*file);
  212650. for (int i = 5; --i >= 0;)
  212651. {
  212652. if (f.exists())
  212653. break;
  212654. f = f.getParentDirectory();
  212655. }
  212656. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  212657. }
  212658. int64 File::getBytesFreeOnVolume() const throw()
  212659. {
  212660. struct statfs buf;
  212661. if (doStatFS (this, buf))
  212662. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  212663. return 0;
  212664. }
  212665. int64 File::getVolumeTotalSize() const throw()
  212666. {
  212667. struct statfs buf;
  212668. if (doStatFS (this, buf))
  212669. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  212670. return 0;
  212671. }
  212672. const String juce_getVolumeLabel (const String& filenameOnVolume,
  212673. int& volumeSerialNumber) throw()
  212674. {
  212675. volumeSerialNumber = 0;
  212676. #if JUCE_MAC
  212677. struct VolAttrBuf
  212678. {
  212679. u_int32_t length;
  212680. attrreference_t mountPointRef;
  212681. char mountPointSpace [MAXPATHLEN];
  212682. } attrBuf;
  212683. struct attrlist attrList;
  212684. zerostruct (attrList);
  212685. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  212686. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  212687. File f (filenameOnVolume);
  212688. for (;;)
  212689. {
  212690. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  212691. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  212692. {
  212693. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  212694. (int) attrBuf.mountPointRef.attr_length);
  212695. }
  212696. const File parent (f.getParentDirectory());
  212697. if (f == parent)
  212698. break;
  212699. f = parent;
  212700. }
  212701. #endif
  212702. return String::empty;
  212703. }
  212704. void juce_runSystemCommand (const String& command)
  212705. {
  212706. int result = system ((const char*) command.toUTF8());
  212707. (void) result;
  212708. }
  212709. const String juce_getOutputFromCommand (const String& command)
  212710. {
  212711. // slight bodge here, as we just pipe the output into a temp file and read it...
  212712. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  212713. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  212714. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  212715. String result (tempFile.loadFileAsString());
  212716. tempFile.deleteFile();
  212717. return result;
  212718. }
  212719. #if JUCE_64BIT
  212720. #define filedesc ((long long) internal)
  212721. #else
  212722. #define filedesc ((int) internal)
  212723. #endif
  212724. InterProcessLock::InterProcessLock (const String& name_) throw()
  212725. : internal (0),
  212726. name (name_),
  212727. reentrancyLevel (0)
  212728. {
  212729. #if JUCE_MAC
  212730. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  212731. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  212732. #else
  212733. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  212734. #endif
  212735. temp.create();
  212736. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  212737. }
  212738. InterProcessLock::~InterProcessLock() throw()
  212739. {
  212740. while (reentrancyLevel > 0)
  212741. this->exit();
  212742. close (filedesc);
  212743. }
  212744. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  212745. {
  212746. if (internal == 0)
  212747. return false;
  212748. if (reentrancyLevel != 0)
  212749. return true;
  212750. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  212751. struct flock fl;
  212752. zerostruct (fl);
  212753. fl.l_whence = SEEK_SET;
  212754. fl.l_type = F_WRLCK;
  212755. for (;;)
  212756. {
  212757. const int result = fcntl (filedesc, F_SETLK, &fl);
  212758. if (result >= 0)
  212759. {
  212760. ++reentrancyLevel;
  212761. return true;
  212762. }
  212763. if (errno != EINTR)
  212764. {
  212765. if (timeOutMillisecs == 0
  212766. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  212767. break;
  212768. Thread::sleep (10);
  212769. }
  212770. }
  212771. return false;
  212772. }
  212773. void InterProcessLock::exit() throw()
  212774. {
  212775. if (reentrancyLevel > 0 && internal != 0)
  212776. {
  212777. --reentrancyLevel;
  212778. struct flock fl;
  212779. zerostruct (fl);
  212780. fl.l_whence = SEEK_SET;
  212781. fl.l_type = F_UNLCK;
  212782. for (;;)
  212783. {
  212784. const int result = fcntl (filedesc, F_SETLKW, &fl);
  212785. if (result >= 0 || errno != EINTR)
  212786. break;
  212787. }
  212788. }
  212789. }
  212790. /********* End of inlined file: juce_posix_SharedCode.h *********/
  212791. /********* Start of inlined file: juce_linux_Files.cpp *********/
  212792. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212793. // compiled on its own).
  212794. #ifdef JUCE_INCLUDED_FILE
  212795. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  212796. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  212797. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  212798. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  212799. void juce_getFileTimes (const String& fileName,
  212800. int64& modificationTime,
  212801. int64& accessTime,
  212802. int64& creationTime) throw()
  212803. {
  212804. modificationTime = 0;
  212805. accessTime = 0;
  212806. creationTime = 0;
  212807. struct stat info;
  212808. const int res = stat (fileName.toUTF8(), &info);
  212809. if (res == 0)
  212810. {
  212811. modificationTime = (int64) info.st_mtime * 1000;
  212812. accessTime = (int64) info.st_atime * 1000;
  212813. creationTime = (int64) info.st_ctime * 1000;
  212814. }
  212815. }
  212816. bool juce_setFileTimes (const String& fileName,
  212817. int64 modificationTime,
  212818. int64 accessTime,
  212819. int64 creationTime) throw()
  212820. {
  212821. struct utimbuf times;
  212822. times.actime = (time_t) (accessTime / 1000);
  212823. times.modtime = (time_t) (modificationTime / 1000);
  212824. return utime (fileName.toUTF8(), &times) == 0;
  212825. }
  212826. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  212827. {
  212828. struct stat info;
  212829. const int res = stat (fileName.toUTF8(), &info);
  212830. if (res != 0)
  212831. return false;
  212832. info.st_mode &= 0777; // Just permissions
  212833. if( isReadOnly )
  212834. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  212835. else
  212836. // Give everybody write permission?
  212837. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  212838. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  212839. }
  212840. bool juce_copyFile (const String& s, const String& d) throw()
  212841. {
  212842. const File source (s), dest (d);
  212843. FileInputStream* in = source.createInputStream();
  212844. bool ok = false;
  212845. if (in != 0)
  212846. {
  212847. if (dest.deleteFile())
  212848. {
  212849. FileOutputStream* const out = dest.createOutputStream();
  212850. if (out != 0)
  212851. {
  212852. const int bytesCopied = out->writeFromInputStream (*in, -1);
  212853. delete out;
  212854. ok = (bytesCopied == source.getSize());
  212855. if (! ok)
  212856. dest.deleteFile();
  212857. }
  212858. }
  212859. delete in;
  212860. }
  212861. return ok;
  212862. }
  212863. const StringArray juce_getFileSystemRoots() throw()
  212864. {
  212865. StringArray s;
  212866. s.add (T("/"));
  212867. return s;
  212868. }
  212869. bool File::isOnCDRomDrive() const throw()
  212870. {
  212871. struct statfs buf;
  212872. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212873. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  212874. // Assume not if this fails for some reason
  212875. return false;
  212876. }
  212877. bool File::isOnHardDisk() const throw()
  212878. {
  212879. struct statfs buf;
  212880. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212881. {
  212882. switch (buf.f_type)
  212883. {
  212884. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  212885. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  212886. case U_NFS_SUPER_MAGIC: // Network NFS
  212887. case U_SMB_SUPER_MAGIC: // Network Samba
  212888. return false;
  212889. default:
  212890. // Assume anything else is a hard-disk (but note it could
  212891. // be a RAM disk. There isn't a good way of determining
  212892. // this for sure)
  212893. return true;
  212894. }
  212895. }
  212896. // Assume so if this fails for some reason
  212897. return true;
  212898. }
  212899. bool File::isOnRemovableDrive() const throw()
  212900. {
  212901. jassertfalse // xxx not implemented for linux!
  212902. return false;
  212903. }
  212904. bool File::isHidden() const throw()
  212905. {
  212906. return getFileName().startsWithChar (T('.'));
  212907. }
  212908. const File File::getSpecialLocation (const SpecialLocationType type)
  212909. {
  212910. switch (type)
  212911. {
  212912. case userHomeDirectory:
  212913. {
  212914. const char* homeDir = getenv ("HOME");
  212915. if (homeDir == 0)
  212916. {
  212917. struct passwd* const pw = getpwuid (getuid());
  212918. if (pw != 0)
  212919. homeDir = pw->pw_dir;
  212920. }
  212921. return File (String::fromUTF8 ((const uint8*) homeDir));
  212922. }
  212923. case userDocumentsDirectory:
  212924. case userMusicDirectory:
  212925. case userMoviesDirectory:
  212926. case userApplicationDataDirectory:
  212927. return File ("~");
  212928. case userDesktopDirectory:
  212929. return File ("~/Desktop");
  212930. case commonApplicationDataDirectory:
  212931. return File ("/var");
  212932. case globalApplicationsDirectory:
  212933. return File ("/usr");
  212934. case tempDirectory:
  212935. {
  212936. File tmp ("/var/tmp");
  212937. if (! tmp.isDirectory())
  212938. {
  212939. tmp = T("/tmp");
  212940. if (! tmp.isDirectory())
  212941. tmp = File::getCurrentWorkingDirectory();
  212942. }
  212943. return tmp;
  212944. }
  212945. case currentExecutableFile:
  212946. case currentApplicationFile:
  212947. return juce_getExecutableFile();
  212948. default:
  212949. jassertfalse // unknown type?
  212950. break;
  212951. }
  212952. return File::nonexistent;
  212953. }
  212954. const File File::getCurrentWorkingDirectory() throw()
  212955. {
  212956. char buf [2048];
  212957. return File (String::fromUTF8 ((const uint8*) getcwd (buf, sizeof (buf))));
  212958. }
  212959. bool File::setAsCurrentWorkingDirectory() const throw()
  212960. {
  212961. return chdir (getFullPathName().toUTF8()) == 0;
  212962. }
  212963. const String File::getVersion() const throw()
  212964. {
  212965. return String::empty; // xxx not yet implemented
  212966. }
  212967. const File File::getLinkedTarget() const throw()
  212968. {
  212969. char buffer [4096];
  212970. size_t numChars = readlink ((const char*) getFullPathName().toUTF8(),
  212971. buffer, sizeof (buffer));
  212972. if (numChars > 0 && numChars <= sizeof (buffer))
  212973. return File (String::fromUTF8 ((const uint8*) buffer, (int) numChars));
  212974. return *this;
  212975. }
  212976. bool File::moveToTrash() const throw()
  212977. {
  212978. if (! exists())
  212979. return true;
  212980. File trashCan (T("~/.Trash"));
  212981. if (! trashCan.isDirectory())
  212982. trashCan = T("~/.local/share/Trash/files");
  212983. if (! trashCan.isDirectory())
  212984. return false;
  212985. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  212986. getFileExtension()));
  212987. }
  212988. struct FindFileStruct
  212989. {
  212990. String parentDir, wildCard;
  212991. DIR* dir;
  212992. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  212993. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  212994. {
  212995. const char* const wildcardUTF8 = wildCard.toUTF8();
  212996. for (;;)
  212997. {
  212998. struct dirent* const de = readdir (dir);
  212999. if (de == 0)
  213000. break;
  213001. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  213002. {
  213003. result = String::fromUTF8 ((const uint8*) de->d_name);
  213004. const String path (parentDir + result);
  213005. if (isDir != 0 || fileSize != 0)
  213006. {
  213007. struct stat info;
  213008. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  213009. if (isDir != 0)
  213010. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  213011. if (isHidden != 0)
  213012. *isHidden = (de->d_name[0] == '.');
  213013. if (fileSize != 0)
  213014. *fileSize = statOk ? info.st_size : 0;
  213015. }
  213016. if (modTime != 0 || creationTime != 0)
  213017. {
  213018. int64 m, a, c;
  213019. juce_getFileTimes (path, m, a, c);
  213020. if (modTime != 0)
  213021. *modTime = m;
  213022. if (creationTime != 0)
  213023. *creationTime = c;
  213024. }
  213025. if (isReadOnly != 0)
  213026. *isReadOnly = ! juce_canWriteToFile (path);
  213027. return true;
  213028. }
  213029. }
  213030. return false;
  213031. }
  213032. };
  213033. // returns 0 on failure
  213034. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  213035. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  213036. Time* creationTime, bool* isReadOnly) throw()
  213037. {
  213038. DIR* d = opendir (directory.toUTF8());
  213039. if (d != 0)
  213040. {
  213041. FindFileStruct* ff = new FindFileStruct();
  213042. ff->parentDir = directory;
  213043. if (!ff->parentDir.endsWithChar (File::separator))
  213044. ff->parentDir += File::separator;
  213045. ff->wildCard = wildCard;
  213046. if (wildCard == T("*.*"))
  213047. ff->wildCard = T("*");
  213048. ff->dir = d;
  213049. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  213050. {
  213051. return ff;
  213052. }
  213053. else
  213054. {
  213055. firstResultFile = String::empty;
  213056. isDir = false;
  213057. isHidden = false;
  213058. closedir (d);
  213059. delete ff;
  213060. }
  213061. }
  213062. return 0;
  213063. }
  213064. bool juce_findFileNext (void* handle, String& resultFile,
  213065. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  213066. {
  213067. FindFileStruct* const ff = (FindFileStruct*) handle;
  213068. if (ff != 0)
  213069. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  213070. return false;
  213071. }
  213072. void juce_findFileClose (void* handle) throw()
  213073. {
  213074. FindFileStruct* const ff = (FindFileStruct*) handle;
  213075. if (ff != 0)
  213076. {
  213077. closedir (ff->dir);
  213078. delete ff;
  213079. }
  213080. }
  213081. bool juce_launchFile (const String& fileName,
  213082. const String& parameters) throw()
  213083. {
  213084. String cmdString (fileName);
  213085. cmdString << " " << parameters;
  213086. if (URL::isProbablyAWebsiteURL (fileName)
  213087. || URL::isProbablyAnEmailAddress (fileName))
  213088. {
  213089. // create a command that tries to launch a bunch of likely browsers
  213090. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  213091. StringArray cmdLines;
  213092. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  213093. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  213094. cmdString = cmdLines.joinIntoString (T(" || "));
  213095. }
  213096. if (cmdString.startsWithIgnoreCase (T("file:")))
  213097. cmdString = cmdString.substring (5);
  213098. const char* const argv[4] = { "/bin/sh", "-c", (const char*) cmdString.toUTF8(), 0 };
  213099. const int cpid = fork();
  213100. if (cpid == 0)
  213101. {
  213102. setsid();
  213103. // Child process
  213104. execve (argv[0], (char**) argv, environ);
  213105. exit (0);
  213106. }
  213107. return cpid >= 0;
  213108. }
  213109. #endif
  213110. /********* End of inlined file: juce_linux_Files.cpp *********/
  213111. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  213112. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  213113. // compiled on its own).
  213114. #if JUCE_INCLUDED_FILE
  213115. struct NamedPipeInternal
  213116. {
  213117. String pipeInName, pipeOutName;
  213118. int pipeIn, pipeOut;
  213119. bool volatile createdPipe, blocked, stopReadOperation;
  213120. static void signalHandler (int) {}
  213121. };
  213122. void NamedPipe::cancelPendingReads()
  213123. {
  213124. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  213125. {
  213126. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213127. intern->stopReadOperation = true;
  213128. char buffer [1] = { 0 };
  213129. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  213130. (void) bytesWritten;
  213131. int timeout = 2000;
  213132. while (intern->blocked && --timeout >= 0)
  213133. Thread::sleep (2);
  213134. intern->stopReadOperation = false;
  213135. }
  213136. }
  213137. void NamedPipe::close()
  213138. {
  213139. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213140. if (intern != 0)
  213141. {
  213142. internal = 0;
  213143. if (intern->pipeIn != -1)
  213144. ::close (intern->pipeIn);
  213145. if (intern->pipeOut != -1)
  213146. ::close (intern->pipeOut);
  213147. if (intern->createdPipe)
  213148. {
  213149. unlink (intern->pipeInName);
  213150. unlink (intern->pipeOutName);
  213151. }
  213152. delete intern;
  213153. }
  213154. }
  213155. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  213156. {
  213157. close();
  213158. NamedPipeInternal* const intern = new NamedPipeInternal();
  213159. internal = intern;
  213160. intern->createdPipe = createPipe;
  213161. intern->blocked = false;
  213162. intern->stopReadOperation = false;
  213163. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  213164. siginterrupt (SIGPIPE, 1);
  213165. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  213166. intern->pipeInName = pipePath + T("_in");
  213167. intern->pipeOutName = pipePath + T("_out");
  213168. intern->pipeIn = -1;
  213169. intern->pipeOut = -1;
  213170. if (createPipe)
  213171. {
  213172. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  213173. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  213174. {
  213175. delete intern;
  213176. internal = 0;
  213177. return false;
  213178. }
  213179. }
  213180. return true;
  213181. }
  213182. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  213183. {
  213184. int bytesRead = -1;
  213185. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213186. if (intern != 0)
  213187. {
  213188. intern->blocked = true;
  213189. if (intern->pipeIn == -1)
  213190. {
  213191. if (intern->createdPipe)
  213192. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  213193. else
  213194. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  213195. if (intern->pipeIn == -1)
  213196. {
  213197. intern->blocked = false;
  213198. return -1;
  213199. }
  213200. }
  213201. bytesRead = 0;
  213202. char* p = (char*) destBuffer;
  213203. while (bytesRead < maxBytesToRead)
  213204. {
  213205. const int bytesThisTime = maxBytesToRead - bytesRead;
  213206. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  213207. if (numRead <= 0 || intern->stopReadOperation)
  213208. {
  213209. bytesRead = -1;
  213210. break;
  213211. }
  213212. bytesRead += numRead;
  213213. p += bytesRead;
  213214. }
  213215. intern->blocked = false;
  213216. }
  213217. return bytesRead;
  213218. }
  213219. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  213220. {
  213221. int bytesWritten = -1;
  213222. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213223. if (intern != 0)
  213224. {
  213225. if (intern->pipeOut == -1)
  213226. {
  213227. if (intern->createdPipe)
  213228. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  213229. else
  213230. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  213231. if (intern->pipeOut == -1)
  213232. {
  213233. return -1;
  213234. }
  213235. }
  213236. const char* p = (const char*) sourceBuffer;
  213237. bytesWritten = 0;
  213238. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  213239. while (bytesWritten < numBytesToWrite
  213240. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  213241. {
  213242. const int bytesThisTime = numBytesToWrite - bytesWritten;
  213243. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  213244. if (numWritten <= 0)
  213245. {
  213246. bytesWritten = -1;
  213247. break;
  213248. }
  213249. bytesWritten += numWritten;
  213250. p += bytesWritten;
  213251. }
  213252. }
  213253. return bytesWritten;
  213254. }
  213255. #endif
  213256. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  213257. /********* Start of inlined file: juce_linux_Network.cpp *********/
  213258. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213259. // compiled on its own).
  213260. #ifdef JUCE_INCLUDED_FILE
  213261. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  213262. {
  213263. int numResults = 0;
  213264. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  213265. if (s != -1)
  213266. {
  213267. char buf [1024];
  213268. struct ifconf ifc;
  213269. ifc.ifc_len = sizeof (buf);
  213270. ifc.ifc_buf = buf;
  213271. ioctl (s, SIOCGIFCONF, &ifc);
  213272. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  213273. {
  213274. struct ifreq ifr;
  213275. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  213276. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  213277. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  213278. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  213279. && numResults < maxNum)
  213280. {
  213281. int64 a = 0;
  213282. for (int j = 6; --j >= 0;)
  213283. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  213284. *addresses++ = a;
  213285. ++numResults;
  213286. }
  213287. }
  213288. close (s);
  213289. }
  213290. return numResults;
  213291. }
  213292. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  213293. const String& emailSubject,
  213294. const String& bodyText,
  213295. const StringArray& filesToAttach)
  213296. {
  213297. jassertfalse // xxx todo
  213298. return false;
  213299. }
  213300. /** A HTTP input stream that uses sockets.
  213301. */
  213302. class JUCE_HTTPSocketStream
  213303. {
  213304. public:
  213305. JUCE_HTTPSocketStream()
  213306. : readPosition (0),
  213307. socketHandle (-1),
  213308. levelsOfRedirection (0),
  213309. timeoutSeconds (15)
  213310. {
  213311. }
  213312. ~JUCE_HTTPSocketStream()
  213313. {
  213314. closeSocket();
  213315. }
  213316. bool open (const String& url,
  213317. const String& headers,
  213318. const MemoryBlock& postData,
  213319. const bool isPost,
  213320. URL::OpenStreamProgressCallback* callback,
  213321. void* callbackContext,
  213322. int timeOutMs)
  213323. {
  213324. closeSocket();
  213325. uint32 timeOutTime = Time::getMillisecondCounter();
  213326. if (timeOutMs == 0)
  213327. timeOutTime += 60000;
  213328. else if (timeOutMs < 0)
  213329. timeOutTime = 0xffffffff;
  213330. else
  213331. timeOutTime += timeOutMs;
  213332. String hostName, hostPath;
  213333. int hostPort;
  213334. if (! decomposeURL (url, hostName, hostPath, hostPort))
  213335. return false;
  213336. const struct hostent* host = 0;
  213337. int port = 0;
  213338. String proxyName, proxyPath;
  213339. int proxyPort = 0;
  213340. String proxyURL (getenv ("http_proxy"));
  213341. if (proxyURL.startsWithIgnoreCase (T("http://")))
  213342. {
  213343. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  213344. return false;
  213345. host = gethostbyname ((const char*) proxyName.toUTF8());
  213346. port = proxyPort;
  213347. }
  213348. else
  213349. {
  213350. host = gethostbyname ((const char*) hostName.toUTF8());
  213351. port = hostPort;
  213352. }
  213353. if (host == 0)
  213354. return false;
  213355. struct sockaddr_in address;
  213356. zerostruct (address);
  213357. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  213358. address.sin_family = host->h_addrtype;
  213359. address.sin_port = htons (port);
  213360. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  213361. if (socketHandle == -1)
  213362. return false;
  213363. int receiveBufferSize = 16384;
  213364. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  213365. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  213366. #if JUCE_MAC
  213367. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  213368. #endif
  213369. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  213370. {
  213371. closeSocket();
  213372. return false;
  213373. }
  213374. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  213375. proxyName, proxyPort,
  213376. hostPath, url,
  213377. headers, postData,
  213378. isPost));
  213379. int totalHeaderSent = 0;
  213380. while (totalHeaderSent < requestHeader.getSize())
  213381. {
  213382. if (Time::getMillisecondCounter() > timeOutTime)
  213383. {
  213384. closeSocket();
  213385. return false;
  213386. }
  213387. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  213388. if (send (socketHandle,
  213389. ((const char*) requestHeader.getData()) + totalHeaderSent,
  213390. numToSend, 0)
  213391. != numToSend)
  213392. {
  213393. closeSocket();
  213394. return false;
  213395. }
  213396. totalHeaderSent += numToSend;
  213397. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  213398. {
  213399. closeSocket();
  213400. return false;
  213401. }
  213402. }
  213403. const String responseHeader (readResponse (timeOutTime));
  213404. if (responseHeader.isNotEmpty())
  213405. {
  213406. //DBG (responseHeader);
  213407. StringArray lines;
  213408. lines.addLines (responseHeader);
  213409. // NB - using charToString() here instead of just T(" "), because that was
  213410. // causing a mysterious gcc internal compiler error...
  213411. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  213412. .substring (0, 3).getIntValue();
  213413. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  213414. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  213415. String location (findHeaderItem (lines, T("Location:")));
  213416. if (statusCode >= 300 && statusCode < 400
  213417. && location.isNotEmpty())
  213418. {
  213419. if (! location.startsWithIgnoreCase (T("http://")))
  213420. location = T("http://") + location;
  213421. if (levelsOfRedirection++ < 3)
  213422. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  213423. }
  213424. else
  213425. {
  213426. levelsOfRedirection = 0;
  213427. return true;
  213428. }
  213429. }
  213430. closeSocket();
  213431. return false;
  213432. }
  213433. int read (void* buffer, int bytesToRead)
  213434. {
  213435. fd_set readbits;
  213436. FD_ZERO (&readbits);
  213437. FD_SET (socketHandle, &readbits);
  213438. struct timeval tv;
  213439. tv.tv_sec = timeoutSeconds;
  213440. tv.tv_usec = 0;
  213441. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213442. return 0; // (timeout)
  213443. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  213444. readPosition += bytesRead;
  213445. return bytesRead;
  213446. }
  213447. int readPosition;
  213448. juce_UseDebuggingNewOperator
  213449. private:
  213450. int socketHandle, levelsOfRedirection;
  213451. const int timeoutSeconds;
  213452. void closeSocket()
  213453. {
  213454. if (socketHandle >= 0)
  213455. close (socketHandle);
  213456. socketHandle = -1;
  213457. }
  213458. const MemoryBlock createRequestHeader (const String& hostName,
  213459. const int hostPort,
  213460. const String& proxyName,
  213461. const int proxyPort,
  213462. const String& hostPath,
  213463. const String& originalURL,
  213464. const String& headers,
  213465. const MemoryBlock& postData,
  213466. const bool isPost)
  213467. {
  213468. String header (isPost ? "POST " : "GET ");
  213469. if (proxyName.isEmpty())
  213470. {
  213471. header << hostPath << " HTTP/1.0\r\nHost: "
  213472. << hostName << ':' << hostPort;
  213473. }
  213474. else
  213475. {
  213476. header << originalURL << " HTTP/1.0\r\nHost: "
  213477. << proxyName << ':' << proxyPort;
  213478. }
  213479. header << "\r\nUser-Agent: JUCE/"
  213480. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  213481. << "\r\nConnection: Close\r\nContent-Length: "
  213482. << postData.getSize() << "\r\n"
  213483. << headers << "\r\n";
  213484. MemoryBlock mb;
  213485. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  213486. mb.append (postData.getData(), postData.getSize());
  213487. return mb;
  213488. }
  213489. const String readResponse (const uint32 timeOutTime)
  213490. {
  213491. int bytesRead = 0, numConsecutiveLFs = 0;
  213492. MemoryBlock buffer (1024, true);
  213493. while (numConsecutiveLFs < 2 && bytesRead < 32768
  213494. && Time::getMillisecondCounter() <= timeOutTime)
  213495. {
  213496. fd_set readbits;
  213497. FD_ZERO (&readbits);
  213498. FD_SET (socketHandle, &readbits);
  213499. struct timeval tv;
  213500. tv.tv_sec = timeoutSeconds;
  213501. tv.tv_usec = 0;
  213502. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213503. return String::empty; // (timeout)
  213504. buffer.ensureSize (bytesRead + 8, true);
  213505. char* const dest = (char*) buffer.getData() + bytesRead;
  213506. if (recv (socketHandle, dest, 1, 0) == -1)
  213507. return String::empty;
  213508. const char lastByte = *dest;
  213509. ++bytesRead;
  213510. if (lastByte == '\n')
  213511. ++numConsecutiveLFs;
  213512. else if (lastByte != '\r')
  213513. numConsecutiveLFs = 0;
  213514. }
  213515. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  213516. if (header.startsWithIgnoreCase (T("HTTP/")))
  213517. return header.trimEnd();
  213518. return String::empty;
  213519. }
  213520. static bool decomposeURL (const String& url,
  213521. String& host, String& path, int& port)
  213522. {
  213523. if (! url.startsWithIgnoreCase (T("http://")))
  213524. return false;
  213525. const int nextSlash = url.indexOfChar (7, '/');
  213526. int nextColon = url.indexOfChar (7, ':');
  213527. if (nextColon > nextSlash && nextSlash > 0)
  213528. nextColon = -1;
  213529. if (nextColon >= 0)
  213530. {
  213531. host = url.substring (7, nextColon);
  213532. if (nextSlash >= 0)
  213533. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  213534. else
  213535. port = url.substring (nextColon + 1).getIntValue();
  213536. }
  213537. else
  213538. {
  213539. port = 80;
  213540. if (nextSlash >= 0)
  213541. host = url.substring (7, nextSlash);
  213542. else
  213543. host = url.substring (7);
  213544. }
  213545. if (nextSlash >= 0)
  213546. path = url.substring (nextSlash);
  213547. else
  213548. path = T("/");
  213549. return true;
  213550. }
  213551. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  213552. {
  213553. for (int i = 0; i < lines.size(); ++i)
  213554. if (lines[i].startsWithIgnoreCase (itemName))
  213555. return lines[i].substring (itemName.length()).trim();
  213556. return String::empty;
  213557. }
  213558. };
  213559. bool juce_isOnLine()
  213560. {
  213561. return true;
  213562. }
  213563. void* juce_openInternetFile (const String& url,
  213564. const String& headers,
  213565. const MemoryBlock& postData,
  213566. const bool isPost,
  213567. URL::OpenStreamProgressCallback* callback,
  213568. void* callbackContext,
  213569. int timeOutMs)
  213570. {
  213571. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  213572. if (s->open (url, headers, postData, isPost,
  213573. callback, callbackContext, timeOutMs))
  213574. return s;
  213575. delete s;
  213576. return 0;
  213577. }
  213578. void juce_closeInternetFile (void* handle)
  213579. {
  213580. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213581. if (s != 0)
  213582. delete s;
  213583. }
  213584. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  213585. {
  213586. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213587. if (s != 0)
  213588. return s->read (buffer, bytesToRead);
  213589. return 0;
  213590. }
  213591. int64 juce_getInternetFileContentLength (void* handle)
  213592. {
  213593. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213594. if (s != 0)
  213595. {
  213596. //xxx todo
  213597. jassertfalse
  213598. }
  213599. return -1;
  213600. }
  213601. int juce_seekInInternetFile (void* handle, int newPosition)
  213602. {
  213603. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213604. if (s != 0)
  213605. return s->readPosition;
  213606. return 0;
  213607. }
  213608. #endif
  213609. /********* End of inlined file: juce_linux_Network.cpp *********/
  213610. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  213611. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213612. // compiled on its own).
  213613. #ifdef JUCE_INCLUDED_FILE
  213614. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  213615. {
  213616. unsigned int cpu = 0;
  213617. unsigned int ext = 0;
  213618. unsigned int family = 0;
  213619. unsigned int dummy = 0;
  213620. #if JUCE_64BIT
  213621. __asm__ ("cpuid"
  213622. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213623. #else
  213624. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  213625. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213626. #endif
  213627. if (familyModel != 0)
  213628. *familyModel = family;
  213629. if (extFeatures != 0)
  213630. *extFeatures = ext;
  213631. return cpu;
  213632. }*/
  213633. void Logger::outputDebugString (const String& text) throw()
  213634. {
  213635. fputs (text.toUTF8(), stdout);
  213636. fputs ("\n", stdout);
  213637. }
  213638. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  213639. {
  213640. String text;
  213641. va_list args;
  213642. va_start (args, format);
  213643. text.vprintf(format, args);
  213644. outputDebugString(text);
  213645. }
  213646. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  213647. {
  213648. return Linux;
  213649. }
  213650. const String SystemStats::getOperatingSystemName() throw()
  213651. {
  213652. return T("Linux");
  213653. }
  213654. bool SystemStats::isOperatingSystem64Bit() throw()
  213655. {
  213656. #if JUCE_64BIT
  213657. return true;
  213658. #else
  213659. //xxx not sure how to find this out?..
  213660. return false;
  213661. #endif
  213662. }
  213663. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  213664. {
  213665. String info;
  213666. char buf [256];
  213667. FILE* f = fopen ("/proc/cpuinfo", "r");
  213668. while (f != 0 && fgets (buf, sizeof(buf), f))
  213669. {
  213670. if (strncmp (buf, key, strlen (key)) == 0)
  213671. {
  213672. char* p = buf;
  213673. while (*p && *p != '\n')
  213674. ++p;
  213675. if (*p != 0)
  213676. *p = 0;
  213677. p = buf;
  213678. while (*p != 0 && *p != ':')
  213679. ++p;
  213680. if (*p != 0 && *(p + 1) != 0)
  213681. info = p + 2;
  213682. if (! lastOne)
  213683. break;
  213684. }
  213685. }
  213686. fclose (f);
  213687. return info;
  213688. }
  213689. bool SystemStats::hasMMX() throw()
  213690. {
  213691. return getCpuInfo ("flags").contains (T("mmx"));
  213692. }
  213693. bool SystemStats::hasSSE() throw()
  213694. {
  213695. return getCpuInfo ("flags").contains (T("sse"));
  213696. }
  213697. bool SystemStats::hasSSE2() throw()
  213698. {
  213699. return getCpuInfo ("flags").contains (T("sse2"));
  213700. }
  213701. bool SystemStats::has3DNow() throw()
  213702. {
  213703. return getCpuInfo ("flags").contains (T("3dnow"));
  213704. }
  213705. const String SystemStats::getCpuVendor() throw()
  213706. {
  213707. return getCpuInfo ("vendor_id");
  213708. }
  213709. int SystemStats::getCpuSpeedInMegaherz() throw()
  213710. {
  213711. const String speed (getCpuInfo ("cpu MHz"));
  213712. return (int) (speed.getFloatValue() + 0.5f);
  213713. }
  213714. int SystemStats::getMemorySizeInMegabytes() throw()
  213715. {
  213716. struct sysinfo sysi;
  213717. if (sysinfo (&sysi) == 0)
  213718. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  213719. return 0;
  213720. }
  213721. uint32 juce_millisecondsSinceStartup() throw()
  213722. {
  213723. static unsigned int calibrate = 0;
  213724. static bool calibrated = false;
  213725. timeval t;
  213726. unsigned int ret = 0;
  213727. if (! gettimeofday (&t, 0))
  213728. {
  213729. if (! calibrated)
  213730. {
  213731. struct sysinfo sysi;
  213732. if (sysinfo (&sysi) == 0)
  213733. // Safe to assume system was not brought up earlier than 1970!
  213734. calibrate = t.tv_sec - sysi.uptime;
  213735. calibrated = true;
  213736. }
  213737. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  213738. }
  213739. return ret;
  213740. }
  213741. double Time::getMillisecondCounterHiRes() throw()
  213742. {
  213743. return getHighResolutionTicks() * 0.001;
  213744. }
  213745. int64 Time::getHighResolutionTicks() throw()
  213746. {
  213747. timeval t;
  213748. if (gettimeofday (&t, 0))
  213749. return 0;
  213750. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  213751. }
  213752. int64 Time::getHighResolutionTicksPerSecond() throw()
  213753. {
  213754. // Microseconds
  213755. return 1000000;
  213756. }
  213757. bool Time::setSystemTimeToThisTime() const throw()
  213758. {
  213759. timeval t;
  213760. t.tv_sec = millisSinceEpoch % 1000000;
  213761. t.tv_usec = millisSinceEpoch - t.tv_sec;
  213762. return settimeofday (&t, NULL) ? false : true;
  213763. }
  213764. int SystemStats::getPageSize() throw()
  213765. {
  213766. static int systemPageSize = 0;
  213767. if (systemPageSize == 0)
  213768. systemPageSize = sysconf (_SC_PAGESIZE);
  213769. return systemPageSize;
  213770. }
  213771. int SystemStats::getNumCpus() throw()
  213772. {
  213773. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  213774. return lastCpu + 1;
  213775. }
  213776. void SystemStats::initialiseStats() throw()
  213777. {
  213778. // Process starts off as root when running suid
  213779. Process::lowerPrivilege();
  213780. String s (SystemStats::getJUCEVersion());
  213781. }
  213782. void PlatformUtilities::fpuReset()
  213783. {
  213784. }
  213785. #endif
  213786. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  213787. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  213788. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213789. // compiled on its own).
  213790. #ifdef JUCE_INCLUDED_FILE
  213791. /*
  213792. Note that a lot of methods that you'd expect to find in this file actually
  213793. live in juce_posix_SharedCode.h!
  213794. */
  213795. void JUCE_API juce_threadEntryPoint (void*);
  213796. void* threadEntryProc (void* value) throw()
  213797. {
  213798. // New threads start off as root when running suid
  213799. Process::lowerPrivilege();
  213800. juce_threadEntryPoint (value);
  213801. return 0;
  213802. }
  213803. void* juce_createThread (void* userData) throw()
  213804. {
  213805. pthread_t handle = 0;
  213806. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  213807. {
  213808. pthread_detach (handle);
  213809. return (void*)handle;
  213810. }
  213811. return 0;
  213812. }
  213813. void juce_killThread (void* handle) throw()
  213814. {
  213815. if (handle != 0)
  213816. pthread_cancel ((pthread_t)handle);
  213817. }
  213818. void juce_setCurrentThreadName (const String& /*name*/) throw()
  213819. {
  213820. }
  213821. Thread::ThreadID Thread::getCurrentThreadId() throw()
  213822. {
  213823. return (ThreadID) pthread_self();
  213824. }
  213825. /*
  213826. * This is all a bit non-ideal... the trouble is that on Linux you
  213827. * need to call setpriority to affect the dynamic priority for
  213828. * non-realtime processes, but this requires the pid, which is not
  213829. * accessible from the pthread_t. We could get it by calling getpid
  213830. * once each thread has started, but then we would need a list of
  213831. * running threads etc etc.
  213832. * Also there is no such thing as IDLE priority on Linux.
  213833. * For the moment, map idle, low and normal process priorities to
  213834. * SCHED_OTHER, with the thread priority ignored for these classes.
  213835. * Map high priority processes to the lower half of the SCHED_RR
  213836. * range, and realtime to the upper half
  213837. */
  213838. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  213839. // priority of the current thread
  213840. bool juce_setThreadPriority (void* handle, int priority) throw()
  213841. {
  213842. struct sched_param param;
  213843. int policy, maxp, minp, pri;
  213844. if (handle == 0)
  213845. handle = (void*) pthread_self();
  213846. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  213847. && policy != SCHED_OTHER)
  213848. {
  213849. minp = sched_get_priority_min(policy);
  213850. maxp = sched_get_priority_max(policy);
  213851. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  213852. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  213853. // Realtime process priority
  213854. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  213855. else
  213856. // High process priority
  213857. param.__sched_priority = minp + pri;
  213858. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  213859. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  213860. }
  213861. return false;
  213862. }
  213863. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  213864. {
  213865. #if SUPPORT_AFFINITIES
  213866. cpu_set_t affinity;
  213867. CPU_ZERO (&affinity);
  213868. for (int i = 0; i < 32; ++i)
  213869. if ((affinityMask & (1 << i)) != 0)
  213870. CPU_SET (i, &affinity);
  213871. /*
  213872. N.B. If this line causes a compile error, then you've probably not got the latest
  213873. version of glibc installed.
  213874. If you don't want to update your copy of glibc and don't care about cpu affinities,
  213875. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  213876. from the linuxincludes.h file.
  213877. */
  213878. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  213879. sched_yield();
  213880. #else
  213881. /* affinities aren't supported because either the appropriate header files weren't found,
  213882. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  213883. */
  213884. jassertfalse
  213885. #endif
  213886. }
  213887. void Thread::yield() throw()
  213888. {
  213889. sched_yield();
  213890. }
  213891. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  213892. void Process::setPriority (ProcessPriority prior)
  213893. {
  213894. struct sched_param param;
  213895. int policy, maxp, minp;
  213896. const int p = (int) prior;
  213897. if (p <= 1)
  213898. policy = SCHED_OTHER;
  213899. else
  213900. policy = SCHED_RR;
  213901. minp = sched_get_priority_min (policy);
  213902. maxp = sched_get_priority_max (policy);
  213903. if (p < 2)
  213904. param.__sched_priority = 0;
  213905. else if (p == 2 )
  213906. // Set to middle of lower realtime priority range
  213907. param.__sched_priority = minp + (maxp - minp) / 4;
  213908. else
  213909. // Set to middle of higher realtime priority range
  213910. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  213911. pthread_setschedparam (pthread_self(), policy, &param);
  213912. }
  213913. void Process::terminate()
  213914. {
  213915. exit (0);
  213916. }
  213917. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  213918. {
  213919. static char testResult = 0;
  213920. if (testResult == 0)
  213921. {
  213922. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  213923. if (testResult >= 0)
  213924. {
  213925. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  213926. testResult = 1;
  213927. }
  213928. }
  213929. return testResult < 0;
  213930. }
  213931. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  213932. {
  213933. return juce_isRunningUnderDebugger();
  213934. }
  213935. void Process::raisePrivilege()
  213936. {
  213937. // If running suid root, change effective user
  213938. // to root
  213939. if (geteuid() != 0 && getuid() == 0)
  213940. {
  213941. setreuid (geteuid(), getuid());
  213942. setregid (getegid(), getgid());
  213943. }
  213944. }
  213945. void Process::lowerPrivilege()
  213946. {
  213947. // If runing suid root, change effective user
  213948. // back to real user
  213949. if (geteuid() == 0 && getuid() != 0)
  213950. {
  213951. setreuid (geteuid(), getuid());
  213952. setregid (getegid(), getgid());
  213953. }
  213954. }
  213955. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213956. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  213957. {
  213958. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  213959. }
  213960. void PlatformUtilities::freeDynamicLibrary (void* handle)
  213961. {
  213962. dlclose(handle);
  213963. }
  213964. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  213965. {
  213966. return dlsym (libraryHandle, (const char*) procedureName);
  213967. }
  213968. #endif
  213969. #endif
  213970. /********* End of inlined file: juce_linux_Threads.cpp *********/
  213971. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213972. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  213973. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213974. // compiled on its own).
  213975. #ifdef JUCE_INCLUDED_FILE
  213976. #ifdef JUCE_DEBUG
  213977. #define JUCE_DEBUG_XERRORS 1
  213978. #endif
  213979. Display* display = 0; // This is also referenced from WindowDriver.cpp
  213980. static Window juce_messageWindowHandle = None;
  213981. #define SpecialAtom "JUCESpecialAtom"
  213982. #define BroadcastAtom "JUCEBroadcastAtom"
  213983. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  213984. static Atom specialId;
  213985. static Atom broadcastId;
  213986. static Atom specialCallbackId;
  213987. // This is referenced from WindowDriver.cpp
  213988. XContext improbableNumber;
  213989. // Defined in WindowDriver.cpp
  213990. extern void juce_windowMessageReceive (XEvent* event);
  213991. struct MessageThreadFuncCall
  213992. {
  213993. MessageCallbackFunction* func;
  213994. void* parameter;
  213995. void* result;
  213996. CriticalSection lock;
  213997. WaitableEvent event;
  213998. };
  213999. static bool errorCondition = false;
  214000. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  214001. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  214002. // (defined in another file to avoid problems including certain headers in this one)
  214003. extern bool juce_isRunningAsApplication();
  214004. // Usually happens when client-server connection is broken
  214005. static int ioErrorHandler (Display* display)
  214006. {
  214007. DBG (T("ERROR: connection to X server broken.. terminating."));
  214008. errorCondition = true;
  214009. if (juce_isRunningAsApplication())
  214010. Process::terminate();
  214011. return 0;
  214012. }
  214013. // A protocol error has occurred
  214014. static int errorHandler (Display* display, XErrorEvent* event)
  214015. {
  214016. #ifdef JUCE_DEBUG_XERRORS
  214017. char errorStr[64] = { 0 };
  214018. char requestStr[64] = { 0 };
  214019. XGetErrorText (display, event->error_code, errorStr, 64);
  214020. XGetErrorDatabaseText (display,
  214021. "XRequest",
  214022. (const char*) String (event->request_code),
  214023. "Unknown",
  214024. requestStr,
  214025. 64);
  214026. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  214027. #endif
  214028. return 0;
  214029. }
  214030. static bool breakIn = false;
  214031. // Breakin from keyboard
  214032. static void sig_handler (int sig)
  214033. {
  214034. if (sig == SIGINT)
  214035. {
  214036. breakIn = true;
  214037. return;
  214038. }
  214039. static bool reentrant = false;
  214040. if (reentrant == false)
  214041. {
  214042. reentrant = true;
  214043. // Illegal instruction
  214044. fflush (stdout);
  214045. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  214046. errorCondition = true;
  214047. if (juce_isRunningAsApplication())
  214048. Process::terminate();
  214049. }
  214050. else
  214051. {
  214052. if (juce_isRunningAsApplication())
  214053. exit(0);
  214054. }
  214055. }
  214056. void MessageManager::doPlatformSpecificInitialisation()
  214057. {
  214058. // Initialise xlib for multiple thread support
  214059. static bool initThreadCalled = false;
  214060. if (! initThreadCalled)
  214061. {
  214062. if (! XInitThreads())
  214063. {
  214064. // This is fatal! Print error and closedown
  214065. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  214066. if (juce_isRunningAsApplication())
  214067. Process::terminate();
  214068. return;
  214069. }
  214070. initThreadCalled = true;
  214071. }
  214072. // This is called if the client/server connection is broken
  214073. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  214074. // This is called if a protocol error occurs
  214075. oldErrorHandler = XSetErrorHandler (errorHandler);
  214076. // Install signal handler for break-in
  214077. struct sigaction saction;
  214078. sigset_t maskSet;
  214079. sigemptyset (&maskSet);
  214080. saction.sa_handler = sig_handler;
  214081. saction.sa_mask = maskSet;
  214082. saction.sa_flags = 0;
  214083. sigaction (SIGINT, &saction, NULL);
  214084. #ifndef _DEBUG
  214085. // Setup signal handlers for various fatal errors
  214086. sigaction (SIGILL, &saction, NULL);
  214087. sigaction (SIGBUS, &saction, NULL);
  214088. sigaction (SIGFPE, &saction, NULL);
  214089. sigaction (SIGSEGV, &saction, NULL);
  214090. sigaction (SIGSYS, &saction, NULL);
  214091. #endif
  214092. String displayName (getenv ("DISPLAY"));
  214093. if (displayName.isEmpty())
  214094. displayName = T(":0.0");
  214095. display = XOpenDisplay (displayName);
  214096. if (display == 0)
  214097. {
  214098. // This is fatal! Print error and closedown
  214099. Logger::outputDebugString ("Failed to open the X display.");
  214100. if (juce_isRunningAsApplication())
  214101. Process::terminate();
  214102. return;
  214103. }
  214104. // Get defaults for various properties
  214105. int screen = DefaultScreen (display);
  214106. Window root = RootWindow (display, screen);
  214107. Visual* visual = DefaultVisual (display, screen);
  214108. // Create atoms for our ClientMessages (these cannot be deleted)
  214109. specialId = XInternAtom (display, SpecialAtom, false);
  214110. broadcastId = XInternAtom (display, BroadcastAtom, false);
  214111. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  214112. // Create a context to store user data associated with Windows we
  214113. // create in WindowDriver
  214114. improbableNumber = XUniqueContext();
  214115. // We're only interested in client messages for this window
  214116. // which are always sent
  214117. XSetWindowAttributes swa;
  214118. swa.event_mask = NoEventMask;
  214119. // Create our message window (this will never be mapped)
  214120. juce_messageWindowHandle = XCreateWindow (display, root,
  214121. 0, 0, 1, 1, 0, 0, InputOnly,
  214122. visual, CWEventMask, &swa);
  214123. }
  214124. void MessageManager::doPlatformSpecificShutdown()
  214125. {
  214126. if (errorCondition == false)
  214127. {
  214128. XDestroyWindow (display, juce_messageWindowHandle);
  214129. XCloseDisplay (display);
  214130. // reset pointers
  214131. juce_messageWindowHandle = 0;
  214132. display = 0;
  214133. // Restore original error handlers
  214134. XSetIOErrorHandler (oldIOErrorHandler);
  214135. oldIOErrorHandler = 0;
  214136. XSetErrorHandler (oldErrorHandler);
  214137. oldErrorHandler = 0;
  214138. }
  214139. }
  214140. bool juce_postMessageToSystemQueue (void* message)
  214141. {
  214142. if (errorCondition)
  214143. return false;
  214144. XClientMessageEvent clientMsg;
  214145. clientMsg.display = display;
  214146. clientMsg.window = juce_messageWindowHandle;
  214147. clientMsg.type = ClientMessage;
  214148. clientMsg.format = 32;
  214149. clientMsg.message_type = specialId;
  214150. #if JUCE_64BIT
  214151. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  214152. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  214153. #else
  214154. clientMsg.data.l[0] = (long) message;
  214155. #endif
  214156. XSendEvent (display, juce_messageWindowHandle, false,
  214157. NoEventMask, (XEvent*) &clientMsg);
  214158. XFlush (display); // This is necessary to ensure the event is delivered
  214159. return true;
  214160. }
  214161. void MessageManager::broadcastMessage (const String& value) throw()
  214162. {
  214163. }
  214164. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  214165. void* parameter)
  214166. {
  214167. void* retVal = 0;
  214168. if (! errorCondition)
  214169. {
  214170. if (! isThisTheMessageThread())
  214171. {
  214172. static MessageThreadFuncCall messageFuncCallContext;
  214173. const ScopedLock sl (messageFuncCallContext.lock);
  214174. XClientMessageEvent clientMsg;
  214175. clientMsg.display = display;
  214176. clientMsg.window = juce_messageWindowHandle;
  214177. clientMsg.type = ClientMessage;
  214178. clientMsg.format = 32;
  214179. clientMsg.message_type = specialCallbackId;
  214180. #if JUCE_64BIT
  214181. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  214182. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  214183. #else
  214184. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  214185. #endif
  214186. messageFuncCallContext.func = func;
  214187. messageFuncCallContext.parameter = parameter;
  214188. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  214189. return 0;
  214190. XFlush (display); // This is necessary to ensure the event is delivered
  214191. // Wait for it to complete before continuing
  214192. messageFuncCallContext.event.wait();
  214193. retVal = messageFuncCallContext.result;
  214194. }
  214195. else
  214196. {
  214197. // Just call the function directly
  214198. retVal = func (parameter);
  214199. }
  214200. }
  214201. return retVal;
  214202. }
  214203. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  214204. {
  214205. if (errorCondition)
  214206. return false;
  214207. if (breakIn)
  214208. {
  214209. errorCondition = true;
  214210. if (juce_isRunningAsApplication())
  214211. Process::terminate();
  214212. return false;
  214213. }
  214214. if (returnIfNoPendingMessages && ! XPending (display))
  214215. return false;
  214216. XEvent evt;
  214217. XNextEvent (display, &evt);
  214218. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  214219. {
  214220. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  214221. if (clientMsg->format != 32)
  214222. {
  214223. jassertfalse
  214224. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  214225. }
  214226. else
  214227. {
  214228. JUCE_TRY
  214229. {
  214230. #if JUCE_64BIT
  214231. void* const messagePtr
  214232. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  214233. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  214234. #else
  214235. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  214236. #endif
  214237. if (clientMsg->message_type == specialId)
  214238. {
  214239. MessageManager::getInstance()->deliverMessage (messagePtr);
  214240. }
  214241. else if (clientMsg->message_type == specialCallbackId)
  214242. {
  214243. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  214244. MessageCallbackFunction* func = call->func;
  214245. call->result = (*func) (call->parameter);
  214246. call->event.signal();
  214247. }
  214248. else if (clientMsg->message_type == broadcastId)
  214249. {
  214250. #if 0
  214251. TCHAR buffer[8192];
  214252. zeromem (buffer, sizeof (buffer));
  214253. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  214254. mq->deliverBroadcastMessage (String (buffer));
  214255. #endif
  214256. }
  214257. else
  214258. {
  214259. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  214260. }
  214261. }
  214262. JUCE_CATCH_ALL
  214263. }
  214264. }
  214265. else if (evt.xany.window != juce_messageWindowHandle)
  214266. {
  214267. juce_windowMessageReceive (&evt);
  214268. }
  214269. return true;
  214270. }
  214271. #endif
  214272. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  214273. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  214274. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214275. // compiled on its own).
  214276. #ifdef JUCE_INCLUDED_FILE
  214277. class FreeTypeFontFace
  214278. {
  214279. public:
  214280. enum FontStyle
  214281. {
  214282. Plain = 0,
  214283. Bold = 1,
  214284. Italic = 2
  214285. };
  214286. struct FontNameIndex
  214287. {
  214288. String fileName;
  214289. int faceIndex;
  214290. };
  214291. FreeTypeFontFace (const String& familyName)
  214292. : hasSerif (false),
  214293. monospaced (false)
  214294. {
  214295. family = familyName;
  214296. }
  214297. void setFileName (const String& name,
  214298. const int faceIndex,
  214299. FontStyle style)
  214300. {
  214301. if (names[(int) style].fileName.isEmpty())
  214302. {
  214303. names[(int) style].fileName = name;
  214304. names[(int) style].faceIndex = faceIndex;
  214305. }
  214306. }
  214307. const String& getFamilyName() const throw()
  214308. {
  214309. return family;
  214310. }
  214311. const String& getFileName (int style, int* faceIndex) const throw()
  214312. {
  214313. *faceIndex = names [style].faceIndex;
  214314. return names[style].fileName;
  214315. }
  214316. void setMonospaced (bool mono) { monospaced = mono; }
  214317. bool getMonospaced () const throw() { return monospaced; }
  214318. void setSerif (const bool serif) { hasSerif = serif; }
  214319. bool getSerif () const throw() { return hasSerif; }
  214320. private:
  214321. String family;
  214322. FontNameIndex names[4];
  214323. bool hasSerif, monospaced;
  214324. };
  214325. class FreeTypeInterface : public DeletedAtShutdown
  214326. {
  214327. public:
  214328. FreeTypeInterface() throw()
  214329. : lastFace (0),
  214330. lastBold (false),
  214331. lastItalic (false)
  214332. {
  214333. if (FT_Init_FreeType (&ftLib) != 0)
  214334. {
  214335. ftLib = 0;
  214336. DBG (T("Failed to initialize FreeType"));
  214337. }
  214338. StringArray fontDirs;
  214339. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  214340. fontDirs.removeEmptyStrings (true);
  214341. if (fontDirs.size() == 0)
  214342. {
  214343. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  214344. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  214345. if (fontsInfo != 0)
  214346. {
  214347. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  214348. {
  214349. fontDirs.add (e->getAllSubText().trim());
  214350. }
  214351. delete fontsInfo;
  214352. }
  214353. }
  214354. if (fontDirs.size() == 0)
  214355. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  214356. for (int i = 0; i < fontDirs.size(); ++i)
  214357. enumerateFaces (fontDirs[i]);
  214358. }
  214359. ~FreeTypeInterface() throw()
  214360. {
  214361. if (lastFace != 0)
  214362. FT_Done_Face (lastFace);
  214363. if (ftLib != 0)
  214364. FT_Done_FreeType (ftLib);
  214365. clearSingletonInstance();
  214366. }
  214367. FreeTypeFontFace* findOrCreate (const String& familyName,
  214368. const bool create = false) throw()
  214369. {
  214370. for (int i = 0; i < faces.size(); i++)
  214371. if (faces[i]->getFamilyName() == familyName)
  214372. return faces[i];
  214373. if (! create)
  214374. return NULL;
  214375. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  214376. faces.add (newFace);
  214377. return newFace;
  214378. }
  214379. // Enumerate all font faces available in a given directory
  214380. void enumerateFaces (const String& path) throw()
  214381. {
  214382. File dirPath (path);
  214383. if (path.isEmpty() || ! dirPath.isDirectory())
  214384. return;
  214385. DirectoryIterator di (dirPath, true);
  214386. while (di.next())
  214387. {
  214388. File possible (di.getFile());
  214389. if (possible.hasFileExtension (T("ttf"))
  214390. || possible.hasFileExtension (T("pfb"))
  214391. || possible.hasFileExtension (T("pcf")))
  214392. {
  214393. FT_Face face;
  214394. int faceIndex = 0;
  214395. int numFaces = 0;
  214396. do
  214397. {
  214398. if (FT_New_Face (ftLib,
  214399. possible.getFullPathName(),
  214400. faceIndex,
  214401. &face) == 0)
  214402. {
  214403. if (faceIndex == 0)
  214404. numFaces = face->num_faces;
  214405. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  214406. {
  214407. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  214408. int style = (int) FreeTypeFontFace::Plain;
  214409. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  214410. style |= (int) FreeTypeFontFace::Bold;
  214411. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  214412. style |= (int) FreeTypeFontFace::Italic;
  214413. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  214414. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  214415. newFace->setMonospaced (true);
  214416. else
  214417. newFace->setMonospaced (false);
  214418. // Surely there must be a better way to do this?
  214419. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  214420. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  214421. || String (face->family_name).containsIgnoreCase (T("Arial")))
  214422. {
  214423. newFace->setSerif (false);
  214424. }
  214425. else
  214426. {
  214427. newFace->setSerif (true);
  214428. }
  214429. }
  214430. FT_Done_Face (face);
  214431. }
  214432. ++faceIndex;
  214433. }
  214434. while (faceIndex < numFaces);
  214435. }
  214436. }
  214437. }
  214438. // Create a FreeType face object for a given font
  214439. FT_Face createFT_Face (const String& fontName,
  214440. const bool bold,
  214441. const bool italic) throw()
  214442. {
  214443. FT_Face face = NULL;
  214444. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  214445. {
  214446. face = lastFace;
  214447. }
  214448. else
  214449. {
  214450. if (lastFace)
  214451. {
  214452. FT_Done_Face (lastFace);
  214453. lastFace = NULL;
  214454. }
  214455. lastFontName = fontName;
  214456. lastBold = bold;
  214457. lastItalic = italic;
  214458. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  214459. if (ftFace != 0)
  214460. {
  214461. int style = (int) FreeTypeFontFace::Plain;
  214462. if (bold)
  214463. style |= (int) FreeTypeFontFace::Bold;
  214464. if (italic)
  214465. style |= (int) FreeTypeFontFace::Italic;
  214466. int faceIndex;
  214467. String fileName (ftFace->getFileName (style, &faceIndex));
  214468. if (fileName.isEmpty())
  214469. {
  214470. style ^= (int) FreeTypeFontFace::Bold;
  214471. fileName = ftFace->getFileName (style, &faceIndex);
  214472. if (fileName.isEmpty())
  214473. {
  214474. style ^= (int) FreeTypeFontFace::Bold;
  214475. style ^= (int) FreeTypeFontFace::Italic;
  214476. fileName = ftFace->getFileName (style, &faceIndex);
  214477. if (! fileName.length())
  214478. {
  214479. style ^= (int) FreeTypeFontFace::Bold;
  214480. fileName = ftFace->getFileName (style, &faceIndex);
  214481. }
  214482. }
  214483. }
  214484. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  214485. {
  214486. face = lastFace;
  214487. // If there isn't a unicode charmap then select the first one.
  214488. if (FT_Select_Charmap (face, ft_encoding_unicode))
  214489. FT_Set_Charmap (face, face->charmaps[0]);
  214490. }
  214491. }
  214492. }
  214493. return face;
  214494. }
  214495. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  214496. {
  214497. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  214498. const float height = (float) (face->ascender - face->descender);
  214499. const float scaleX = 1.0f / height;
  214500. const float scaleY = -1.0f / height;
  214501. Path destShape;
  214502. #define CONVERTX(val) (scaleX * (val).x)
  214503. #define CONVERTY(val) (scaleY * (val).y)
  214504. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  214505. | FT_LOAD_NO_BITMAP
  214506. | FT_LOAD_IGNORE_TRANSFORM) != 0
  214507. || face->glyph->format != ft_glyph_format_outline)
  214508. {
  214509. return false;
  214510. }
  214511. const FT_Outline* const outline = &face->glyph->outline;
  214512. const short* const contours = outline->contours;
  214513. const char* const tags = outline->tags;
  214514. FT_Vector* const points = outline->points;
  214515. for (int c = 0; c < outline->n_contours; c++)
  214516. {
  214517. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  214518. const int endPoint = contours[c];
  214519. for (int p = startPoint; p <= endPoint; p++)
  214520. {
  214521. const float x = CONVERTX (points[p]);
  214522. const float y = CONVERTY (points[p]);
  214523. if (p == startPoint)
  214524. {
  214525. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214526. {
  214527. float x2 = CONVERTX (points [endPoint]);
  214528. float y2 = CONVERTY (points [endPoint]);
  214529. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  214530. {
  214531. x2 = (x + x2) * 0.5f;
  214532. y2 = (y + y2) * 0.5f;
  214533. }
  214534. destShape.startNewSubPath (x2, y2);
  214535. }
  214536. else
  214537. {
  214538. destShape.startNewSubPath (x, y);
  214539. }
  214540. }
  214541. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  214542. {
  214543. if (p != startPoint)
  214544. destShape.lineTo (x, y);
  214545. }
  214546. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214547. {
  214548. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  214549. float x2 = CONVERTX (points [nextIndex]);
  214550. float y2 = CONVERTY (points [nextIndex]);
  214551. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  214552. {
  214553. x2 = (x + x2) * 0.5f;
  214554. y2 = (y + y2) * 0.5f;
  214555. }
  214556. else
  214557. {
  214558. ++p;
  214559. }
  214560. destShape.quadraticTo (x, y, x2, y2);
  214561. }
  214562. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  214563. {
  214564. if (p >= endPoint)
  214565. return false;
  214566. const int next1 = p + 1;
  214567. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  214568. const float x2 = CONVERTX (points [next1]);
  214569. const float y2 = CONVERTY (points [next1]);
  214570. const float x3 = CONVERTX (points [next2]);
  214571. const float y3 = CONVERTY (points [next2]);
  214572. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  214573. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  214574. return false;
  214575. destShape.cubicTo (x, y, x2, y2, x3, y3);
  214576. p += 2;
  214577. }
  214578. }
  214579. destShape.closeSubPath();
  214580. }
  214581. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  214582. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  214583. addKerning (face, dest, character, glyphIndex);
  214584. return true;
  214585. }
  214586. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  214587. {
  214588. const float height = (float) (face->ascender - face->descender);
  214589. uint32 rightGlyphIndex;
  214590. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  214591. while (rightGlyphIndex != 0)
  214592. {
  214593. FT_Vector kerning;
  214594. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  214595. {
  214596. if (kerning.x != 0)
  214597. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  214598. }
  214599. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  214600. }
  214601. }
  214602. // Add a glyph to a font
  214603. bool addGlyphToFont (const uint32 character,
  214604. const tchar* fontName, bool bold, bool italic,
  214605. Typeface& dest) throw()
  214606. {
  214607. FT_Face face = createFT_Face (fontName, bold, italic);
  214608. if (face != 0)
  214609. return addGlyph (face, dest, character);
  214610. return false;
  214611. }
  214612. // Create a Typeface object for given name/style
  214613. bool createTypeface (const String& fontName,
  214614. const bool bold, const bool italic,
  214615. Typeface& dest,
  214616. const bool addAllGlyphs) throw()
  214617. {
  214618. dest.clear();
  214619. dest.setName (fontName);
  214620. dest.setBold (bold);
  214621. dest.setItalic (italic);
  214622. FT_Face face = createFT_Face (fontName, bold, italic);
  214623. if (face == 0)
  214624. {
  214625. #ifdef JUCE_DEBUG
  214626. String msg (T("Failed to create typeface: "));
  214627. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  214628. DBG (msg);
  214629. #endif
  214630. return face;
  214631. }
  214632. const float height = (float) (face->ascender - face->descender);
  214633. dest.setAscent (face->ascender / height);
  214634. dest.setDefaultCharacter (L' ');
  214635. if (addAllGlyphs)
  214636. {
  214637. uint32 glyphIndex;
  214638. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  214639. while (glyphIndex != 0)
  214640. {
  214641. addGlyph (face, dest, charCode);
  214642. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  214643. }
  214644. }
  214645. return true;
  214646. }
  214647. void getFamilyNames (StringArray& familyNames) const throw()
  214648. {
  214649. for (int i = 0; i < faces.size(); i++)
  214650. familyNames.add (faces[i]->getFamilyName());
  214651. }
  214652. void getMonospacedNames (StringArray& monoSpaced) const throw()
  214653. {
  214654. for (int i = 0; i < faces.size(); i++)
  214655. if (faces[i]->getMonospaced())
  214656. monoSpaced.add (faces[i]->getFamilyName());
  214657. }
  214658. void getSerifNames (StringArray& serif) const throw()
  214659. {
  214660. for (int i = 0; i < faces.size(); i++)
  214661. if (faces[i]->getSerif())
  214662. serif.add (faces[i]->getFamilyName());
  214663. }
  214664. void getSansSerifNames (StringArray& sansSerif) const throw()
  214665. {
  214666. for (int i = 0; i < faces.size(); i++)
  214667. if (! faces[i]->getSerif())
  214668. sansSerif.add (faces[i]->getFamilyName());
  214669. }
  214670. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  214671. private:
  214672. FT_Library ftLib;
  214673. FT_Face lastFace;
  214674. String lastFontName;
  214675. bool lastBold, lastItalic;
  214676. OwnedArray<FreeTypeFontFace> faces;
  214677. };
  214678. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  214679. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  214680. bool bold, bool italic,
  214681. bool addAllGlyphsToFont) throw()
  214682. {
  214683. FreeTypeInterface::getInstance()
  214684. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  214685. }
  214686. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  214687. {
  214688. return FreeTypeInterface::getInstance()
  214689. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  214690. }
  214691. const StringArray Font::findAllTypefaceNames() throw()
  214692. {
  214693. StringArray s;
  214694. FreeTypeInterface::getInstance()->getFamilyNames (s);
  214695. s.sort (true);
  214696. return s;
  214697. }
  214698. static const String pickBestFont (const StringArray& names,
  214699. const char* const choicesString)
  214700. {
  214701. StringArray choices;
  214702. choices.addTokens (String (choicesString), T(","), 0);
  214703. choices.trim();
  214704. choices.removeEmptyStrings();
  214705. int i, j;
  214706. for (j = 0; j < choices.size(); ++j)
  214707. if (names.contains (choices[j], true))
  214708. return choices[j];
  214709. for (j = 0; j < choices.size(); ++j)
  214710. for (i = 0; i < names.size(); i++)
  214711. if (names[i].startsWithIgnoreCase (choices[j]))
  214712. return names[i];
  214713. for (j = 0; j < choices.size(); ++j)
  214714. for (i = 0; i < names.size(); i++)
  214715. if (names[i].containsIgnoreCase (choices[j]))
  214716. return names[i];
  214717. return names[0];
  214718. }
  214719. static const String linux_getDefaultSansSerifFontName()
  214720. {
  214721. StringArray allFonts;
  214722. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  214723. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  214724. }
  214725. static const String linux_getDefaultSerifFontName()
  214726. {
  214727. StringArray allFonts;
  214728. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  214729. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  214730. }
  214731. static const String linux_getDefaultMonospacedFontName()
  214732. {
  214733. StringArray allFonts;
  214734. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  214735. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  214736. }
  214737. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  214738. {
  214739. defaultSans = linux_getDefaultSansSerifFontName();
  214740. defaultSerif = linux_getDefaultSerifFontName();
  214741. defaultFixed = linux_getDefaultMonospacedFontName();
  214742. }
  214743. #endif
  214744. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  214745. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  214746. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214747. // compiled on its own).
  214748. #ifdef JUCE_INCLUDED_FILE
  214749. #define TAKE_FOCUS 0
  214750. #define DELETE_WINDOW 1
  214751. #define SYSTEM_TRAY_REQUEST_DOCK 0
  214752. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  214753. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  214754. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  214755. static Atom wm_ChangeState = None;
  214756. static Atom wm_State = None;
  214757. static Atom wm_Protocols = None;
  214758. static Atom wm_ProtocolList [2] = { None, None };
  214759. static Atom wm_ActiveWin = None;
  214760. #define ourDndVersion 3
  214761. static Atom XA_XdndAware = None;
  214762. static Atom XA_XdndEnter = None;
  214763. static Atom XA_XdndLeave = None;
  214764. static Atom XA_XdndPosition = None;
  214765. static Atom XA_XdndStatus = None;
  214766. static Atom XA_XdndDrop = None;
  214767. static Atom XA_XdndFinished = None;
  214768. static Atom XA_XdndSelection = None;
  214769. static Atom XA_XdndProxy = None;
  214770. static Atom XA_XdndTypeList = None;
  214771. static Atom XA_XdndActionList = None;
  214772. static Atom XA_XdndActionDescription = None;
  214773. static Atom XA_XdndActionCopy = None;
  214774. static Atom XA_XdndActionMove = None;
  214775. static Atom XA_XdndActionLink = None;
  214776. static Atom XA_XdndActionAsk = None;
  214777. static Atom XA_XdndActionPrivate = None;
  214778. static Atom XA_JXSelectionWindowProperty = None;
  214779. static Atom XA_MimeTextPlain = None;
  214780. static Atom XA_MimeTextUriList = None;
  214781. static Atom XA_MimeRootDrop = None;
  214782. static XErrorHandler oldHandler = 0;
  214783. static int trappedErrorCode = 0;
  214784. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  214785. {
  214786. trappedErrorCode = err->error_code;
  214787. return 0;
  214788. }
  214789. static void trapErrors()
  214790. {
  214791. trappedErrorCode = 0;
  214792. oldHandler = XSetErrorHandler (errorTrapHandler);
  214793. }
  214794. static bool untrapErrors()
  214795. {
  214796. XSetErrorHandler (oldHandler);
  214797. return (trappedErrorCode == 0);
  214798. }
  214799. static bool isActiveApplication = false;
  214800. bool Process::isForegroundProcess() throw()
  214801. {
  214802. return isActiveApplication;
  214803. }
  214804. // (used in the messaging code, declared here for build reasons)
  214805. bool juce_isRunningAsApplication()
  214806. {
  214807. return JUCEApplication::getInstance() != 0;
  214808. }
  214809. // These are defined in juce_linux_Messaging.cpp
  214810. extern Display* display;
  214811. extern XContext improbableNumber;
  214812. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  214813. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  214814. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  214815. static int pointerMap[5];
  214816. static int lastMousePosX = 0, lastMousePosY = 0;
  214817. enum MouseButtons
  214818. {
  214819. NoButton = 0,
  214820. LeftButton = 1,
  214821. MiddleButton = 2,
  214822. RightButton = 3,
  214823. WheelUp = 4,
  214824. WheelDown = 5
  214825. };
  214826. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  214827. {
  214828. Window root, child;
  214829. int winx, winy;
  214830. unsigned int mask;
  214831. mouseMods = 0;
  214832. if (XQueryPointer (display,
  214833. RootWindow (display, DefaultScreen (display)),
  214834. &root, &child,
  214835. &x, &y, &winx, &winy, &mask) == False)
  214836. {
  214837. // Pointer not on the default screen
  214838. x = y = -1;
  214839. }
  214840. else
  214841. {
  214842. if ((mask & Button1Mask) != 0)
  214843. mouseMods |= ModifierKeys::leftButtonModifier;
  214844. if ((mask & Button2Mask) != 0)
  214845. mouseMods |= ModifierKeys::middleButtonModifier;
  214846. if ((mask & Button3Mask) != 0)
  214847. mouseMods |= ModifierKeys::rightButtonModifier;
  214848. }
  214849. }
  214850. static int AltMask = 0;
  214851. static int NumLockMask = 0;
  214852. static bool numLock = 0;
  214853. static bool capsLock = 0;
  214854. static char keyStates [32];
  214855. static void updateKeyStates (const int keycode, const bool press) throw()
  214856. {
  214857. const int keybyte = keycode >> 3;
  214858. const int keybit = (1 << (keycode & 7));
  214859. if (press)
  214860. keyStates [keybyte] |= keybit;
  214861. else
  214862. keyStates [keybyte] &= ~keybit;
  214863. }
  214864. static bool keyDown (const int keycode) throw()
  214865. {
  214866. const int keybyte = keycode >> 3;
  214867. const int keybit = (1 << (keycode & 7));
  214868. return (keyStates [keybyte] & keybit) != 0;
  214869. }
  214870. static const int extendedKeyModifier = 0x10000000;
  214871. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  214872. {
  214873. int keysym;
  214874. if (keyCode & extendedKeyModifier)
  214875. {
  214876. keysym = 0xff00 | (keyCode & 0xff);
  214877. }
  214878. else
  214879. {
  214880. keysym = keyCode;
  214881. if (keysym == (XK_Tab & 0xff)
  214882. || keysym == (XK_Return & 0xff)
  214883. || keysym == (XK_Escape & 0xff)
  214884. || keysym == (XK_BackSpace & 0xff))
  214885. {
  214886. keysym |= 0xff00;
  214887. }
  214888. }
  214889. return keyDown (XKeysymToKeycode (display, keysym));
  214890. }
  214891. // Alt and Num lock are not defined by standard X
  214892. // modifier constants: check what they're mapped to
  214893. static void getModifierMapping() throw()
  214894. {
  214895. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  214896. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  214897. AltMask = 0;
  214898. NumLockMask = 0;
  214899. XModifierKeymap* mapping = XGetModifierMapping (display);
  214900. if (mapping)
  214901. {
  214902. for (int i = 0; i < 8; i++)
  214903. {
  214904. if (mapping->modifiermap [i << 1] == altLeftCode)
  214905. AltMask = 1 << i;
  214906. else if (mapping->modifiermap [i << 1] == numLockCode)
  214907. NumLockMask = 1 << i;
  214908. }
  214909. XFreeModifiermap (mapping);
  214910. }
  214911. }
  214912. static int currentModifiers = 0;
  214913. void ModifierKeys::updateCurrentModifiers() throw()
  214914. {
  214915. currentModifierFlags = currentModifiers;
  214916. }
  214917. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  214918. {
  214919. int x, y, mouseMods;
  214920. getMousePos (x, y, mouseMods);
  214921. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  214922. currentModifiers |= mouseMods;
  214923. return ModifierKeys (currentModifiers);
  214924. }
  214925. static void updateKeyModifiers (const int status) throw()
  214926. {
  214927. currentModifiers &= ~(ModifierKeys::shiftModifier
  214928. | ModifierKeys::ctrlModifier
  214929. | ModifierKeys::altModifier);
  214930. if (status & ShiftMask)
  214931. currentModifiers |= ModifierKeys::shiftModifier;
  214932. if (status & ControlMask)
  214933. currentModifiers |= ModifierKeys::ctrlModifier;
  214934. if (status & AltMask)
  214935. currentModifiers |= ModifierKeys::altModifier;
  214936. numLock = ((status & NumLockMask) != 0);
  214937. capsLock = ((status & LockMask) != 0);
  214938. }
  214939. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  214940. {
  214941. int modifier = 0;
  214942. bool isModifier = true;
  214943. switch (sym)
  214944. {
  214945. case XK_Shift_L:
  214946. case XK_Shift_R:
  214947. modifier = ModifierKeys::shiftModifier;
  214948. break;
  214949. case XK_Control_L:
  214950. case XK_Control_R:
  214951. modifier = ModifierKeys::ctrlModifier;
  214952. break;
  214953. case XK_Alt_L:
  214954. case XK_Alt_R:
  214955. modifier = ModifierKeys::altModifier;
  214956. break;
  214957. case XK_Num_Lock:
  214958. if (press)
  214959. numLock = ! numLock;
  214960. break;
  214961. case XK_Caps_Lock:
  214962. if (press)
  214963. capsLock = ! capsLock;
  214964. break;
  214965. case XK_Scroll_Lock:
  214966. break;
  214967. default:
  214968. isModifier = false;
  214969. break;
  214970. }
  214971. if (modifier != 0)
  214972. {
  214973. if (press)
  214974. currentModifiers |= modifier;
  214975. else
  214976. currentModifiers &= ~modifier;
  214977. }
  214978. return isModifier;
  214979. }
  214980. #if JUCE_USE_XSHM
  214981. static bool isShmAvailable() throw()
  214982. {
  214983. static bool isChecked = false;
  214984. static bool isAvailable = false;
  214985. if (! isChecked)
  214986. {
  214987. isChecked = true;
  214988. int major, minor;
  214989. Bool pixmaps;
  214990. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  214991. {
  214992. trapErrors();
  214993. XShmSegmentInfo segmentInfo;
  214994. zerostruct (segmentInfo);
  214995. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  214996. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  214997. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214998. xImage->bytes_per_line * xImage->height,
  214999. IPC_CREAT | 0777)) >= 0)
  215000. {
  215001. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215002. if (segmentInfo.shmaddr != (void*) -1)
  215003. {
  215004. segmentInfo.readOnly = False;
  215005. xImage->data = segmentInfo.shmaddr;
  215006. XSync (display, False);
  215007. if (XShmAttach (display, &segmentInfo) != 0)
  215008. {
  215009. XSync (display, False);
  215010. XShmDetach (display, &segmentInfo);
  215011. isAvailable = true;
  215012. }
  215013. }
  215014. XFlush (display);
  215015. XDestroyImage (xImage);
  215016. shmdt (segmentInfo.shmaddr);
  215017. }
  215018. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215019. isAvailable &= untrapErrors();
  215020. }
  215021. }
  215022. return isAvailable;
  215023. }
  215024. #endif
  215025. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  215026. {
  215027. const int width = image.getWidth();
  215028. const int height = image.getHeight();
  215029. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  215030. int index = 0;
  215031. for (int y = 0; y < height; ++y)
  215032. for (int x = 0; x < width; ++x)
  215033. colour[index++] = image.getPixelAt (x, y).getARGB();
  215034. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  215035. 0, (char*) colour, width, height, 32, 0);
  215036. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  215037. width, height, 24);
  215038. GC gc = XCreateGC (display, pixmap, 0, 0);
  215039. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  215040. XFreeGC (display, gc);
  215041. juce_free (colour);
  215042. return pixmap;
  215043. }
  215044. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  215045. {
  215046. const int width = image.getWidth();
  215047. const int height = image.getHeight();
  215048. const int stride = (width + 7) >> 3;
  215049. uint8* const mask = (uint8*) juce_calloc (stride * height);
  215050. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  215051. for (int y = 0; y < height; ++y)
  215052. {
  215053. for (int x = 0; x < width; ++x)
  215054. {
  215055. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  215056. const int offset = y * stride + (x >> 3);
  215057. if (image.getPixelAt (x, y).getAlpha() >= 128)
  215058. mask[offset] |= bit;
  215059. }
  215060. }
  215061. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  215062. (char*) mask, width, height, 1, 0, 1);
  215063. juce_free (mask);
  215064. return pixmap;
  215065. }
  215066. class XBitmapImage : public Image
  215067. {
  215068. public:
  215069. XBitmapImage (const PixelFormat format_, const int w, const int h,
  215070. const bool clearImage, const bool is16Bit_)
  215071. : Image (format_, w, h),
  215072. is16Bit (is16Bit_)
  215073. {
  215074. jassert (format_ == RGB || format_ == ARGB);
  215075. pixelStride = (format_ == RGB) ? 3 : 4;
  215076. lineStride = ((w * pixelStride + 3) & ~3);
  215077. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  215078. #if JUCE_USE_XSHM
  215079. usingXShm = false;
  215080. if ((! is16Bit) && isShmAvailable())
  215081. {
  215082. zerostruct (segmentInfo);
  215083. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  215084. if (xImage != 0)
  215085. {
  215086. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215087. xImage->bytes_per_line * xImage->height,
  215088. IPC_CREAT | 0777)) >= 0)
  215089. {
  215090. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215091. if (segmentInfo.shmaddr != (void*) -1)
  215092. {
  215093. segmentInfo.readOnly = False;
  215094. xImage->data = segmentInfo.shmaddr;
  215095. imageData = (uint8*) segmentInfo.shmaddr;
  215096. XSync (display, False);
  215097. if (XShmAttach (display, &segmentInfo) != 0)
  215098. {
  215099. XSync (display, False);
  215100. usingXShm = true;
  215101. }
  215102. else
  215103. {
  215104. jassertfalse
  215105. }
  215106. }
  215107. else
  215108. {
  215109. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215110. }
  215111. }
  215112. }
  215113. }
  215114. if (! usingXShm)
  215115. #endif
  215116. {
  215117. imageData = (uint8*) juce_malloc (lineStride * h);
  215118. if (format_ == ARGB && clearImage)
  215119. zeromem (imageData, h * lineStride);
  215120. xImage = (XImage*) juce_calloc (sizeof (XImage));
  215121. xImage->width = w;
  215122. xImage->height = h;
  215123. xImage->xoffset = 0;
  215124. xImage->format = ZPixmap;
  215125. xImage->data = (char*) imageData;
  215126. xImage->byte_order = ImageByteOrder (display);
  215127. xImage->bitmap_unit = BitmapUnit (display);
  215128. xImage->bitmap_bit_order = BitmapBitOrder (display);
  215129. xImage->bitmap_pad = 32;
  215130. xImage->depth = pixelStride * 8;
  215131. xImage->bytes_per_line = lineStride;
  215132. xImage->bits_per_pixel = pixelStride * 8;
  215133. xImage->red_mask = 0x00FF0000;
  215134. xImage->green_mask = 0x0000FF00;
  215135. xImage->blue_mask = 0x000000FF;
  215136. if (is16Bit)
  215137. {
  215138. const int pixelStride = 2;
  215139. const int lineStride = ((w * pixelStride + 3) & ~3);
  215140. xImage->data = (char*) juce_malloc (lineStride * h);
  215141. xImage->bitmap_pad = 16;
  215142. xImage->depth = pixelStride * 8;
  215143. xImage->bytes_per_line = lineStride;
  215144. xImage->bits_per_pixel = pixelStride * 8;
  215145. xImage->red_mask = visual->red_mask;
  215146. xImage->green_mask = visual->green_mask;
  215147. xImage->blue_mask = visual->blue_mask;
  215148. }
  215149. if (! XInitImage (xImage))
  215150. {
  215151. jassertfalse
  215152. }
  215153. }
  215154. }
  215155. ~XBitmapImage()
  215156. {
  215157. #if JUCE_USE_XSHM
  215158. if (usingXShm)
  215159. {
  215160. XShmDetach (display, &segmentInfo);
  215161. XFlush (display);
  215162. XDestroyImage (xImage);
  215163. shmdt (segmentInfo.shmaddr);
  215164. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215165. }
  215166. else
  215167. #endif
  215168. {
  215169. juce_free (xImage->data);
  215170. xImage->data = 0;
  215171. XDestroyImage (xImage);
  215172. }
  215173. if (! is16Bit)
  215174. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  215175. }
  215176. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  215177. {
  215178. static GC gc = 0;
  215179. if (gc == 0)
  215180. gc = DefaultGC (display, DefaultScreen (display));
  215181. if (is16Bit)
  215182. {
  215183. const uint32 rMask = xImage->red_mask;
  215184. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  215185. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  215186. const uint32 gMask = xImage->green_mask;
  215187. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  215188. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  215189. const uint32 bMask = xImage->blue_mask;
  215190. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  215191. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  215192. int ls, ps;
  215193. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  215194. for (int y = sy; y < sy + dh; ++y)
  215195. {
  215196. const uint8* p = pixels + y * ls + sx * ps;
  215197. for (int x = sx; x < sx + dw; ++x)
  215198. {
  215199. const PixelRGB* const pixel = (const PixelRGB*) p;
  215200. p += ps;
  215201. XPutPixel (xImage, x, y,
  215202. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  215203. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  215204. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  215205. }
  215206. }
  215207. releasePixelDataReadOnly (pixels);
  215208. }
  215209. // blit results to screen.
  215210. #if JUCE_USE_XSHM
  215211. if (usingXShm)
  215212. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  215213. else
  215214. #endif
  215215. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  215216. }
  215217. juce_UseDebuggingNewOperator
  215218. private:
  215219. XImage* xImage;
  215220. const bool is16Bit;
  215221. #if JUCE_USE_XSHM
  215222. XShmSegmentInfo segmentInfo;
  215223. bool usingXShm;
  215224. #endif
  215225. static int getShiftNeeded (const uint32 mask) throw()
  215226. {
  215227. for (int i = 32; --i >= 0;)
  215228. if (((mask >> i) & 1) != 0)
  215229. return i - 7;
  215230. jassertfalse
  215231. return 0;
  215232. }
  215233. };
  215234. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215235. class LinuxComponentPeer : public ComponentPeer
  215236. {
  215237. public:
  215238. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  215239. : ComponentPeer (component, windowStyleFlags),
  215240. windowH (0),
  215241. parentWindow (0),
  215242. wx (0),
  215243. wy (0),
  215244. ww (0),
  215245. wh (0),
  215246. taskbarImage (0),
  215247. fullScreen (false),
  215248. entered (false),
  215249. mapped (false)
  215250. {
  215251. // it's dangerous to create a window on a thread other than the message thread..
  215252. checkMessageManagerIsLocked
  215253. repainter = new LinuxRepaintManager (this);
  215254. createWindow();
  215255. setTitle (component->getName());
  215256. }
  215257. ~LinuxComponentPeer()
  215258. {
  215259. // it's dangerous to delete a window on a thread other than the message thread..
  215260. checkMessageManagerIsLocked
  215261. deleteTaskBarIcon();
  215262. deleteIconPixmaps();
  215263. destroyWindow();
  215264. windowH = 0;
  215265. delete repainter;
  215266. }
  215267. void* getNativeHandle() const
  215268. {
  215269. return (void*) windowH;
  215270. }
  215271. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  215272. {
  215273. XPointer peer = 0;
  215274. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  215275. {
  215276. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  215277. peer = 0;
  215278. }
  215279. return (LinuxComponentPeer*) peer;
  215280. }
  215281. void setVisible (bool shouldBeVisible)
  215282. {
  215283. if (shouldBeVisible)
  215284. XMapWindow (display, windowH);
  215285. else
  215286. XUnmapWindow (display, windowH);
  215287. }
  215288. void setTitle (const String& title)
  215289. {
  215290. setWindowTitle (windowH, title);
  215291. }
  215292. void setPosition (int x, int y)
  215293. {
  215294. setBounds (x, y, ww, wh, false);
  215295. }
  215296. void setSize (int w, int h)
  215297. {
  215298. setBounds (wx, wy, w, h, false);
  215299. }
  215300. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  215301. {
  215302. fullScreen = isNowFullScreen;
  215303. if (windowH != 0)
  215304. {
  215305. const ComponentDeletionWatcher deletionChecker (component);
  215306. wx = x;
  215307. wy = y;
  215308. ww = jmax (1, w);
  215309. wh = jmax (1, h);
  215310. // Make sure the Window manager does what we want
  215311. XSizeHints* hints = XAllocSizeHints();
  215312. hints->flags = USSize | USPosition;
  215313. hints->width = ww;
  215314. hints->height = wh;
  215315. hints->x = wx;
  215316. hints->y = wy;
  215317. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  215318. {
  215319. hints->min_width = hints->max_width = hints->width;
  215320. hints->min_height = hints->max_height = hints->height;
  215321. hints->flags |= PMinSize | PMaxSize;
  215322. }
  215323. XSetWMNormalHints (display, windowH, hints);
  215324. XFree (hints);
  215325. XMoveResizeWindow (display, windowH,
  215326. wx - windowBorder.getLeft(),
  215327. wy - windowBorder.getTop(), ww, wh);
  215328. if (! deletionChecker.hasBeenDeleted())
  215329. {
  215330. updateBorderSize();
  215331. handleMovedOrResized();
  215332. }
  215333. }
  215334. }
  215335. void getBounds (int& x, int& y, int& w, int& h) const
  215336. {
  215337. x = wx;
  215338. y = wy;
  215339. w = ww;
  215340. h = wh;
  215341. }
  215342. int getScreenX() const
  215343. {
  215344. return wx;
  215345. }
  215346. int getScreenY() const
  215347. {
  215348. return wy;
  215349. }
  215350. void relativePositionToGlobal (int& x, int& y)
  215351. {
  215352. x += wx;
  215353. y += wy;
  215354. }
  215355. void globalPositionToRelative (int& x, int& y)
  215356. {
  215357. x -= wx;
  215358. y -= wy;
  215359. }
  215360. void setMinimised (bool shouldBeMinimised)
  215361. {
  215362. if (shouldBeMinimised)
  215363. {
  215364. Window root = RootWindow (display, DefaultScreen (display));
  215365. XClientMessageEvent clientMsg;
  215366. clientMsg.display = display;
  215367. clientMsg.window = windowH;
  215368. clientMsg.type = ClientMessage;
  215369. clientMsg.format = 32;
  215370. clientMsg.message_type = wm_ChangeState;
  215371. clientMsg.data.l[0] = IconicState;
  215372. XSendEvent (display, root, false,
  215373. SubstructureRedirectMask | SubstructureNotifyMask,
  215374. (XEvent*) &clientMsg);
  215375. }
  215376. else
  215377. {
  215378. setVisible (true);
  215379. }
  215380. }
  215381. bool isMinimised() const
  215382. {
  215383. bool minimised = false;
  215384. unsigned char* stateProp;
  215385. unsigned long nitems, bytesLeft;
  215386. Atom actualType;
  215387. int actualFormat;
  215388. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  215389. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  215390. &stateProp) == Success
  215391. && actualType == wm_State
  215392. && actualFormat == 32
  215393. && nitems > 0)
  215394. {
  215395. if (((unsigned long*) stateProp)[0] == IconicState)
  215396. minimised = true;
  215397. XFree (stateProp);
  215398. }
  215399. return minimised;
  215400. }
  215401. void setFullScreen (const bool shouldBeFullScreen)
  215402. {
  215403. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  215404. setMinimised (false);
  215405. if (fullScreen != shouldBeFullScreen)
  215406. {
  215407. if (shouldBeFullScreen)
  215408. r = Desktop::getInstance().getMainMonitorArea();
  215409. if (! r.isEmpty())
  215410. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  215411. getComponent()->repaint();
  215412. }
  215413. }
  215414. bool isFullScreen() const
  215415. {
  215416. return fullScreen;
  215417. }
  215418. bool isChildWindowOf (Window possibleParent) const
  215419. {
  215420. Window* windowList = 0;
  215421. uint32 windowListSize = 0;
  215422. Window parent, root;
  215423. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  215424. {
  215425. if (windowList != 0)
  215426. XFree (windowList);
  215427. return parent == possibleParent;
  215428. }
  215429. return false;
  215430. }
  215431. bool isFrontWindow() const
  215432. {
  215433. Window* windowList = 0;
  215434. uint32 windowListSize = 0;
  215435. bool result = false;
  215436. Window parent, root = RootWindow (display, DefaultScreen (display));
  215437. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  215438. {
  215439. for (int i = windowListSize; --i >= 0;)
  215440. {
  215441. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  215442. if (peer != 0)
  215443. {
  215444. result = (peer == this);
  215445. break;
  215446. }
  215447. }
  215448. }
  215449. if (windowList != 0)
  215450. XFree (windowList);
  215451. return result;
  215452. }
  215453. bool contains (int x, int y, bool trueIfInAChildWindow) const
  215454. {
  215455. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  215456. if (((unsigned int) x) >= (unsigned int) ww
  215457. || ((unsigned int) y) >= (unsigned int) wh)
  215458. return false;
  215459. bool inFront = false;
  215460. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  215461. {
  215462. Component* const c = Desktop::getInstance().getComponent (i);
  215463. if (inFront)
  215464. {
  215465. if (c->contains (x + wx - c->getScreenX(),
  215466. y + wy - c->getScreenY()))
  215467. {
  215468. return false;
  215469. }
  215470. }
  215471. else if (c == getComponent())
  215472. {
  215473. inFront = true;
  215474. }
  215475. }
  215476. if (trueIfInAChildWindow)
  215477. return true;
  215478. ::Window root, child;
  215479. unsigned int bw, depth;
  215480. int wx, wy, w, h;
  215481. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  215482. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  215483. &bw, &depth))
  215484. {
  215485. return false;
  215486. }
  215487. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  215488. return false;
  215489. return child == None;
  215490. }
  215491. const BorderSize getFrameSize() const
  215492. {
  215493. return BorderSize();
  215494. }
  215495. bool setAlwaysOnTop (bool alwaysOnTop)
  215496. {
  215497. if (windowH != 0)
  215498. {
  215499. const bool wasVisible = component->isVisible();
  215500. if (wasVisible)
  215501. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  215502. XSetWindowAttributes swa;
  215503. swa.override_redirect = alwaysOnTop ? True : False;
  215504. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  215505. if (wasVisible)
  215506. setVisible (true);
  215507. }
  215508. return true;
  215509. }
  215510. void toFront (bool makeActive)
  215511. {
  215512. if (makeActive)
  215513. {
  215514. setVisible (true);
  215515. grabFocus();
  215516. }
  215517. XEvent ev;
  215518. ev.xclient.type = ClientMessage;
  215519. ev.xclient.serial = 0;
  215520. ev.xclient.send_event = True;
  215521. ev.xclient.message_type = wm_ActiveWin;
  215522. ev.xclient.window = windowH;
  215523. ev.xclient.format = 32;
  215524. ev.xclient.data.l[0] = 2;
  215525. ev.xclient.data.l[1] = CurrentTime;
  215526. ev.xclient.data.l[2] = 0;
  215527. ev.xclient.data.l[3] = 0;
  215528. ev.xclient.data.l[4] = 0;
  215529. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  215530. False,
  215531. SubstructureRedirectMask | SubstructureNotifyMask,
  215532. &ev);
  215533. XWindowAttributes attr;
  215534. XGetWindowAttributes (display, windowH, &attr);
  215535. if (attr.override_redirect)
  215536. XRaiseWindow (display, windowH);
  215537. XSync (display, False);
  215538. handleBroughtToFront();
  215539. }
  215540. void toBehind (ComponentPeer* other)
  215541. {
  215542. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  215543. jassert (otherPeer != 0); // wrong type of window?
  215544. if (otherPeer != 0)
  215545. {
  215546. setMinimised (false);
  215547. Window newStack[] = { otherPeer->windowH, windowH };
  215548. XRestackWindows (display, newStack, 2);
  215549. }
  215550. }
  215551. bool isFocused() const
  215552. {
  215553. int revert;
  215554. Window focusedWindow = 0;
  215555. XGetInputFocus (display, &focusedWindow, &revert);
  215556. return focusedWindow == windowH;
  215557. }
  215558. void grabFocus()
  215559. {
  215560. XWindowAttributes atts;
  215561. if (windowH != 0
  215562. && XGetWindowAttributes (display, windowH, &atts)
  215563. && atts.map_state == IsViewable
  215564. && ! isFocused())
  215565. {
  215566. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  215567. isActiveApplication = true;
  215568. }
  215569. }
  215570. void textInputRequired (int /*x*/, int /*y*/)
  215571. {
  215572. }
  215573. void repaint (int x, int y, int w, int h)
  215574. {
  215575. if (Rectangle::intersectRectangles (x, y, w, h,
  215576. 0, 0,
  215577. getComponent()->getWidth(),
  215578. getComponent()->getHeight()))
  215579. {
  215580. repainter->repaint (x, y, w, h);
  215581. }
  215582. }
  215583. void performAnyPendingRepaintsNow()
  215584. {
  215585. repainter->performAnyPendingRepaintsNow();
  215586. }
  215587. void setIcon (const Image& newIcon)
  215588. {
  215589. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  215590. unsigned long* const data = (unsigned long*) juce_malloc (dataSize * sizeof (uint32));
  215591. int index = 0;
  215592. data[index++] = newIcon.getWidth();
  215593. data[index++] = newIcon.getHeight();
  215594. for (int y = 0; y < newIcon.getHeight(); ++y)
  215595. for (int x = 0; x < newIcon.getWidth(); ++x)
  215596. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  215597. XChangeProperty (display, windowH,
  215598. XInternAtom (display, "_NET_WM_ICON", False),
  215599. XA_CARDINAL, 32, PropModeReplace,
  215600. (unsigned char*) data, dataSize);
  215601. juce_free (data);
  215602. deleteIconPixmaps();
  215603. XWMHints* wmHints = XGetWMHints (display, windowH);
  215604. if (wmHints == 0)
  215605. wmHints = XAllocWMHints();
  215606. wmHints->flags |= IconPixmapHint | IconMaskHint;
  215607. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  215608. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  215609. XSetWMHints (display, windowH, wmHints);
  215610. XFree (wmHints);
  215611. XSync (display, False);
  215612. }
  215613. void deleteIconPixmaps()
  215614. {
  215615. XWMHints* wmHints = XGetWMHints (display, windowH);
  215616. if (wmHints != 0)
  215617. {
  215618. if ((wmHints->flags & IconPixmapHint) != 0)
  215619. {
  215620. wmHints->flags &= ~IconPixmapHint;
  215621. XFreePixmap (display, wmHints->icon_pixmap);
  215622. }
  215623. if ((wmHints->flags & IconMaskHint) != 0)
  215624. {
  215625. wmHints->flags &= ~IconMaskHint;
  215626. XFreePixmap (display, wmHints->icon_mask);
  215627. }
  215628. XSetWMHints (display, windowH, wmHints);
  215629. XFree (wmHints);
  215630. }
  215631. }
  215632. void handleWindowMessage (XEvent* event)
  215633. {
  215634. switch (event->xany.type)
  215635. {
  215636. case 2: // 'KeyPress'
  215637. {
  215638. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  215639. updateKeyStates (keyEvent->keycode, true);
  215640. char utf8 [64];
  215641. zeromem (utf8, sizeof (utf8));
  215642. KeySym sym;
  215643. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  215644. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  215645. int keyCode = (int) unicodeChar;
  215646. if (keyCode < 0x20)
  215647. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  215648. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  215649. const int oldMods = currentModifiers;
  215650. bool keyPressed = false;
  215651. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  215652. if ((sym & 0xff00) == 0xff00)
  215653. {
  215654. // Translate keypad
  215655. if (sym == XK_KP_Divide)
  215656. keyCode = XK_slash;
  215657. else if (sym == XK_KP_Multiply)
  215658. keyCode = XK_asterisk;
  215659. else if (sym == XK_KP_Subtract)
  215660. keyCode = XK_hyphen;
  215661. else if (sym == XK_KP_Add)
  215662. keyCode = XK_plus;
  215663. else if (sym == XK_KP_Enter)
  215664. keyCode = XK_Return;
  215665. else if (sym == XK_KP_Decimal)
  215666. keyCode = numLock ? XK_period : XK_Delete;
  215667. else if (sym == XK_KP_0)
  215668. keyCode = numLock ? XK_0 : XK_Insert;
  215669. else if (sym == XK_KP_1)
  215670. keyCode = numLock ? XK_1 : XK_End;
  215671. else if (sym == XK_KP_2)
  215672. keyCode = numLock ? XK_2 : XK_Down;
  215673. else if (sym == XK_KP_3)
  215674. keyCode = numLock ? XK_3 : XK_Page_Down;
  215675. else if (sym == XK_KP_4)
  215676. keyCode = numLock ? XK_4 : XK_Left;
  215677. else if (sym == XK_KP_5)
  215678. keyCode = XK_5;
  215679. else if (sym == XK_KP_6)
  215680. keyCode = numLock ? XK_6 : XK_Right;
  215681. else if (sym == XK_KP_7)
  215682. keyCode = numLock ? XK_7 : XK_Home;
  215683. else if (sym == XK_KP_8)
  215684. keyCode = numLock ? XK_8 : XK_Up;
  215685. else if (sym == XK_KP_9)
  215686. keyCode = numLock ? XK_9 : XK_Page_Up;
  215687. switch (sym)
  215688. {
  215689. case XK_Left:
  215690. case XK_Right:
  215691. case XK_Up:
  215692. case XK_Down:
  215693. case XK_Page_Up:
  215694. case XK_Page_Down:
  215695. case XK_End:
  215696. case XK_Home:
  215697. case XK_Delete:
  215698. case XK_Insert:
  215699. keyPressed = true;
  215700. keyCode = (sym & 0xff) | extendedKeyModifier;
  215701. break;
  215702. case XK_Tab:
  215703. case XK_Return:
  215704. case XK_Escape:
  215705. case XK_BackSpace:
  215706. keyPressed = true;
  215707. keyCode &= 0xff;
  215708. break;
  215709. default:
  215710. {
  215711. if (sym >= XK_F1 && sym <= XK_F16)
  215712. {
  215713. keyPressed = true;
  215714. keyCode = (sym & 0xff) | extendedKeyModifier;
  215715. }
  215716. break;
  215717. }
  215718. }
  215719. }
  215720. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  215721. keyPressed = true;
  215722. if (oldMods != currentModifiers)
  215723. handleModifierKeysChange();
  215724. if (keyDownChange)
  215725. handleKeyUpOrDown (true);
  215726. if (keyPressed)
  215727. handleKeyPress (keyCode, unicodeChar);
  215728. break;
  215729. }
  215730. case KeyRelease:
  215731. {
  215732. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  215733. updateKeyStates (keyEvent->keycode, false);
  215734. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  215735. const int oldMods = currentModifiers;
  215736. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  215737. if (oldMods != currentModifiers)
  215738. handleModifierKeysChange();
  215739. if (keyDownChange)
  215740. handleKeyUpOrDown (false);
  215741. break;
  215742. }
  215743. case ButtonPress:
  215744. {
  215745. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  215746. bool buttonMsg = false;
  215747. bool wheelUpMsg = false;
  215748. bool wheelDownMsg = false;
  215749. const int map = pointerMap [buttonPressEvent->button - Button1];
  215750. if (map == LeftButton)
  215751. {
  215752. currentModifiers |= ModifierKeys::leftButtonModifier;
  215753. buttonMsg = true;
  215754. }
  215755. else if (map == RightButton)
  215756. {
  215757. currentModifiers |= ModifierKeys::rightButtonModifier;
  215758. buttonMsg = true;
  215759. }
  215760. else if (map == MiddleButton)
  215761. {
  215762. currentModifiers |= ModifierKeys::middleButtonModifier;
  215763. buttonMsg = true;
  215764. }
  215765. else if (map == WheelUp)
  215766. {
  215767. wheelUpMsg = true;
  215768. }
  215769. else if (map == WheelDown)
  215770. {
  215771. wheelDownMsg = true;
  215772. }
  215773. updateKeyModifiers (buttonPressEvent->state);
  215774. if (buttonMsg)
  215775. {
  215776. toFront (true);
  215777. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  215778. getEventTime (buttonPressEvent->time));
  215779. }
  215780. else if (wheelUpMsg || wheelDownMsg)
  215781. {
  215782. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  215783. getEventTime (buttonPressEvent->time));
  215784. }
  215785. lastMousePosX = lastMousePosY = 0x100000;
  215786. break;
  215787. }
  215788. case ButtonRelease:
  215789. {
  215790. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  215791. const int oldModifiers = currentModifiers;
  215792. const int map = pointerMap [buttonRelEvent->button - Button1];
  215793. if (map == LeftButton)
  215794. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  215795. else if (map == RightButton)
  215796. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  215797. else if (map == MiddleButton)
  215798. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  215799. updateKeyModifiers (buttonRelEvent->state);
  215800. handleMouseUp (oldModifiers,
  215801. buttonRelEvent->x, buttonRelEvent->y,
  215802. getEventTime (buttonRelEvent->time));
  215803. lastMousePosX = lastMousePosY = 0x100000;
  215804. break;
  215805. }
  215806. case MotionNotify:
  215807. {
  215808. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  215809. updateKeyModifiers (movedEvent->state);
  215810. int x, y, mouseMods;
  215811. getMousePos (x, y, mouseMods);
  215812. if (lastMousePosX != x || lastMousePosY != y)
  215813. {
  215814. lastMousePosX = x;
  215815. lastMousePosY = y;
  215816. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  215817. {
  215818. Window wRoot = 0, wParent = 0;
  215819. Window* wChild = 0;
  215820. unsigned int numChildren;
  215821. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  215822. if (wParent != 0
  215823. && wParent != windowH
  215824. && wParent != wRoot)
  215825. {
  215826. parentWindow = wParent;
  215827. updateBounds();
  215828. x -= getScreenX();
  215829. y -= getScreenY();
  215830. }
  215831. else
  215832. {
  215833. parentWindow = 0;
  215834. x -= getScreenX();
  215835. y -= getScreenY();
  215836. }
  215837. }
  215838. else
  215839. {
  215840. x -= getScreenX();
  215841. y -= getScreenY();
  215842. }
  215843. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  215844. handleMouseMove (x, y, getEventTime (movedEvent->time));
  215845. else
  215846. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  215847. }
  215848. break;
  215849. }
  215850. case EnterNotify:
  215851. {
  215852. lastMousePosX = lastMousePosY = 0x100000;
  215853. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  215854. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215855. && ! entered)
  215856. {
  215857. updateKeyModifiers (enterEvent->state);
  215858. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  215859. entered = true;
  215860. }
  215861. break;
  215862. }
  215863. case LeaveNotify:
  215864. {
  215865. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  215866. // Suppress the normal leave if we've got a pointer grab, or if
  215867. // it's a bogus one caused by clicking a mouse button when running
  215868. // in a Window manager
  215869. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215870. && leaveEvent->mode == NotifyNormal)
  215871. || leaveEvent->mode == NotifyUngrab)
  215872. {
  215873. updateKeyModifiers (leaveEvent->state);
  215874. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  215875. entered = false;
  215876. }
  215877. break;
  215878. }
  215879. case FocusIn:
  215880. {
  215881. isActiveApplication = true;
  215882. if (isFocused())
  215883. handleFocusGain();
  215884. break;
  215885. }
  215886. case FocusOut:
  215887. {
  215888. isActiveApplication = false;
  215889. if (! isFocused())
  215890. handleFocusLoss();
  215891. break;
  215892. }
  215893. case Expose:
  215894. {
  215895. // Batch together all pending expose events
  215896. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  215897. XEvent nextEvent;
  215898. if (exposeEvent->window != windowH)
  215899. {
  215900. Window child;
  215901. XTranslateCoordinates (display, exposeEvent->window, windowH,
  215902. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  215903. &child);
  215904. }
  215905. repaint (exposeEvent->x, exposeEvent->y,
  215906. exposeEvent->width, exposeEvent->height);
  215907. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  215908. {
  215909. XPeekEvent (display, (XEvent*) &nextEvent);
  215910. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  215911. break;
  215912. XNextEvent (display, (XEvent*) &nextEvent);
  215913. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  215914. repaint (nextExposeEvent->x, nextExposeEvent->y,
  215915. nextExposeEvent->width, nextExposeEvent->height);
  215916. }
  215917. break;
  215918. }
  215919. case CirculateNotify:
  215920. case CreateNotify:
  215921. case DestroyNotify:
  215922. // Think we can ignore these
  215923. break;
  215924. case ConfigureNotify:
  215925. {
  215926. updateBounds();
  215927. updateBorderSize();
  215928. handleMovedOrResized();
  215929. // if the native title bar is dragged, need to tell any active menus, etc.
  215930. if ((styleFlags & windowHasTitleBar) != 0
  215931. && component->isCurrentlyBlockedByAnotherModalComponent())
  215932. {
  215933. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  215934. if (currentModalComp != 0)
  215935. currentModalComp->inputAttemptWhenModal();
  215936. }
  215937. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  215938. if (confEvent->window == windowH
  215939. && confEvent->above != 0
  215940. && isFrontWindow())
  215941. {
  215942. handleBroughtToFront();
  215943. }
  215944. break;
  215945. }
  215946. case ReparentNotify:
  215947. case GravityNotify:
  215948. {
  215949. parentWindow = 0;
  215950. Window wRoot = 0;
  215951. Window* wChild = 0;
  215952. unsigned int numChildren;
  215953. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  215954. if (parentWindow == windowH || parentWindow == wRoot)
  215955. parentWindow = 0;
  215956. updateBounds();
  215957. updateBorderSize();
  215958. handleMovedOrResized();
  215959. break;
  215960. }
  215961. case MapNotify:
  215962. mapped = true;
  215963. handleBroughtToFront();
  215964. break;
  215965. case UnmapNotify:
  215966. mapped = false;
  215967. break;
  215968. case MappingNotify:
  215969. {
  215970. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  215971. if (mappingEvent->request != MappingPointer)
  215972. {
  215973. // Deal with modifier/keyboard mapping
  215974. XRefreshKeyboardMapping (mappingEvent);
  215975. getModifierMapping();
  215976. }
  215977. break;
  215978. }
  215979. case ClientMessage:
  215980. {
  215981. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  215982. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  215983. {
  215984. const Atom atom = (Atom) clientMsg->data.l[0];
  215985. if (atom == wm_ProtocolList [TAKE_FOCUS])
  215986. {
  215987. XWindowAttributes atts;
  215988. if (clientMsg->window != 0
  215989. && XGetWindowAttributes (display, clientMsg->window, &atts))
  215990. {
  215991. if (atts.map_state == IsViewable)
  215992. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  215993. }
  215994. }
  215995. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  215996. {
  215997. handleUserClosingWindow();
  215998. }
  215999. }
  216000. else if (clientMsg->message_type == XA_XdndEnter)
  216001. {
  216002. handleDragAndDropEnter (clientMsg);
  216003. }
  216004. else if (clientMsg->message_type == XA_XdndLeave)
  216005. {
  216006. resetDragAndDrop();
  216007. }
  216008. else if (clientMsg->message_type == XA_XdndPosition)
  216009. {
  216010. handleDragAndDropPosition (clientMsg);
  216011. }
  216012. else if (clientMsg->message_type == XA_XdndDrop)
  216013. {
  216014. handleDragAndDropDrop (clientMsg);
  216015. }
  216016. else if (clientMsg->message_type == XA_XdndStatus)
  216017. {
  216018. handleDragAndDropStatus (clientMsg);
  216019. }
  216020. else if (clientMsg->message_type == XA_XdndFinished)
  216021. {
  216022. resetDragAndDrop();
  216023. }
  216024. break;
  216025. }
  216026. case SelectionNotify:
  216027. handleDragAndDropSelection (event);
  216028. break;
  216029. case SelectionClear:
  216030. case SelectionRequest:
  216031. break;
  216032. default:
  216033. break;
  216034. }
  216035. }
  216036. void showMouseCursor (Cursor cursor) throw()
  216037. {
  216038. XDefineCursor (display, windowH, cursor);
  216039. }
  216040. void setTaskBarIcon (const Image& image)
  216041. {
  216042. deleteTaskBarIcon();
  216043. taskbarImage = image.createCopy();
  216044. Screen* const screen = XDefaultScreenOfDisplay (display);
  216045. const int screenNumber = XScreenNumberOfScreen (screen);
  216046. char screenAtom[32];
  216047. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  216048. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  216049. XGrabServer (display);
  216050. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  216051. if (managerWin != None)
  216052. XSelectInput (display, managerWin, StructureNotifyMask);
  216053. XUngrabServer (display);
  216054. XFlush (display);
  216055. if (managerWin != None)
  216056. {
  216057. XEvent ev;
  216058. zerostruct (ev);
  216059. ev.xclient.type = ClientMessage;
  216060. ev.xclient.window = managerWin;
  216061. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  216062. ev.xclient.format = 32;
  216063. ev.xclient.data.l[0] = CurrentTime;
  216064. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  216065. ev.xclient.data.l[2] = windowH;
  216066. ev.xclient.data.l[3] = 0;
  216067. ev.xclient.data.l[4] = 0;
  216068. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  216069. XSync (display, False);
  216070. }
  216071. // For older KDE's ...
  216072. long atomData = 1;
  216073. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  216074. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  216075. // For more recent KDE's...
  216076. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  216077. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  216078. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  216079. XSizeHints* hints = XAllocSizeHints();
  216080. hints->flags = PMinSize;
  216081. hints->min_width = 22;
  216082. hints->min_height = 22;
  216083. XSetWMNormalHints (display, windowH, hints);
  216084. XFree (hints);
  216085. }
  216086. void deleteTaskBarIcon()
  216087. {
  216088. deleteAndZero (taskbarImage);
  216089. }
  216090. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  216091. juce_UseDebuggingNewOperator
  216092. bool dontRepaint;
  216093. private:
  216094. class LinuxRepaintManager : public Timer
  216095. {
  216096. public:
  216097. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  216098. : peer (peer_),
  216099. image (0),
  216100. lastTimeImageUsed (0)
  216101. {
  216102. #if JUCE_USE_XSHM
  216103. useARGBImagesForRendering = isShmAvailable();
  216104. if (useARGBImagesForRendering)
  216105. {
  216106. XShmSegmentInfo segmentinfo;
  216107. XImage* const testImage
  216108. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  216109. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  216110. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  216111. XDestroyImage (testImage);
  216112. }
  216113. #endif
  216114. }
  216115. ~LinuxRepaintManager()
  216116. {
  216117. delete image;
  216118. }
  216119. void timerCallback()
  216120. {
  216121. if (! regionsNeedingRepaint.isEmpty())
  216122. {
  216123. stopTimer();
  216124. performAnyPendingRepaintsNow();
  216125. }
  216126. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  216127. {
  216128. stopTimer();
  216129. deleteAndZero (image);
  216130. }
  216131. }
  216132. void repaint (int x, int y, int w, int h)
  216133. {
  216134. if (! isTimerRunning())
  216135. startTimer (repaintTimerPeriod);
  216136. regionsNeedingRepaint.add (x, y, w, h);
  216137. }
  216138. void performAnyPendingRepaintsNow()
  216139. {
  216140. peer->clearMaskedRegion();
  216141. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  216142. if (! totalArea.isEmpty())
  216143. {
  216144. if (image == 0 || image->getWidth() < totalArea.getWidth()
  216145. || image->getHeight() < totalArea.getHeight())
  216146. {
  216147. delete image;
  216148. #if JUCE_USE_XSHM
  216149. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  216150. : Image::RGB,
  216151. #else
  216152. image = new XBitmapImage (Image::RGB,
  216153. #endif
  216154. (totalArea.getWidth() + 31) & ~31,
  216155. (totalArea.getHeight() + 31) & ~31,
  216156. false,
  216157. peer->depthIs16Bit);
  216158. }
  216159. startTimer (repaintTimerPeriod);
  216160. LowLevelGraphicsSoftwareRenderer context (*image);
  216161. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  216162. if (context.reduceClipRegion (regionsNeedingRepaint))
  216163. peer->handlePaint (context);
  216164. if (! peer->maskedRegion.isEmpty())
  216165. regionsNeedingRepaint.subtract (peer->maskedRegion);
  216166. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  216167. {
  216168. const Rectangle& r = *i.getRectangle();
  216169. image->blitToWindow (peer->windowH,
  216170. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  216171. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  216172. }
  216173. }
  216174. regionsNeedingRepaint.clear();
  216175. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  216176. startTimer (repaintTimerPeriod);
  216177. }
  216178. private:
  216179. LinuxComponentPeer* const peer;
  216180. XBitmapImage* image;
  216181. uint32 lastTimeImageUsed;
  216182. RectangleList regionsNeedingRepaint;
  216183. #if JUCE_USE_XSHM
  216184. bool useARGBImagesForRendering;
  216185. #endif
  216186. LinuxRepaintManager (const LinuxRepaintManager&);
  216187. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  216188. };
  216189. LinuxRepaintManager* repainter;
  216190. friend class LinuxRepaintManager;
  216191. Window windowH, parentWindow;
  216192. int wx, wy, ww, wh;
  216193. Image* taskbarImage;
  216194. bool fullScreen, entered, mapped, depthIs16Bit;
  216195. BorderSize windowBorder;
  216196. void removeWindowDecorations (Window wndH)
  216197. {
  216198. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216199. if (hints != None)
  216200. {
  216201. typedef struct
  216202. {
  216203. unsigned long flags;
  216204. unsigned long functions;
  216205. unsigned long decorations;
  216206. long input_mode;
  216207. unsigned long status;
  216208. } MotifWmHints;
  216209. MotifWmHints motifHints;
  216210. zerostruct (motifHints);
  216211. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  216212. motifHints.decorations = 0;
  216213. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216214. (unsigned char*) &motifHints, 4);
  216215. }
  216216. hints = XInternAtom (display, "_WIN_HINTS", True);
  216217. if (hints != None)
  216218. {
  216219. long gnomeHints = 0;
  216220. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216221. (unsigned char*) &gnomeHints, 1);
  216222. }
  216223. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  216224. if (hints != None)
  216225. {
  216226. long kwmHints = 2; /*KDE_tinyDecoration*/
  216227. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216228. (unsigned char*) &kwmHints, 1);
  216229. }
  216230. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  216231. if (hints != None)
  216232. {
  216233. int netHints [2];
  216234. int numHints = 0;
  216235. if ((styleFlags & windowIsTemporary) != 0)
  216236. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  216237. else
  216238. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  216239. if (netHints [numHints] != 0)
  216240. ++numHints;
  216241. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  216242. if (netHints [numHints] != 0)
  216243. ++numHints;
  216244. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216245. (unsigned char*) &netHints, numHints);
  216246. }
  216247. }
  216248. void addWindowButtons (Window wndH)
  216249. {
  216250. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216251. if (hints != None)
  216252. {
  216253. typedef struct
  216254. {
  216255. unsigned long flags;
  216256. unsigned long functions;
  216257. unsigned long decorations;
  216258. long input_mode;
  216259. unsigned long status;
  216260. } MotifWmHints;
  216261. MotifWmHints motifHints;
  216262. zerostruct (motifHints);
  216263. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  216264. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  216265. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  216266. if ((styleFlags & windowHasCloseButton) != 0)
  216267. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  216268. if ((styleFlags & windowHasMinimiseButton) != 0)
  216269. {
  216270. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  216271. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  216272. }
  216273. if ((styleFlags & windowHasMaximiseButton) != 0)
  216274. {
  216275. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  216276. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  216277. }
  216278. if ((styleFlags & windowIsResizable) != 0)
  216279. {
  216280. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  216281. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  216282. }
  216283. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  216284. }
  216285. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  216286. if (hints != None)
  216287. {
  216288. int netHints [6];
  216289. int num = 0;
  216290. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  216291. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  216292. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  216293. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  216294. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216295. (unsigned char*) &netHints, num);
  216296. }
  216297. }
  216298. void createWindow()
  216299. {
  216300. static bool atomsInitialised = false;
  216301. if (! atomsInitialised)
  216302. {
  216303. atomsInitialised = true;
  216304. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  216305. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  216306. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  216307. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  216308. wm_State = XInternAtom (display, "WM_STATE", 1);
  216309. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  216310. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  216311. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  216312. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  216313. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  216314. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  216315. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  216316. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  216317. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  216318. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  216319. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  216320. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  216321. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  216322. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  216323. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  216324. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  216325. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  216326. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  216327. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  216328. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  216329. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  216330. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  216331. }
  216332. resetDragAndDrop();
  216333. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  216334. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  216335. allowedMimeTypeAtoms [1] = XA_OtherMime;
  216336. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  216337. allowedActions [0] = XA_XdndActionMove;
  216338. allowedActions [1] = XA_XdndActionCopy;
  216339. allowedActions [2] = XA_XdndActionLink;
  216340. allowedActions [3] = XA_XdndActionAsk;
  216341. allowedActions [4] = XA_XdndActionPrivate;
  216342. // Get defaults for various properties
  216343. const int screen = DefaultScreen (display);
  216344. Window root = RootWindow (display, screen);
  216345. // Attempt to create a 24-bit window on the default screen. If this is not
  216346. // possible then exit
  216347. XVisualInfo desiredVisual;
  216348. desiredVisual.screen = screen;
  216349. desiredVisual.depth = 24;
  216350. depthIs16Bit = false;
  216351. int numVisuals;
  216352. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216353. &desiredVisual, &numVisuals);
  216354. if (numVisuals < 1 || visuals == 0)
  216355. {
  216356. XFree (visuals);
  216357. desiredVisual.depth = 16;
  216358. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216359. &desiredVisual, &numVisuals);
  216360. if (numVisuals < 1 || visuals == 0)
  216361. {
  216362. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  216363. Process::terminate();
  216364. }
  216365. depthIs16Bit = true;
  216366. }
  216367. XFree (visuals);
  216368. // Set up the window attributes
  216369. XSetWindowAttributes swa;
  216370. swa.border_pixel = 0;
  216371. swa.background_pixmap = None;
  216372. swa.colormap = DefaultColormap (display, screen);
  216373. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  216374. swa.event_mask = eventMask;
  216375. Window wndH = XCreateWindow (display, root,
  216376. 0, 0, 1, 1,
  216377. 0, 0, InputOutput, (Visual*) CopyFromParent,
  216378. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  216379. &swa);
  216380. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  216381. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  216382. GrabModeAsync, GrabModeAsync, None, None);
  216383. // Set the window context to identify the window handle object
  216384. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  216385. {
  216386. // Failed
  216387. jassertfalse
  216388. Logger::outputDebugString ("Failed to create context information for window.\n");
  216389. XDestroyWindow (display, wndH);
  216390. wndH = 0;
  216391. }
  216392. // Set window manager hints
  216393. XWMHints* wmHints = XAllocWMHints();
  216394. wmHints->flags = InputHint | StateHint;
  216395. wmHints->input = True; // Locally active input model
  216396. wmHints->initial_state = NormalState;
  216397. XSetWMHints (display, wndH, wmHints);
  216398. XFree (wmHints);
  216399. if ((styleFlags & windowIsSemiTransparent) != 0)
  216400. {
  216401. //xxx
  216402. }
  216403. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  216404. {
  216405. //xxx
  216406. }
  216407. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  216408. if ((styleFlags & windowHasTitleBar) == 0)
  216409. removeWindowDecorations (wndH);
  216410. else
  216411. addWindowButtons (wndH);
  216412. // Set window manager protocols
  216413. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  216414. (unsigned char*) wm_ProtocolList, 2);
  216415. // Set drag and drop flags
  216416. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  216417. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  216418. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  216419. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  216420. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  216421. (const unsigned char*) "", 0);
  216422. unsigned long dndVersion = ourDndVersion;
  216423. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  216424. (const unsigned char*) &dndVersion, 1);
  216425. // Set window name
  216426. setWindowTitle (wndH, getComponent()->getName());
  216427. // Initialise the pointer and keyboard mapping
  216428. // This is not the same as the logical pointer mapping the X server uses:
  216429. // we don't mess with this.
  216430. static bool mappingInitialised = false;
  216431. if (! mappingInitialised)
  216432. {
  216433. mappingInitialised = true;
  216434. const int numButtons = XGetPointerMapping (display, 0, 0);
  216435. if (numButtons == 2)
  216436. {
  216437. pointerMap[0] = LeftButton;
  216438. pointerMap[1] = RightButton;
  216439. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  216440. }
  216441. else if (numButtons >= 3)
  216442. {
  216443. pointerMap[0] = LeftButton;
  216444. pointerMap[1] = MiddleButton;
  216445. pointerMap[2] = RightButton;
  216446. if (numButtons >= 5)
  216447. {
  216448. pointerMap[3] = WheelUp;
  216449. pointerMap[4] = WheelDown;
  216450. }
  216451. }
  216452. getModifierMapping();
  216453. }
  216454. windowH = wndH;
  216455. }
  216456. void destroyWindow()
  216457. {
  216458. XPointer handlePointer;
  216459. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  216460. XDeleteContext (display, (XID) windowH, improbableNumber);
  216461. XDestroyWindow (display, windowH);
  216462. // Wait for it to complete and then remove any events for this
  216463. // window from the event queue.
  216464. XSync (display, false);
  216465. XEvent event;
  216466. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  216467. {}
  216468. }
  216469. static int64 getEventTime (::Time t) throw()
  216470. {
  216471. static int64 eventTimeOffset = 0x12345678;
  216472. const int64 thisMessageTime = t;
  216473. if (eventTimeOffset == 0x12345678)
  216474. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  216475. return eventTimeOffset + thisMessageTime;
  216476. }
  216477. static void setWindowTitle (Window xwin, const char* const title) throw()
  216478. {
  216479. XTextProperty nameProperty;
  216480. char* strings[] = { (char*) title };
  216481. if (XStringListToTextProperty (strings, 1, &nameProperty))
  216482. {
  216483. XSetWMName (display, xwin, &nameProperty);
  216484. XSetWMIconName (display, xwin, &nameProperty);
  216485. XFree (nameProperty.value);
  216486. }
  216487. }
  216488. void updateBorderSize()
  216489. {
  216490. if ((styleFlags & windowHasTitleBar) == 0)
  216491. {
  216492. windowBorder = BorderSize (0);
  216493. }
  216494. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  216495. {
  216496. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  216497. if (hints != None)
  216498. {
  216499. unsigned char* data = 0;
  216500. unsigned long nitems, bytesLeft;
  216501. Atom actualType;
  216502. int actualFormat;
  216503. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  216504. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216505. &data) == Success)
  216506. {
  216507. const unsigned long* const sizes = (const unsigned long*) data;
  216508. if (actualFormat == 32)
  216509. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  216510. (int) sizes[3], (int) sizes[1]);
  216511. XFree (data);
  216512. }
  216513. }
  216514. }
  216515. }
  216516. void updateBounds()
  216517. {
  216518. jassert (windowH != 0);
  216519. if (windowH != 0)
  216520. {
  216521. Window root, child;
  216522. unsigned int bw, depth;
  216523. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216524. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  216525. &bw, &depth))
  216526. {
  216527. wx = wy = ww = wh = 0;
  216528. }
  216529. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  216530. {
  216531. wx = wy = 0;
  216532. }
  216533. }
  216534. }
  216535. void resetDragAndDrop()
  216536. {
  216537. dragAndDropFiles.clear();
  216538. lastDropX = lastDropY = -1;
  216539. dragAndDropCurrentMimeType = 0;
  216540. dragAndDropSourceWindow = 0;
  216541. srcMimeTypeAtomList.clear();
  216542. }
  216543. void sendDragAndDropMessage (XClientMessageEvent& msg)
  216544. {
  216545. msg.type = ClientMessage;
  216546. msg.display = display;
  216547. msg.window = dragAndDropSourceWindow;
  216548. msg.format = 32;
  216549. msg.data.l[0] = windowH;
  216550. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  216551. }
  216552. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  216553. {
  216554. XClientMessageEvent msg;
  216555. zerostruct (msg);
  216556. msg.message_type = XA_XdndStatus;
  216557. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  216558. msg.data.l[4] = dropAction;
  216559. sendDragAndDropMessage (msg);
  216560. }
  216561. void sendDragAndDropLeave()
  216562. {
  216563. XClientMessageEvent msg;
  216564. zerostruct (msg);
  216565. msg.message_type = XA_XdndLeave;
  216566. sendDragAndDropMessage (msg);
  216567. }
  216568. void sendDragAndDropFinish()
  216569. {
  216570. XClientMessageEvent msg;
  216571. zerostruct (msg);
  216572. msg.message_type = XA_XdndFinished;
  216573. sendDragAndDropMessage (msg);
  216574. }
  216575. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  216576. {
  216577. if ((clientMsg->data.l[1] & 1) == 0)
  216578. {
  216579. sendDragAndDropLeave();
  216580. if (dragAndDropFiles.size() > 0)
  216581. handleFileDragExit (dragAndDropFiles);
  216582. dragAndDropFiles.clear();
  216583. }
  216584. }
  216585. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  216586. {
  216587. if (dragAndDropSourceWindow == 0)
  216588. return;
  216589. dragAndDropSourceWindow = clientMsg->data.l[0];
  216590. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  216591. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  216592. if (lastDropX != dropX || lastDropY != dropY)
  216593. {
  216594. lastDropX = dropX;
  216595. lastDropY = dropY;
  216596. dragAndDropTimestamp = clientMsg->data.l[3];
  216597. Atom targetAction = XA_XdndActionCopy;
  216598. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  216599. {
  216600. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  216601. {
  216602. targetAction = allowedActions[i];
  216603. break;
  216604. }
  216605. }
  216606. sendDragAndDropStatus (true, targetAction);
  216607. if (dragAndDropFiles.size() == 0)
  216608. updateDraggedFileList (clientMsg);
  216609. if (dragAndDropFiles.size() > 0)
  216610. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  216611. }
  216612. }
  216613. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  216614. {
  216615. if (dragAndDropFiles.size() == 0)
  216616. updateDraggedFileList (clientMsg);
  216617. const StringArray files (dragAndDropFiles);
  216618. const int lastX = lastDropX, lastY = lastDropY;
  216619. sendDragAndDropFinish();
  216620. resetDragAndDrop();
  216621. if (files.size() > 0)
  216622. handleFileDragDrop (files, lastX, lastY);
  216623. }
  216624. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  216625. {
  216626. dragAndDropFiles.clear();
  216627. srcMimeTypeAtomList.clear();
  216628. dragAndDropCurrentMimeType = 0;
  216629. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  216630. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  216631. {
  216632. dragAndDropSourceWindow = 0;
  216633. return;
  216634. }
  216635. dragAndDropSourceWindow = clientMsg->data.l[0];
  216636. if ((clientMsg->data.l[1] & 1) != 0)
  216637. {
  216638. Atom actual;
  216639. int format;
  216640. unsigned long count = 0, remaining = 0;
  216641. unsigned char* data = 0;
  216642. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  216643. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  216644. &count, &remaining, &data);
  216645. if (data != 0)
  216646. {
  216647. if (actual == XA_ATOM && format == 32 && count != 0)
  216648. {
  216649. const unsigned long* const types = (const unsigned long*) data;
  216650. for (unsigned int i = 0; i < count; ++i)
  216651. if (types[i] != None)
  216652. srcMimeTypeAtomList.add (types[i]);
  216653. }
  216654. XFree (data);
  216655. }
  216656. }
  216657. if (srcMimeTypeAtomList.size() == 0)
  216658. {
  216659. for (int i = 2; i < 5; ++i)
  216660. if (clientMsg->data.l[i] != None)
  216661. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  216662. if (srcMimeTypeAtomList.size() == 0)
  216663. {
  216664. dragAndDropSourceWindow = 0;
  216665. return;
  216666. }
  216667. }
  216668. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  216669. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  216670. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  216671. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  216672. handleDragAndDropPosition (clientMsg);
  216673. }
  216674. void handleDragAndDropSelection (const XEvent* const evt)
  216675. {
  216676. dragAndDropFiles.clear();
  216677. if (evt->xselection.property != 0)
  216678. {
  216679. StringArray lines;
  216680. {
  216681. MemoryBlock dropData;
  216682. for (;;)
  216683. {
  216684. Atom actual;
  216685. uint8* data = 0;
  216686. unsigned long count = 0, remaining = 0;
  216687. int format = 0;
  216688. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  216689. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  216690. &format, &count, &remaining, &data) == Success)
  216691. {
  216692. dropData.append (data, count * format / 8);
  216693. XFree (data);
  216694. if (remaining == 0)
  216695. break;
  216696. }
  216697. else
  216698. {
  216699. XFree (data);
  216700. break;
  216701. }
  216702. }
  216703. lines.addLines (dropData.toString());
  216704. }
  216705. for (int i = 0; i < lines.size(); ++i)
  216706. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  216707. dragAndDropFiles.trim();
  216708. dragAndDropFiles.removeEmptyStrings();
  216709. }
  216710. }
  216711. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  216712. {
  216713. dragAndDropFiles.clear();
  216714. if (dragAndDropSourceWindow != None
  216715. && dragAndDropCurrentMimeType != 0)
  216716. {
  216717. dragAndDropTimestamp = clientMsg->data.l[2];
  216718. XConvertSelection (display,
  216719. XA_XdndSelection,
  216720. dragAndDropCurrentMimeType,
  216721. XA_JXSelectionWindowProperty,
  216722. windowH,
  216723. dragAndDropTimestamp);
  216724. }
  216725. }
  216726. StringArray dragAndDropFiles;
  216727. int dragAndDropTimestamp, lastDropX, lastDropY;
  216728. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  216729. Window dragAndDropSourceWindow;
  216730. unsigned int allowedActions [5];
  216731. unsigned int allowedMimeTypeAtoms [3];
  216732. Array <Atom> srcMimeTypeAtomList;
  216733. };
  216734. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  216735. {
  216736. if (enableOrDisable)
  216737. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  216738. }
  216739. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  216740. {
  216741. return new LinuxComponentPeer (this, styleFlags);
  216742. }
  216743. // (this callback is hooked up in the messaging code)
  216744. void juce_windowMessageReceive (XEvent* event)
  216745. {
  216746. if (event->xany.window != None)
  216747. {
  216748. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  216749. if (ComponentPeer::isValidPeer (peer))
  216750. peer->handleWindowMessage (event);
  216751. }
  216752. else
  216753. {
  216754. switch (event->xany.type)
  216755. {
  216756. case KeymapNotify:
  216757. {
  216758. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  216759. memcpy (keyStates, keymapEvent->key_vector, 32);
  216760. break;
  216761. }
  216762. default:
  216763. break;
  216764. }
  216765. }
  216766. }
  216767. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  216768. {
  216769. #if JUCE_USE_XINERAMA
  216770. int major_opcode, first_event, first_error;
  216771. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  216772. && XineramaIsActive (display))
  216773. {
  216774. int numMonitors = 0;
  216775. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  216776. if (screens != 0)
  216777. {
  216778. for (int i = numMonitors; --i >= 0;)
  216779. {
  216780. int index = screens[i].screen_number;
  216781. if (index >= 0)
  216782. {
  216783. while (monitorCoords.size() < index)
  216784. monitorCoords.add (Rectangle (0, 0, 0, 0));
  216785. monitorCoords.set (index, Rectangle (screens[i].x_org,
  216786. screens[i].y_org,
  216787. screens[i].width,
  216788. screens[i].height));
  216789. }
  216790. }
  216791. XFree (screens);
  216792. }
  216793. }
  216794. if (monitorCoords.size() == 0)
  216795. #endif
  216796. {
  216797. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  216798. if (hints != None)
  216799. {
  216800. const int numMonitors = ScreenCount (display);
  216801. for (int i = 0; i < numMonitors; ++i)
  216802. {
  216803. Window root = RootWindow (display, i);
  216804. unsigned long nitems, bytesLeft;
  216805. Atom actualType;
  216806. int actualFormat;
  216807. unsigned char* data = 0;
  216808. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  216809. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216810. &data) == Success)
  216811. {
  216812. const long* const position = (const long*) data;
  216813. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  216814. monitorCoords.add (Rectangle (position[0], position[1],
  216815. position[2], position[3]));
  216816. XFree (data);
  216817. }
  216818. }
  216819. }
  216820. if (monitorCoords.size() == 0)
  216821. {
  216822. monitorCoords.add (Rectangle (0, 0,
  216823. DisplayWidth (display, DefaultScreen (display)),
  216824. DisplayHeight (display, DefaultScreen (display))));
  216825. }
  216826. }
  216827. }
  216828. bool Desktop::canUseSemiTransparentWindows() throw()
  216829. {
  216830. return false;
  216831. }
  216832. void Desktop::getMousePosition (int& x, int& y) throw()
  216833. {
  216834. int mouseMods;
  216835. getMousePos (x, y, mouseMods);
  216836. }
  216837. void Desktop::setMousePosition (int x, int y) throw()
  216838. {
  216839. Window root = RootWindow (display, DefaultScreen (display));
  216840. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  216841. }
  216842. static bool screenSaverAllowed = true;
  216843. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  216844. {
  216845. if (screenSaverAllowed != isEnabled)
  216846. {
  216847. screenSaverAllowed = isEnabled;
  216848. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  216849. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  216850. if (xScreenSaverSuspend == 0)
  216851. {
  216852. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  216853. if (h != 0)
  216854. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  216855. }
  216856. if (xScreenSaverSuspend != 0)
  216857. xScreenSaverSuspend (display, ! isEnabled);
  216858. }
  216859. }
  216860. bool Desktop::isScreenSaverEnabled() throw()
  216861. {
  216862. return screenSaverAllowed;
  216863. }
  216864. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  216865. {
  216866. Window root = RootWindow (display, DefaultScreen (display));
  216867. const unsigned int imageW = image.getWidth();
  216868. const unsigned int imageH = image.getHeight();
  216869. unsigned int cursorW, cursorH;
  216870. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  216871. return 0;
  216872. Image im (Image::ARGB, cursorW, cursorH, true);
  216873. Graphics g (im);
  216874. if (imageW > cursorW || imageH > cursorH)
  216875. {
  216876. hotspotX = (hotspotX * cursorW) / imageW;
  216877. hotspotY = (hotspotY * cursorH) / imageH;
  216878. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  216879. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  216880. false);
  216881. }
  216882. else
  216883. {
  216884. g.drawImageAt (&image, 0, 0);
  216885. }
  216886. const int stride = (cursorW + 7) >> 3;
  216887. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  216888. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  216889. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216890. for (int y = cursorH; --y >= 0;)
  216891. {
  216892. for (int x = cursorW; --x >= 0;)
  216893. {
  216894. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216895. const int offset = y * stride + (x >> 3);
  216896. const Colour c (im.getPixelAt (x, y));
  216897. if (c.getAlpha() >= 128)
  216898. maskPlane[offset] |= mask;
  216899. if (c.getBrightness() >= 0.5f)
  216900. sourcePlane[offset] |= mask;
  216901. }
  216902. }
  216903. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  216904. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  216905. juce_free (maskPlane);
  216906. juce_free (sourcePlane);
  216907. XColor white, black;
  216908. black.red = black.green = black.blue = 0;
  216909. white.red = white.green = white.blue = 0xffff;
  216910. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  216911. XFreePixmap (display, sourcePixmap);
  216912. XFreePixmap (display, maskPixmap);
  216913. return result;
  216914. }
  216915. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  216916. {
  216917. if (cursorHandle != None)
  216918. XFreeCursor (display, (Cursor) cursorHandle);
  216919. }
  216920. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  216921. {
  216922. unsigned int shape;
  216923. switch (type)
  216924. {
  216925. case MouseCursor::NoCursor:
  216926. {
  216927. const Image im (Image::ARGB, 16, 16, true);
  216928. return juce_createMouseCursorFromImage (im, 0, 0);
  216929. }
  216930. case MouseCursor::NormalCursor:
  216931. return (void*) None; // Use parent cursor
  216932. case MouseCursor::DraggingHandCursor:
  216933. {
  216934. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  216935. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  216936. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  216937. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  216938. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  216939. const int dragHandDataSize = 99;
  216940. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  216941. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  216942. delete im;
  216943. return dragHandCursor;
  216944. }
  216945. case MouseCursor::CopyingCursor:
  216946. {
  216947. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  216948. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  216949. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  216950. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  216951. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  216952. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  216953. const int copyCursorSize = 119;
  216954. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  216955. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  216956. delete im;
  216957. return copyCursor;
  216958. }
  216959. case MouseCursor::WaitCursor:
  216960. shape = XC_watch;
  216961. break;
  216962. case MouseCursor::IBeamCursor:
  216963. shape = XC_xterm;
  216964. break;
  216965. case MouseCursor::PointingHandCursor:
  216966. shape = XC_hand2;
  216967. break;
  216968. case MouseCursor::LeftRightResizeCursor:
  216969. shape = XC_sb_h_double_arrow;
  216970. break;
  216971. case MouseCursor::UpDownResizeCursor:
  216972. shape = XC_sb_v_double_arrow;
  216973. break;
  216974. case MouseCursor::UpDownLeftRightResizeCursor:
  216975. shape = XC_fleur;
  216976. break;
  216977. case MouseCursor::TopEdgeResizeCursor:
  216978. shape = XC_top_side;
  216979. break;
  216980. case MouseCursor::BottomEdgeResizeCursor:
  216981. shape = XC_bottom_side;
  216982. break;
  216983. case MouseCursor::LeftEdgeResizeCursor:
  216984. shape = XC_left_side;
  216985. break;
  216986. case MouseCursor::RightEdgeResizeCursor:
  216987. shape = XC_right_side;
  216988. break;
  216989. case MouseCursor::TopLeftCornerResizeCursor:
  216990. shape = XC_top_left_corner;
  216991. break;
  216992. case MouseCursor::TopRightCornerResizeCursor:
  216993. shape = XC_top_right_corner;
  216994. break;
  216995. case MouseCursor::BottomLeftCornerResizeCursor:
  216996. shape = XC_bottom_left_corner;
  216997. break;
  216998. case MouseCursor::BottomRightCornerResizeCursor:
  216999. shape = XC_bottom_right_corner;
  217000. break;
  217001. case MouseCursor::CrosshairCursor:
  217002. shape = XC_crosshair;
  217003. break;
  217004. default:
  217005. return (void*) None; // Use parent cursor
  217006. }
  217007. return (void*) XCreateFontCursor (display, shape);
  217008. }
  217009. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  217010. {
  217011. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  217012. if (lp != 0)
  217013. lp->showMouseCursor ((Cursor) getHandle());
  217014. }
  217015. void MouseCursor::showInAllWindows() const throw()
  217016. {
  217017. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  217018. showInWindow (ComponentPeer::getPeer (i));
  217019. }
  217020. Image* juce_createIconForFile (const File& file)
  217021. {
  217022. return 0;
  217023. }
  217024. #if JUCE_OPENGL
  217025. class WindowedGLContext : public OpenGLContext
  217026. {
  217027. public:
  217028. WindowedGLContext (Component* const component,
  217029. const OpenGLPixelFormat& pixelFormat_,
  217030. GLXContext sharedContext)
  217031. : renderContext (0),
  217032. embeddedWindow (0),
  217033. pixelFormat (pixelFormat_)
  217034. {
  217035. jassert (component != 0);
  217036. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  217037. if (peer == 0)
  217038. return;
  217039. XSync (display, False);
  217040. GLint attribs [64];
  217041. int n = 0;
  217042. attribs[n++] = GLX_RGBA;
  217043. attribs[n++] = GLX_DOUBLEBUFFER;
  217044. attribs[n++] = GLX_RED_SIZE;
  217045. attribs[n++] = pixelFormat.redBits;
  217046. attribs[n++] = GLX_GREEN_SIZE;
  217047. attribs[n++] = pixelFormat.greenBits;
  217048. attribs[n++] = GLX_BLUE_SIZE;
  217049. attribs[n++] = pixelFormat.blueBits;
  217050. attribs[n++] = GLX_ALPHA_SIZE;
  217051. attribs[n++] = pixelFormat.alphaBits;
  217052. attribs[n++] = GLX_DEPTH_SIZE;
  217053. attribs[n++] = pixelFormat.depthBufferBits;
  217054. attribs[n++] = GLX_STENCIL_SIZE;
  217055. attribs[n++] = pixelFormat.stencilBufferBits;
  217056. attribs[n++] = GLX_ACCUM_RED_SIZE;
  217057. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  217058. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  217059. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  217060. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  217061. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  217062. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  217063. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  217064. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  217065. attribs[n++] = None;
  217066. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  217067. if (bestVisual == 0)
  217068. return;
  217069. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  217070. Window windowH = (Window) peer->getNativeHandle();
  217071. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  217072. XSetWindowAttributes swa;
  217073. swa.colormap = colourMap;
  217074. swa.border_pixel = 0;
  217075. swa.event_mask = ExposureMask | StructureNotifyMask;
  217076. embeddedWindow = XCreateWindow (display, windowH,
  217077. 0, 0, 1, 1, 0,
  217078. bestVisual->depth,
  217079. InputOutput,
  217080. bestVisual->visual,
  217081. CWBorderPixel | CWColormap | CWEventMask,
  217082. &swa);
  217083. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  217084. XMapWindow (display, embeddedWindow);
  217085. XFreeColormap (display, colourMap);
  217086. XFree (bestVisual);
  217087. XSync (display, False);
  217088. }
  217089. ~WindowedGLContext()
  217090. {
  217091. makeInactive();
  217092. glXDestroyContext (display, renderContext);
  217093. XUnmapWindow (display, embeddedWindow);
  217094. XDestroyWindow (display, embeddedWindow);
  217095. }
  217096. bool makeActive() const throw()
  217097. {
  217098. jassert (renderContext != 0);
  217099. return glXMakeCurrent (display, embeddedWindow, renderContext)
  217100. && XSync (display, False);
  217101. }
  217102. bool makeInactive() const throw()
  217103. {
  217104. return (! isActive()) || glXMakeCurrent (display, None, 0);
  217105. }
  217106. bool isActive() const throw()
  217107. {
  217108. return glXGetCurrentContext() == renderContext;
  217109. }
  217110. const OpenGLPixelFormat getPixelFormat() const
  217111. {
  217112. return pixelFormat;
  217113. }
  217114. void* getRawContext() const throw()
  217115. {
  217116. return renderContext;
  217117. }
  217118. void updateWindowPosition (int x, int y, int w, int h, int)
  217119. {
  217120. XMoveResizeWindow (display, embeddedWindow,
  217121. x, y, jmax (1, w), jmax (1, h));
  217122. }
  217123. void swapBuffers()
  217124. {
  217125. glXSwapBuffers (display, embeddedWindow);
  217126. }
  217127. bool setSwapInterval (const int numFramesPerSwap)
  217128. {
  217129. // xxx needs doing..
  217130. return false;
  217131. }
  217132. int getSwapInterval() const
  217133. {
  217134. // xxx needs doing..
  217135. return 0;
  217136. }
  217137. void repaint()
  217138. {
  217139. }
  217140. juce_UseDebuggingNewOperator
  217141. GLXContext renderContext;
  217142. private:
  217143. Window embeddedWindow;
  217144. OpenGLPixelFormat pixelFormat;
  217145. WindowedGLContext (const WindowedGLContext&);
  217146. const WindowedGLContext& operator= (const WindowedGLContext&);
  217147. };
  217148. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  217149. const OpenGLPixelFormat& pixelFormat,
  217150. const OpenGLContext* const contextToShareWith)
  217151. {
  217152. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  217153. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  217154. if (c->renderContext == 0)
  217155. deleteAndZero (c);
  217156. return c;
  217157. }
  217158. void juce_glViewport (const int w, const int h)
  217159. {
  217160. glViewport (0, 0, w, h);
  217161. }
  217162. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  217163. OwnedArray <OpenGLPixelFormat>& results)
  217164. {
  217165. results.add (new OpenGLPixelFormat()); // xxx
  217166. }
  217167. #endif
  217168. static void initClipboard (Window root, Atom* cutBuffers) throw()
  217169. {
  217170. static bool init = false;
  217171. if (! init)
  217172. {
  217173. init = true;
  217174. // Make sure all cut buffers exist before use
  217175. for (int i = 0; i < 8; i++)
  217176. {
  217177. XChangeProperty (display, root, cutBuffers[i],
  217178. XA_STRING, 8, PropModeAppend, NULL, 0);
  217179. }
  217180. }
  217181. }
  217182. // Clipboard implemented currently using cut buffers
  217183. // rather than the more powerful selection method
  217184. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  217185. {
  217186. Window root = RootWindow (display, DefaultScreen (display));
  217187. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217188. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217189. initClipboard (root, cutBuffers);
  217190. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  217191. XChangeProperty (display, root, cutBuffers[0],
  217192. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  217193. clipText.length());
  217194. }
  217195. const String SystemClipboard::getTextFromClipboard() throw()
  217196. {
  217197. const int bufSize = 64; // in words
  217198. String returnData;
  217199. int byteOffset = 0;
  217200. Window root = RootWindow (display, DefaultScreen (display));
  217201. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217202. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217203. initClipboard (root, cutBuffers);
  217204. for (;;)
  217205. {
  217206. unsigned long bytesLeft = 0, nitems = 0;
  217207. unsigned char* clipData = 0;
  217208. int actualFormat = 0;
  217209. Atom actualType;
  217210. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  217211. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  217212. &clipData) == Success)
  217213. {
  217214. if (actualType == XA_STRING && actualFormat == 8)
  217215. {
  217216. byteOffset += nitems;
  217217. returnData += String ((const char*) clipData, nitems);
  217218. }
  217219. else
  217220. {
  217221. bytesLeft = 0;
  217222. }
  217223. if (clipData != 0)
  217224. XFree (clipData);
  217225. }
  217226. if (bytesLeft == 0)
  217227. break;
  217228. }
  217229. return returnData;
  217230. }
  217231. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  217232. {
  217233. jassertfalse // not implemented!
  217234. return false;
  217235. }
  217236. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  217237. {
  217238. jassertfalse // not implemented!
  217239. return false;
  217240. }
  217241. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  217242. {
  217243. if (! isOnDesktop ())
  217244. addToDesktop (0);
  217245. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217246. if (wp != 0)
  217247. {
  217248. wp->setTaskBarIcon (newImage);
  217249. setVisible (true);
  217250. toFront (false);
  217251. repaint();
  217252. }
  217253. }
  217254. void SystemTrayIconComponent::paint (Graphics& g)
  217255. {
  217256. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217257. if (wp != 0)
  217258. {
  217259. const Image* const image = wp->getTaskbarIcon();
  217260. if (image != 0)
  217261. {
  217262. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  217263. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  217264. false);
  217265. }
  217266. }
  217267. }
  217268. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  217269. {
  217270. // xxx not yet implemented!
  217271. }
  217272. void PlatformUtilities::beep()
  217273. {
  217274. fprintf (stdout, "\a");
  217275. fflush (stdout);
  217276. }
  217277. bool AlertWindow::showNativeDialogBox (const String& title,
  217278. const String& bodyText,
  217279. bool isOkCancel)
  217280. {
  217281. // xxx this is supposed to pop up an alert!
  217282. Logger::outputDebugString (title + ": " + bodyText);
  217283. // use a non-native one for the time being..
  217284. if (isOkCancel)
  217285. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  217286. else
  217287. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  217288. return true;
  217289. }
  217290. const int KeyPress::spaceKey = XK_space & 0xff;
  217291. const int KeyPress::returnKey = XK_Return & 0xff;
  217292. const int KeyPress::escapeKey = XK_Escape & 0xff;
  217293. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  217294. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  217295. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  217296. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  217297. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  217298. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  217299. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  217300. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  217301. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  217302. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  217303. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  217304. const int KeyPress::tabKey = XK_Tab & 0xff;
  217305. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  217306. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  217307. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  217308. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  217309. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  217310. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  217311. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  217312. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  217313. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  217314. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  217315. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  217316. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  217317. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  217318. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  217319. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  217320. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  217321. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  217322. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  217323. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  217324. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  217325. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  217326. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  217327. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  217328. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  217329. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  217330. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  217331. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  217332. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  217333. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  217334. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  217335. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  217336. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  217337. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  217338. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  217339. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  217340. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  217341. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  217342. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  217343. #endif
  217344. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  217345. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  217346. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217347. // compiled on its own).
  217348. #ifdef JUCE_INCLUDED_FILE && JUCE_ALSA
  217349. static const int maxNumChans = 64;
  217350. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  217351. {
  217352. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  217353. snd_pcm_hw_params_t* hwParams;
  217354. snd_pcm_hw_params_alloca (&hwParams);
  217355. for (int i = 0; ratesToTry[i] != 0; ++i)
  217356. {
  217357. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  217358. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  217359. {
  217360. rates.addIfNotAlreadyThere (ratesToTry[i]);
  217361. }
  217362. }
  217363. }
  217364. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  217365. {
  217366. snd_pcm_hw_params_t *params;
  217367. snd_pcm_hw_params_alloca (&params);
  217368. if (snd_pcm_hw_params_any (handle, params) >= 0)
  217369. {
  217370. snd_pcm_hw_params_get_channels_min (params, minChans);
  217371. snd_pcm_hw_params_get_channels_max (params, maxChans);
  217372. }
  217373. }
  217374. static void getDeviceProperties (const String& id,
  217375. unsigned int& minChansOut,
  217376. unsigned int& maxChansOut,
  217377. unsigned int& minChansIn,
  217378. unsigned int& maxChansIn,
  217379. Array <int>& rates)
  217380. {
  217381. if (id.isEmpty())
  217382. return;
  217383. snd_ctl_t* handle;
  217384. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  217385. {
  217386. snd_pcm_info_t* info;
  217387. snd_pcm_info_alloca (&info);
  217388. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  217389. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  217390. snd_pcm_info_set_subdevice (info, 0);
  217391. if (snd_ctl_pcm_info (handle, info) >= 0)
  217392. {
  217393. snd_pcm_t* pcmHandle;
  217394. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217395. {
  217396. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  217397. getDeviceSampleRates (pcmHandle, rates);
  217398. snd_pcm_close (pcmHandle);
  217399. }
  217400. }
  217401. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  217402. if (snd_ctl_pcm_info (handle, info) >= 0)
  217403. {
  217404. snd_pcm_t* pcmHandle;
  217405. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217406. {
  217407. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  217408. if (rates.size() == 0)
  217409. getDeviceSampleRates (pcmHandle, rates);
  217410. snd_pcm_close (pcmHandle);
  217411. }
  217412. }
  217413. snd_ctl_close (handle);
  217414. }
  217415. }
  217416. class ALSADevice
  217417. {
  217418. public:
  217419. ALSADevice (const String& id,
  217420. const bool forInput)
  217421. : handle (0),
  217422. bitDepth (16),
  217423. numChannelsRunning (0),
  217424. isInput (forInput),
  217425. sampleFormat (AudioDataConverters::int16LE)
  217426. {
  217427. failed (snd_pcm_open (&handle, id,
  217428. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  217429. SND_PCM_ASYNC));
  217430. }
  217431. ~ALSADevice()
  217432. {
  217433. if (handle != 0)
  217434. snd_pcm_close (handle);
  217435. }
  217436. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  217437. {
  217438. if (handle == 0)
  217439. return false;
  217440. snd_pcm_hw_params_t* hwParams;
  217441. snd_pcm_hw_params_alloca (&hwParams);
  217442. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  217443. return false;
  217444. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  217445. isInterleaved = false;
  217446. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  217447. isInterleaved = true;
  217448. else
  217449. {
  217450. jassertfalse
  217451. return false;
  217452. }
  217453. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  217454. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  217455. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  217456. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  217457. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  217458. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  217459. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  217460. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  217461. bitDepth = 0;
  217462. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  217463. {
  217464. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  217465. {
  217466. bitDepth = formatsToTry [i + 1];
  217467. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  217468. break;
  217469. }
  217470. }
  217471. if (bitDepth == 0)
  217472. {
  217473. error = "device doesn't support a compatible PCM format";
  217474. DBG (T("ALSA error: ") + error + T("\n"));
  217475. return false;
  217476. }
  217477. int dir = 0;
  217478. unsigned int periods = 4;
  217479. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  217480. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  217481. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  217482. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  217483. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  217484. || failed (snd_pcm_hw_params (handle, hwParams)))
  217485. {
  217486. return false;
  217487. }
  217488. snd_pcm_sw_params_t* swParams;
  217489. snd_pcm_sw_params_alloca (&swParams);
  217490. snd_pcm_uframes_t boundary;
  217491. if (failed (snd_pcm_sw_params_current (handle, swParams))
  217492. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  217493. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  217494. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  217495. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  217496. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  217497. || failed (snd_pcm_sw_params (handle, swParams)))
  217498. {
  217499. return false;
  217500. }
  217501. /*
  217502. #ifdef JUCE_DEBUG
  217503. // enable this to dump the config of the devices that get opened
  217504. snd_output_t* out;
  217505. snd_output_stdio_attach (&out, stderr, 0);
  217506. snd_pcm_hw_params_dump (hwParams, out);
  217507. snd_pcm_sw_params_dump (swParams, out);
  217508. #endif
  217509. */
  217510. numChannelsRunning = numChannels;
  217511. return true;
  217512. }
  217513. bool write (float** const data, const int numSamples)
  217514. {
  217515. if (isInterleaved)
  217516. {
  217517. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217518. float* interleaved = (float*) scratch;
  217519. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  217520. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217521. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  217522. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217523. return false;
  217524. }
  217525. else
  217526. {
  217527. for (int i = 0; i < numChannelsRunning; ++i)
  217528. if (data[i] != 0)
  217529. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  217530. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  217531. if (failed (num))
  217532. {
  217533. if (num == -EPIPE)
  217534. {
  217535. if (failed (snd_pcm_prepare (handle)))
  217536. return false;
  217537. }
  217538. else if (num != -ESTRPIPE)
  217539. return false;
  217540. }
  217541. }
  217542. return true;
  217543. }
  217544. bool read (float** const data, const int numSamples)
  217545. {
  217546. if (isInterleaved)
  217547. {
  217548. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217549. float* interleaved = (float*) scratch;
  217550. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  217551. if (failed (num))
  217552. {
  217553. if (num == -EPIPE)
  217554. {
  217555. if (failed (snd_pcm_prepare (handle)))
  217556. return false;
  217557. }
  217558. else if (num != -ESTRPIPE)
  217559. return false;
  217560. }
  217561. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217562. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  217563. }
  217564. else
  217565. {
  217566. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  217567. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217568. return false;
  217569. for (int i = 0; i < numChannelsRunning; ++i)
  217570. if (data[i] != 0)
  217571. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  217572. }
  217573. return true;
  217574. }
  217575. juce_UseDebuggingNewOperator
  217576. snd_pcm_t* handle;
  217577. String error;
  217578. int bitDepth, numChannelsRunning;
  217579. private:
  217580. const bool isInput;
  217581. bool isInterleaved;
  217582. MemoryBlock scratch;
  217583. AudioDataConverters::DataFormat sampleFormat;
  217584. bool failed (const int errorNum)
  217585. {
  217586. if (errorNum >= 0)
  217587. return false;
  217588. error = snd_strerror (errorNum);
  217589. DBG (T("ALSA error: ") + error + T("\n"));
  217590. return true;
  217591. }
  217592. };
  217593. class ALSAThread : public Thread
  217594. {
  217595. public:
  217596. ALSAThread (const String& inputId_,
  217597. const String& outputId_)
  217598. : Thread ("Juce ALSA"),
  217599. sampleRate (0),
  217600. bufferSize (0),
  217601. callback (0),
  217602. inputId (inputId_),
  217603. outputId (outputId_),
  217604. outputDevice (0),
  217605. inputDevice (0),
  217606. numCallbacks (0),
  217607. totalNumInputChannels (0),
  217608. totalNumOutputChannels (0)
  217609. {
  217610. zeromem (outputChannelData, sizeof (outputChannelData));
  217611. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217612. zeromem (inputChannelData, sizeof (inputChannelData));
  217613. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217614. initialiseRatesAndChannels();
  217615. }
  217616. ~ALSAThread()
  217617. {
  217618. close();
  217619. }
  217620. void open (BitArray inputChannels,
  217621. BitArray outputChannels,
  217622. const double sampleRate_,
  217623. const int bufferSize_)
  217624. {
  217625. close();
  217626. error = String::empty;
  217627. sampleRate = sampleRate_;
  217628. bufferSize = bufferSize_;
  217629. currentInputChans.clear();
  217630. currentOutputChans.clear();
  217631. if (inputChannels.getHighestBit() >= 0)
  217632. {
  217633. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), minChansIn); ++i)
  217634. {
  217635. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217636. if (inputChannels[i])
  217637. {
  217638. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  217639. currentInputChans.setBit (i);
  217640. }
  217641. }
  217642. }
  217643. if (outputChannels.getHighestBit() >= 0)
  217644. {
  217645. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), minChansOut); ++i)
  217646. {
  217647. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217648. if (outputChannels[i])
  217649. {
  217650. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  217651. currentOutputChans.setBit (i);
  217652. }
  217653. }
  217654. }
  217655. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  217656. {
  217657. outputDevice = new ALSADevice (outputId, false);
  217658. if (outputDevice->error.isNotEmpty())
  217659. {
  217660. error = outputDevice->error;
  217661. deleteAndZero (outputDevice);
  217662. return;
  217663. }
  217664. currentOutputChans.setRange (0, minChansOut, true);
  217665. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  217666. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  217667. bufferSize))
  217668. {
  217669. error = outputDevice->error;
  217670. deleteAndZero (outputDevice);
  217671. return;
  217672. }
  217673. }
  217674. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  217675. {
  217676. inputDevice = new ALSADevice (inputId, true);
  217677. if (inputDevice->error.isNotEmpty())
  217678. {
  217679. error = inputDevice->error;
  217680. deleteAndZero (inputDevice);
  217681. return;
  217682. }
  217683. currentInputChans.setRange (0, minChansIn, true);
  217684. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  217685. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  217686. bufferSize))
  217687. {
  217688. error = inputDevice->error;
  217689. deleteAndZero (inputDevice);
  217690. return;
  217691. }
  217692. }
  217693. if (outputDevice == 0 && inputDevice == 0)
  217694. {
  217695. error = "no channels";
  217696. return;
  217697. }
  217698. if (outputDevice != 0 && inputDevice != 0)
  217699. {
  217700. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  217701. }
  217702. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  217703. return;
  217704. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  217705. return;
  217706. startThread (9);
  217707. int count = 1000;
  217708. while (numCallbacks == 0)
  217709. {
  217710. sleep (5);
  217711. if (--count < 0 || ! isThreadRunning())
  217712. {
  217713. error = "device didn't start";
  217714. break;
  217715. }
  217716. }
  217717. }
  217718. void close()
  217719. {
  217720. stopThread (6000);
  217721. deleteAndZero (inputDevice);
  217722. deleteAndZero (outputDevice);
  217723. for (int i = 0; i < maxNumChans; ++i)
  217724. {
  217725. juce_free (inputChannelData [i]);
  217726. juce_free (outputChannelData [i]);
  217727. }
  217728. zeromem (outputChannelData, sizeof (outputChannelData));
  217729. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217730. zeromem (inputChannelData, sizeof (inputChannelData));
  217731. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217732. totalNumOutputChannels = 0;
  217733. totalNumInputChannels = 0;
  217734. numCallbacks = 0;
  217735. }
  217736. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  217737. {
  217738. const ScopedLock sl (callbackLock);
  217739. callback = newCallback;
  217740. }
  217741. void run()
  217742. {
  217743. while (! threadShouldExit())
  217744. {
  217745. if (inputDevice != 0)
  217746. {
  217747. if (! inputDevice->read (inputChannelData, bufferSize))
  217748. {
  217749. DBG ("ALSA: read failure");
  217750. break;
  217751. }
  217752. }
  217753. if (threadShouldExit())
  217754. break;
  217755. {
  217756. const ScopedLock sl (callbackLock);
  217757. ++numCallbacks;
  217758. if (callback != 0)
  217759. {
  217760. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  217761. totalNumInputChannels,
  217762. outputChannelDataForCallback,
  217763. totalNumOutputChannels,
  217764. bufferSize);
  217765. }
  217766. else
  217767. {
  217768. for (int i = 0; i < totalNumOutputChannels; ++i)
  217769. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  217770. }
  217771. }
  217772. if (outputDevice != 0)
  217773. {
  217774. failed (snd_pcm_wait (outputDevice->handle, 2000));
  217775. if (threadShouldExit())
  217776. break;
  217777. failed (snd_pcm_avail_update (outputDevice->handle));
  217778. if (! outputDevice->write (outputChannelData, bufferSize))
  217779. {
  217780. DBG ("ALSA: write failure");
  217781. break;
  217782. }
  217783. }
  217784. }
  217785. }
  217786. int getBitDepth() const throw()
  217787. {
  217788. if (outputDevice != 0)
  217789. return outputDevice->bitDepth;
  217790. if (inputDevice != 0)
  217791. return inputDevice->bitDepth;
  217792. return 16;
  217793. }
  217794. juce_UseDebuggingNewOperator
  217795. String error;
  217796. double sampleRate;
  217797. int bufferSize;
  217798. BitArray currentInputChans, currentOutputChans;
  217799. Array <int> sampleRates;
  217800. StringArray channelNamesOut, channelNamesIn;
  217801. AudioIODeviceCallback* callback;
  217802. private:
  217803. const String inputId, outputId;
  217804. ALSADevice* outputDevice;
  217805. ALSADevice* inputDevice;
  217806. int numCallbacks;
  217807. CriticalSection callbackLock;
  217808. float* outputChannelData [maxNumChans];
  217809. float* outputChannelDataForCallback [maxNumChans];
  217810. int totalNumInputChannels;
  217811. float* inputChannelData [maxNumChans];
  217812. float* inputChannelDataForCallback [maxNumChans];
  217813. int totalNumOutputChannels;
  217814. unsigned int minChansOut, maxChansOut;
  217815. unsigned int minChansIn, maxChansIn;
  217816. bool failed (const int errorNum) throw()
  217817. {
  217818. if (errorNum >= 0)
  217819. return false;
  217820. error = snd_strerror (errorNum);
  217821. DBG (T("ALSA error: ") + error + T("\n"));
  217822. return true;
  217823. }
  217824. void initialiseRatesAndChannels() throw()
  217825. {
  217826. sampleRates.clear();
  217827. channelNamesOut.clear();
  217828. channelNamesIn.clear();
  217829. minChansOut = 0;
  217830. maxChansOut = 0;
  217831. minChansIn = 0;
  217832. maxChansIn = 0;
  217833. unsigned int dummy = 0;
  217834. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  217835. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  217836. unsigned int i;
  217837. for (i = 0; i < maxChansOut; ++i)
  217838. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  217839. for (i = 0; i < maxChansIn; ++i)
  217840. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  217841. }
  217842. };
  217843. class ALSAAudioIODevice : public AudioIODevice
  217844. {
  217845. public:
  217846. ALSAAudioIODevice (const String& deviceName,
  217847. const String& inputId_,
  217848. const String& outputId_)
  217849. : AudioIODevice (deviceName, T("ALSA")),
  217850. inputId (inputId_),
  217851. outputId (outputId_),
  217852. isOpen_ (false),
  217853. isStarted (false),
  217854. internal (0)
  217855. {
  217856. internal = new ALSAThread (inputId, outputId);
  217857. }
  217858. ~ALSAAudioIODevice()
  217859. {
  217860. delete internal;
  217861. }
  217862. const StringArray getOutputChannelNames()
  217863. {
  217864. return internal->channelNamesOut;
  217865. }
  217866. const StringArray getInputChannelNames()
  217867. {
  217868. return internal->channelNamesIn;
  217869. }
  217870. int getNumSampleRates()
  217871. {
  217872. return internal->sampleRates.size();
  217873. }
  217874. double getSampleRate (int index)
  217875. {
  217876. return internal->sampleRates [index];
  217877. }
  217878. int getNumBufferSizesAvailable()
  217879. {
  217880. return 50;
  217881. }
  217882. int getBufferSizeSamples (int index)
  217883. {
  217884. int n = 16;
  217885. for (int i = 0; i < index; ++i)
  217886. n += n < 64 ? 16
  217887. : (n < 512 ? 32
  217888. : (n < 1024 ? 64
  217889. : (n < 2048 ? 128 : 256)));
  217890. return n;
  217891. }
  217892. int getDefaultBufferSize()
  217893. {
  217894. return 512;
  217895. }
  217896. const String open (const BitArray& inputChannels,
  217897. const BitArray& outputChannels,
  217898. double sampleRate,
  217899. int bufferSizeSamples)
  217900. {
  217901. close();
  217902. if (bufferSizeSamples <= 0)
  217903. bufferSizeSamples = getDefaultBufferSize();
  217904. if (sampleRate <= 0)
  217905. {
  217906. for (int i = 0; i < getNumSampleRates(); ++i)
  217907. {
  217908. if (getSampleRate (i) >= 44100)
  217909. {
  217910. sampleRate = getSampleRate (i);
  217911. break;
  217912. }
  217913. }
  217914. }
  217915. internal->open (inputChannels, outputChannels,
  217916. sampleRate, bufferSizeSamples);
  217917. isOpen_ = internal->error.isEmpty();
  217918. return internal->error;
  217919. }
  217920. void close()
  217921. {
  217922. stop();
  217923. internal->close();
  217924. isOpen_ = false;
  217925. }
  217926. bool isOpen()
  217927. {
  217928. return isOpen_;
  217929. }
  217930. int getCurrentBufferSizeSamples()
  217931. {
  217932. return internal->bufferSize;
  217933. }
  217934. double getCurrentSampleRate()
  217935. {
  217936. return internal->sampleRate;
  217937. }
  217938. int getCurrentBitDepth()
  217939. {
  217940. return internal->getBitDepth();
  217941. }
  217942. const BitArray getActiveOutputChannels() const
  217943. {
  217944. return internal->currentOutputChans;
  217945. }
  217946. const BitArray getActiveInputChannels() const
  217947. {
  217948. return internal->currentInputChans;
  217949. }
  217950. int getOutputLatencyInSamples()
  217951. {
  217952. return 0;
  217953. }
  217954. int getInputLatencyInSamples()
  217955. {
  217956. return 0;
  217957. }
  217958. void start (AudioIODeviceCallback* callback)
  217959. {
  217960. if (! isOpen_)
  217961. callback = 0;
  217962. internal->setCallback (callback);
  217963. if (callback != 0)
  217964. callback->audioDeviceAboutToStart (this);
  217965. isStarted = (callback != 0);
  217966. }
  217967. void stop()
  217968. {
  217969. AudioIODeviceCallback* const oldCallback = internal->callback;
  217970. start (0);
  217971. if (oldCallback != 0)
  217972. oldCallback->audioDeviceStopped();
  217973. }
  217974. bool isPlaying()
  217975. {
  217976. return isStarted && internal->error.isEmpty();
  217977. }
  217978. const String getLastError()
  217979. {
  217980. return internal->error;
  217981. }
  217982. String inputId, outputId;
  217983. private:
  217984. bool isOpen_, isStarted;
  217985. ALSAThread* internal;
  217986. };
  217987. class ALSAAudioIODeviceType : public AudioIODeviceType
  217988. {
  217989. public:
  217990. ALSAAudioIODeviceType()
  217991. : AudioIODeviceType (T("ALSA")),
  217992. hasScanned (false)
  217993. {
  217994. }
  217995. ~ALSAAudioIODeviceType()
  217996. {
  217997. }
  217998. void scanForDevices()
  217999. {
  218000. if (hasScanned)
  218001. return;
  218002. hasScanned = true;
  218003. inputNames.clear();
  218004. inputIds.clear();
  218005. outputNames.clear();
  218006. outputIds.clear();
  218007. snd_ctl_t* handle;
  218008. snd_ctl_card_info_t* info;
  218009. snd_ctl_card_info_alloca (&info);
  218010. int cardNum = -1;
  218011. while (outputIds.size() + inputIds.size() <= 32)
  218012. {
  218013. snd_card_next (&cardNum);
  218014. if (cardNum < 0)
  218015. break;
  218016. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  218017. {
  218018. if (snd_ctl_card_info (handle, info) >= 0)
  218019. {
  218020. String cardId (snd_ctl_card_info_get_id (info));
  218021. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  218022. cardId = String (cardNum);
  218023. int device = -1;
  218024. for (;;)
  218025. {
  218026. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  218027. break;
  218028. String id, name;
  218029. id << "hw:" << cardId << ',' << device;
  218030. bool isInput, isOutput;
  218031. if (testDevice (id, isInput, isOutput))
  218032. {
  218033. name << snd_ctl_card_info_get_name (info);
  218034. if (name.isEmpty())
  218035. name = id;
  218036. if (isInput)
  218037. {
  218038. inputNames.add (name);
  218039. inputIds.add (id);
  218040. }
  218041. if (isOutput)
  218042. {
  218043. outputNames.add (name);
  218044. outputIds.add (id);
  218045. }
  218046. }
  218047. }
  218048. }
  218049. snd_ctl_close (handle);
  218050. }
  218051. }
  218052. inputNames.appendNumbersToDuplicates (false, true);
  218053. outputNames.appendNumbersToDuplicates (false, true);
  218054. }
  218055. const StringArray getDeviceNames (const bool wantInputNames) const
  218056. {
  218057. jassert (hasScanned); // need to call scanForDevices() before doing this
  218058. return wantInputNames ? inputNames : outputNames;
  218059. }
  218060. int getDefaultDeviceIndex (const bool forInput) const
  218061. {
  218062. jassert (hasScanned); // need to call scanForDevices() before doing this
  218063. return 0;
  218064. }
  218065. bool hasSeparateInputsAndOutputs() const { return true; }
  218066. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  218067. {
  218068. jassert (hasScanned); // need to call scanForDevices() before doing this
  218069. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  218070. if (d == 0)
  218071. return -1;
  218072. return asInput ? inputIds.indexOf (d->inputId)
  218073. : outputIds.indexOf (d->outputId);
  218074. }
  218075. AudioIODevice* createDevice (const String& outputDeviceName,
  218076. const String& inputDeviceName)
  218077. {
  218078. jassert (hasScanned); // need to call scanForDevices() before doing this
  218079. const int inputIndex = inputNames.indexOf (inputDeviceName);
  218080. const int outputIndex = outputNames.indexOf (outputDeviceName);
  218081. String deviceName (outputDeviceName);
  218082. if (deviceName.isEmpty())
  218083. deviceName = inputDeviceName;
  218084. if (index >= 0)
  218085. return new ALSAAudioIODevice (deviceName,
  218086. inputIds [inputIndex],
  218087. outputIds [outputIndex]);
  218088. return 0;
  218089. }
  218090. juce_UseDebuggingNewOperator
  218091. private:
  218092. StringArray inputNames, outputNames, inputIds, outputIds;
  218093. bool hasScanned;
  218094. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  218095. {
  218096. unsigned int minChansOut = 0, maxChansOut = 0;
  218097. unsigned int minChansIn = 0, maxChansIn = 0;
  218098. Array <int> rates;
  218099. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  218100. DBG (T("ALSA device: ") + id
  218101. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  218102. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  218103. + T(" rates=") + String (rates.size()));
  218104. isInput = maxChansIn > 0;
  218105. isOutput = maxChansOut > 0;
  218106. return (isInput || isOutput) && rates.size() > 0;
  218107. }
  218108. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  218109. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  218110. };
  218111. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  218112. {
  218113. return new ALSAAudioIODeviceType();
  218114. }
  218115. #endif
  218116. /********* End of inlined file: juce_linux_Audio.cpp *********/
  218117. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  218118. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218119. // compiled on its own).
  218120. #ifdef JUCE_INCLUDED_FILE
  218121. #if JUCE_ALSA
  218122. static snd_seq_t* iterateDevices (const bool forInput,
  218123. StringArray& deviceNamesFound,
  218124. const int deviceIndexToOpen)
  218125. {
  218126. snd_seq_t* returnedHandle = 0;
  218127. snd_seq_t* seqHandle;
  218128. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  218129. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  218130. {
  218131. snd_seq_system_info_t* systemInfo;
  218132. snd_seq_client_info_t* clientInfo;
  218133. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  218134. {
  218135. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  218136. && snd_seq_client_info_malloc (&clientInfo) == 0)
  218137. {
  218138. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  218139. while (--numClients >= 0 && returnedHandle == 0)
  218140. {
  218141. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  218142. {
  218143. snd_seq_port_info_t* portInfo;
  218144. if (snd_seq_port_info_malloc (&portInfo) == 0)
  218145. {
  218146. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  218147. const int client = snd_seq_client_info_get_client (clientInfo);
  218148. snd_seq_port_info_set_client (portInfo, client);
  218149. snd_seq_port_info_set_port (portInfo, -1);
  218150. while (--numPorts >= 0)
  218151. {
  218152. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  218153. && (snd_seq_port_info_get_capability (portInfo)
  218154. & (forInput ? SND_SEQ_PORT_CAP_READ
  218155. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  218156. {
  218157. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  218158. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  218159. {
  218160. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  218161. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  218162. if (sourcePort != -1)
  218163. {
  218164. snd_seq_set_client_name (seqHandle,
  218165. forInput ? "Juce Midi Input"
  218166. : "Juce Midi Output");
  218167. const int portId
  218168. = snd_seq_create_simple_port (seqHandle,
  218169. forInput ? "Juce Midi In Port"
  218170. : "Juce Midi Out Port",
  218171. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218172. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218173. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218174. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  218175. returnedHandle = seqHandle;
  218176. }
  218177. }
  218178. }
  218179. }
  218180. snd_seq_port_info_free (portInfo);
  218181. }
  218182. }
  218183. }
  218184. snd_seq_client_info_free (clientInfo);
  218185. }
  218186. snd_seq_system_info_free (systemInfo);
  218187. }
  218188. if (returnedHandle == 0)
  218189. snd_seq_close (seqHandle);
  218190. }
  218191. deviceNamesFound.appendNumbersToDuplicates (true, true);
  218192. return returnedHandle;
  218193. }
  218194. static snd_seq_t* createDevice (const bool forInput,
  218195. const String& deviceNameToOpen)
  218196. {
  218197. snd_seq_t* seqHandle = 0;
  218198. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  218199. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  218200. {
  218201. snd_seq_set_client_name (seqHandle,
  218202. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  218203. : (deviceNameToOpen + T(" Output"))));
  218204. const int portId
  218205. = snd_seq_create_simple_port (seqHandle,
  218206. forInput ? "in"
  218207. : "out",
  218208. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218209. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218210. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  218211. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218212. if (portId < 0)
  218213. {
  218214. snd_seq_close (seqHandle);
  218215. seqHandle = 0;
  218216. }
  218217. }
  218218. return seqHandle;
  218219. }
  218220. class MidiOutputDevice
  218221. {
  218222. public:
  218223. MidiOutputDevice (MidiOutput* const midiOutput_,
  218224. snd_seq_t* const seqHandle_)
  218225. :
  218226. midiOutput (midiOutput_),
  218227. seqHandle (seqHandle_),
  218228. maxEventSize (16 * 1024)
  218229. {
  218230. jassert (seqHandle != 0 && midiOutput != 0);
  218231. snd_midi_event_new (maxEventSize, &midiParser);
  218232. }
  218233. ~MidiOutputDevice()
  218234. {
  218235. snd_midi_event_free (midiParser);
  218236. snd_seq_close (seqHandle);
  218237. }
  218238. void sendMessageNow (const MidiMessage& message)
  218239. {
  218240. if (message.getRawDataSize() > maxEventSize)
  218241. {
  218242. maxEventSize = message.getRawDataSize();
  218243. snd_midi_event_free (midiParser);
  218244. snd_midi_event_new (maxEventSize, &midiParser);
  218245. }
  218246. snd_seq_event_t event;
  218247. snd_seq_ev_clear (&event);
  218248. snd_midi_event_encode (midiParser,
  218249. message.getRawData(),
  218250. message.getRawDataSize(),
  218251. &event);
  218252. snd_midi_event_reset_encode (midiParser);
  218253. snd_seq_ev_set_source (&event, 0);
  218254. snd_seq_ev_set_subs (&event);
  218255. snd_seq_ev_set_direct (&event);
  218256. snd_seq_event_output (seqHandle, &event);
  218257. snd_seq_drain_output (seqHandle);
  218258. }
  218259. juce_UseDebuggingNewOperator
  218260. private:
  218261. MidiOutput* const midiOutput;
  218262. snd_seq_t* const seqHandle;
  218263. snd_midi_event_t* midiParser;
  218264. int maxEventSize;
  218265. };
  218266. const StringArray MidiOutput::getDevices()
  218267. {
  218268. StringArray devices;
  218269. iterateDevices (false, devices, -1);
  218270. return devices;
  218271. }
  218272. int MidiOutput::getDefaultDeviceIndex()
  218273. {
  218274. return 0;
  218275. }
  218276. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  218277. {
  218278. MidiOutput* newDevice = 0;
  218279. StringArray devices;
  218280. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  218281. if (handle != 0)
  218282. {
  218283. newDevice = new MidiOutput();
  218284. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218285. }
  218286. return newDevice;
  218287. }
  218288. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  218289. {
  218290. MidiOutput* newDevice = 0;
  218291. snd_seq_t* const handle = createDevice (false, deviceName);
  218292. if (handle != 0)
  218293. {
  218294. newDevice = new MidiOutput();
  218295. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218296. }
  218297. return newDevice;
  218298. }
  218299. MidiOutput::~MidiOutput()
  218300. {
  218301. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  218302. delete device;
  218303. }
  218304. void MidiOutput::reset()
  218305. {
  218306. }
  218307. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218308. {
  218309. return false;
  218310. }
  218311. void MidiOutput::setVolume (float leftVol, float rightVol)
  218312. {
  218313. }
  218314. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218315. {
  218316. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  218317. }
  218318. class MidiInputThread : public Thread
  218319. {
  218320. public:
  218321. MidiInputThread (MidiInput* const midiInput_,
  218322. snd_seq_t* const seqHandle_,
  218323. MidiInputCallback* const callback_)
  218324. : Thread (T("Juce MIDI Input")),
  218325. midiInput (midiInput_),
  218326. seqHandle (seqHandle_),
  218327. callback (callback_)
  218328. {
  218329. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  218330. }
  218331. ~MidiInputThread()
  218332. {
  218333. snd_seq_close (seqHandle);
  218334. }
  218335. void run()
  218336. {
  218337. const int maxEventSize = 16 * 1024;
  218338. snd_midi_event_t* midiParser;
  218339. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  218340. {
  218341. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  218342. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  218343. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  218344. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  218345. while (! threadShouldExit())
  218346. {
  218347. if (poll (pfd, numPfds, 500) > 0)
  218348. {
  218349. snd_seq_event_t* inputEvent = 0;
  218350. snd_seq_nonblock (seqHandle, 1);
  218351. do
  218352. {
  218353. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  218354. {
  218355. // xxx what about SYSEXes that are too big for the buffer?
  218356. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  218357. snd_midi_event_reset_decode (midiParser);
  218358. if (numBytes > 0)
  218359. {
  218360. const MidiMessage message ((const uint8*) buffer,
  218361. numBytes,
  218362. Time::getMillisecondCounter() * 0.001);
  218363. callback->handleIncomingMidiMessage (midiInput, message);
  218364. }
  218365. snd_seq_free_event (inputEvent);
  218366. }
  218367. }
  218368. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  218369. snd_seq_free_event (inputEvent);
  218370. }
  218371. }
  218372. snd_midi_event_free (midiParser);
  218373. juce_free (buffer);
  218374. }
  218375. };
  218376. juce_UseDebuggingNewOperator
  218377. private:
  218378. MidiInput* const midiInput;
  218379. snd_seq_t* const seqHandle;
  218380. MidiInputCallback* const callback;
  218381. };
  218382. MidiInput::MidiInput (const String& name_)
  218383. : name (name_),
  218384. internal (0)
  218385. {
  218386. }
  218387. MidiInput::~MidiInput()
  218388. {
  218389. stop();
  218390. MidiInputThread* const thread = (MidiInputThread*) internal;
  218391. delete thread;
  218392. }
  218393. void MidiInput::start()
  218394. {
  218395. ((MidiInputThread*) internal)->startThread();
  218396. }
  218397. void MidiInput::stop()
  218398. {
  218399. ((MidiInputThread*) internal)->stopThread (3000);
  218400. }
  218401. int MidiInput::getDefaultDeviceIndex()
  218402. {
  218403. return 0;
  218404. }
  218405. const StringArray MidiInput::getDevices()
  218406. {
  218407. StringArray devices;
  218408. iterateDevices (true, devices, -1);
  218409. return devices;
  218410. }
  218411. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  218412. {
  218413. MidiInput* newDevice = 0;
  218414. StringArray devices;
  218415. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  218416. if (handle != 0)
  218417. {
  218418. newDevice = new MidiInput (devices [deviceIndex]);
  218419. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218420. }
  218421. return newDevice;
  218422. }
  218423. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  218424. {
  218425. MidiInput* newDevice = 0;
  218426. snd_seq_t* const handle = createDevice (true, deviceName);
  218427. if (handle != 0)
  218428. {
  218429. newDevice = new MidiInput (deviceName);
  218430. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218431. }
  218432. return newDevice;
  218433. }
  218434. #else
  218435. // (These are just stub functions if ALSA is unavailable...)
  218436. const StringArray MidiOutput::getDevices() { return StringArray(); }
  218437. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  218438. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  218439. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  218440. MidiOutput::~MidiOutput() {}
  218441. void MidiOutput::reset() {}
  218442. bool MidiOutput::getVolume (float&, float&) { return false; }
  218443. void MidiOutput::setVolume (float, float) {}
  218444. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  218445. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  218446. MidiInput::~MidiInput() {}
  218447. void MidiInput::start() {}
  218448. void MidiInput::stop() {}
  218449. int MidiInput::getDefaultDeviceIndex() { return 0; }
  218450. const StringArray MidiInput::getDevices() { return StringArray(); }
  218451. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  218452. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  218453. #endif
  218454. #endif
  218455. /********* End of inlined file: juce_linux_Midi.cpp *********/
  218456. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  218457. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218458. // compiled on its own).
  218459. #ifdef JUCE_INCLUDED_FILE
  218460. AudioCDReader::AudioCDReader()
  218461. : AudioFormatReader (0, T("CD Audio"))
  218462. {
  218463. }
  218464. const StringArray AudioCDReader::getAvailableCDNames()
  218465. {
  218466. StringArray names;
  218467. return names;
  218468. }
  218469. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  218470. {
  218471. return 0;
  218472. }
  218473. AudioCDReader::~AudioCDReader()
  218474. {
  218475. }
  218476. void AudioCDReader::refreshTrackLengths()
  218477. {
  218478. }
  218479. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  218480. int64 startSampleInFile, int numSamples)
  218481. {
  218482. return false;
  218483. }
  218484. bool AudioCDReader::isCDStillPresent() const
  218485. {
  218486. return false;
  218487. }
  218488. int AudioCDReader::getNumTracks() const
  218489. {
  218490. return 0;
  218491. }
  218492. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  218493. {
  218494. return 0;
  218495. }
  218496. bool AudioCDReader::isTrackAudio (int trackNum) const
  218497. {
  218498. return false;
  218499. }
  218500. void AudioCDReader::enableIndexScanning (bool b)
  218501. {
  218502. }
  218503. int AudioCDReader::getLastIndex() const
  218504. {
  218505. return 0;
  218506. }
  218507. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  218508. {
  218509. return Array<int>();
  218510. }
  218511. int AudioCDReader::getCDDBId()
  218512. {
  218513. return 0;
  218514. }
  218515. #endif
  218516. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  218517. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  218518. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218519. // compiled on its own).
  218520. #ifdef JUCE_INCLUDED_FILE
  218521. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218522. const String& title,
  218523. const File& file,
  218524. const String& filters,
  218525. bool isDirectory,
  218526. bool isSave,
  218527. bool warnAboutOverwritingExistingFiles,
  218528. bool selectMultipleFiles,
  218529. FilePreviewComponent* previewComponent)
  218530. {
  218531. //xxx ain't got one!
  218532. jassertfalse
  218533. }
  218534. #endif
  218535. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  218536. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218537. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218538. // compiled on its own).
  218539. #ifdef JUCE_INCLUDED_FILE
  218540. #if JUCE_WEB_BROWSER
  218541. /*
  218542. Sorry.. This class isn't implemented on Linux!
  218543. */
  218544. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  218545. : browser (0),
  218546. blankPageShown (false),
  218547. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  218548. {
  218549. setOpaque (true);
  218550. }
  218551. WebBrowserComponent::~WebBrowserComponent()
  218552. {
  218553. }
  218554. void WebBrowserComponent::goToURL (const String& url,
  218555. const StringArray* headers,
  218556. const MemoryBlock* postData)
  218557. {
  218558. lastURL = url;
  218559. lastHeaders.clear();
  218560. if (headers != 0)
  218561. lastHeaders = *headers;
  218562. lastPostData.setSize (0);
  218563. if (postData != 0)
  218564. lastPostData = *postData;
  218565. blankPageShown = false;
  218566. }
  218567. void WebBrowserComponent::stop()
  218568. {
  218569. }
  218570. void WebBrowserComponent::goBack()
  218571. {
  218572. lastURL = String::empty;
  218573. blankPageShown = false;
  218574. }
  218575. void WebBrowserComponent::goForward()
  218576. {
  218577. lastURL = String::empty;
  218578. }
  218579. void WebBrowserComponent::refresh()
  218580. {
  218581. }
  218582. void WebBrowserComponent::paint (Graphics& g)
  218583. {
  218584. g.fillAll (Colours::white);
  218585. }
  218586. void WebBrowserComponent::checkWindowAssociation()
  218587. {
  218588. }
  218589. void WebBrowserComponent::reloadLastURL()
  218590. {
  218591. if (lastURL.isNotEmpty())
  218592. {
  218593. goToURL (lastURL, &lastHeaders, &lastPostData);
  218594. lastURL = String::empty;
  218595. }
  218596. }
  218597. void WebBrowserComponent::parentHierarchyChanged()
  218598. {
  218599. checkWindowAssociation();
  218600. }
  218601. void WebBrowserComponent::resized()
  218602. {
  218603. }
  218604. void WebBrowserComponent::visibilityChanged()
  218605. {
  218606. checkWindowAssociation();
  218607. }
  218608. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  218609. {
  218610. return true;
  218611. }
  218612. #endif
  218613. #endif
  218614. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218615. #endif
  218616. END_JUCE_NAMESPACE
  218617. /********* End of inlined file: juce_linux_NativeCode.cpp *********/
  218618. #endif
  218619. #if JUCE_MAC || JUCE_IPHONE
  218620. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  218621. /*
  218622. This file wraps together all the mac-specific code, so that
  218623. we can include all the native headers just once, and compile all our
  218624. platform-specific stuff in one big lump, keeping it out of the way of
  218625. the rest of the codebase.
  218626. */
  218627. BEGIN_JUCE_NAMESPACE
  218628. #undef Point
  218629. #define JUCE_INCLUDED_FILE 1
  218630. // Now include the actual code files..
  218631. /********* Start of inlined file: juce_mac_ObjCSuffix.h *********/
  218632. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  218633. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  218634. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  218635. cross-linked so that when you make a call to a class that you thought was private, it ends up
  218636. actually calling into a similarly named class in the other module's address space.
  218637. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  218638. have unique names, and should avoid this problem.
  218639. If you're using the amalgamated version, you can just set this macro to something unique before
  218640. you include juce_amalgamated.cpp.
  218641. */
  218642. #ifndef JUCE_ObjCExtraSuffix
  218643. #define JUCE_ObjCExtraSuffix 3
  218644. #endif
  218645. #define appendMacro1(a, b, c, d) a ## _ ## b ## _ ## c ## _ ## d
  218646. #define appendMacro2(a, b, c, d) appendMacro1(a, b, c, d)
  218647. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_ObjCExtraSuffix)
  218648. /********* End of inlined file: juce_mac_ObjCSuffix.h *********/
  218649. /********* Start of inlined file: juce_mac_Strings.mm *********/
  218650. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218651. // compiled on its own).
  218652. #ifdef JUCE_INCLUDED_FILE
  218653. static const String nsStringToJuce (NSString* s)
  218654. {
  218655. return String::fromUTF8 ((uint8*) [s UTF8String]);
  218656. }
  218657. static NSString* juceStringToNS (const String& s)
  218658. {
  218659. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  218660. }
  218661. static const String convertUTF16ToString (const UniChar* utf16)
  218662. {
  218663. String s;
  218664. while (*utf16 != 0)
  218665. s += (juce_wchar) *utf16++;
  218666. return s;
  218667. }
  218668. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  218669. {
  218670. String result;
  218671. if (cfString != 0)
  218672. {
  218673. #if JUCE_STRINGS_ARE_UNICODE
  218674. CFRange range = { 0, CFStringGetLength (cfString) };
  218675. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  218676. CFStringGetCharacters (cfString, range, u);
  218677. u[range.length] = 0;
  218678. result = convertUTF16ToString (u);
  218679. juce_free (u);
  218680. #else
  218681. const int len = CFStringGetLength (cfString);
  218682. char* buffer = (char*) juce_malloc (len + 1);
  218683. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  218684. result = buffer;
  218685. juce_free (buffer);
  218686. #endif
  218687. }
  218688. return result;
  218689. }
  218690. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  218691. {
  218692. #if JUCE_STRINGS_ARE_UNICODE
  218693. const int len = s.length();
  218694. const juce_wchar* t = (const juce_wchar*) s;
  218695. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  218696. for (int i = 0; i <= len; ++i)
  218697. temp[i] = t[i];
  218698. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  218699. juce_free (temp);
  218700. return result;
  218701. #else
  218702. return CFStringCreateWithCString (kCFAllocatorDefault,
  218703. (const char*) s,
  218704. CFStringGetSystemEncoding());
  218705. #endif
  218706. }
  218707. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  218708. {
  218709. #if JUCE_IPHONE
  218710. const ScopedAutoReleasePool pool;
  218711. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  218712. #else
  218713. UnicodeMapping map;
  218714. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218715. kUnicodeNoSubset,
  218716. kTextEncodingDefaultFormat);
  218717. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218718. kUnicodeCanonicalCompVariant,
  218719. kTextEncodingDefaultFormat);
  218720. map.mappingVersion = kUnicodeUseLatestMapping;
  218721. UnicodeToTextInfo conversionInfo = 0;
  218722. String result;
  218723. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  218724. {
  218725. const int len = s.length();
  218726. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218727. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218728. for (int i = 0; i <= len; ++i)
  218729. tempIn[i] = s[i];
  218730. ByteCount bytesRead = 0;
  218731. ByteCount outputBufferSize = 0;
  218732. if (ConvertFromUnicodeToText (conversionInfo,
  218733. len * sizeof (UniChar), tempIn,
  218734. kUnicodeDefaultDirectionMask,
  218735. 0, 0, 0, 0,
  218736. len * sizeof (UniChar), &bytesRead,
  218737. &outputBufferSize, tempOut) == noErr)
  218738. {
  218739. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  218740. tchar* t = const_cast <tchar*> ((const tchar*) result);
  218741. unsigned int i;
  218742. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  218743. t[i] = (tchar) tempOut[i];
  218744. t[i] = 0;
  218745. }
  218746. juce_free (tempIn);
  218747. juce_free (tempOut);
  218748. DisposeUnicodeToTextInfo (&conversionInfo);
  218749. }
  218750. return result;
  218751. #endif
  218752. }
  218753. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218754. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  218755. {
  218756. #if JUCE_IPHONE
  218757. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  218758. forPasteboardType: @"public.text"];
  218759. #else
  218760. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  218761. owner: nil];
  218762. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  218763. forType: NSStringPboardType];
  218764. #endif
  218765. }
  218766. const String SystemClipboard::getTextFromClipboard() throw()
  218767. {
  218768. #if JUCE_IPHONE
  218769. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  218770. #else
  218771. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  218772. #endif
  218773. return text == 0 ? String::empty
  218774. : nsStringToJuce (text);
  218775. }
  218776. #endif
  218777. #endif
  218778. /********* End of inlined file: juce_mac_Strings.mm *********/
  218779. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  218780. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218781. // compiled on its own).
  218782. #ifdef JUCE_INCLUDED_FILE
  218783. static int64 highResTimerFrequency = 0;
  218784. static double highResTimerToMillisecRatio = 0;
  218785. #if JUCE_INTEL
  218786. static void juce_getCpuVendor (char* const v) throw()
  218787. {
  218788. int vendor[4];
  218789. zerostruct (vendor);
  218790. int dummy = 0;
  218791. asm ("mov %%ebx, %%esi \n\t"
  218792. "cpuid \n\t"
  218793. "xchg %%esi, %%ebx"
  218794. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  218795. memcpy (v, vendor, 16);
  218796. }
  218797. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  218798. {
  218799. unsigned int cpu = 0;
  218800. unsigned int ext = 0;
  218801. unsigned int family = 0;
  218802. unsigned int dummy = 0;
  218803. asm ("mov %%ebx, %%esi \n\t"
  218804. "cpuid \n\t"
  218805. "xchg %%esi, %%ebx"
  218806. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  218807. familyModel = family;
  218808. extFeatures = ext;
  218809. return cpu;
  218810. }
  218811. struct CPUFlags
  218812. {
  218813. bool hasMMX : 1;
  218814. bool hasSSE : 1;
  218815. bool hasSSE2 : 1;
  218816. bool has3DNow : 1;
  218817. };
  218818. static CPUFlags cpuFlags;
  218819. #endif
  218820. void SystemStats::initialiseStats() throw()
  218821. {
  218822. static bool initialised = false;
  218823. if (! initialised)
  218824. {
  218825. initialised = true;
  218826. #if JUCE_MAC
  218827. // extremely annoying: adding this line stops the apple menu items from working. Of
  218828. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  218829. // any events.
  218830. //NSApplicationLoad();
  218831. [NSApplication sharedApplication];
  218832. #endif
  218833. #if JUCE_INTEL
  218834. {
  218835. unsigned int familyModel, extFeatures;
  218836. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  218837. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  218838. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  218839. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  218840. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  218841. }
  218842. #endif
  218843. mach_timebase_info_data_t timebase;
  218844. (void) mach_timebase_info (&timebase);
  218845. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  218846. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  218847. String s (SystemStats::getJUCEVersion());
  218848. rlimit lim;
  218849. getrlimit (RLIMIT_NOFILE, &lim);
  218850. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  218851. setrlimit (RLIMIT_NOFILE, &lim);
  218852. }
  218853. }
  218854. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  218855. {
  218856. return MacOSX;
  218857. }
  218858. const String SystemStats::getOperatingSystemName() throw()
  218859. {
  218860. return T("Mac OS X");
  218861. }
  218862. bool SystemStats::isOperatingSystem64Bit() throw()
  218863. {
  218864. #if JUCE_64BIT
  218865. return true;
  218866. #else
  218867. //xxx not sure how to find this out?..
  218868. return false;
  218869. #endif
  218870. }
  218871. int SystemStats::getMemorySizeInMegabytes() throw()
  218872. {
  218873. uint64 mem = 0;
  218874. size_t memSize = sizeof (mem);
  218875. int mib[] = { CTL_HW, HW_MEMSIZE };
  218876. sysctl (mib, 2, &mem, &memSize, 0, 0);
  218877. return mem / (1024 * 1024);
  218878. }
  218879. bool SystemStats::hasMMX() throw()
  218880. {
  218881. #if JUCE_INTEL
  218882. return cpuFlags.hasMMX;
  218883. #else
  218884. return false;
  218885. #endif
  218886. }
  218887. bool SystemStats::hasSSE() throw()
  218888. {
  218889. #if JUCE_INTEL
  218890. return cpuFlags.hasSSE;
  218891. #else
  218892. return false;
  218893. #endif
  218894. }
  218895. bool SystemStats::hasSSE2() throw()
  218896. {
  218897. #if JUCE_INTEL
  218898. return cpuFlags.hasSSE2;
  218899. #else
  218900. return false;
  218901. #endif
  218902. }
  218903. bool SystemStats::has3DNow() throw()
  218904. {
  218905. #if JUCE_INTEL
  218906. return cpuFlags.has3DNow;
  218907. #else
  218908. return false;
  218909. #endif
  218910. }
  218911. const String SystemStats::getCpuVendor() throw()
  218912. {
  218913. #if JUCE_INTEL
  218914. char v [16];
  218915. juce_getCpuVendor (v);
  218916. return String (v, 16);
  218917. #else
  218918. return String::empty;
  218919. #endif
  218920. }
  218921. int SystemStats::getCpuSpeedInMegaherz() throw()
  218922. {
  218923. uint64 speedHz = 0;
  218924. size_t speedSize = sizeof (speedHz);
  218925. int mib[] = { CTL_HW, HW_CPU_FREQ };
  218926. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  218927. #if JUCE_BIG_ENDIAN
  218928. if (speedSize == 4)
  218929. speedHz >>= 32;
  218930. #endif
  218931. return speedHz / 1000000;
  218932. }
  218933. int SystemStats::getNumCpus() throw()
  218934. {
  218935. #if MACOS_10_4_OR_EARLIER
  218936. return MPProcessors();
  218937. #else
  218938. return [[NSProcessInfo processInfo] activeProcessorCount];
  218939. #endif
  218940. }
  218941. uint32 juce_millisecondsSinceStartup() throw()
  218942. {
  218943. return (uint32) (mach_absolute_time() * highResTimerToMillisecRatio);
  218944. }
  218945. double Time::getMillisecondCounterHiRes() throw()
  218946. {
  218947. return mach_absolute_time() * highResTimerToMillisecRatio;
  218948. }
  218949. int64 Time::getHighResolutionTicks() throw()
  218950. {
  218951. return (int64) mach_absolute_time();
  218952. }
  218953. int64 Time::getHighResolutionTicksPerSecond() throw()
  218954. {
  218955. return highResTimerFrequency;
  218956. }
  218957. int64 SystemStats::getClockCycleCounter() throw()
  218958. {
  218959. return (int64) mach_absolute_time();
  218960. }
  218961. bool Time::setSystemTimeToThisTime() const throw()
  218962. {
  218963. jassertfalse
  218964. return false;
  218965. }
  218966. int SystemStats::getPageSize() throw()
  218967. {
  218968. return NSPageSize();
  218969. }
  218970. void PlatformUtilities::fpuReset()
  218971. {
  218972. }
  218973. #endif
  218974. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  218975. /********* Start of inlined file: juce_mac_Network.mm *********/
  218976. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218977. // compiled on its own).
  218978. #if JUCE_INCLUDED_FILE
  218979. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  218980. {
  218981. #ifndef IFT_ETHER
  218982. #define IFT_ETHER 6
  218983. #endif
  218984. ifaddrs* addrs = 0;
  218985. int numResults = 0;
  218986. if (getifaddrs (&addrs) == 0)
  218987. {
  218988. const ifaddrs* cursor = addrs;
  218989. while (cursor != 0 && numResults < maxNum)
  218990. {
  218991. if (cursor->ifa_addr->sa_family == AF_LINK)
  218992. {
  218993. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  218994. if (sadd->sdl_type == IFT_ETHER)
  218995. {
  218996. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  218997. uint64 a = 0;
  218998. for (int i = 6; --i >= 0;)
  218999. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  219000. *addresses++ = (int64) a;
  219001. ++numResults;
  219002. }
  219003. }
  219004. cursor = cursor->ifa_next;
  219005. }
  219006. freeifaddrs (addrs);
  219007. }
  219008. return numResults;
  219009. }
  219010. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  219011. const String& emailSubject,
  219012. const String& bodyText,
  219013. const StringArray& filesToAttach)
  219014. {
  219015. #if JUCE_IPHONE
  219016. //xxx probably need to use MFMailComposeViewController
  219017. jassertfalse
  219018. return false;
  219019. #else
  219020. const ScopedAutoReleasePool pool;
  219021. String script;
  219022. script << "tell application \"Mail\"\r\n"
  219023. "set newMessage to make new outgoing message with properties {subject:\""
  219024. << emailSubject.replace (T("\""), T("\\\""))
  219025. << "\", content:\""
  219026. << bodyText.replace (T("\""), T("\\\""))
  219027. << "\" & return & return}\r\n"
  219028. "tell newMessage\r\n"
  219029. "set visible to true\r\n"
  219030. "set sender to \"sdfsdfsdfewf\"\r\n"
  219031. "make new to recipient at end of to recipients with properties {address:\""
  219032. << targetEmailAddress
  219033. << "\"}\r\n";
  219034. for (int i = 0; i < filesToAttach.size(); ++i)
  219035. {
  219036. script << "tell content\r\n"
  219037. "make new attachment with properties {file name:\""
  219038. << filesToAttach[i].replace (T("\""), T("\\\""))
  219039. << "\"} at after the last paragraph\r\n"
  219040. "end tell\r\n";
  219041. }
  219042. script << "end tell\r\n"
  219043. "end tell\r\n";
  219044. NSAppleScript* s = [[NSAppleScript alloc]
  219045. initWithSource: juceStringToNS (script)];
  219046. NSDictionary* error = 0;
  219047. const bool ok = [s executeAndReturnError: &error] != nil;
  219048. [s release];
  219049. return ok;
  219050. #endif
  219051. }
  219052. END_JUCE_NAMESPACE
  219053. using namespace JUCE_NAMESPACE;
  219054. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  219055. @interface JuceURLConnection : NSObject
  219056. {
  219057. @public
  219058. NSURLRequest* request;
  219059. NSURLConnection* connection;
  219060. NSMutableData* data;
  219061. Thread* runLoopThread;
  219062. bool initialised, hasFailed, hasFinished;
  219063. int position;
  219064. int64 contentLength;
  219065. NSLock* dataLock;
  219066. }
  219067. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  219068. - (void) dealloc;
  219069. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  219070. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  219071. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  219072. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  219073. - (BOOL) isOpen;
  219074. - (int) read: (char*) dest numBytes: (int) num;
  219075. - (int) readPosition;
  219076. - (void) stop;
  219077. - (void) createConnection;
  219078. @end
  219079. class JuceURLConnectionMessageThread : public Thread
  219080. {
  219081. JuceURLConnection* owner;
  219082. public:
  219083. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  219084. : Thread (T("http connection")),
  219085. owner (owner_)
  219086. {
  219087. }
  219088. ~JuceURLConnectionMessageThread()
  219089. {
  219090. stopThread (10000);
  219091. }
  219092. void run()
  219093. {
  219094. [owner createConnection];
  219095. while (! threadShouldExit())
  219096. {
  219097. const ScopedAutoReleasePool pool;
  219098. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  219099. }
  219100. }
  219101. };
  219102. @implementation JuceURLConnection
  219103. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  219104. withCallback: (URL::OpenStreamProgressCallback*) callback
  219105. withContext: (void*) context;
  219106. {
  219107. [super init];
  219108. request = req;
  219109. [request retain];
  219110. data = [[NSMutableData data] retain];
  219111. dataLock = [[NSLock alloc] init];
  219112. connection = 0;
  219113. initialised = false;
  219114. hasFailed = false;
  219115. hasFinished = false;
  219116. contentLength = -1;
  219117. runLoopThread = new JuceURLConnectionMessageThread (self);
  219118. runLoopThread->startThread();
  219119. while (runLoopThread->isThreadRunning() && ! initialised)
  219120. {
  219121. if (callback != 0)
  219122. callback (context, -1, [[request HTTPBody] length]);
  219123. Thread::sleep (1);
  219124. }
  219125. return self;
  219126. }
  219127. - (void) dealloc
  219128. {
  219129. [self stop];
  219130. delete runLoopThread;
  219131. [connection release];
  219132. [data release];
  219133. [dataLock release];
  219134. [request release];
  219135. [super dealloc];
  219136. }
  219137. - (void) createConnection
  219138. {
  219139. connection = [[NSURLConnection alloc] initWithRequest: request
  219140. delegate: [self retain]];
  219141. if (connection == nil)
  219142. runLoopThread->signalThreadShouldExit();
  219143. }
  219144. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  219145. {
  219146. [dataLock lock];
  219147. [data setLength: 0];
  219148. [dataLock unlock];
  219149. initialised = true;
  219150. contentLength = [response expectedContentLength];
  219151. }
  219152. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  219153. {
  219154. DBG (nsStringToJuce ([error description]));
  219155. hasFailed = true;
  219156. initialised = true;
  219157. runLoopThread->signalThreadShouldExit();
  219158. }
  219159. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  219160. {
  219161. [dataLock lock];
  219162. [data appendData: newData];
  219163. [dataLock unlock];
  219164. initialised = true;
  219165. }
  219166. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  219167. {
  219168. hasFinished = true;
  219169. initialised = true;
  219170. runLoopThread->signalThreadShouldExit();
  219171. }
  219172. - (BOOL) isOpen
  219173. {
  219174. return connection != 0 && ! hasFailed;
  219175. }
  219176. - (int) readPosition
  219177. {
  219178. return position;
  219179. }
  219180. - (int) read: (char*) dest numBytes: (int) numNeeded
  219181. {
  219182. int numDone = 0;
  219183. while (numNeeded > 0)
  219184. {
  219185. int available = jmin (numNeeded, [data length]);
  219186. if (available > 0)
  219187. {
  219188. [dataLock lock];
  219189. [data getBytes: dest length: available];
  219190. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  219191. [dataLock unlock];
  219192. numDone += available;
  219193. numNeeded -= available;
  219194. dest += available;
  219195. }
  219196. else
  219197. {
  219198. if (hasFailed || hasFinished)
  219199. break;
  219200. Thread::sleep (1);
  219201. }
  219202. }
  219203. position += numDone;
  219204. return numDone;
  219205. }
  219206. - (void) stop
  219207. {
  219208. [connection cancel];
  219209. runLoopThread->stopThread (10000);
  219210. }
  219211. @end
  219212. BEGIN_JUCE_NAMESPACE
  219213. bool juce_isOnLine()
  219214. {
  219215. return true;
  219216. }
  219217. void* juce_openInternetFile (const String& url,
  219218. const String& headers,
  219219. const MemoryBlock& postData,
  219220. const bool isPost,
  219221. URL::OpenStreamProgressCallback* callback,
  219222. void* callbackContext,
  219223. int timeOutMs)
  219224. {
  219225. const ScopedAutoReleasePool pool;
  219226. NSMutableURLRequest* req = [NSMutableURLRequest
  219227. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  219228. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219229. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  219230. if (req == nil)
  219231. return 0;
  219232. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  219233. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  219234. StringArray headerLines;
  219235. headerLines.addLines (headers);
  219236. headerLines.removeEmptyStrings (true);
  219237. for (int i = 0; i < headerLines.size(); ++i)
  219238. {
  219239. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219240. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219241. if (key.isNotEmpty() && value.isNotEmpty())
  219242. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  219243. }
  219244. if (isPost && postData.getSize() > 0)
  219245. {
  219246. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  219247. length: postData.getSize()]];
  219248. }
  219249. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  219250. withCallback: callback
  219251. withContext: callbackContext];
  219252. if ([s isOpen])
  219253. return s;
  219254. [s release];
  219255. return 0;
  219256. }
  219257. void juce_closeInternetFile (void* handle)
  219258. {
  219259. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219260. if (s != 0)
  219261. {
  219262. const ScopedAutoReleasePool pool;
  219263. [s stop];
  219264. [s release];
  219265. }
  219266. }
  219267. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  219268. {
  219269. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219270. if (s != 0)
  219271. {
  219272. const ScopedAutoReleasePool pool;
  219273. return [s read: (char*) buffer numBytes: bytesToRead];
  219274. }
  219275. return 0;
  219276. }
  219277. int64 juce_getInternetFileContentLength (void* handle)
  219278. {
  219279. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219280. if (s != 0)
  219281. return s->contentLength;
  219282. return -1;
  219283. }
  219284. int juce_seekInInternetFile (void* handle, int newPosition)
  219285. {
  219286. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219287. if (s != 0)
  219288. return [s readPosition];
  219289. return 0;
  219290. }
  219291. #endif
  219292. /********* End of inlined file: juce_mac_Network.mm *********/
  219293. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  219294. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219295. // compiled on its own).
  219296. #if JUCE_INCLUDED_FILE
  219297. struct NamedPipeInternal
  219298. {
  219299. String pipeInName, pipeOutName;
  219300. int pipeIn, pipeOut;
  219301. bool volatile createdPipe, blocked, stopReadOperation;
  219302. static void signalHandler (int) {}
  219303. };
  219304. void NamedPipe::cancelPendingReads()
  219305. {
  219306. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  219307. {
  219308. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219309. intern->stopReadOperation = true;
  219310. char buffer [1] = { 0 };
  219311. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  219312. (void) bytesWritten;
  219313. int timeout = 2000;
  219314. while (intern->blocked && --timeout >= 0)
  219315. Thread::sleep (2);
  219316. intern->stopReadOperation = false;
  219317. }
  219318. }
  219319. void NamedPipe::close()
  219320. {
  219321. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219322. if (intern != 0)
  219323. {
  219324. internal = 0;
  219325. if (intern->pipeIn != -1)
  219326. ::close (intern->pipeIn);
  219327. if (intern->pipeOut != -1)
  219328. ::close (intern->pipeOut);
  219329. if (intern->createdPipe)
  219330. {
  219331. unlink (intern->pipeInName);
  219332. unlink (intern->pipeOutName);
  219333. }
  219334. delete intern;
  219335. }
  219336. }
  219337. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  219338. {
  219339. close();
  219340. NamedPipeInternal* const intern = new NamedPipeInternal();
  219341. internal = intern;
  219342. intern->createdPipe = createPipe;
  219343. intern->blocked = false;
  219344. intern->stopReadOperation = false;
  219345. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  219346. siginterrupt (SIGPIPE, 1);
  219347. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  219348. intern->pipeInName = pipePath + T("_in");
  219349. intern->pipeOutName = pipePath + T("_out");
  219350. intern->pipeIn = -1;
  219351. intern->pipeOut = -1;
  219352. if (createPipe)
  219353. {
  219354. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  219355. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  219356. {
  219357. delete intern;
  219358. internal = 0;
  219359. return false;
  219360. }
  219361. }
  219362. return true;
  219363. }
  219364. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  219365. {
  219366. int bytesRead = -1;
  219367. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219368. if (intern != 0)
  219369. {
  219370. intern->blocked = true;
  219371. if (intern->pipeIn == -1)
  219372. {
  219373. if (intern->createdPipe)
  219374. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  219375. else
  219376. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  219377. if (intern->pipeIn == -1)
  219378. {
  219379. intern->blocked = false;
  219380. return -1;
  219381. }
  219382. }
  219383. bytesRead = 0;
  219384. char* p = (char*) destBuffer;
  219385. while (bytesRead < maxBytesToRead)
  219386. {
  219387. const int bytesThisTime = maxBytesToRead - bytesRead;
  219388. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  219389. if (numRead <= 0 || intern->stopReadOperation)
  219390. {
  219391. bytesRead = -1;
  219392. break;
  219393. }
  219394. bytesRead += numRead;
  219395. p += bytesRead;
  219396. }
  219397. intern->blocked = false;
  219398. }
  219399. return bytesRead;
  219400. }
  219401. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  219402. {
  219403. int bytesWritten = -1;
  219404. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219405. if (intern != 0)
  219406. {
  219407. if (intern->pipeOut == -1)
  219408. {
  219409. if (intern->createdPipe)
  219410. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  219411. else
  219412. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  219413. if (intern->pipeOut == -1)
  219414. {
  219415. return -1;
  219416. }
  219417. }
  219418. const char* p = (const char*) sourceBuffer;
  219419. bytesWritten = 0;
  219420. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  219421. while (bytesWritten < numBytesToWrite
  219422. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  219423. {
  219424. const int bytesThisTime = numBytesToWrite - bytesWritten;
  219425. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  219426. if (numWritten <= 0)
  219427. {
  219428. bytesWritten = -1;
  219429. break;
  219430. }
  219431. bytesWritten += numWritten;
  219432. p += bytesWritten;
  219433. }
  219434. }
  219435. return bytesWritten;
  219436. }
  219437. #endif
  219438. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  219439. /********* Start of inlined file: juce_mac_Threads.mm *********/
  219440. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219441. // compiled on its own).
  219442. #ifdef JUCE_INCLUDED_FILE
  219443. /*
  219444. Note that a lot of methods that you'd expect to find in this file actually
  219445. live in juce_posix_SharedCode.h!
  219446. */
  219447. void JUCE_API juce_threadEntryPoint (void*);
  219448. void* threadEntryProc (void* userData) throw()
  219449. {
  219450. const ScopedAutoReleasePool pool;
  219451. juce_threadEntryPoint (userData);
  219452. return 0;
  219453. }
  219454. void* juce_createThread (void* userData) throw()
  219455. {
  219456. pthread_t handle = 0;
  219457. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  219458. {
  219459. pthread_detach (handle);
  219460. return (void*) handle;
  219461. }
  219462. return 0;
  219463. }
  219464. void juce_killThread (void* handle) throw()
  219465. {
  219466. if (handle != 0)
  219467. pthread_cancel ((pthread_t) handle);
  219468. }
  219469. void juce_setCurrentThreadName (const String& /*name*/) throw()
  219470. {
  219471. }
  219472. Thread::ThreadID Thread::getCurrentThreadId() throw()
  219473. {
  219474. return (ThreadID) pthread_self();
  219475. }
  219476. bool juce_setThreadPriority (void* handle, int priority) throw()
  219477. {
  219478. if (handle == 0)
  219479. handle = (void*) pthread_self();
  219480. struct sched_param param;
  219481. int policy;
  219482. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  219483. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  219484. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  219485. }
  219486. void Thread::yield() throw()
  219487. {
  219488. sched_yield();
  219489. }
  219490. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  219491. {
  219492. // xxx
  219493. jassertfalse
  219494. }
  219495. bool Process::isForegroundProcess() throw()
  219496. {
  219497. #if JUCE_MAC
  219498. return [NSApp isActive];
  219499. #else
  219500. return true; // xxx change this if more than one app is ever possible on the iPhone!
  219501. #endif
  219502. }
  219503. void Process::raisePrivilege()
  219504. {
  219505. jassertfalse
  219506. }
  219507. void Process::lowerPrivilege()
  219508. {
  219509. jassertfalse
  219510. }
  219511. void Process::terminate()
  219512. {
  219513. exit (0);
  219514. }
  219515. void Process::setPriority (ProcessPriority p)
  219516. {
  219517. // xxx
  219518. }
  219519. #endif
  219520. /********* End of inlined file: juce_mac_Threads.mm *********/
  219521. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  219522. /*
  219523. This file contains posix routines that are common to both the Linux and Mac builds.
  219524. It gets included directly in the cpp files for these platforms.
  219525. */
  219526. CriticalSection::CriticalSection() throw()
  219527. {
  219528. pthread_mutexattr_t atts;
  219529. pthread_mutexattr_init (&atts);
  219530. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  219531. pthread_mutex_init (&internal, &atts);
  219532. }
  219533. CriticalSection::~CriticalSection() throw()
  219534. {
  219535. pthread_mutex_destroy (&internal);
  219536. }
  219537. void CriticalSection::enter() const throw()
  219538. {
  219539. pthread_mutex_lock (&internal);
  219540. }
  219541. bool CriticalSection::tryEnter() const throw()
  219542. {
  219543. return pthread_mutex_trylock (&internal) == 0;
  219544. }
  219545. void CriticalSection::exit() const throw()
  219546. {
  219547. pthread_mutex_unlock (&internal);
  219548. }
  219549. struct EventStruct
  219550. {
  219551. pthread_cond_t condition;
  219552. pthread_mutex_t mutex;
  219553. bool triggered;
  219554. };
  219555. WaitableEvent::WaitableEvent() throw()
  219556. {
  219557. EventStruct* const es = new EventStruct();
  219558. es->triggered = false;
  219559. pthread_cond_init (&es->condition, 0);
  219560. pthread_mutex_init (&es->mutex, 0);
  219561. internal = es;
  219562. }
  219563. WaitableEvent::~WaitableEvent() throw()
  219564. {
  219565. EventStruct* const es = (EventStruct*) internal;
  219566. pthread_cond_destroy (&es->condition);
  219567. pthread_mutex_destroy (&es->mutex);
  219568. delete es;
  219569. }
  219570. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  219571. {
  219572. EventStruct* const es = (EventStruct*) internal;
  219573. bool ok = true;
  219574. pthread_mutex_lock (&es->mutex);
  219575. if (timeOutMillisecs < 0)
  219576. {
  219577. while (! es->triggered)
  219578. pthread_cond_wait (&es->condition, &es->mutex);
  219579. }
  219580. else
  219581. {
  219582. while (! es->triggered)
  219583. {
  219584. struct timeval t;
  219585. gettimeofday (&t, 0);
  219586. struct timespec time;
  219587. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  219588. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  219589. if (time.tv_nsec >= 1000000000)
  219590. {
  219591. time.tv_nsec -= 1000000000;
  219592. time.tv_sec++;
  219593. }
  219594. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  219595. {
  219596. ok = false;
  219597. break;
  219598. }
  219599. }
  219600. }
  219601. es->triggered = false;
  219602. pthread_mutex_unlock (&es->mutex);
  219603. return ok;
  219604. }
  219605. void WaitableEvent::signal() const throw()
  219606. {
  219607. EventStruct* const es = (EventStruct*) internal;
  219608. pthread_mutex_lock (&es->mutex);
  219609. es->triggered = true;
  219610. pthread_cond_broadcast (&es->condition);
  219611. pthread_mutex_unlock (&es->mutex);
  219612. }
  219613. void WaitableEvent::reset() const throw()
  219614. {
  219615. EventStruct* const es = (EventStruct*) internal;
  219616. pthread_mutex_lock (&es->mutex);
  219617. es->triggered = false;
  219618. pthread_mutex_unlock (&es->mutex);
  219619. }
  219620. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  219621. {
  219622. struct timespec time;
  219623. time.tv_sec = millisecs / 1000;
  219624. time.tv_nsec = (millisecs % 1000) * 1000000;
  219625. nanosleep (&time, 0);
  219626. }
  219627. const tchar File::separator = T('/');
  219628. const tchar* File::separatorString = T("/");
  219629. bool juce_copyFile (const String& s, const String& d) throw();
  219630. static bool juce_stat (const String& fileName, struct stat& info) throw()
  219631. {
  219632. return fileName.isNotEmpty()
  219633. && (stat (fileName.toUTF8(), &info) == 0);
  219634. }
  219635. bool juce_isDirectory (const String& fileName) throw()
  219636. {
  219637. struct stat info;
  219638. return fileName.isEmpty()
  219639. || (juce_stat (fileName, info)
  219640. && ((info.st_mode & S_IFDIR) != 0));
  219641. }
  219642. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  219643. {
  219644. if (fileName.isEmpty())
  219645. return false;
  219646. const char* const fileNameUTF8 = fileName.toUTF8();
  219647. bool exists = access (fileNameUTF8, F_OK) == 0;
  219648. if (exists && dontCountDirectories)
  219649. {
  219650. struct stat info;
  219651. const int res = stat (fileNameUTF8, &info);
  219652. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  219653. exists = false;
  219654. }
  219655. return exists;
  219656. }
  219657. int64 juce_getFileSize (const String& fileName) throw()
  219658. {
  219659. struct stat info;
  219660. return juce_stat (fileName, info) ? info.st_size : 0;
  219661. }
  219662. bool juce_canWriteToFile (const String& fileName) throw()
  219663. {
  219664. return access (fileName.toUTF8(), W_OK) == 0;
  219665. }
  219666. bool juce_deleteFile (const String& fileName) throw()
  219667. {
  219668. if (juce_isDirectory (fileName))
  219669. return rmdir ((const char*) fileName.toUTF8()) == 0;
  219670. else
  219671. return remove ((const char*) fileName.toUTF8()) == 0;
  219672. }
  219673. bool juce_moveFile (const String& source, const String& dest) throw()
  219674. {
  219675. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  219676. return true;
  219677. if (juce_canWriteToFile (source)
  219678. && juce_copyFile (source, dest))
  219679. {
  219680. if (juce_deleteFile (source))
  219681. return true;
  219682. juce_deleteFile (dest);
  219683. }
  219684. return false;
  219685. }
  219686. void juce_createDirectory (const String& fileName) throw()
  219687. {
  219688. mkdir (fileName.toUTF8(), 0777);
  219689. }
  219690. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  219691. {
  219692. int flags = O_RDONLY;
  219693. if (forWriting)
  219694. {
  219695. if (juce_fileExists (fileName, false))
  219696. {
  219697. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  219698. if (f != -1)
  219699. lseek (f, 0, SEEK_END);
  219700. return (void*) f;
  219701. }
  219702. else
  219703. {
  219704. flags = O_RDWR + O_CREAT;
  219705. }
  219706. }
  219707. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  219708. }
  219709. void juce_fileClose (void* handle) throw()
  219710. {
  219711. if (handle != 0)
  219712. close ((int) (pointer_sized_int) handle);
  219713. }
  219714. int juce_fileRead (void* handle, void* buffer, int size) throw()
  219715. {
  219716. if (handle != 0)
  219717. return read ((int) (pointer_sized_int) handle, buffer, size);
  219718. return 0;
  219719. }
  219720. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  219721. {
  219722. if (handle != 0)
  219723. return write ((int) (pointer_sized_int) handle, buffer, size);
  219724. return 0;
  219725. }
  219726. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  219727. {
  219728. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  219729. return pos;
  219730. return -1;
  219731. }
  219732. int64 juce_fileGetPosition (void* handle) throw()
  219733. {
  219734. if (handle != 0)
  219735. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  219736. else
  219737. return -1;
  219738. }
  219739. void juce_fileFlush (void* handle) throw()
  219740. {
  219741. if (handle != 0)
  219742. fsync ((int) (pointer_sized_int) handle);
  219743. }
  219744. const File juce_getExecutableFile()
  219745. {
  219746. Dl_info exeInfo;
  219747. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  219748. return File (exeInfo.dli_fname);
  219749. }
  219750. // if this file doesn't exist, find a parent of it that does..
  219751. static bool doStatFS (const File* file, struct statfs& result) throw()
  219752. {
  219753. File f (*file);
  219754. for (int i = 5; --i >= 0;)
  219755. {
  219756. if (f.exists())
  219757. break;
  219758. f = f.getParentDirectory();
  219759. }
  219760. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  219761. }
  219762. int64 File::getBytesFreeOnVolume() const throw()
  219763. {
  219764. struct statfs buf;
  219765. if (doStatFS (this, buf))
  219766. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  219767. return 0;
  219768. }
  219769. int64 File::getVolumeTotalSize() const throw()
  219770. {
  219771. struct statfs buf;
  219772. if (doStatFS (this, buf))
  219773. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  219774. return 0;
  219775. }
  219776. const String juce_getVolumeLabel (const String& filenameOnVolume,
  219777. int& volumeSerialNumber) throw()
  219778. {
  219779. volumeSerialNumber = 0;
  219780. #if JUCE_MAC
  219781. struct VolAttrBuf
  219782. {
  219783. u_int32_t length;
  219784. attrreference_t mountPointRef;
  219785. char mountPointSpace [MAXPATHLEN];
  219786. } attrBuf;
  219787. struct attrlist attrList;
  219788. zerostruct (attrList);
  219789. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  219790. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  219791. File f (filenameOnVolume);
  219792. for (;;)
  219793. {
  219794. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  219795. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  219796. {
  219797. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  219798. (int) attrBuf.mountPointRef.attr_length);
  219799. }
  219800. const File parent (f.getParentDirectory());
  219801. if (f == parent)
  219802. break;
  219803. f = parent;
  219804. }
  219805. #endif
  219806. return String::empty;
  219807. }
  219808. void juce_runSystemCommand (const String& command)
  219809. {
  219810. int result = system ((const char*) command.toUTF8());
  219811. (void) result;
  219812. }
  219813. const String juce_getOutputFromCommand (const String& command)
  219814. {
  219815. // slight bodge here, as we just pipe the output into a temp file and read it...
  219816. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  219817. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  219818. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  219819. String result (tempFile.loadFileAsString());
  219820. tempFile.deleteFile();
  219821. return result;
  219822. }
  219823. #if JUCE_64BIT
  219824. #define filedesc ((long long) internal)
  219825. #else
  219826. #define filedesc ((int) internal)
  219827. #endif
  219828. InterProcessLock::InterProcessLock (const String& name_) throw()
  219829. : internal (0),
  219830. name (name_),
  219831. reentrancyLevel (0)
  219832. {
  219833. #if JUCE_MAC
  219834. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  219835. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  219836. #else
  219837. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  219838. #endif
  219839. temp.create();
  219840. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  219841. }
  219842. InterProcessLock::~InterProcessLock() throw()
  219843. {
  219844. while (reentrancyLevel > 0)
  219845. this->exit();
  219846. close (filedesc);
  219847. }
  219848. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  219849. {
  219850. if (internal == 0)
  219851. return false;
  219852. if (reentrancyLevel != 0)
  219853. return true;
  219854. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  219855. struct flock fl;
  219856. zerostruct (fl);
  219857. fl.l_whence = SEEK_SET;
  219858. fl.l_type = F_WRLCK;
  219859. for (;;)
  219860. {
  219861. const int result = fcntl (filedesc, F_SETLK, &fl);
  219862. if (result >= 0)
  219863. {
  219864. ++reentrancyLevel;
  219865. return true;
  219866. }
  219867. if (errno != EINTR)
  219868. {
  219869. if (timeOutMillisecs == 0
  219870. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  219871. break;
  219872. Thread::sleep (10);
  219873. }
  219874. }
  219875. return false;
  219876. }
  219877. void InterProcessLock::exit() throw()
  219878. {
  219879. if (reentrancyLevel > 0 && internal != 0)
  219880. {
  219881. --reentrancyLevel;
  219882. struct flock fl;
  219883. zerostruct (fl);
  219884. fl.l_whence = SEEK_SET;
  219885. fl.l_type = F_UNLCK;
  219886. for (;;)
  219887. {
  219888. const int result = fcntl (filedesc, F_SETLKW, &fl);
  219889. if (result >= 0 || errno != EINTR)
  219890. break;
  219891. }
  219892. }
  219893. }
  219894. /********* End of inlined file: juce_posix_SharedCode.h *********/
  219895. /********* Start of inlined file: juce_mac_Files.mm *********/
  219896. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219897. // compiled on its own).
  219898. #ifdef JUCE_INCLUDED_FILE
  219899. /*
  219900. Note that a lot of methods that you'd expect to find in this file actually
  219901. live in juce_posix_SharedCode.h!
  219902. */
  219903. void juce_getFileTimes (const String& fileName,
  219904. int64& modificationTime,
  219905. int64& accessTime,
  219906. int64& creationTime) throw()
  219907. {
  219908. modificationTime = 0;
  219909. accessTime = 0;
  219910. creationTime = 0;
  219911. struct stat info;
  219912. const int res = stat (fileName.toUTF8(), &info);
  219913. if (res == 0)
  219914. {
  219915. modificationTime = (int64) info.st_mtime * 1000;
  219916. accessTime = (int64) info.st_atime * 1000;
  219917. creationTime = (int64) info.st_ctime * 1000;
  219918. }
  219919. }
  219920. bool juce_setFileTimes (const String& fileName,
  219921. int64 modificationTime,
  219922. int64 accessTime,
  219923. int64 creationTime) throw()
  219924. {
  219925. struct utimbuf times;
  219926. times.actime = (time_t) (accessTime / 1000);
  219927. times.modtime = (time_t) (modificationTime / 1000);
  219928. return utime (fileName.toUTF8(), &times) == 0;
  219929. }
  219930. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  219931. {
  219932. struct stat info;
  219933. const int res = stat (fileName.toUTF8(), &info);
  219934. if (res != 0)
  219935. return false;
  219936. info.st_mode &= 0777; // Just permissions
  219937. if (isReadOnly)
  219938. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  219939. else
  219940. // Give everybody write permission?
  219941. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  219942. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  219943. }
  219944. bool juce_copyFile (const String& src, const String& dst) throw()
  219945. {
  219946. const ScopedAutoReleasePool pool;
  219947. NSFileManager* fm = [NSFileManager defaultManager];
  219948. return [fm fileExistsAtPath: juceStringToNS (src)]
  219949. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  219950. && [fm copyItemAtPath: juceStringToNS (src)
  219951. toPath: juceStringToNS (dst)
  219952. error: nil];
  219953. #else
  219954. && [fm copyPath: juceStringToNS (src)
  219955. toPath: juceStringToNS (dst)
  219956. handler: nil];
  219957. #endif
  219958. }
  219959. const StringArray juce_getFileSystemRoots() throw()
  219960. {
  219961. StringArray s;
  219962. s.add (T("/"));
  219963. return s;
  219964. }
  219965. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  219966. {
  219967. struct statfs buf;
  219968. if (doStatFS (f, buf))
  219969. {
  219970. const String type (buf.f_fstypename);
  219971. while (*types != 0)
  219972. if (type.equalsIgnoreCase (*types++))
  219973. return true;
  219974. }
  219975. return false;
  219976. }
  219977. bool File::isOnCDRomDrive() const throw()
  219978. {
  219979. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  219980. return isFileOnDriveType (this, (const char**) cdTypes);
  219981. }
  219982. bool File::isOnHardDisk() const throw()
  219983. {
  219984. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  219985. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  219986. }
  219987. bool File::isOnRemovableDrive() const throw()
  219988. {
  219989. #if JUCE_IPHONE
  219990. return false; // xxx is this possible?
  219991. #else
  219992. const ScopedAutoReleasePool pool;
  219993. BOOL removable = false;
  219994. [[NSWorkspace sharedWorkspace]
  219995. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  219996. isRemovable: &removable
  219997. isWritable: nil
  219998. isUnmountable: nil
  219999. description: nil
  220000. type: nil];
  220001. return removable;
  220002. #endif
  220003. }
  220004. static bool juce_isHiddenFile (const String& path) throw()
  220005. {
  220006. #if JUCE_IPHONE
  220007. return File (path).getFileName().startsWithChar (T('.'));
  220008. #else
  220009. FSRef ref;
  220010. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  220011. return false;
  220012. FSCatalogInfo info;
  220013. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  220014. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  220015. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  220016. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  220017. #endif
  220018. }
  220019. bool File::isHidden() const throw()
  220020. {
  220021. return juce_isHiddenFile (getFullPathName());
  220022. }
  220023. const File File::getSpecialLocation (const SpecialLocationType type)
  220024. {
  220025. const ScopedAutoReleasePool pool;
  220026. String resultPath;
  220027. switch (type)
  220028. {
  220029. case userHomeDirectory:
  220030. resultPath = nsStringToJuce (NSHomeDirectory());
  220031. break;
  220032. case userDocumentsDirectory:
  220033. resultPath = "~/Documents";
  220034. break;
  220035. case userDesktopDirectory:
  220036. resultPath = "~/Desktop";
  220037. break;
  220038. case userApplicationDataDirectory:
  220039. resultPath = "~/Library";
  220040. break;
  220041. case commonApplicationDataDirectory:
  220042. resultPath = "/Library";
  220043. break;
  220044. case globalApplicationsDirectory:
  220045. resultPath = "/Applications";
  220046. break;
  220047. case userMusicDirectory:
  220048. resultPath = "~/Music";
  220049. break;
  220050. case userMoviesDirectory:
  220051. resultPath = "~/Movies";
  220052. break;
  220053. case tempDirectory:
  220054. {
  220055. File tmp (T("~/Library/Caches/") + juce_getExecutableFile().getFileNameWithoutExtension());
  220056. tmp.createDirectory();
  220057. return tmp.getFullPathName();
  220058. }
  220059. case currentExecutableFile:
  220060. return juce_getExecutableFile();
  220061. case currentApplicationFile:
  220062. {
  220063. const File exe (juce_getExecutableFile());
  220064. const File parent (exe.getParentDirectory());
  220065. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  220066. ? parent.getParentDirectory().getParentDirectory()
  220067. : exe;
  220068. }
  220069. default:
  220070. jassertfalse // unknown type?
  220071. break;
  220072. }
  220073. if (resultPath != 0)
  220074. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  220075. return File::nonexistent;
  220076. }
  220077. const File File::getCurrentWorkingDirectory() throw()
  220078. {
  220079. char buf [2048];
  220080. getcwd (buf, sizeof(buf));
  220081. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  220082. }
  220083. bool File::setAsCurrentWorkingDirectory() const throw()
  220084. {
  220085. return chdir (getFullPathName().toUTF8()) == 0;
  220086. }
  220087. const String File::getVersion() const throw()
  220088. {
  220089. const ScopedAutoReleasePool pool;
  220090. String result;
  220091. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  220092. if (bundle != 0)
  220093. {
  220094. NSDictionary* info = [bundle infoDictionary];
  220095. if (info != 0)
  220096. {
  220097. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  220098. if (name != nil)
  220099. result = nsStringToJuce (name);
  220100. }
  220101. }
  220102. return result;
  220103. }
  220104. const File File::getLinkedTarget() const throw()
  220105. {
  220106. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  220107. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  220108. #else
  220109. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  220110. #endif
  220111. if (dest != nil)
  220112. return File (nsStringToJuce (dest));
  220113. return *this;
  220114. }
  220115. bool File::moveToTrash() const throw()
  220116. {
  220117. if (! exists())
  220118. return true;
  220119. #if JUCE_IPHONE
  220120. return deleteFile(); //xxx is there a trashcan on the iPhone?
  220121. #else
  220122. const ScopedAutoReleasePool pool;
  220123. NSString* p = juceStringToNS (getFullPathName());
  220124. return [[NSWorkspace sharedWorkspace]
  220125. performFileOperation: NSWorkspaceRecycleOperation
  220126. source: [p stringByDeletingLastPathComponent]
  220127. destination: @""
  220128. files: [NSArray arrayWithObject: [p lastPathComponent]]
  220129. tag: nil ];
  220130. #endif
  220131. }
  220132. struct FindFileStruct
  220133. {
  220134. NSDirectoryEnumerator* enumerator;
  220135. String parentDir, wildCard;
  220136. };
  220137. bool juce_findFileNext (void* handle, String& resultFile,
  220138. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  220139. {
  220140. FindFileStruct* ff = (FindFileStruct*) handle;
  220141. NSString* file;
  220142. const char* const wildcardUTF8 = ff->wildCard.toUTF8();
  220143. for (;;)
  220144. {
  220145. if (ff == 0 || (file = [ff->enumerator nextObject]) == 0)
  220146. return false;
  220147. [ff->enumerator skipDescendents];
  220148. resultFile = nsStringToJuce (file);
  220149. if (fnmatch (wildcardUTF8, resultFile.toUTF8(), FNM_CASEFOLD) != 0)
  220150. continue;
  220151. const String path (ff->parentDir + resultFile);
  220152. if (isDir != 0 || fileSize != 0)
  220153. {
  220154. struct stat info;
  220155. const bool statOk = juce_stat (path, info);
  220156. if (isDir != 0)
  220157. *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  220158. if (isHidden != 0)
  220159. *isHidden = juce_isHiddenFile (path);
  220160. if (fileSize != 0)
  220161. *fileSize = statOk ? info.st_size : 0;
  220162. }
  220163. if (modTime != 0 || creationTime != 0)
  220164. {
  220165. int64 m, a, c;
  220166. juce_getFileTimes (path, m, a, c);
  220167. if (modTime != 0)
  220168. *modTime = m;
  220169. if (creationTime != 0)
  220170. *creationTime = c;
  220171. }
  220172. if (isReadOnly != 0)
  220173. *isReadOnly = ! juce_canWriteToFile (path);
  220174. return true;
  220175. }
  220176. }
  220177. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  220178. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  220179. Time* creationTime, bool* isReadOnly) throw()
  220180. {
  220181. NSDirectoryEnumerator* e = [[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory)];
  220182. if (e != 0)
  220183. {
  220184. FindFileStruct* ff = new FindFileStruct();
  220185. ff->enumerator = [e retain];
  220186. ff->parentDir = directory;
  220187. ff->wildCard = wildCard;
  220188. if (! ff->parentDir.endsWithChar (File::separator))
  220189. ff->parentDir += File::separator;
  220190. if (juce_findFileNext (ff, firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  220191. return ff;
  220192. [e release];
  220193. delete ff;
  220194. }
  220195. return 0;
  220196. }
  220197. void juce_findFileClose (void* handle) throw()
  220198. {
  220199. FindFileStruct* ff = (FindFileStruct*) handle;
  220200. [ff->enumerator release];
  220201. delete ff;
  220202. }
  220203. bool juce_launchExecutable (const String& pathAndArguments) throw()
  220204. {
  220205. const char* const argv[4] = { "/bin/sh", "-c", (const char*) pathAndArguments, 0 };
  220206. const int cpid = fork();
  220207. if (cpid == 0)
  220208. {
  220209. // Child process
  220210. if (execve (argv[0], (char**) argv, 0) < 0)
  220211. exit (0);
  220212. }
  220213. else
  220214. {
  220215. if (cpid < 0)
  220216. return false;
  220217. }
  220218. return true;
  220219. }
  220220. bool juce_launchFile (const String& fileName,
  220221. const String& parameters) throw()
  220222. {
  220223. #if JUCE_IPHONE
  220224. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  220225. #else
  220226. const ScopedAutoReleasePool pool;
  220227. if (parameters.isEmpty())
  220228. {
  220229. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  220230. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  220231. }
  220232. bool ok = false;
  220233. FSRef ref;
  220234. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  220235. {
  220236. if (PlatformUtilities::isBundle (fileName))
  220237. {
  220238. NSMutableArray* urls = [NSMutableArray array];
  220239. StringArray docs;
  220240. docs.addTokens (parameters, true);
  220241. for (int i = 0; i < docs.size(); ++i)
  220242. [urls addObject: juceStringToNS (docs[i])];
  220243. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  220244. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  220245. options: nil
  220246. additionalEventParamDescriptor: nil
  220247. launchIdentifiers: nil];
  220248. }
  220249. else
  220250. {
  220251. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  220252. }
  220253. }
  220254. return ok;
  220255. #endif
  220256. }
  220257. #if ! JUCE_IPHONE
  220258. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  220259. {
  220260. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  220261. }
  220262. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  220263. {
  220264. uint8 path [2048];
  220265. zeromem (path, sizeof (path));
  220266. String result;
  220267. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  220268. result = String::fromUTF8 (path);
  220269. return PlatformUtilities::convertToPrecomposedUnicode (result);
  220270. }
  220271. #endif
  220272. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  220273. {
  220274. const ScopedAutoReleasePool pool;
  220275. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  220276. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  220277. #else
  220278. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  220279. #endif
  220280. return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  220281. }
  220282. bool PlatformUtilities::isBundle (const String& filename)
  220283. {
  220284. #if JUCE_IPHONE
  220285. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  220286. #else
  220287. const ScopedAutoReleasePool pool;
  220288. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  220289. #endif
  220290. }
  220291. #endif
  220292. /********* End of inlined file: juce_mac_Files.mm *********/
  220293. #if JUCE_IPHONE
  220294. /********* Start of inlined file: juce_iphone_MiscUtilities.mm *********/
  220295. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220296. // compiled on its own).
  220297. #ifdef JUCE_INCLUDED_FILE
  220298. static JUCEApplication* juce_intialisingApp;
  220299. END_JUCE_NAMESPACE
  220300. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  220301. {
  220302. }
  220303. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  220304. - (void) applicationWillResignActive: (UIApplication*) application;
  220305. @end
  220306. @implementation JuceAppStartupDelegate
  220307. - (void) applicationDidFinishLaunching: (UIApplication*) application
  220308. {
  220309. String dummy;
  220310. if (! juce_intialisingApp->initialiseApp (dummy))
  220311. {
  220312. // (should quit)
  220313. }
  220314. }
  220315. - (void) applicationWillResignActive: (UIApplication*) application
  220316. {
  220317. JUCEApplication::shutdownAppAndClearUp();
  220318. }
  220319. @end
  220320. BEGIN_JUCE_NAMESPACE
  220321. int juce_IPhoneMain (int argc, char* argv[], JUCEApplication* app)
  220322. {
  220323. juce_intialisingApp = app;
  220324. return UIApplicationMain (argc, argv, nil, @"JuceAppStartupDelegate");
  220325. }
  220326. ScopedAutoReleasePool::ScopedAutoReleasePool()
  220327. {
  220328. pool = [[NSAutoreleasePool alloc] init];
  220329. }
  220330. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  220331. {
  220332. [((NSAutoreleasePool*) pool) release];
  220333. }
  220334. void PlatformUtilities::beep()
  220335. {
  220336. //xxx
  220337. //AudioServicesPlaySystemSound ();
  220338. }
  220339. void PlatformUtilities::addItemToDock (const File& file)
  220340. {
  220341. }
  220342. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220343. bool AlertWindow::showNativeDialogBox (const String& title,
  220344. const String& bodyText,
  220345. bool isOkCancel)
  220346. {
  220347. const ScopedAutoReleasePool pool;
  220348. UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  220349. message: juceStringToNS (title)
  220350. delegate: nil
  220351. cancelButtonTitle: @"OK"
  220352. otherButtonTitles: (isOkCancel ? @"Cancel" : nil), nil] autorelease];
  220353. alert.cancelButtonIndex = alert.firstOtherButtonIndex;
  220354. [alert show];
  220355. // xxx need to use a delegate to find which button was clicked
  220356. return false;
  220357. }
  220358. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220359. {
  220360. jassertfalse // not implemented!
  220361. return false;
  220362. }
  220363. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220364. {
  220365. jassertfalse // not implemented!
  220366. return false;
  220367. }
  220368. bool Desktop::canUseSemiTransparentWindows() throw()
  220369. {
  220370. return true;
  220371. }
  220372. void Desktop::getMousePosition (int& x, int& y) throw()
  220373. {
  220374. x = 0;
  220375. y = 0;
  220376. }
  220377. void Desktop::setMousePosition (int x, int y) throw()
  220378. {
  220379. }
  220380. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220381. {
  220382. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  220383. }
  220384. bool Desktop::isScreenSaverEnabled() throw()
  220385. {
  220386. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  220387. }
  220388. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220389. {
  220390. const ScopedAutoReleasePool pool;
  220391. monitorCoords.clear();
  220392. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  220393. : [[UIScreen mainScreen] bounds];
  220394. monitorCoords.add (Rectangle ((int) r.origin.x,
  220395. (int) r.origin.y,
  220396. (int) r.size.width,
  220397. (int) r.size.height));
  220398. }
  220399. #endif
  220400. #endif
  220401. /********* End of inlined file: juce_iphone_MiscUtilities.mm *********/
  220402. #else
  220403. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  220404. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220405. // compiled on its own).
  220406. #ifdef JUCE_INCLUDED_FILE
  220407. ScopedAutoReleasePool::ScopedAutoReleasePool()
  220408. {
  220409. pool = [[NSAutoreleasePool alloc] init];
  220410. }
  220411. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  220412. {
  220413. [((NSAutoreleasePool*) pool) release];
  220414. }
  220415. void PlatformUtilities::beep()
  220416. {
  220417. NSBeep();
  220418. }
  220419. void PlatformUtilities::addItemToDock (const File& file)
  220420. {
  220421. // check that it's not already there...
  220422. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  220423. .containsIgnoreCase (file.getFullPathName()))
  220424. {
  220425. juce_runSystemCommand ("defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>"
  220426. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  220427. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  220428. }
  220429. }
  220430. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220431. bool AlertWindow::showNativeDialogBox (const String& title,
  220432. const String& bodyText,
  220433. bool isOkCancel)
  220434. {
  220435. const ScopedAutoReleasePool pool;
  220436. return NSRunAlertPanel (juceStringToNS (title),
  220437. juceStringToNS (bodyText),
  220438. @"Ok",
  220439. isOkCancel ? @"Cancel" : nil,
  220440. nil) == NSAlertDefaultReturn;
  220441. }
  220442. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220443. {
  220444. if (files.size() == 0)
  220445. return false;
  220446. Component* sourceComp = Component::getComponentUnderMouse();
  220447. if (sourceComp == 0)
  220448. {
  220449. jassertfalse // this method must be called in response to a
  220450. // component's mouseDrag event!
  220451. return false;
  220452. }
  220453. const ScopedAutoReleasePool pool;
  220454. NSView* view = (NSView*) sourceComp->getWindowHandle();
  220455. if (view == 0)
  220456. return false;
  220457. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  220458. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  220459. owner: nil];
  220460. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  220461. for (int i = 0; i < files.size(); ++i)
  220462. [filesArray addObject: juceStringToNS (files[i])];
  220463. [pboard setPropertyList: filesArray
  220464. forType: NSFilenamesPboardType];
  220465. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  220466. fromView: nil];
  220467. dragPosition.x -= 16;
  220468. dragPosition.y -= 16;
  220469. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  220470. at: dragPosition
  220471. offset: NSMakeSize (0, 0)
  220472. event: [[view window] currentEvent]
  220473. pasteboard: pboard
  220474. source: view
  220475. slideBack: YES];
  220476. return true;
  220477. }
  220478. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220479. {
  220480. jassertfalse // not implemented!
  220481. return false;
  220482. }
  220483. bool Desktop::canUseSemiTransparentWindows() throw()
  220484. {
  220485. return true;
  220486. }
  220487. void Desktop::getMousePosition (int& x, int& y) throw()
  220488. {
  220489. const ScopedAutoReleasePool pool;
  220490. const NSPoint p ([NSEvent mouseLocation]);
  220491. x = roundFloatToInt (p.x);
  220492. y = roundFloatToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y);
  220493. }
  220494. void Desktop::setMousePosition (int x, int y) throw()
  220495. {
  220496. // this rubbish needs to be done around the warp call, to avoid causing a
  220497. // bizarre glitch..
  220498. CGAssociateMouseAndMouseCursorPosition (false);
  220499. #if (! defined (MAC_OS_X_VERSION_10_6)) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
  220500. CGSetLocalEventsSuppressionInterval (0);
  220501. #endif
  220502. CGPoint pos = { x, y };
  220503. CGWarpMouseCursorPosition (pos);
  220504. CGAssociateMouseAndMouseCursorPosition (true);
  220505. }
  220506. #if MACOS_10_4_OR_EARLIER
  220507. class ScreenSaverDefeater : public Timer,
  220508. public DeletedAtShutdown
  220509. {
  220510. public:
  220511. ScreenSaverDefeater() throw()
  220512. {
  220513. startTimer (10000);
  220514. timerCallback();
  220515. }
  220516. ~ScreenSaverDefeater() {}
  220517. void timerCallback()
  220518. {
  220519. if (Process::isForegroundProcess())
  220520. UpdateSystemActivity (UsrActivity);
  220521. }
  220522. };
  220523. static ScreenSaverDefeater* screenSaverDefeater = 0;
  220524. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220525. {
  220526. if (isEnabled)
  220527. {
  220528. deleteAndZero (screenSaverDefeater);
  220529. }
  220530. else if (screenSaverDefeater == 0)
  220531. {
  220532. screenSaverDefeater = new ScreenSaverDefeater();
  220533. }
  220534. }
  220535. bool Desktop::isScreenSaverEnabled() throw()
  220536. {
  220537. return screenSaverDefeater == 0;
  220538. }
  220539. #else
  220540. static IOPMAssertionID screenSaverDisablerID = 0;
  220541. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220542. {
  220543. if (isEnabled)
  220544. {
  220545. if (screenSaverDisablerID != 0)
  220546. {
  220547. IOPMAssertionRelease (screenSaverDisablerID);
  220548. screenSaverDisablerID = 0;
  220549. }
  220550. }
  220551. else
  220552. {
  220553. if (screenSaverDisablerID == 0)
  220554. {
  220555. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  220556. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220557. CFSTR ("Juce"), &screenSaverDisablerID);
  220558. #else
  220559. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220560. &screenSaverDisablerID);
  220561. #endif
  220562. }
  220563. }
  220564. }
  220565. bool Desktop::isScreenSaverEnabled() throw()
  220566. {
  220567. return screenSaverDisablerID == 0;
  220568. }
  220569. #endif
  220570. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220571. {
  220572. const ScopedAutoReleasePool pool;
  220573. monitorCoords.clear();
  220574. NSArray* screens = [NSScreen screens];
  220575. const float mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  220576. for (unsigned int i = 0; i < [screens count]; ++i)
  220577. {
  220578. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  220579. NSRect r = clipToWorkArea ? [s visibleFrame]
  220580. : [s frame];
  220581. monitorCoords.add (Rectangle ((int) r.origin.x,
  220582. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  220583. (int) r.size.width,
  220584. (int) r.size.height));
  220585. }
  220586. jassert (monitorCoords.size() > 0);
  220587. }
  220588. #endif
  220589. #endif
  220590. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  220591. #endif
  220592. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  220593. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220594. // compiled on its own).
  220595. #ifdef JUCE_INCLUDED_FILE
  220596. void Logger::outputDebugString (const String& text) throw()
  220597. {
  220598. fputs (text.toUTF8(), stderr);
  220599. fputs ("\n", stderr);
  220600. }
  220601. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  220602. {
  220603. String text;
  220604. va_list args;
  220605. va_start (args, format);
  220606. text.vprintf (format, args);
  220607. outputDebugString (text);
  220608. }
  220609. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  220610. {
  220611. static char testResult = 0;
  220612. if (testResult == 0)
  220613. {
  220614. struct kinfo_proc info;
  220615. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  220616. size_t sz = sizeof (info);
  220617. sysctl (m, 4, &info, &sz, 0, 0);
  220618. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  220619. }
  220620. return testResult > 0;
  220621. }
  220622. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  220623. {
  220624. return juce_isRunningUnderDebugger();
  220625. }
  220626. #endif
  220627. /********* End of inlined file: juce_mac_Debugging.mm *********/
  220628. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220629. #if JUCE_IPHONE
  220630. /********* Start of inlined file: juce_iphone_UIViewComponentPeer.mm *********/
  220631. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220632. // compiled on its own).
  220633. #ifdef JUCE_INCLUDED_FILE
  220634. class UIViewComponentPeer;
  220635. END_JUCE_NAMESPACE
  220636. #define JuceUIView MakeObjCClassName(JuceUIView)
  220637. @interface JuceUIView : UIView
  220638. {
  220639. @public
  220640. UIViewComponentPeer* owner;
  220641. }
  220642. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  220643. - (void) dealloc;
  220644. - (void) drawRect: (CGRect) r;
  220645. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  220646. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  220647. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  220648. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  220649. - (BOOL) becomeFirstResponder;
  220650. - (BOOL) resignFirstResponder;
  220651. - (BOOL) canBecomeFirstResponder;
  220652. @end
  220653. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  220654. @interface JuceUIWindow : UIWindow
  220655. {
  220656. @private
  220657. UIViewComponentPeer* owner;
  220658. bool isZooming;
  220659. }
  220660. - (void) setOwner: (UIViewComponentPeer*) owner;
  220661. - (void) becomeKeyWindow;
  220662. @end
  220663. BEGIN_JUCE_NAMESPACE
  220664. class UIViewComponentPeer : public ComponentPeer
  220665. {
  220666. public:
  220667. UIViewComponentPeer (Component* const component,
  220668. const int windowStyleFlags,
  220669. UIView* viewToAttachTo);
  220670. ~UIViewComponentPeer();
  220671. void* getNativeHandle() const;
  220672. void setVisible (bool shouldBeVisible);
  220673. void setTitle (const String& title);
  220674. void setPosition (int x, int y);
  220675. void setSize (int w, int h);
  220676. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  220677. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  220678. void getBounds (int& x, int& y, int& w, int& h) const;
  220679. int getScreenX() const;
  220680. int getScreenY() const;
  220681. void relativePositionToGlobal (int& x, int& y);
  220682. void globalPositionToRelative (int& x, int& y);
  220683. void setMinimised (bool shouldBeMinimised);
  220684. bool isMinimised() const;
  220685. void setFullScreen (bool shouldBeFullScreen);
  220686. bool isFullScreen() const;
  220687. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  220688. const BorderSize getFrameSize() const;
  220689. bool setAlwaysOnTop (bool alwaysOnTop);
  220690. void toFront (bool makeActiveWindow);
  220691. void toBehind (ComponentPeer* other);
  220692. void setIcon (const Image& newIcon);
  220693. virtual void drawRect (CGRect r);
  220694. virtual bool canBecomeKeyWindow();
  220695. virtual bool windowShouldClose();
  220696. virtual void redirectMovedOrResized();
  220697. virtual CGRect constrainRect (CGRect r);
  220698. virtual void viewFocusGain();
  220699. virtual void viewFocusLoss();
  220700. bool isFocused() const;
  220701. void grabFocus();
  220702. void textInputRequired (int x, int y);
  220703. void repaint (int x, int y, int w, int h);
  220704. void performAnyPendingRepaintsNow();
  220705. juce_UseDebuggingNewOperator
  220706. UIWindow* window;
  220707. JuceUIView* view;
  220708. bool isSharedWindow, fullScreen;
  220709. };
  220710. END_JUCE_NAMESPACE
  220711. @implementation JuceUIView
  220712. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  220713. withFrame: (CGRect) frame
  220714. {
  220715. [super initWithFrame: frame];
  220716. owner = owner_;
  220717. return self;
  220718. }
  220719. - (void) dealloc
  220720. {
  220721. [super dealloc];
  220722. }
  220723. - (void) drawRect: (CGRect) r
  220724. {
  220725. if (owner != 0)
  220726. owner->drawRect (r);
  220727. }
  220728. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  220729. {
  220730. return false;
  220731. }
  220732. static int currentModifiers = 0;
  220733. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220734. {
  220735. return ModifierKeys (currentModifiers);
  220736. }
  220737. void ModifierKeys::updateCurrentModifiers() throw()
  220738. {
  220739. currentModifierFlags = currentModifiers;
  220740. }
  220741. static int getModifierForButtonNumber (const int num) throw()
  220742. {
  220743. return num == 0 ? ModifierKeys::leftButtonModifier
  220744. : (num == 1 ? ModifierKeys::rightButtonModifier
  220745. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  220746. }
  220747. static int64 getMouseTime (UIEvent* e) { return (int64) [e timestamp] * 1000.0; }
  220748. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  220749. {
  220750. NSArray* const t = [[event touchesForView: self] allObjects];
  220751. switch ([t count])
  220752. {
  220753. case 1: // One finger..
  220754. {
  220755. CGPoint p = [[t objectAtIndex: 0] locationInView: self];
  220756. currentModifiers |= getModifierForButtonNumber (0);
  220757. owner->handleMouseDown (p.x, p.y, getMouseTime (event));
  220758. }
  220759. default:
  220760. //xxx multi-touch..
  220761. break;
  220762. }
  220763. }
  220764. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  220765. {
  220766. NSArray* const t = [[event touchesForView: self] allObjects];
  220767. switch ([t count])
  220768. {
  220769. case 1: // One finger..
  220770. {
  220771. CGPoint p = [[t objectAtIndex: 0] locationInView: self];
  220772. owner->handleMouseDrag (p.x, p.y, getMouseTime (event));
  220773. }
  220774. default:
  220775. //xxx multi-touch..
  220776. break;
  220777. }
  220778. }
  220779. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  220780. {
  220781. NSArray* const t = [[event touchesForView: self] allObjects];
  220782. switch ([t count])
  220783. {
  220784. case 1: // One finger..
  220785. {
  220786. CGPoint p = [[t objectAtIndex: 0] locationInView: self];
  220787. const int oldMods = currentModifiers;
  220788. currentModifiers &= ~getModifierForButtonNumber (0);
  220789. owner->handleMouseUp (oldMods, p.x, p.y, getMouseTime (event));
  220790. }
  220791. default:
  220792. //xxx multi-touch..
  220793. break;
  220794. }
  220795. }
  220796. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  220797. {
  220798. [self touchesEnded: touches withEvent: event];
  220799. }
  220800. - (BOOL) becomeFirstResponder
  220801. {
  220802. if (owner != 0)
  220803. owner->viewFocusGain();
  220804. return true;
  220805. }
  220806. - (BOOL) resignFirstResponder
  220807. {
  220808. if (owner != 0)
  220809. owner->viewFocusLoss();
  220810. return true;
  220811. }
  220812. - (BOOL) canBecomeFirstResponder
  220813. {
  220814. return owner != 0 && owner->canBecomeKeyWindow();
  220815. }
  220816. @end
  220817. @implementation JuceUIWindow
  220818. - (void) setOwner: (UIViewComponentPeer*) owner_
  220819. {
  220820. owner = owner_;
  220821. isZooming = false;
  220822. }
  220823. - (void) becomeKeyWindow
  220824. {
  220825. [super becomeKeyWindow];
  220826. if (owner != 0)
  220827. owner->grabFocus();
  220828. }
  220829. @end
  220830. BEGIN_JUCE_NAMESPACE
  220831. class JuceUIImage
  220832. {
  220833. public:
  220834. JuceUIImage (const int width, const int height, const bool hasAlpha)
  220835. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  220836. width, height, hasAlpha)
  220837. {
  220838. lineStride = 0;
  220839. pixelStride = 0;
  220840. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  220841. lineStride, pixelStride);
  220842. CGDataProviderRef provider = CGDataProviderCreateWithData (0, imageData, lineStride * pixelStride, 0);
  220843. imageRef = CGImageCreate (width, height,
  220844. 8, pixelStride * 8, lineStride,
  220845. CGColorSpaceCreateDeviceRGB(),
  220846. hasAlpha ? (kCGImageAlphaFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault,
  220847. provider,
  220848. 0,
  220849. true, kCGRenderingIntentDefault);
  220850. juceImage.releasePixelDataReadWrite (imageData);
  220851. uiImage = [[UIImage imageWithCGImage: imageRef] retain];
  220852. }
  220853. ~JuceUIImage()
  220854. {
  220855. [uiImage release];
  220856. CFRelease (imageRef);
  220857. }
  220858. Image& getJuceImage() throw() { return juceImage; }
  220859. void draw (const float x, const float y) const
  220860. {
  220861. [uiImage drawAtPoint: CGPointMake (x, y)
  220862. blendMode: kCGBlendModeCopy
  220863. alpha: 1.0f];
  220864. }
  220865. void drawUIImage (UIImage* imageToDraw)
  220866. {
  220867. const ScopedAutoReleasePool pool;
  220868. jassertfalse
  220869. /*[NSGraphicsContext saveGraphicsState];
  220870. [NSGraphicsContext setCurrentContext:
  220871. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  220872. [imageToDraw drawAtPoint: NSZeroPoint
  220873. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  220874. operation: NSCompositeSourceOver
  220875. fraction: 1.0f];
  220876. [[NSGraphicsContext currentContext] flushGraphics];
  220877. [NSGraphicsContext restoreGraphicsState];
  220878. if (juceImage.hasAlphaChannel())
  220879. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());*/
  220880. }
  220881. private:
  220882. Image juceImage;
  220883. CGImageRef imageRef;
  220884. CGDataProviderRef provider;
  220885. UIImage* uiImage;
  220886. uint8* imageData;
  220887. int pixelStride, lineStride;
  220888. /* void swapRGBOrder (const int x, const int y, const int w, int h) const
  220889. {
  220890. #if JUCE_BIG_ENDIAN
  220891. jassert (pixelStride == 4);
  220892. #endif
  220893. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  220894. .contains (Rectangle (x, y, w, h)));
  220895. uint8* start = imageData + x * pixelStride + y * lineStride;
  220896. while (--h >= 0)
  220897. {
  220898. uint8* p = start;
  220899. start += lineStride;
  220900. for (int i = w; --i >= 0;)
  220901. {
  220902. #if JUCE_BIG_ENDIAN
  220903. const uint8 oldp3 = p[3];
  220904. const uint8 oldp1 = p[1];
  220905. p[3] = p[0];
  220906. p[0] = oldp1;
  220907. p[1] = p[2];
  220908. p[2] = oldp3;
  220909. #else
  220910. const uint8 oldp0 = p[0];
  220911. p[0] = p[2];
  220912. p[2] = oldp0;
  220913. #endif
  220914. p += pixelStride;
  220915. }
  220916. }
  220917. }*/
  220918. };
  220919. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  220920. const int windowStyleFlags,
  220921. UIView* viewToAttachTo)
  220922. : ComponentPeer (component, windowStyleFlags),
  220923. window (0),
  220924. view (0),
  220925. isSharedWindow (viewToAttachTo != 0),
  220926. fullScreen (false)
  220927. {
  220928. CGRect r;
  220929. r.origin.x = 0;
  220930. r.origin.y = 0;
  220931. r.size.width = (float) component->getWidth();
  220932. r.size.height = (float) component->getHeight();
  220933. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  220934. if (isSharedWindow)
  220935. {
  220936. window = [viewToAttachTo window];
  220937. [viewToAttachTo addSubview: view];
  220938. setVisible (component->isVisible());
  220939. }
  220940. else
  220941. {
  220942. r.origin.x = (float) component->getX();
  220943. r.origin.y = (float) component->getY();
  220944. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  220945. window = [[JuceUIWindow alloc] init];
  220946. window.frame = r;
  220947. [((JuceUIWindow*) window) setOwner: this];
  220948. if (component->isAlwaysOnTop())
  220949. window.windowLevel = UIWindowLevelAlert;
  220950. [window addSubview: view];
  220951. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  220952. }
  220953. setTitle (component->getName());
  220954. }
  220955. UIViewComponentPeer::~UIViewComponentPeer()
  220956. {
  220957. view->owner = 0;
  220958. [view removeFromSuperview];
  220959. [view release];
  220960. if (! isSharedWindow)
  220961. {
  220962. [((JuceUIWindow*) window) setOwner: 0];
  220963. [window release];
  220964. }
  220965. }
  220966. void* UIViewComponentPeer::getNativeHandle() const
  220967. {
  220968. return view;
  220969. }
  220970. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  220971. {
  220972. view.hidden = ! shouldBeVisible;
  220973. }
  220974. void UIViewComponentPeer::setTitle (const String& title)
  220975. {
  220976. // xxx is this possible?
  220977. }
  220978. void UIViewComponentPeer::setPosition (int x, int y)
  220979. {
  220980. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  220981. }
  220982. void UIViewComponentPeer::setSize (int w, int h)
  220983. {
  220984. setBounds (component->getX(), component->getY(), w, h, false);
  220985. }
  220986. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  220987. {
  220988. fullScreen = isNowFullScreen;
  220989. w = jmax (0, w);
  220990. h = jmax (0, h);
  220991. CGRect r;
  220992. r.origin.x = (float) x;
  220993. r.origin.y = (float) y;
  220994. r.size.width = (float) w;
  220995. r.size.height = (float) h;
  220996. if (isSharedWindow)
  220997. {
  220998. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  220999. if ([view frame].size.width != r.size.width
  221000. || [view frame].size.height != r.size.height)
  221001. [view setNeedsDisplay];
  221002. view.frame = r;
  221003. }
  221004. else
  221005. {
  221006. //r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  221007. window.frame = r;
  221008. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  221009. }
  221010. }
  221011. void UIViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  221012. {
  221013. CGRect r = [view frame];
  221014. if (global && [view window] != 0)
  221015. {
  221016. r = [view convertRect: r toView: nil];
  221017. CGRect wr = [[view window] frame];
  221018. r.origin.x += wr.origin.x;
  221019. r.origin.y += wr.origin.y;
  221020. y = (int) ([[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height);
  221021. }
  221022. else
  221023. {
  221024. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  221025. }
  221026. x = (int) r.origin.x;
  221027. w = (int) r.size.width;
  221028. h = (int) r.size.height;
  221029. }
  221030. void UIViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  221031. {
  221032. getBounds (x, y, w, h, ! isSharedWindow);
  221033. }
  221034. int UIViewComponentPeer::getScreenX() const
  221035. {
  221036. int x, y, w, h;
  221037. getBounds (x, y, w, h, true);
  221038. return x;
  221039. }
  221040. int UIViewComponentPeer::getScreenY() const
  221041. {
  221042. int x, y, w, h;
  221043. getBounds (x, y, w, h, true);
  221044. return y;
  221045. }
  221046. void UIViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  221047. {
  221048. int wx, wy, ww, wh;
  221049. getBounds (wx, wy, ww, wh, true);
  221050. x += wx;
  221051. y += wy;
  221052. }
  221053. void UIViewComponentPeer::globalPositionToRelative (int& x, int& y)
  221054. {
  221055. int wx, wy, ww, wh;
  221056. getBounds (wx, wy, ww, wh, true);
  221057. x -= wx;
  221058. y -= wy;
  221059. }
  221060. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  221061. {
  221062. if (constrainer != 0)
  221063. {
  221064. CGRect current = [window frame];
  221065. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  221066. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  221067. int x = (int) r.origin.x;
  221068. int y = (int) r.origin.y;
  221069. int w = (int) r.size.width;
  221070. int h = (int) r.size.height;
  221071. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  221072. (int) current.size.width, (int) current.size.height);
  221073. constrainer->checkBounds (x, y, w, h,
  221074. original,
  221075. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  221076. y != original.getY() && y + h == original.getBottom(),
  221077. x != original.getX() && x + w == original.getRight(),
  221078. y == original.getY() && y + h != original.getBottom(),
  221079. x == original.getX() && x + w != original.getRight());
  221080. r.origin.x = x;
  221081. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - y;
  221082. r.size.width = w;
  221083. r.size.height = h;
  221084. }
  221085. return r;
  221086. }
  221087. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  221088. {
  221089. // xxx
  221090. }
  221091. bool UIViewComponentPeer::isMinimised() const
  221092. {
  221093. return false;
  221094. }
  221095. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  221096. {
  221097. if (! isSharedWindow)
  221098. {
  221099. Rectangle r (lastNonFullscreenBounds);
  221100. setMinimised (false);
  221101. if (fullScreen != shouldBeFullScreen)
  221102. {
  221103. if (shouldBeFullScreen)
  221104. r = Desktop::getInstance().getMainMonitorArea();
  221105. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  221106. if (r != getComponent()->getBounds() && ! r.isEmpty())
  221107. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  221108. }
  221109. }
  221110. }
  221111. bool UIViewComponentPeer::isFullScreen() const
  221112. {
  221113. return fullScreen;
  221114. }
  221115. bool UIViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  221116. {
  221117. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  221118. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  221119. return false;
  221120. CGPoint p;
  221121. p.x = (float) x;
  221122. p.y = (float) y;
  221123. UIView* v = [view hitTest: p withEvent: nil];
  221124. if (trueIfInAChildWindow)
  221125. return v != nil;
  221126. return v == view;
  221127. }
  221128. const BorderSize UIViewComponentPeer::getFrameSize() const
  221129. {
  221130. BorderSize b;
  221131. if (! isSharedWindow)
  221132. {
  221133. CGRect v = [view convertRect: [view frame] toView: nil];
  221134. CGRect w = [window frame];
  221135. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  221136. b.setBottom ((int) v.origin.y);
  221137. b.setLeft ((int) v.origin.x);
  221138. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  221139. }
  221140. return b;
  221141. }
  221142. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  221143. {
  221144. if (! isSharedWindow)
  221145. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  221146. return true;
  221147. }
  221148. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  221149. {
  221150. if (isSharedWindow)
  221151. [[view superview] bringSubviewToFront: view];
  221152. if (window != 0 && component->isVisible())
  221153. [window makeKeyAndVisible];
  221154. }
  221155. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  221156. {
  221157. UIViewComponentPeer* o = (UIViewComponentPeer*) other;
  221158. if (isSharedWindow)
  221159. {
  221160. [[view superview] insertSubview: view belowSubview: o->view];
  221161. }
  221162. else
  221163. {
  221164. jassertfalse // don't know how to do this
  221165. }
  221166. }
  221167. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  221168. {
  221169. // to do..
  221170. }
  221171. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  221172. void UIViewComponentPeer::viewFocusGain()
  221173. {
  221174. if (currentlyFocusedPeer != this)
  221175. {
  221176. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  221177. currentlyFocusedPeer->handleFocusLoss();
  221178. currentlyFocusedPeer = this;
  221179. handleFocusGain();
  221180. }
  221181. }
  221182. void UIViewComponentPeer::viewFocusLoss()
  221183. {
  221184. if (currentlyFocusedPeer == this)
  221185. {
  221186. currentlyFocusedPeer = 0;
  221187. handleFocusLoss();
  221188. }
  221189. }
  221190. void juce_HandleProcessFocusChange()
  221191. {
  221192. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221193. {
  221194. if (Process::isForegroundProcess())
  221195. {
  221196. currentlyFocusedPeer->handleFocusGain();
  221197. ComponentPeer::bringModalComponentToFront();
  221198. }
  221199. else
  221200. {
  221201. currentlyFocusedPeer->handleFocusLoss();
  221202. // turn kiosk mode off if we lose focus..
  221203. Desktop::getInstance().setKioskModeComponent (0);
  221204. }
  221205. }
  221206. }
  221207. bool UIViewComponentPeer::isFocused() const
  221208. {
  221209. return isSharedWindow ? this == currentlyFocusedPeer
  221210. : (window != 0 && [window isKeyWindow]);
  221211. }
  221212. void UIViewComponentPeer::grabFocus()
  221213. {
  221214. if (window != 0)
  221215. {
  221216. [window makeKeyWindow];
  221217. viewFocusGain();
  221218. }
  221219. }
  221220. void UIViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  221221. {
  221222. }
  221223. void UIViewComponentPeer::drawRect (CGRect r)
  221224. {
  221225. if (r.size.width < 1.0f || r.size.height < 1.0f)
  221226. return;
  221227. DBG (Rectangle (r.origin.x, r.origin.y, r.size.width, r.size.height).toString());
  221228. const float y = r.origin.y;//[view frame].size.height - (r.origin.y + r.size.height);
  221229. JuceUIImage temp ((int) (r.size.width + 0.5f),
  221230. (int) (r.size.height + 0.5f),
  221231. true);//! getComponent()->isOpaque());
  221232. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  221233. const int originX = -roundFloatToInt (r.origin.x);
  221234. const int originY = -roundFloatToInt (y);
  221235. context.setOrigin (originX, originY);
  221236. handlePaint (context);
  221237. //CGContextClipToRect (UIGraphicsGetCurrentContext(), r);
  221238. temp.draw (r.origin.x, r.origin.y);
  221239. }
  221240. bool UIViewComponentPeer::canBecomeKeyWindow()
  221241. {
  221242. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  221243. }
  221244. bool UIViewComponentPeer::windowShouldClose()
  221245. {
  221246. if (! isValidPeer (this))
  221247. return YES;
  221248. handleUserClosingWindow();
  221249. return NO;
  221250. }
  221251. void UIViewComponentPeer::redirectMovedOrResized()
  221252. {
  221253. handleMovedOrResized();
  221254. }
  221255. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221256. {
  221257. }
  221258. void UIViewComponentPeer::repaint (int x, int y, int w, int h)
  221259. {
  221260. [view setNeedsDisplayInRect:
  221261. CGRectMake ((float) x, (float) y,//([view frame].size.height - (y + h)),
  221262. (float) w, (float) h)];
  221263. }
  221264. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  221265. {
  221266. }
  221267. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221268. {
  221269. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  221270. }
  221271. static Image* UIImageToJuceImage (UIImage* image)
  221272. {
  221273. JuceUIImage juceIm ((int) [image size].width,
  221274. (int) [image size].height,
  221275. true);
  221276. juceIm.drawUIImage (image);
  221277. return juceIm.getJuceImage().createCopy();
  221278. }
  221279. Image* juce_createIconForFile (const File& file)
  221280. {
  221281. return 0;
  221282. }
  221283. const int KeyPress::spaceKey = ' ';
  221284. const int KeyPress::returnKey = 0x0d;
  221285. const int KeyPress::escapeKey = 0x1b;
  221286. const int KeyPress::backspaceKey = 0x7f;
  221287. const int KeyPress::leftKey = 0x1000;
  221288. const int KeyPress::rightKey = 0x1001;
  221289. const int KeyPress::upKey = 0x1002;
  221290. const int KeyPress::downKey = 0x1003;
  221291. const int KeyPress::pageUpKey = 0x1004;
  221292. const int KeyPress::pageDownKey = 0x1005;
  221293. const int KeyPress::endKey = 0x1006;
  221294. const int KeyPress::homeKey = 0x1007;
  221295. const int KeyPress::deleteKey = 0x1008;
  221296. const int KeyPress::insertKey = -1;
  221297. const int KeyPress::tabKey = 9;
  221298. const int KeyPress::F1Key = 0x2001;
  221299. const int KeyPress::F2Key = 0x2002;
  221300. const int KeyPress::F3Key = 0x2003;
  221301. const int KeyPress::F4Key = 0x2004;
  221302. const int KeyPress::F5Key = 0x2005;
  221303. const int KeyPress::F6Key = 0x2006;
  221304. const int KeyPress::F7Key = 0x2007;
  221305. const int KeyPress::F8Key = 0x2008;
  221306. const int KeyPress::F9Key = 0x2009;
  221307. const int KeyPress::F10Key = 0x200a;
  221308. const int KeyPress::F11Key = 0x200b;
  221309. const int KeyPress::F12Key = 0x200c;
  221310. const int KeyPress::F13Key = 0x200d;
  221311. const int KeyPress::F14Key = 0x200e;
  221312. const int KeyPress::F15Key = 0x200f;
  221313. const int KeyPress::F16Key = 0x2010;
  221314. const int KeyPress::numberPad0 = 0x30020;
  221315. const int KeyPress::numberPad1 = 0x30021;
  221316. const int KeyPress::numberPad2 = 0x30022;
  221317. const int KeyPress::numberPad3 = 0x30023;
  221318. const int KeyPress::numberPad4 = 0x30024;
  221319. const int KeyPress::numberPad5 = 0x30025;
  221320. const int KeyPress::numberPad6 = 0x30026;
  221321. const int KeyPress::numberPad7 = 0x30027;
  221322. const int KeyPress::numberPad8 = 0x30028;
  221323. const int KeyPress::numberPad9 = 0x30029;
  221324. const int KeyPress::numberPadAdd = 0x3002a;
  221325. const int KeyPress::numberPadSubtract = 0x3002b;
  221326. const int KeyPress::numberPadMultiply = 0x3002c;
  221327. const int KeyPress::numberPadDivide = 0x3002d;
  221328. const int KeyPress::numberPadSeparator = 0x3002e;
  221329. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221330. const int KeyPress::numberPadEquals = 0x30030;
  221331. const int KeyPress::numberPadDelete = 0x30031;
  221332. const int KeyPress::playKey = 0x30000;
  221333. const int KeyPress::stopKey = 0x30001;
  221334. const int KeyPress::fastForwardKey = 0x30002;
  221335. const int KeyPress::rewindKey = 0x30003;
  221336. #endif
  221337. /********* End of inlined file: juce_iphone_UIViewComponentPeer.mm *********/
  221338. /********* Start of inlined file: juce_iphone_Fonts.mm *********/
  221339. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221340. // compiled on its own).
  221341. #ifdef JUCE_INCLUDED_FILE
  221342. class FontHelper
  221343. {
  221344. UIFont* font;
  221345. public:
  221346. String name;
  221347. bool isBold, isItalic, needsItalicTransform;
  221348. float fontSize, totalSize, ascent;
  221349. int refCount;
  221350. FontHelper (const String& name_,
  221351. const bool bold_,
  221352. const bool italic_,
  221353. const float size_)
  221354. : font (0),
  221355. name (name_),
  221356. isBold (bold_),
  221357. isItalic (italic_),
  221358. needsItalicTransform (false),
  221359. fontSize (size_),
  221360. refCount (1)
  221361. {
  221362. //attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  221363. // forKey: NSLigatureAttributeName] retain];
  221364. font = [UIFont fontWithName: juceStringToNS (name_) size: size_];
  221365. if (italic_)
  221366. {
  221367. /* NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  221368. if (newFont == font)
  221369. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  221370. font = newFont;*/
  221371. }
  221372. // if (bold_)
  221373. // font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  221374. [font retain];
  221375. ascent = fabsf (font.ascender);
  221376. totalSize = ascent + fabsf (font.descender);
  221377. }
  221378. ~FontHelper()
  221379. {
  221380. [font release];
  221381. }
  221382. bool getPathAndKerning (const juce_wchar char1,
  221383. const juce_wchar char2,
  221384. Path* path,
  221385. float& kerning,
  221386. float* ascent,
  221387. float* descent)
  221388. {
  221389. const ScopedAutoReleasePool pool;
  221390. return false;
  221391. /* if (font == 0
  221392. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  221393. return false;
  221394. String chars;
  221395. chars << ' ' << char1 << char2;
  221396. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  221397. attributes: attributes] autorelease];
  221398. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  221399. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  221400. [layoutManager addTextContainer: textContainer];
  221401. [textStorage addLayoutManager: layoutManager];
  221402. [textStorage setFont: font];
  221403. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  221404. actualCharacterRange: 0].location;
  221405. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  221406. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  221407. kerning = p2.x - p1.x;
  221408. if (ascent != 0)
  221409. *ascent = this->ascent;
  221410. if (descent != 0)
  221411. *descent = fabsf ([font descender]);
  221412. if (path != 0)
  221413. {
  221414. NSBezierPath* bez = [NSBezierPath bezierPath];
  221415. [bez moveToPoint: NSMakePoint (0, 0)];
  221416. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  221417. inFont: font];
  221418. for (int i = 0; i < [bez elementCount]; ++i)
  221419. {
  221420. NSPoint p[3];
  221421. switch ([bez elementAtIndex: i associatedPoints: p])
  221422. {
  221423. case NSMoveToBezierPathElement:
  221424. path->startNewSubPath (p[0].x, -p[0].y);
  221425. break;
  221426. case NSLineToBezierPathElement:
  221427. path->lineTo (p[0].x, -p[0].y);
  221428. break;
  221429. case NSCurveToBezierPathElement:
  221430. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  221431. break;
  221432. case NSClosePathBezierPathElement:
  221433. path->closeSubPath();
  221434. break;
  221435. default:
  221436. jassertfalse
  221437. break;
  221438. }
  221439. }
  221440. if (needsItalicTransform)
  221441. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  221442. }
  221443. return kerning != 0;*/
  221444. }
  221445. juce_wchar getDefaultChar()
  221446. {
  221447. return 0;
  221448. }
  221449. };
  221450. class FontHelperCache : public Timer,
  221451. public DeletedAtShutdown
  221452. {
  221453. VoidArray cache;
  221454. public:
  221455. FontHelperCache()
  221456. {
  221457. }
  221458. ~FontHelperCache()
  221459. {
  221460. for (int i = cache.size(); --i >= 0;)
  221461. {
  221462. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221463. delete f;
  221464. }
  221465. clearSingletonInstance();
  221466. }
  221467. FontHelper* getFont (const String& name,
  221468. const bool bold,
  221469. const bool italic,
  221470. const float size = 1024)
  221471. {
  221472. for (int i = cache.size(); --i >= 0;)
  221473. {
  221474. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221475. if (f->name == name
  221476. && f->isBold == bold
  221477. && f->isItalic == italic
  221478. && f->fontSize == size)
  221479. {
  221480. f->refCount++;
  221481. return f;
  221482. }
  221483. }
  221484. FontHelper* const f = new FontHelper (name, bold, italic, size);
  221485. cache.add (f);
  221486. return f;
  221487. }
  221488. void releaseFont (FontHelper* f)
  221489. {
  221490. for (int i = cache.size(); --i >= 0;)
  221491. {
  221492. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  221493. if (f == f2)
  221494. {
  221495. f->refCount--;
  221496. if (f->refCount == 0)
  221497. startTimer (5000);
  221498. break;
  221499. }
  221500. }
  221501. }
  221502. void timerCallback()
  221503. {
  221504. stopTimer();
  221505. for (int i = cache.size(); --i >= 0;)
  221506. {
  221507. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221508. if (f->refCount == 0)
  221509. {
  221510. cache.remove (i);
  221511. delete f;
  221512. }
  221513. }
  221514. if (cache.size() == 0)
  221515. delete this;
  221516. }
  221517. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  221518. };
  221519. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  221520. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  221521. bool bold,
  221522. bool italic,
  221523. bool addAllGlyphsToFont) throw()
  221524. {
  221525. // This method is only safe to be called from the normal UI thread..
  221526. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  221527. FontHelper* const helper = FontHelperCache::getInstance()
  221528. ->getFont (fontName, bold, italic);
  221529. clear();
  221530. setAscent (helper->ascent / helper->totalSize);
  221531. setName (fontName);
  221532. setDefaultCharacter (helper->getDefaultChar());
  221533. setBold (bold);
  221534. setItalic (italic);
  221535. if (addAllGlyphsToFont)
  221536. {
  221537. //xxx
  221538. jassertfalse
  221539. }
  221540. FontHelperCache::getInstance()->releaseFont (helper);
  221541. }
  221542. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  221543. {
  221544. // This method is only safe to be called from the normal UI thread..
  221545. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  221546. if (character == 0)
  221547. return false;
  221548. FontHelper* const helper = FontHelperCache::getInstance()
  221549. ->getFont (getName(), isBold(), isItalic());
  221550. Path path;
  221551. float width;
  221552. bool foundOne = false;
  221553. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  221554. {
  221555. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  221556. 1.0f / helper->totalSize));
  221557. addGlyph (character, path, width / helper->totalSize);
  221558. for (int i = 0; i < glyphs.size(); ++i)
  221559. {
  221560. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  221561. float kerning;
  221562. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  221563. {
  221564. kerning = (kerning - width) / helper->totalSize;
  221565. if (kerning != 0)
  221566. addKerningPair (character, g->getCharacter(), kerning);
  221567. }
  221568. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  221569. {
  221570. kerning = kerning / helper->totalSize - g->width;
  221571. if (kerning != 0)
  221572. addKerningPair (g->getCharacter(), character, kerning);
  221573. }
  221574. }
  221575. foundOne = true;
  221576. }
  221577. FontHelperCache::getInstance()->releaseFont (helper);
  221578. return foundOne;
  221579. }
  221580. const StringArray Font::findAllTypefaceNames() throw()
  221581. {
  221582. StringArray names;
  221583. const ScopedAutoReleasePool pool;
  221584. NSArray* fonts = [UIFont familyNames];
  221585. for (unsigned int i = 0; i < [fonts count]; ++i)
  221586. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  221587. names.sort (true);
  221588. return names;
  221589. }
  221590. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  221591. {
  221592. defaultSans = "Lucida Grande";
  221593. defaultSerif = "Times New Roman";
  221594. defaultFixed = "Monaco";
  221595. }
  221596. #endif
  221597. /********* End of inlined file: juce_iphone_Fonts.mm *********/
  221598. /********* Start of inlined file: juce_iphone_MessageManager.mm *********/
  221599. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221600. // compiled on its own).
  221601. #ifdef JUCE_INCLUDED_FILE
  221602. struct CallbackMessagePayload
  221603. {
  221604. MessageCallbackFunction* function;
  221605. void* parameter;
  221606. void* volatile result;
  221607. bool volatile hasBeenExecuted;
  221608. };
  221609. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  221610. for example having more than one juce plugin loaded into a host, then when a
  221611. method is called, the actual code that runs might actually be in a different module
  221612. than the one you expect... So any calls to library functions or statics that are
  221613. made inside obj-c methods will probably end up getting executed in a different DLL's
  221614. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  221615. To work around this insanity, I'm only allowing obj-c methods to make calls to
  221616. virtual methods of an object that's known to live inside the right module's space.
  221617. */
  221618. class AppDelegateRedirector
  221619. {
  221620. public:
  221621. AppDelegateRedirector() {}
  221622. virtual ~AppDelegateRedirector() {}
  221623. virtual BOOL openFile (const NSString* filename)
  221624. {
  221625. if (JUCEApplication::getInstance() != 0)
  221626. {
  221627. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  221628. return YES;
  221629. }
  221630. return NO;
  221631. }
  221632. virtual void openFiles (NSArray* filenames)
  221633. {
  221634. StringArray files;
  221635. for (unsigned int i = 0; i < [filenames count]; ++i)
  221636. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  221637. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  221638. {
  221639. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  221640. }
  221641. }
  221642. virtual void focusChanged()
  221643. {
  221644. juce_HandleProcessFocusChange();
  221645. }
  221646. virtual void deliverMessage (void* message)
  221647. {
  221648. // no need for an mm lock here - deliverMessage locks it
  221649. MessageManager::getInstance()->deliverMessage (message);
  221650. }
  221651. virtual void performCallback (CallbackMessagePayload* pl)
  221652. {
  221653. pl->result = (*pl->function) (pl->parameter);
  221654. pl->hasBeenExecuted = true;
  221655. }
  221656. virtual void deleteSelf()
  221657. {
  221658. delete this;
  221659. }
  221660. };
  221661. END_JUCE_NAMESPACE
  221662. using namespace JUCE_NAMESPACE;
  221663. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  221664. static int numPendingMessages = 0;
  221665. @interface JuceAppDelegate : NSObject <UIApplicationDelegate>
  221666. {
  221667. @private
  221668. id oldDelegate;
  221669. AppDelegateRedirector* redirector;
  221670. @public
  221671. bool flushingMessages;
  221672. }
  221673. - (JuceAppDelegate*) init;
  221674. - (void) dealloc;
  221675. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url;
  221676. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  221677. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  221678. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  221679. - (void) customEvent: (id) data;
  221680. - (void) performCallback: (id) info;
  221681. - (void) dummyMethod;
  221682. @end
  221683. @implementation JuceAppDelegate
  221684. - (JuceAppDelegate*) init
  221685. {
  221686. [super init];
  221687. redirector = new AppDelegateRedirector();
  221688. numPendingMessages = 0;
  221689. flushingMessages = false;
  221690. oldDelegate = [[UIApplication sharedApplication] delegate];
  221691. [[UIApplication sharedApplication] setDelegate: self];
  221692. return self;
  221693. }
  221694. - (void) dealloc
  221695. {
  221696. if (oldDelegate != 0)
  221697. [[UIApplication sharedApplication] setDelegate: oldDelegate];
  221698. redirector->deleteSelf();
  221699. [super dealloc];
  221700. }
  221701. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url
  221702. {
  221703. return redirector->openFile ([url absoluteString]);
  221704. }
  221705. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  221706. {
  221707. redirector->focusChanged();
  221708. }
  221709. - (void) applicationDidResignActive: (NSNotification*) aNotification
  221710. {
  221711. redirector->focusChanged();
  221712. }
  221713. - (void) applicationWillUnhide: (NSNotification*) aNotification
  221714. {
  221715. redirector->focusChanged();
  221716. }
  221717. - (void) customEvent: (id) n
  221718. {
  221719. atomicDecrement (numPendingMessages);
  221720. NSData* data = (NSData*) n;
  221721. void* message = 0;
  221722. [data getBytes: &message length: sizeof (message)];
  221723. [data release];
  221724. if (message != 0 && ! flushingMessages)
  221725. redirector->deliverMessage (message);
  221726. }
  221727. - (void) performCallback: (id) info
  221728. {
  221729. if ([info isKindOfClass: [NSData class]])
  221730. {
  221731. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  221732. if (pl != 0)
  221733. redirector->performCallback (pl);
  221734. }
  221735. else
  221736. {
  221737. jassertfalse // should never get here!
  221738. }
  221739. }
  221740. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  221741. @end
  221742. BEGIN_JUCE_NAMESPACE
  221743. static JuceAppDelegate* juceAppDelegate = 0;
  221744. void MessageManager::runDispatchLoop()
  221745. {
  221746. jassert (isThisTheMessageThread()); // must only be called by the message thread
  221747. runDispatchLoopUntil (-1);
  221748. }
  221749. static const int quitMessageId = 0xfffff321;
  221750. void MessageManager::stopDispatchLoop()
  221751. {
  221752. Message* const m = new Message (quitMessageId, 0, 0, 0);
  221753. m->messageRecipient = 0;
  221754. postMessageToQueue (m);
  221755. quitMessagePosted = true;
  221756. }
  221757. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  221758. {
  221759. const ScopedAutoReleasePool pool;
  221760. jassert (isThisTheMessageThread()); // must only be called by the message thread
  221761. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  221762. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  221763. while (! quitMessagePosted)
  221764. {
  221765. const ScopedAutoReleasePool pool;
  221766. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  221767. beforeDate: endDate];
  221768. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  221769. break;
  221770. }
  221771. return ! quitMessagePosted;
  221772. }
  221773. void MessageManager::doPlatformSpecificInitialisation()
  221774. {
  221775. if (juceAppDelegate == 0)
  221776. juceAppDelegate = [[JuceAppDelegate alloc] init];
  221777. }
  221778. void MessageManager::doPlatformSpecificShutdown()
  221779. {
  221780. if (juceAppDelegate != 0)
  221781. {
  221782. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  221783. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  221784. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  221785. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  221786. juceAppDelegate->flushingMessages = true;
  221787. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  221788. {
  221789. const ScopedAutoReleasePool pool;
  221790. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  221791. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  221792. }
  221793. [juceAppDelegate release];
  221794. juceAppDelegate = 0;
  221795. }
  221796. }
  221797. bool juce_postMessageToSystemQueue (void* message)
  221798. {
  221799. atomicIncrement (numPendingMessages);
  221800. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  221801. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  221802. waitUntilDone: NO];
  221803. return true;
  221804. }
  221805. void MessageManager::broadcastMessage (const String& value) throw()
  221806. {
  221807. }
  221808. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  221809. void* data)
  221810. {
  221811. if (isThisTheMessageThread())
  221812. {
  221813. return (*callback) (data);
  221814. }
  221815. else
  221816. {
  221817. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  221818. // deadlock because the message manager is blocked from running, so can never
  221819. // call your function..
  221820. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  221821. const ScopedAutoReleasePool pool;
  221822. CallbackMessagePayload cmp;
  221823. cmp.function = callback;
  221824. cmp.parameter = data;
  221825. cmp.result = 0;
  221826. cmp.hasBeenExecuted = false;
  221827. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  221828. withObject: [NSData dataWithBytesNoCopy: &cmp
  221829. length: sizeof (cmp)
  221830. freeWhenDone: NO]
  221831. waitUntilDone: YES];
  221832. return cmp.result;
  221833. }
  221834. }
  221835. #endif
  221836. /********* End of inlined file: juce_iphone_MessageManager.mm *********/
  221837. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  221838. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221839. // compiled on its own).
  221840. #ifdef JUCE_INCLUDED_FILE
  221841. #if JUCE_MAC
  221842. END_JUCE_NAMESPACE
  221843. using namespace JUCE_NAMESPACE;
  221844. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  221845. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221846. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  221847. #else
  221848. @interface JuceFileChooserDelegate : NSObject
  221849. #endif
  221850. {
  221851. StringArray* filters;
  221852. }
  221853. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  221854. - (void) dealloc;
  221855. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  221856. @end
  221857. @implementation JuceFileChooserDelegate
  221858. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  221859. {
  221860. [super init];
  221861. filters = filters_;
  221862. return self;
  221863. }
  221864. - (void) dealloc
  221865. {
  221866. delete filters;
  221867. [super dealloc];
  221868. }
  221869. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  221870. {
  221871. const String fname (nsStringToJuce (filename));
  221872. for (int i = filters->size(); --i >= 0;)
  221873. if (fname.matchesWildcard ((*filters)[i], true))
  221874. return true;
  221875. return File (fname).isDirectory();
  221876. }
  221877. @end
  221878. BEGIN_JUCE_NAMESPACE
  221879. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  221880. const String& title,
  221881. const File& currentFileOrDirectory,
  221882. const String& filter,
  221883. bool selectsDirectory,
  221884. bool isSaveDialogue,
  221885. bool warnAboutOverwritingExistingFiles,
  221886. bool selectMultipleFiles,
  221887. FilePreviewComponent* extraInfoComponent)
  221888. {
  221889. const ScopedAutoReleasePool pool;
  221890. StringArray* filters = new StringArray();
  221891. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  221892. filters->trim();
  221893. filters->removeEmptyStrings();
  221894. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  221895. [delegate autorelease];
  221896. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  221897. : [NSOpenPanel openPanel];
  221898. [panel setTitle: juceStringToNS (title)];
  221899. if (! isSaveDialogue)
  221900. {
  221901. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  221902. [openPanel setCanChooseDirectories: selectsDirectory];
  221903. [openPanel setCanChooseFiles: ! selectsDirectory];
  221904. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  221905. }
  221906. [panel setDelegate: delegate];
  221907. String directory, filename;
  221908. if (currentFileOrDirectory.isDirectory())
  221909. {
  221910. directory = currentFileOrDirectory.getFullPathName();
  221911. }
  221912. else
  221913. {
  221914. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  221915. filename = currentFileOrDirectory.getFileName();
  221916. }
  221917. if ([panel runModalForDirectory: juceStringToNS (directory)
  221918. file: juceStringToNS (filename)]
  221919. == NSOKButton)
  221920. {
  221921. if (isSaveDialogue)
  221922. {
  221923. results.add (new File (nsStringToJuce ([panel filename])));
  221924. }
  221925. else
  221926. {
  221927. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  221928. NSArray* urls = [openPanel filenames];
  221929. for (unsigned int i = 0; i < [urls count]; ++i)
  221930. {
  221931. NSString* f = [urls objectAtIndex: i];
  221932. results.add (new File (nsStringToJuce (f)));
  221933. }
  221934. }
  221935. }
  221936. [panel setDelegate: nil];
  221937. }
  221938. #else
  221939. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  221940. const String& title,
  221941. const File& currentFileOrDirectory,
  221942. const String& filter,
  221943. bool selectsDirectory,
  221944. bool isSaveDialogue,
  221945. bool warnAboutOverwritingExistingFiles,
  221946. bool selectMultipleFiles,
  221947. FilePreviewComponent* extraInfoComponent)
  221948. {
  221949. const ScopedAutoReleasePool pool;
  221950. jassertfalse //xxx to do
  221951. }
  221952. #endif
  221953. #endif
  221954. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  221955. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  221956. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221957. // compiled on its own).
  221958. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  221959. #if JUCE_MAC
  221960. END_JUCE_NAMESPACE
  221961. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  221962. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  221963. {
  221964. CriticalSection* contextLock;
  221965. bool needsUpdate;
  221966. }
  221967. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  221968. - (bool) makeActive;
  221969. - (void) makeInactive;
  221970. - (void) reshape;
  221971. @end
  221972. @implementation ThreadSafeNSOpenGLView
  221973. - (id) initWithFrame: (NSRect) frameRect
  221974. pixelFormat: (NSOpenGLPixelFormat*) format
  221975. {
  221976. contextLock = new CriticalSection();
  221977. self = [super initWithFrame: frameRect pixelFormat: format];
  221978. if (self != nil)
  221979. [[NSNotificationCenter defaultCenter] addObserver: self
  221980. selector: @selector (_surfaceNeedsUpdate:)
  221981. name: NSViewGlobalFrameDidChangeNotification
  221982. object: self];
  221983. return self;
  221984. }
  221985. - (void) dealloc
  221986. {
  221987. [[NSNotificationCenter defaultCenter] removeObserver: self];
  221988. delete contextLock;
  221989. [super dealloc];
  221990. }
  221991. - (bool) makeActive
  221992. {
  221993. const ScopedLock sl (*contextLock);
  221994. if ([self openGLContext] == 0)
  221995. return false;
  221996. [[self openGLContext] makeCurrentContext];
  221997. if (needsUpdate)
  221998. {
  221999. [super update];
  222000. needsUpdate = false;
  222001. }
  222002. return true;
  222003. }
  222004. - (void) makeInactive
  222005. {
  222006. const ScopedLock sl (*contextLock);
  222007. [NSOpenGLContext clearCurrentContext];
  222008. }
  222009. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  222010. {
  222011. const ScopedLock sl (*contextLock);
  222012. needsUpdate = true;
  222013. }
  222014. - (void) update
  222015. {
  222016. const ScopedLock sl (*contextLock);
  222017. needsUpdate = true;
  222018. }
  222019. - (void) reshape
  222020. {
  222021. const ScopedLock sl (*contextLock);
  222022. needsUpdate = true;
  222023. }
  222024. @end
  222025. BEGIN_JUCE_NAMESPACE
  222026. class WindowedGLContext : public OpenGLContext
  222027. {
  222028. public:
  222029. WindowedGLContext (Component* const component,
  222030. const OpenGLPixelFormat& pixelFormat_,
  222031. NSOpenGLContext* sharedContext)
  222032. : renderContext (0),
  222033. pixelFormat (pixelFormat_)
  222034. {
  222035. jassert (component != 0);
  222036. NSOpenGLPixelFormatAttribute attribs [64];
  222037. int n = 0;
  222038. attribs[n++] = NSOpenGLPFADoubleBuffer;
  222039. attribs[n++] = NSOpenGLPFAAccelerated;
  222040. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  222041. attribs[n++] = NSOpenGLPFAColorSize;
  222042. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  222043. pixelFormat.greenBits,
  222044. pixelFormat.blueBits);
  222045. attribs[n++] = NSOpenGLPFAAlphaSize;
  222046. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  222047. attribs[n++] = NSOpenGLPFADepthSize;
  222048. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  222049. attribs[n++] = NSOpenGLPFAStencilSize;
  222050. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  222051. attribs[n++] = NSOpenGLPFAAccumSize;
  222052. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  222053. pixelFormat.accumulationBufferGreenBits,
  222054. pixelFormat.accumulationBufferBlueBits,
  222055. pixelFormat.accumulationBufferAlphaBits);
  222056. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222057. attribs[n++] = NSOpenGLPFASampleBuffers;
  222058. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  222059. attribs[n++] = NSOpenGLPFAClosestPolicy;
  222060. attribs[n++] = NSOpenGLPFANoRecovery;
  222061. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  222062. NSOpenGLPixelFormat* format
  222063. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  222064. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222065. pixelFormat: format];
  222066. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  222067. shareContext: sharedContext] autorelease];
  222068. const GLint swapInterval = 1;
  222069. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  222070. [view setOpenGLContext: renderContext];
  222071. [renderContext setView: view];
  222072. [format release];
  222073. viewHolder = new NSViewComponentInternal (view, component);
  222074. }
  222075. ~WindowedGLContext()
  222076. {
  222077. makeInactive();
  222078. [renderContext setView: nil];
  222079. delete viewHolder;
  222080. }
  222081. bool makeActive() const throw()
  222082. {
  222083. jassert (renderContext != 0);
  222084. [view makeActive];
  222085. return isActive();
  222086. }
  222087. bool makeInactive() const throw()
  222088. {
  222089. [view makeInactive];
  222090. return true;
  222091. }
  222092. bool isActive() const throw()
  222093. {
  222094. return [NSOpenGLContext currentContext] == renderContext;
  222095. }
  222096. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  222097. void* getRawContext() const throw() { return renderContext; }
  222098. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222099. {
  222100. }
  222101. void swapBuffers()
  222102. {
  222103. [renderContext flushBuffer];
  222104. }
  222105. bool setSwapInterval (const int numFramesPerSwap)
  222106. {
  222107. [renderContext setValues: (const GLint*) &numFramesPerSwap
  222108. forParameter: NSOpenGLCPSwapInterval];
  222109. return true;
  222110. }
  222111. int getSwapInterval() const
  222112. {
  222113. GLint numFrames = 0;
  222114. [renderContext getValues: &numFrames
  222115. forParameter: NSOpenGLCPSwapInterval];
  222116. return numFrames;
  222117. }
  222118. void repaint()
  222119. {
  222120. // we need to invalidate the juce view that holds this gl view, to make it
  222121. // cause a repaint callback
  222122. NSView* v = (NSView*) viewHolder->view;
  222123. NSRect r = [v frame];
  222124. // bit of a bodge here.. if we only invalidate the area of the gl component,
  222125. // it's completely covered by the NSOpenGLView, so the OS throws away the
  222126. // repaint message, thus never causing our paint() callback, and never repainting
  222127. // the comp. So invalidating just a little bit around the edge helps..
  222128. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  222129. }
  222130. void* getNativeWindowHandle() const { return viewHolder->view; }
  222131. juce_UseDebuggingNewOperator
  222132. NSOpenGLContext* renderContext;
  222133. ThreadSafeNSOpenGLView* view;
  222134. private:
  222135. OpenGLPixelFormat pixelFormat;
  222136. NSViewComponentInternal* viewHolder;
  222137. WindowedGLContext (const WindowedGLContext&);
  222138. const WindowedGLContext& operator= (const WindowedGLContext&);
  222139. };
  222140. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222141. const OpenGLPixelFormat& pixelFormat,
  222142. const OpenGLContext* const contextToShareWith)
  222143. {
  222144. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222145. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  222146. if (c->renderContext == 0)
  222147. deleteAndZero (c);
  222148. return c;
  222149. }
  222150. void* OpenGLComponent::getNativeWindowHandle() const
  222151. {
  222152. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  222153. : 0;
  222154. }
  222155. void juce_glViewport (const int w, const int h)
  222156. {
  222157. glViewport (0, 0, w, h);
  222158. }
  222159. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222160. OwnedArray <OpenGLPixelFormat>& results)
  222161. {
  222162. /* GLint attribs [64];
  222163. int n = 0;
  222164. attribs[n++] = AGL_RGBA;
  222165. attribs[n++] = AGL_DOUBLEBUFFER;
  222166. attribs[n++] = AGL_ACCELERATED;
  222167. attribs[n++] = AGL_NO_RECOVERY;
  222168. attribs[n++] = AGL_NONE;
  222169. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222170. while (p != 0)
  222171. {
  222172. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222173. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222174. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222175. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222176. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222177. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222178. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222179. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222180. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222181. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222182. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222183. results.add (pf);
  222184. p = aglNextPixelFormat (p);
  222185. }*/
  222186. //jassertfalse //xxx can't see how you do this in cocoa!
  222187. }
  222188. #else
  222189. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222190. const OpenGLPixelFormat& pixelFormat,
  222191. const OpenGLContext* const contextToShareWith)
  222192. {
  222193. return 0;
  222194. }
  222195. void juce_glViewport (const int w, const int h)
  222196. {
  222197. //glViewport (0, 0, w, h);
  222198. }
  222199. #endif
  222200. #endif
  222201. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  222202. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  222203. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222204. // compiled on its own).
  222205. #ifdef JUCE_INCLUDED_FILE
  222206. #if JUCE_MAC
  222207. static NSImage* juceImageToNSImage (const Image& image)
  222208. {
  222209. const ScopedAutoReleasePool pool;
  222210. int lineStride, pixelStride;
  222211. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  222212. lineStride, pixelStride);
  222213. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  222214. initWithBitmapDataPlanes: NULL
  222215. pixelsWide: image.getWidth()
  222216. pixelsHigh: image.getHeight()
  222217. bitsPerSample: 8
  222218. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  222219. hasAlpha: image.hasAlphaChannel()
  222220. isPlanar: NO
  222221. colorSpaceName: NSCalibratedRGBColorSpace
  222222. bitmapFormat: (NSBitmapFormat) 0
  222223. bytesPerRow: lineStride
  222224. bitsPerPixel: pixelStride * 8];
  222225. unsigned char* newData = [rep bitmapData];
  222226. memcpy (newData, pixels, lineStride * image.getHeight());
  222227. image.releasePixelDataReadOnly (pixels);
  222228. NSImage* im = [[NSImage alloc] init];
  222229. [im addRepresentation: rep];
  222230. [rep release];
  222231. return im;
  222232. }
  222233. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  222234. {
  222235. NSImage* im = juceImageToNSImage (image);
  222236. NSCursor* c = [[NSCursor alloc] initWithImage: im
  222237. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  222238. [im release];
  222239. return (void*) c;
  222240. }
  222241. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  222242. {
  222243. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  222244. jassert (im != 0);
  222245. if (im == 0)
  222246. return 0;
  222247. void* const curs = juce_createMouseCursorFromImage (*im,
  222248. (int) (hx * im->getWidth()),
  222249. (int) (hy * im->getHeight()));
  222250. delete im;
  222251. return curs;
  222252. }
  222253. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  222254. {
  222255. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  222256. MemoryBlock mb;
  222257. if (f.getChildFile (filename).loadFileAsData (mb))
  222258. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  222259. return 0;
  222260. }
  222261. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  222262. {
  222263. const ScopedAutoReleasePool pool;
  222264. NSCursor* c = 0;
  222265. switch (type)
  222266. {
  222267. case MouseCursor::NormalCursor:
  222268. c = [NSCursor arrowCursor];
  222269. break;
  222270. case MouseCursor::NoCursor:
  222271. {
  222272. Image blank (Image::ARGB, 8, 8, true);
  222273. return juce_createMouseCursorFromImage (blank, 0, 0);
  222274. }
  222275. case MouseCursor::DraggingHandCursor:
  222276. c = [NSCursor openHandCursor];
  222277. break;
  222278. case MouseCursor::CopyingCursor:
  222279. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  222280. case MouseCursor::WaitCursor:
  222281. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  222282. break;
  222283. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  222284. case MouseCursor::IBeamCursor:
  222285. c = [NSCursor IBeamCursor];
  222286. break;
  222287. case MouseCursor::PointingHandCursor:
  222288. c = [NSCursor pointingHandCursor];
  222289. break;
  222290. case MouseCursor::LeftRightResizeCursor:
  222291. c = [NSCursor resizeLeftRightCursor];
  222292. break;
  222293. case MouseCursor::LeftEdgeResizeCursor:
  222294. c = [NSCursor resizeLeftCursor];
  222295. break;
  222296. case MouseCursor::RightEdgeResizeCursor:
  222297. c = [NSCursor resizeRightCursor];
  222298. break;
  222299. case MouseCursor::UpDownResizeCursor:
  222300. case MouseCursor::TopEdgeResizeCursor:
  222301. case MouseCursor::BottomEdgeResizeCursor:
  222302. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  222303. case MouseCursor::TopLeftCornerResizeCursor:
  222304. case MouseCursor::BottomRightCornerResizeCursor:
  222305. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  222306. case MouseCursor::TopRightCornerResizeCursor:
  222307. case MouseCursor::BottomLeftCornerResizeCursor:
  222308. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  222309. case MouseCursor::UpDownLeftRightResizeCursor:
  222310. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  222311. case MouseCursor::CrosshairCursor:
  222312. c = [NSCursor crosshairCursor];
  222313. break;
  222314. }
  222315. [c retain];
  222316. return (void*) c;
  222317. }
  222318. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  222319. {
  222320. NSCursor* c = (NSCursor*) cursorHandle;
  222321. [c release];
  222322. }
  222323. void MouseCursor::showInAllWindows() const throw()
  222324. {
  222325. showInWindow (0);
  222326. }
  222327. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  222328. {
  222329. NSCursor* const c = (NSCursor*) getHandle();
  222330. [c set];
  222331. }
  222332. #else
  222333. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw() { return 0; }
  222334. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw() { return 0; }
  222335. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw() {}
  222336. void MouseCursor::showInAllWindows() const throw() {}
  222337. void MouseCursor::showInWindow (ComponentPeer*) const throw() {}
  222338. #endif
  222339. #endif
  222340. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  222341. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  222342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222343. // compiled on its own).
  222344. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222345. #if JUCE_MAC
  222346. END_JUCE_NAMESPACE
  222347. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  222348. @interface DownloadClickDetector : NSObject
  222349. {
  222350. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  222351. }
  222352. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  222353. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  222354. request: (NSURLRequest*) request
  222355. frame: (WebFrame*) frame
  222356. decisionListener: (id<WebPolicyDecisionListener>) listener;
  222357. @end
  222358. @implementation DownloadClickDetector
  222359. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  222360. {
  222361. [super init];
  222362. ownerComponent = ownerComponent_;
  222363. return self;
  222364. }
  222365. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  222366. request: (NSURLRequest*) request
  222367. frame: (WebFrame*) frame
  222368. decisionListener: (id <WebPolicyDecisionListener>) listener
  222369. {
  222370. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  222371. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  222372. [listener use];
  222373. else
  222374. [listener ignore];
  222375. }
  222376. @end
  222377. BEGIN_JUCE_NAMESPACE
  222378. class WebBrowserComponentInternal : public NSViewComponent
  222379. {
  222380. public:
  222381. WebBrowserComponentInternal (WebBrowserComponent* owner)
  222382. {
  222383. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222384. frameName: @""
  222385. groupName: @""];
  222386. setView (webView);
  222387. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  222388. [webView setPolicyDelegate: clickListener];
  222389. }
  222390. ~WebBrowserComponentInternal()
  222391. {
  222392. [webView setPolicyDelegate: nil];
  222393. [clickListener release];
  222394. setView (0);
  222395. }
  222396. void goToURL (const String& url,
  222397. const StringArray* headers,
  222398. const MemoryBlock* postData)
  222399. {
  222400. NSMutableURLRequest* r
  222401. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  222402. cachePolicy: NSURLRequestUseProtocolCachePolicy
  222403. timeoutInterval: 30.0];
  222404. if (postData != 0 && postData->getSize() > 0)
  222405. {
  222406. [r setHTTPMethod: @"POST"];
  222407. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  222408. length: postData->getSize()]];
  222409. }
  222410. if (headers != 0)
  222411. {
  222412. for (int i = 0; i < headers->size(); ++i)
  222413. {
  222414. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  222415. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  222416. [r setValue: juceStringToNS (headerValue)
  222417. forHTTPHeaderField: juceStringToNS (headerName)];
  222418. }
  222419. }
  222420. stop();
  222421. [[webView mainFrame] loadRequest: r];
  222422. }
  222423. void goBack()
  222424. {
  222425. [webView goBack];
  222426. }
  222427. void goForward()
  222428. {
  222429. [webView goForward];
  222430. }
  222431. void stop()
  222432. {
  222433. [webView stopLoading: nil];
  222434. }
  222435. void refresh()
  222436. {
  222437. [webView reload: nil];
  222438. }
  222439. private:
  222440. WebView* webView;
  222441. DownloadClickDetector* clickListener;
  222442. };
  222443. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222444. : browser (0),
  222445. blankPageShown (false),
  222446. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222447. {
  222448. setOpaque (true);
  222449. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  222450. }
  222451. WebBrowserComponent::~WebBrowserComponent()
  222452. {
  222453. deleteAndZero (browser);
  222454. }
  222455. void WebBrowserComponent::goToURL (const String& url,
  222456. const StringArray* headers,
  222457. const MemoryBlock* postData)
  222458. {
  222459. lastURL = url;
  222460. lastHeaders.clear();
  222461. if (headers != 0)
  222462. lastHeaders = *headers;
  222463. lastPostData.setSize (0);
  222464. if (postData != 0)
  222465. lastPostData = *postData;
  222466. blankPageShown = false;
  222467. browser->goToURL (url, headers, postData);
  222468. }
  222469. void WebBrowserComponent::stop()
  222470. {
  222471. browser->stop();
  222472. }
  222473. void WebBrowserComponent::goBack()
  222474. {
  222475. lastURL = String::empty;
  222476. blankPageShown = false;
  222477. browser->goBack();
  222478. }
  222479. void WebBrowserComponent::goForward()
  222480. {
  222481. lastURL = String::empty;
  222482. browser->goForward();
  222483. }
  222484. void WebBrowserComponent::refresh()
  222485. {
  222486. browser->refresh();
  222487. }
  222488. void WebBrowserComponent::paint (Graphics& g)
  222489. {
  222490. }
  222491. void WebBrowserComponent::checkWindowAssociation()
  222492. {
  222493. if (isShowing())
  222494. {
  222495. if (blankPageShown)
  222496. goBack();
  222497. }
  222498. else
  222499. {
  222500. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  222501. {
  222502. // when the component becomes invisible, some stuff like flash
  222503. // carries on playing audio, so we need to force it onto a blank
  222504. // page to avoid this, (and send it back when it's made visible again).
  222505. blankPageShown = true;
  222506. browser->goToURL ("about:blank", 0, 0);
  222507. }
  222508. }
  222509. }
  222510. void WebBrowserComponent::reloadLastURL()
  222511. {
  222512. if (lastURL.isNotEmpty())
  222513. {
  222514. goToURL (lastURL, &lastHeaders, &lastPostData);
  222515. lastURL = String::empty;
  222516. }
  222517. }
  222518. void WebBrowserComponent::parentHierarchyChanged()
  222519. {
  222520. checkWindowAssociation();
  222521. }
  222522. void WebBrowserComponent::resized()
  222523. {
  222524. browser->setSize (getWidth(), getHeight());
  222525. }
  222526. void WebBrowserComponent::visibilityChanged()
  222527. {
  222528. checkWindowAssociation();
  222529. }
  222530. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222531. {
  222532. return true;
  222533. }
  222534. #else
  222535. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222536. {
  222537. }
  222538. WebBrowserComponent::~WebBrowserComponent()
  222539. {
  222540. }
  222541. void WebBrowserComponent::goToURL (const String& url,
  222542. const StringArray* headers,
  222543. const MemoryBlock* postData)
  222544. {
  222545. }
  222546. void WebBrowserComponent::stop()
  222547. {
  222548. }
  222549. void WebBrowserComponent::goBack()
  222550. {
  222551. }
  222552. void WebBrowserComponent::goForward()
  222553. {
  222554. }
  222555. void WebBrowserComponent::refresh()
  222556. {
  222557. }
  222558. void WebBrowserComponent::paint (Graphics& g)
  222559. {
  222560. }
  222561. void WebBrowserComponent::checkWindowAssociation()
  222562. {
  222563. }
  222564. void WebBrowserComponent::reloadLastURL()
  222565. {
  222566. }
  222567. void WebBrowserComponent::parentHierarchyChanged()
  222568. {
  222569. }
  222570. void WebBrowserComponent::resized()
  222571. {
  222572. }
  222573. void WebBrowserComponent::visibilityChanged()
  222574. {
  222575. }
  222576. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222577. {
  222578. return true;
  222579. }
  222580. #endif
  222581. #endif
  222582. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  222583. /********* Start of inlined file: juce_iphone_Audio.cpp *********/
  222584. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222585. // compiled on its own).
  222586. #ifdef JUCE_INCLUDED_FILE
  222587. #endif
  222588. /********* End of inlined file: juce_iphone_Audio.cpp *********/
  222589. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  222590. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222591. // compiled on its own).
  222592. #ifdef JUCE_INCLUDED_FILE
  222593. #if JUCE_MAC
  222594. #undef log
  222595. #define log(a) Logger::writeToLog(a)
  222596. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  222597. {
  222598. if (err == noErr)
  222599. return true;
  222600. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  222601. jassertfalse
  222602. return false;
  222603. }
  222604. #undef OK
  222605. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  222606. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  222607. {
  222608. String result;
  222609. CFStringRef str = 0;
  222610. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  222611. if (str != 0)
  222612. {
  222613. result = PlatformUtilities::cfStringToJuceString (str);
  222614. CFRelease (str);
  222615. str = 0;
  222616. }
  222617. MIDIEntityRef entity = 0;
  222618. MIDIEndpointGetEntity (endpoint, &entity);
  222619. if (entity == 0)
  222620. return result; // probably virtual
  222621. if (result.isEmpty())
  222622. {
  222623. // endpoint name has zero length - try the entity
  222624. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  222625. if (str != 0)
  222626. {
  222627. result += PlatformUtilities::cfStringToJuceString (str);
  222628. CFRelease (str);
  222629. str = 0;
  222630. }
  222631. }
  222632. // now consider the device's name
  222633. MIDIDeviceRef device = 0;
  222634. MIDIEntityGetDevice (entity, &device);
  222635. if (device == 0)
  222636. return result;
  222637. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  222638. if (str != 0)
  222639. {
  222640. const String s (PlatformUtilities::cfStringToJuceString (str));
  222641. CFRelease (str);
  222642. // if an external device has only one entity, throw away
  222643. // the endpoint name and just use the device name
  222644. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  222645. {
  222646. result = s;
  222647. }
  222648. else if (! result.startsWithIgnoreCase (s))
  222649. {
  222650. // prepend the device name to the entity name
  222651. result = (s + T(" ") + result).trimEnd();
  222652. }
  222653. }
  222654. return result;
  222655. }
  222656. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  222657. {
  222658. String result;
  222659. // Does the endpoint have connections?
  222660. CFDataRef connections = 0;
  222661. int numConnections = 0;
  222662. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  222663. if (connections != 0)
  222664. {
  222665. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  222666. if (numConnections > 0)
  222667. {
  222668. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  222669. for (int i = 0; i < numConnections; ++i, ++pid)
  222670. {
  222671. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  222672. MIDIObjectRef connObject;
  222673. MIDIObjectType connObjectType;
  222674. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  222675. if (err == noErr)
  222676. {
  222677. String s;
  222678. if (connObjectType == kMIDIObjectType_ExternalSource
  222679. || connObjectType == kMIDIObjectType_ExternalDestination)
  222680. {
  222681. // Connected to an external device's endpoint (10.3 and later).
  222682. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  222683. }
  222684. else
  222685. {
  222686. // Connected to an external device (10.2) (or something else, catch-all)
  222687. CFStringRef str = 0;
  222688. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  222689. if (str != 0)
  222690. {
  222691. s = PlatformUtilities::cfStringToJuceString (str);
  222692. CFRelease (str);
  222693. }
  222694. }
  222695. if (s.isNotEmpty())
  222696. {
  222697. if (result.isNotEmpty())
  222698. result += (", ");
  222699. result += s;
  222700. }
  222701. }
  222702. }
  222703. }
  222704. CFRelease (connections);
  222705. }
  222706. if (result.isNotEmpty())
  222707. return result;
  222708. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  222709. return getEndpointName (endpoint, false);
  222710. }
  222711. const StringArray MidiOutput::getDevices()
  222712. {
  222713. StringArray s;
  222714. const ItemCount num = MIDIGetNumberOfDestinations();
  222715. for (ItemCount i = 0; i < num; ++i)
  222716. {
  222717. MIDIEndpointRef dest = MIDIGetDestination (i);
  222718. if (dest != 0)
  222719. {
  222720. String name (getConnectedEndpointName (dest));
  222721. if (name.isEmpty())
  222722. name = "<error>";
  222723. s.add (name);
  222724. }
  222725. else
  222726. {
  222727. s.add ("<error>");
  222728. }
  222729. }
  222730. return s;
  222731. }
  222732. int MidiOutput::getDefaultDeviceIndex()
  222733. {
  222734. return 0;
  222735. }
  222736. static MIDIClientRef globalMidiClient;
  222737. static bool hasGlobalClientBeenCreated = false;
  222738. static bool makeSureClientExists()
  222739. {
  222740. if (! hasGlobalClientBeenCreated)
  222741. {
  222742. String name (T("JUCE"));
  222743. if (JUCEApplication::getInstance() != 0)
  222744. name = JUCEApplication::getInstance()->getApplicationName();
  222745. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  222746. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  222747. CFRelease (appName);
  222748. }
  222749. return hasGlobalClientBeenCreated;
  222750. }
  222751. struct MidiPortAndEndpoint
  222752. {
  222753. MIDIPortRef port;
  222754. MIDIEndpointRef endPoint;
  222755. };
  222756. MidiOutput* MidiOutput::openDevice (int index)
  222757. {
  222758. MidiOutput* mo = 0;
  222759. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  222760. {
  222761. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  222762. CFStringRef pname;
  222763. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  222764. {
  222765. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  222766. if (makeSureClientExists())
  222767. {
  222768. MIDIPortRef port;
  222769. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  222770. {
  222771. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  222772. mpe->port = port;
  222773. mpe->endPoint = endPoint;
  222774. mo = new MidiOutput();
  222775. mo->internal = (void*)mpe;
  222776. }
  222777. }
  222778. CFRelease (pname);
  222779. }
  222780. }
  222781. return mo;
  222782. }
  222783. MidiOutput::~MidiOutput()
  222784. {
  222785. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  222786. MIDIPortDispose (mpe->port);
  222787. delete mpe;
  222788. }
  222789. void MidiOutput::reset()
  222790. {
  222791. }
  222792. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222793. {
  222794. return false;
  222795. }
  222796. void MidiOutput::setVolume (float leftVol, float rightVol)
  222797. {
  222798. }
  222799. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222800. {
  222801. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  222802. if (message.isSysEx())
  222803. {
  222804. const int maxPacketSize = 256;
  222805. int pos = 0, bytesLeft = message.getRawDataSize();
  222806. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  222807. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  222808. packets->numPackets = numPackets;
  222809. MIDIPacket* p = packets->packet;
  222810. for (int i = 0; i < numPackets; ++i)
  222811. {
  222812. p->timeStamp = 0;
  222813. p->length = jmin (maxPacketSize, bytesLeft);
  222814. memcpy (p->data, message.getRawData() + pos, p->length);
  222815. pos += p->length;
  222816. bytesLeft -= p->length;
  222817. p = MIDIPacketNext (p);
  222818. }
  222819. MIDISend (mpe->port, mpe->endPoint, packets);
  222820. juce_free (packets);
  222821. }
  222822. else
  222823. {
  222824. MIDIPacketList packets;
  222825. packets.numPackets = 1;
  222826. packets.packet[0].timeStamp = 0;
  222827. packets.packet[0].length = message.getRawDataSize();
  222828. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  222829. MIDISend (mpe->port, mpe->endPoint, &packets);
  222830. }
  222831. }
  222832. const StringArray MidiInput::getDevices()
  222833. {
  222834. StringArray s;
  222835. const ItemCount num = MIDIGetNumberOfSources();
  222836. for (ItemCount i = 0; i < num; ++i)
  222837. {
  222838. MIDIEndpointRef source = MIDIGetSource (i);
  222839. if (source != 0)
  222840. {
  222841. String name (getConnectedEndpointName (source));
  222842. if (name.isEmpty())
  222843. name = "<error>";
  222844. s.add (name);
  222845. }
  222846. else
  222847. {
  222848. s.add ("<error>");
  222849. }
  222850. }
  222851. return s;
  222852. }
  222853. int MidiInput::getDefaultDeviceIndex()
  222854. {
  222855. return 0;
  222856. }
  222857. struct MidiPortAndCallback
  222858. {
  222859. MidiInput* input;
  222860. MIDIPortRef port;
  222861. MIDIEndpointRef endPoint;
  222862. MidiInputCallback* callback;
  222863. MemoryBlock pendingData;
  222864. int pendingBytes;
  222865. double pendingDataTime;
  222866. bool active;
  222867. };
  222868. static CriticalSection callbackLock;
  222869. static VoidArray activeCallbacks;
  222870. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  222871. {
  222872. if (*d == 0xf0)
  222873. {
  222874. mpe->pendingBytes = 0;
  222875. mpe->pendingDataTime = time;
  222876. }
  222877. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  222878. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  222879. uint8* dest = totalMessage + mpe->pendingBytes;
  222880. while (size > 0)
  222881. {
  222882. if (mpe->pendingBytes > 0 && *d >= 0x80)
  222883. {
  222884. if (*d >= 0xfa || *d == 0xf8)
  222885. {
  222886. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  222887. ++d;
  222888. --size;
  222889. }
  222890. else
  222891. {
  222892. if (*d == 0xf7)
  222893. {
  222894. *dest++ = *d++;
  222895. mpe->pendingBytes++;
  222896. --size;
  222897. }
  222898. break;
  222899. }
  222900. }
  222901. else
  222902. {
  222903. *dest++ = *d++;
  222904. mpe->pendingBytes++;
  222905. --size;
  222906. }
  222907. }
  222908. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  222909. {
  222910. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  222911. mpe->pendingBytes,
  222912. mpe->pendingDataTime));
  222913. mpe->pendingBytes = 0;
  222914. }
  222915. else
  222916. {
  222917. mpe->callback->handlePartialSysexMessage (mpe->input,
  222918. totalMessage,
  222919. mpe->pendingBytes,
  222920. mpe->pendingDataTime);
  222921. }
  222922. }
  222923. static void midiInputProc (const MIDIPacketList* pktlist,
  222924. void* readProcRefCon,
  222925. void* srcConnRefCon)
  222926. {
  222927. double time = Time::getMillisecondCounterHiRes() * 0.001;
  222928. const double originalTime = time;
  222929. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  222930. const ScopedLock sl (callbackLock);
  222931. if (activeCallbacks.contains (mpe) && mpe->active)
  222932. {
  222933. const MIDIPacket* packet = &pktlist->packet[0];
  222934. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  222935. {
  222936. const uint8* d = (const uint8*) (packet->data);
  222937. int size = packet->length;
  222938. while (size > 0)
  222939. {
  222940. time = originalTime;
  222941. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  222942. {
  222943. processSysex (mpe, d, size, time);
  222944. }
  222945. else
  222946. {
  222947. int used = 0;
  222948. const MidiMessage m (d, size, used, 0, time);
  222949. if (used <= 0)
  222950. {
  222951. jassertfalse // malformed midi message
  222952. break;
  222953. }
  222954. else
  222955. {
  222956. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  222957. }
  222958. size -= used;
  222959. d += used;
  222960. }
  222961. }
  222962. packet = MIDIPacketNext (packet);
  222963. }
  222964. }
  222965. }
  222966. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  222967. {
  222968. MidiInput* mi = 0;
  222969. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  222970. {
  222971. MIDIEndpointRef endPoint = MIDIGetSource (index);
  222972. if (endPoint != 0)
  222973. {
  222974. CFStringRef pname;
  222975. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  222976. {
  222977. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  222978. if (makeSureClientExists())
  222979. {
  222980. MIDIPortRef port;
  222981. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  222982. mpe->active = false;
  222983. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  222984. {
  222985. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  222986. {
  222987. mpe->port = port;
  222988. mpe->endPoint = endPoint;
  222989. mpe->callback = callback;
  222990. mpe->pendingBytes = 0;
  222991. mpe->pendingData.ensureSize (128);
  222992. mi = new MidiInput (getDevices() [index]);
  222993. mpe->input = mi;
  222994. mi->internal = (void*) mpe;
  222995. const ScopedLock sl (callbackLock);
  222996. activeCallbacks.add (mpe);
  222997. }
  222998. else
  222999. {
  223000. OK (MIDIPortDispose (port));
  223001. delete mpe;
  223002. }
  223003. }
  223004. else
  223005. {
  223006. delete mpe;
  223007. }
  223008. }
  223009. }
  223010. CFRelease (pname);
  223011. }
  223012. }
  223013. return mi;
  223014. }
  223015. MidiInput::MidiInput (const String& name_)
  223016. : name (name_)
  223017. {
  223018. }
  223019. MidiInput::~MidiInput()
  223020. {
  223021. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  223022. mpe->active = false;
  223023. callbackLock.enter();
  223024. activeCallbacks.removeValue (mpe);
  223025. callbackLock.exit();
  223026. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  223027. OK (MIDIPortDispose (mpe->port));
  223028. delete mpe;
  223029. }
  223030. void MidiInput::start()
  223031. {
  223032. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  223033. const ScopedLock sl (callbackLock);
  223034. mpe->active = true;
  223035. }
  223036. void MidiInput::stop()
  223037. {
  223038. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  223039. const ScopedLock sl (callbackLock);
  223040. mpe->active = false;
  223041. }
  223042. #undef log
  223043. #else
  223044. MidiOutput::~MidiOutput()
  223045. {
  223046. }
  223047. void MidiOutput::reset()
  223048. {
  223049. }
  223050. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223051. {
  223052. return false;
  223053. }
  223054. void MidiOutput::setVolume (float leftVol, float rightVol)
  223055. {
  223056. }
  223057. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223058. {
  223059. }
  223060. const StringArray MidiOutput::getDevices()
  223061. {
  223062. return StringArray();
  223063. }
  223064. MidiOutput* MidiOutput::openDevice (int index)
  223065. {
  223066. return 0;
  223067. }
  223068. const StringArray MidiInput::getDevices()
  223069. {
  223070. return StringArray();
  223071. }
  223072. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  223073. {
  223074. return 0;
  223075. }
  223076. #endif
  223077. #endif
  223078. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  223079. #else
  223080. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  223081. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223082. // compiled on its own).
  223083. #ifdef JUCE_INCLUDED_FILE
  223084. class NSViewComponentPeer;
  223085. END_JUCE_NAMESPACE
  223086. #define JuceNSView MakeObjCClassName(JuceNSView)
  223087. @interface JuceNSView : NSView
  223088. {
  223089. @public
  223090. NSViewComponentPeer* owner;
  223091. NSNotificationCenter* notificationCenter;
  223092. }
  223093. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  223094. - (void) dealloc;
  223095. - (BOOL) isOpaque;
  223096. - (void) drawRect: (NSRect) r;
  223097. - (void) mouseDown: (NSEvent*) ev;
  223098. - (void) asyncMouseDown: (NSEvent*) ev;
  223099. - (void) mouseUp: (NSEvent*) ev;
  223100. - (void) asyncMouseUp: (NSEvent*) ev;
  223101. - (void) mouseDragged: (NSEvent*) ev;
  223102. - (void) mouseMoved: (NSEvent*) ev;
  223103. - (void) mouseEntered: (NSEvent*) ev;
  223104. - (void) mouseExited: (NSEvent*) ev;
  223105. - (void) rightMouseDown: (NSEvent*) ev;
  223106. - (void) rightMouseDragged: (NSEvent*) ev;
  223107. - (void) rightMouseUp: (NSEvent*) ev;
  223108. - (void) otherMouseDown: (NSEvent*) ev;
  223109. - (void) otherMouseDragged: (NSEvent*) ev;
  223110. - (void) otherMouseUp: (NSEvent*) ev;
  223111. - (void) scrollWheel: (NSEvent*) ev;
  223112. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  223113. - (void) frameChanged: (NSNotification*) n;
  223114. - (void) keyDown: (NSEvent*) ev;
  223115. - (void) keyUp: (NSEvent*) ev;
  223116. - (void) flagsChanged: (NSEvent*) ev;
  223117. #if MACOS_10_4_OR_EARLIER
  223118. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  223119. #endif
  223120. - (BOOL) becomeFirstResponder;
  223121. - (BOOL) resignFirstResponder;
  223122. - (BOOL) acceptsFirstResponder;
  223123. - (NSArray*) getSupportedDragTypes;
  223124. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  223125. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  223126. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  223127. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  223128. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  223129. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  223130. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  223131. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  223132. @end
  223133. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  223134. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223135. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  223136. #else
  223137. @interface JuceNSWindow : NSWindow
  223138. #endif
  223139. {
  223140. @private
  223141. NSViewComponentPeer* owner;
  223142. bool isZooming;
  223143. }
  223144. - (void) setOwner: (NSViewComponentPeer*) owner;
  223145. - (BOOL) canBecomeKeyWindow;
  223146. - (void) becomeKeyWindow;
  223147. - (BOOL) windowShouldClose: (id) window;
  223148. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  223149. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  223150. - (void) zoom: (id) sender;
  223151. @end
  223152. BEGIN_JUCE_NAMESPACE
  223153. class NSViewComponentPeer : public ComponentPeer
  223154. {
  223155. public:
  223156. NSViewComponentPeer (Component* const component,
  223157. const int windowStyleFlags,
  223158. NSView* viewToAttachTo);
  223159. ~NSViewComponentPeer();
  223160. void* getNativeHandle() const;
  223161. void setVisible (bool shouldBeVisible);
  223162. void setTitle (const String& title);
  223163. void setPosition (int x, int y);
  223164. void setSize (int w, int h);
  223165. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  223166. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  223167. void getBounds (int& x, int& y, int& w, int& h) const;
  223168. int getScreenX() const;
  223169. int getScreenY() const;
  223170. void relativePositionToGlobal (int& x, int& y);
  223171. void globalPositionToRelative (int& x, int& y);
  223172. void setMinimised (bool shouldBeMinimised);
  223173. bool isMinimised() const;
  223174. void setFullScreen (bool shouldBeFullScreen);
  223175. bool isFullScreen() const;
  223176. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  223177. const BorderSize getFrameSize() const;
  223178. bool setAlwaysOnTop (bool alwaysOnTop);
  223179. void toFront (bool makeActiveWindow);
  223180. void toBehind (ComponentPeer* other);
  223181. void setIcon (const Image& newIcon);
  223182. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  223183. for example having more than one juce plugin loaded into a host, then when a
  223184. method is called, the actual code that runs might actually be in a different module
  223185. than the one you expect... So any calls to library functions or statics that are
  223186. made inside obj-c methods will probably end up getting executed in a different DLL's
  223187. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  223188. To work around this insanity, I'm only allowing obj-c methods to make calls to
  223189. virtual methods of an object that's known to live inside the right module's space.
  223190. */
  223191. virtual void redirectMouseDown (NSEvent* ev);
  223192. virtual void redirectMouseUp (NSEvent* ev);
  223193. virtual void redirectMouseDrag (NSEvent* ev);
  223194. virtual void redirectMouseMove (NSEvent* ev);
  223195. virtual void redirectMouseEnter (NSEvent* ev);
  223196. virtual void redirectMouseExit (NSEvent* ev);
  223197. virtual void redirectMouseWheel (NSEvent* ev);
  223198. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  223199. virtual bool redirectKeyDown (NSEvent* ev);
  223200. virtual bool redirectKeyUp (NSEvent* ev);
  223201. virtual void redirectModKeyChange (NSEvent* ev);
  223202. #if MACOS_10_4_OR_EARLIER
  223203. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  223204. #endif
  223205. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  223206. virtual bool isOpaque();
  223207. virtual void drawRect (NSRect r);
  223208. virtual bool canBecomeKeyWindow();
  223209. virtual bool windowShouldClose();
  223210. virtual void redirectMovedOrResized();
  223211. virtual NSRect constrainRect (NSRect r);
  223212. static void showArrowCursorIfNeeded();
  223213. virtual void viewFocusGain();
  223214. virtual void viewFocusLoss();
  223215. bool isFocused() const;
  223216. void grabFocus();
  223217. void textInputRequired (int x, int y);
  223218. void repaint (int x, int y, int w, int h);
  223219. void performAnyPendingRepaintsNow();
  223220. juce_UseDebuggingNewOperator
  223221. NSWindow* window;
  223222. JuceNSView* view;
  223223. bool isSharedWindow, fullScreen;
  223224. };
  223225. END_JUCE_NAMESPACE
  223226. @implementation JuceNSView
  223227. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  223228. withFrame: (NSRect) frame
  223229. {
  223230. [super initWithFrame: frame];
  223231. owner = owner_;
  223232. notificationCenter = [NSNotificationCenter defaultCenter];
  223233. [notificationCenter addObserver: self
  223234. selector: @selector (frameChanged:)
  223235. name: NSViewFrameDidChangeNotification
  223236. object: self];
  223237. if (! owner_->isSharedWindow)
  223238. {
  223239. [notificationCenter addObserver: self
  223240. selector: @selector (frameChanged:)
  223241. name: NSWindowDidMoveNotification
  223242. object: owner_->window];
  223243. }
  223244. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  223245. return self;
  223246. }
  223247. - (void) dealloc
  223248. {
  223249. [notificationCenter removeObserver: self];
  223250. [super dealloc];
  223251. }
  223252. - (void) drawRect: (NSRect) r
  223253. {
  223254. if (owner != 0)
  223255. owner->drawRect (r);
  223256. }
  223257. - (BOOL) isOpaque
  223258. {
  223259. return owner == 0 || owner->isOpaque();
  223260. }
  223261. - (void) mouseDown: (NSEvent*) ev
  223262. {
  223263. // In some host situations, the host will stop modal loops from working
  223264. // correctly if they're called from a mouse event, so we'll trigger
  223265. // the event asynchronously..
  223266. if (JUCEApplication::getInstance() == 0)
  223267. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  223268. withObject: ev
  223269. waitUntilDone: NO];
  223270. else
  223271. [self asyncMouseDown: ev];
  223272. }
  223273. - (void) asyncMouseDown: (NSEvent*) ev
  223274. {
  223275. if (owner != 0)
  223276. owner->redirectMouseDown (ev);
  223277. }
  223278. - (void) mouseUp: (NSEvent*) ev
  223279. {
  223280. // In some host situations, the host will stop modal loops from working
  223281. // correctly if they're called from a mouse event, so we'll trigger
  223282. // the event asynchronously..
  223283. if (JUCEApplication::getInstance() == 0)
  223284. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  223285. withObject: ev
  223286. waitUntilDone: NO];
  223287. else
  223288. [self asyncMouseUp: ev];
  223289. }
  223290. - (void) asyncMouseUp: (NSEvent*) ev
  223291. {
  223292. if (owner != 0)
  223293. owner->redirectMouseUp (ev);
  223294. }
  223295. - (void) mouseDragged: (NSEvent*) ev
  223296. {
  223297. if (owner != 0)
  223298. owner->redirectMouseDrag (ev);
  223299. }
  223300. - (void) mouseMoved: (NSEvent*) ev
  223301. {
  223302. if (owner != 0)
  223303. owner->redirectMouseMove (ev);
  223304. }
  223305. - (void) mouseEntered: (NSEvent*) ev
  223306. {
  223307. if (owner != 0)
  223308. owner->redirectMouseEnter (ev);
  223309. }
  223310. - (void) mouseExited: (NSEvent*) ev
  223311. {
  223312. if (owner != 0)
  223313. owner->redirectMouseExit (ev);
  223314. }
  223315. - (void) rightMouseDown: (NSEvent*) ev
  223316. {
  223317. [self mouseDown: ev];
  223318. }
  223319. - (void) rightMouseDragged: (NSEvent*) ev
  223320. {
  223321. [self mouseDragged: ev];
  223322. }
  223323. - (void) rightMouseUp: (NSEvent*) ev
  223324. {
  223325. [self mouseUp: ev];
  223326. }
  223327. - (void) otherMouseDown: (NSEvent*) ev
  223328. {
  223329. [self mouseDown: ev];
  223330. }
  223331. - (void) otherMouseDragged: (NSEvent*) ev
  223332. {
  223333. [self mouseDragged: ev];
  223334. }
  223335. - (void) otherMouseUp: (NSEvent*) ev
  223336. {
  223337. [self mouseUp: ev];
  223338. }
  223339. - (void) scrollWheel: (NSEvent*) ev
  223340. {
  223341. if (owner != 0)
  223342. owner->redirectMouseWheel (ev);
  223343. }
  223344. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  223345. {
  223346. return YES;
  223347. }
  223348. - (void) frameChanged: (NSNotification*) n
  223349. {
  223350. if (owner != 0)
  223351. owner->redirectMovedOrResized();
  223352. }
  223353. - (void) keyDown: (NSEvent*) ev
  223354. {
  223355. if (owner == 0 || ! owner->redirectKeyDown (ev))
  223356. [super keyDown: ev];
  223357. }
  223358. - (void) keyUp: (NSEvent*) ev
  223359. {
  223360. if (owner == 0 || ! owner->redirectKeyUp (ev))
  223361. [super keyUp: ev];
  223362. }
  223363. - (void) flagsChanged: (NSEvent*) ev
  223364. {
  223365. if (owner != 0)
  223366. owner->redirectModKeyChange (ev);
  223367. }
  223368. #if MACOS_10_4_OR_EARLIER
  223369. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  223370. {
  223371. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  223372. return true;
  223373. return [super performKeyEquivalent: ev];
  223374. }
  223375. #endif
  223376. - (BOOL) becomeFirstResponder
  223377. {
  223378. if (owner != 0)
  223379. owner->viewFocusGain();
  223380. return true;
  223381. }
  223382. - (BOOL) resignFirstResponder
  223383. {
  223384. if (owner != 0)
  223385. owner->viewFocusLoss();
  223386. return true;
  223387. }
  223388. - (BOOL) acceptsFirstResponder
  223389. {
  223390. return owner != 0 && owner->canBecomeKeyWindow();
  223391. }
  223392. - (NSArray*) getSupportedDragTypes
  223393. {
  223394. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  223395. }
  223396. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  223397. {
  223398. return owner != 0 && owner->sendDragCallback (type, sender);
  223399. }
  223400. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  223401. {
  223402. if ([self sendDragCallback: 0 sender: sender])
  223403. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  223404. else
  223405. return NSDragOperationNone;
  223406. }
  223407. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  223408. {
  223409. if ([self sendDragCallback: 0 sender: sender])
  223410. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  223411. else
  223412. return NSDragOperationNone;
  223413. }
  223414. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  223415. {
  223416. [self sendDragCallback: 1 sender: sender];
  223417. }
  223418. - (void) draggingExited: (id <NSDraggingInfo>) sender
  223419. {
  223420. [self sendDragCallback: 1 sender: sender];
  223421. }
  223422. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  223423. {
  223424. return YES;
  223425. }
  223426. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  223427. {
  223428. return [self sendDragCallback: 2 sender: sender];
  223429. }
  223430. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  223431. {
  223432. }
  223433. @end
  223434. @implementation JuceNSWindow
  223435. - (void) setOwner: (NSViewComponentPeer*) owner_
  223436. {
  223437. owner = owner_;
  223438. isZooming = false;
  223439. }
  223440. - (BOOL) canBecomeKeyWindow
  223441. {
  223442. return owner != 0 && owner->canBecomeKeyWindow();
  223443. }
  223444. - (void) becomeKeyWindow
  223445. {
  223446. [super becomeKeyWindow];
  223447. if (owner != 0)
  223448. owner->grabFocus();
  223449. }
  223450. - (BOOL) windowShouldClose: (id) window
  223451. {
  223452. return owner == 0 || owner->windowShouldClose();
  223453. }
  223454. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  223455. {
  223456. if (owner != 0)
  223457. frameRect = owner->constrainRect (frameRect);
  223458. return frameRect;
  223459. }
  223460. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  223461. {
  223462. if (isZooming)
  223463. return proposedFrameSize;
  223464. NSRect frameRect = [self frame];
  223465. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  223466. frameRect.size = proposedFrameSize;
  223467. if (owner != 0)
  223468. frameRect = owner->constrainRect (frameRect);
  223469. return frameRect.size;
  223470. }
  223471. - (void) zoom: (id) sender
  223472. {
  223473. isZooming = true;
  223474. [super zoom: sender];
  223475. isZooming = false;
  223476. }
  223477. - (void) windowWillMove: (NSNotification*) notification
  223478. {
  223479. if (juce::Component::getCurrentlyModalComponent() != 0
  223480. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  223481. && (owner->getStyleFlags() & juce::ComponentPeer::windowHasTitleBar) != 0)
  223482. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  223483. }
  223484. @end
  223485. BEGIN_JUCE_NAMESPACE
  223486. class JuceNSImage
  223487. {
  223488. public:
  223489. JuceNSImage (const int width, const int height, const bool hasAlpha)
  223490. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  223491. width, height, hasAlpha)
  223492. {
  223493. lineStride = 0;
  223494. pixelStride = 0;
  223495. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  223496. lineStride, pixelStride);
  223497. imageRep = [[NSBitmapImageRep alloc]
  223498. initWithBitmapDataPlanes: &imageData
  223499. pixelsWide: width
  223500. pixelsHigh: height
  223501. bitsPerSample: 8
  223502. samplesPerPixel: pixelStride
  223503. hasAlpha: hasAlpha
  223504. isPlanar: NO
  223505. colorSpaceName: NSCalibratedRGBColorSpace
  223506. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  223507. bytesPerRow: lineStride
  223508. bitsPerPixel: 8 * pixelStride ];
  223509. juceImage.releasePixelDataReadWrite (imageData);
  223510. }
  223511. ~JuceNSImage()
  223512. {
  223513. [imageRep release];
  223514. }
  223515. Image& getJuceImage() throw() { return juceImage; }
  223516. void draw (const float x, const float y,
  223517. const RectangleList& clip,
  223518. const int originX, const int originY) const
  223519. {
  223520. // Our data is BGRA and the damned image rep only takes RGBA, so
  223521. // we need to byte-swap the active areas if there's an alpha channel...
  223522. if (juceImage.hasAlphaChannel())
  223523. {
  223524. RectangleList::Iterator iter (clip);
  223525. while (iter.next())
  223526. {
  223527. const Rectangle* const r = iter.getRectangle();
  223528. swapRGBOrder (r->getX() + originX,
  223529. r->getY() + originY,
  223530. r->getWidth(),
  223531. r->getHeight());
  223532. }
  223533. }
  223534. NSPoint p;
  223535. p.x = x;
  223536. p.y = y;
  223537. [imageRep drawAtPoint: p];
  223538. }
  223539. void drawNSImage (NSImage* imageToDraw)
  223540. {
  223541. const ScopedAutoReleasePool pool;
  223542. [NSGraphicsContext saveGraphicsState];
  223543. [NSGraphicsContext setCurrentContext:
  223544. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  223545. [imageToDraw drawAtPoint: NSZeroPoint
  223546. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  223547. operation: NSCompositeSourceOver
  223548. fraction: 1.0f];
  223549. [[NSGraphicsContext currentContext] flushGraphics];
  223550. [NSGraphicsContext restoreGraphicsState];
  223551. if (juceImage.hasAlphaChannel())
  223552. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  223553. }
  223554. private:
  223555. Image juceImage;
  223556. NSBitmapImageRep* imageRep;
  223557. uint8* imageData;
  223558. int pixelStride, lineStride;
  223559. void swapRGBOrder (const int x, const int y, const int w, int h) const
  223560. {
  223561. #if JUCE_BIG_ENDIAN
  223562. jassert (pixelStride == 4);
  223563. #endif
  223564. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  223565. .contains (Rectangle (x, y, w, h)));
  223566. uint8* start = imageData + x * pixelStride + y * lineStride;
  223567. while (--h >= 0)
  223568. {
  223569. uint8* p = start;
  223570. start += lineStride;
  223571. for (int i = w; --i >= 0;)
  223572. {
  223573. #if JUCE_BIG_ENDIAN
  223574. const uint8 oldp3 = p[3];
  223575. const uint8 oldp1 = p[1];
  223576. p[3] = p[0];
  223577. p[0] = oldp1;
  223578. p[1] = p[2];
  223579. p[2] = oldp3;
  223580. #else
  223581. const uint8 oldp0 = p[0];
  223582. p[0] = p[2];
  223583. p[2] = oldp0;
  223584. #endif
  223585. p += pixelStride;
  223586. }
  223587. }
  223588. }
  223589. };
  223590. static ComponentPeer* currentlyFocusedPeer = 0;
  223591. static VoidArray keysCurrentlyDown;
  223592. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  223593. {
  223594. if (keysCurrentlyDown.contains ((void*) keyCode))
  223595. return true;
  223596. if (keyCode >= 'A' && keyCode <= 'Z'
  223597. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  223598. return true;
  223599. if (keyCode >= 'a' && keyCode <= 'z'
  223600. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  223601. return true;
  223602. return false;
  223603. }
  223604. static int getKeyCodeFromEvent (NSEvent* ev)
  223605. {
  223606. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  223607. int keyCode = unmodified[0];
  223608. if (keyCode == 0x19) // (backwards-tab)
  223609. keyCode = '\t';
  223610. else if (keyCode == 0x03) // (enter)
  223611. keyCode = '\r';
  223612. return keyCode;
  223613. }
  223614. static int currentModifiers = 0;
  223615. static void updateModifiers (NSEvent* e)
  223616. {
  223617. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  223618. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  223619. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  223620. m |= ModifierKeys::shiftModifier;
  223621. if (([e modifierFlags] & NSControlKeyMask) != 0)
  223622. m |= ModifierKeys::ctrlModifier;
  223623. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  223624. m |= ModifierKeys::altModifier;
  223625. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  223626. m |= ModifierKeys::commandModifier;
  223627. currentModifiers = m;
  223628. }
  223629. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  223630. {
  223631. updateModifiers (ev);
  223632. int keyCode = getKeyCodeFromEvent (ev);
  223633. if (keyCode != 0)
  223634. {
  223635. if (isKeyDown)
  223636. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  223637. else
  223638. keysCurrentlyDown.removeValue ((void*) keyCode);
  223639. }
  223640. }
  223641. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  223642. {
  223643. return ModifierKeys (currentModifiers);
  223644. }
  223645. void ModifierKeys::updateCurrentModifiers() throw()
  223646. {
  223647. currentModifierFlags = currentModifiers;
  223648. }
  223649. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  223650. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  223651. {
  223652. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  223653. x = roundFloatToInt (p.x);
  223654. y = roundFloatToInt ([view frame].size.height - p.y);
  223655. }
  223656. static int getModifierForButtonNumber (const int num) throw()
  223657. {
  223658. return num == 0 ? ModifierKeys::leftButtonModifier
  223659. : (num == 1 ? ModifierKeys::rightButtonModifier
  223660. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  223661. }
  223662. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  223663. const int windowStyleFlags,
  223664. NSView* viewToAttachTo)
  223665. : ComponentPeer (component, windowStyleFlags),
  223666. window (0),
  223667. view (0),
  223668. isSharedWindow (viewToAttachTo != 0),
  223669. fullScreen (false)
  223670. {
  223671. NSRect r;
  223672. r.origin.x = 0;
  223673. r.origin.y = 0;
  223674. r.size.width = (float) component->getWidth();
  223675. r.size.height = (float) component->getHeight();
  223676. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  223677. [view setPostsFrameChangedNotifications: YES];
  223678. if (isSharedWindow)
  223679. {
  223680. window = [viewToAttachTo window];
  223681. [viewToAttachTo addSubview: view];
  223682. setVisible (component->isVisible());
  223683. }
  223684. else
  223685. {
  223686. r.origin.x = (float) component->getX();
  223687. r.origin.y = (float) component->getY();
  223688. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  223689. unsigned int style = 0;
  223690. if ((windowStyleFlags & windowHasTitleBar) == 0)
  223691. style = NSBorderlessWindowMask;
  223692. else
  223693. style = NSTitledWindowMask;
  223694. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  223695. style |= NSMiniaturizableWindowMask;
  223696. if ((windowStyleFlags & windowHasCloseButton) != 0)
  223697. style |= NSClosableWindowMask;
  223698. if ((windowStyleFlags & windowIsResizable) != 0)
  223699. style |= NSResizableWindowMask;
  223700. window = [[JuceNSWindow alloc] initWithContentRect: r
  223701. styleMask: style
  223702. backing: NSBackingStoreBuffered
  223703. defer: YES];
  223704. [((JuceNSWindow*) window) setOwner: this];
  223705. [window orderOut: nil];
  223706. [window setDelegate: (JuceNSWindow*) window];
  223707. [window setOpaque: component->isOpaque()];
  223708. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  223709. if (component->isAlwaysOnTop())
  223710. [window setLevel: NSFloatingWindowLevel];
  223711. [window setContentView: view];
  223712. [window setAutodisplay: YES];
  223713. [window setAcceptsMouseMovedEvents: YES];
  223714. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  223715. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  223716. [window setReleasedWhenClosed: YES];
  223717. [window retain];
  223718. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  223719. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  223720. }
  223721. setTitle (component->getName());
  223722. }
  223723. NSViewComponentPeer::~NSViewComponentPeer()
  223724. {
  223725. view->owner = 0;
  223726. [view removeFromSuperview];
  223727. [view release];
  223728. if (! isSharedWindow)
  223729. {
  223730. [((JuceNSWindow*) window) setOwner: 0];
  223731. [window close];
  223732. [window release];
  223733. }
  223734. }
  223735. void* NSViewComponentPeer::getNativeHandle() const
  223736. {
  223737. return view;
  223738. }
  223739. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  223740. {
  223741. if (isSharedWindow)
  223742. {
  223743. [view setHidden: ! shouldBeVisible];
  223744. }
  223745. else
  223746. {
  223747. if (shouldBeVisible)
  223748. [window orderFront: nil];
  223749. else
  223750. [window orderOut: nil];
  223751. }
  223752. }
  223753. void NSViewComponentPeer::setTitle (const String& title)
  223754. {
  223755. const ScopedAutoReleasePool pool;
  223756. if (! isSharedWindow)
  223757. [window setTitle: juceStringToNS (title)];
  223758. }
  223759. void NSViewComponentPeer::setPosition (int x, int y)
  223760. {
  223761. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  223762. }
  223763. void NSViewComponentPeer::setSize (int w, int h)
  223764. {
  223765. setBounds (component->getX(), component->getY(), w, h, false);
  223766. }
  223767. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  223768. {
  223769. fullScreen = isNowFullScreen;
  223770. w = jmax (0, w);
  223771. h = jmax (0, h);
  223772. NSRect r;
  223773. r.origin.x = (float) x;
  223774. r.origin.y = (float) y;
  223775. r.size.width = (float) w;
  223776. r.size.height = (float) h;
  223777. if (isSharedWindow)
  223778. {
  223779. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  223780. if ([view frame].size.width != r.size.width
  223781. || [view frame].size.height != r.size.height)
  223782. [view setNeedsDisplay: true];
  223783. [view setFrame: r];
  223784. }
  223785. else
  223786. {
  223787. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  223788. [window setFrame: [window frameRectForContentRect: r]
  223789. display: true];
  223790. }
  223791. }
  223792. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  223793. {
  223794. NSRect r = [view frame];
  223795. if (global && [view window] != 0)
  223796. {
  223797. r = [view convertRect: r toView: nil];
  223798. NSRect wr = [[view window] frame];
  223799. r.origin.x += wr.origin.x;
  223800. r.origin.y += wr.origin.y;
  223801. y = (int) ([[[NSScreen screens] objectAtIndex:0] frame].size.height - r.origin.y - r.size.height);
  223802. }
  223803. else
  223804. {
  223805. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  223806. }
  223807. x = (int) r.origin.x;
  223808. w = (int) r.size.width;
  223809. h = (int) r.size.height;
  223810. }
  223811. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  223812. {
  223813. getBounds (x, y, w, h, ! isSharedWindow);
  223814. }
  223815. int NSViewComponentPeer::getScreenX() const
  223816. {
  223817. int x, y, w, h;
  223818. getBounds (x, y, w, h, true);
  223819. return x;
  223820. }
  223821. int NSViewComponentPeer::getScreenY() const
  223822. {
  223823. int x, y, w, h;
  223824. getBounds (x, y, w, h, true);
  223825. return y;
  223826. }
  223827. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  223828. {
  223829. int wx, wy, ww, wh;
  223830. getBounds (wx, wy, ww, wh, true);
  223831. x += wx;
  223832. y += wy;
  223833. }
  223834. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  223835. {
  223836. int wx, wy, ww, wh;
  223837. getBounds (wx, wy, ww, wh, true);
  223838. x -= wx;
  223839. y -= wy;
  223840. }
  223841. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  223842. {
  223843. if (constrainer != 0)
  223844. {
  223845. NSRect current = [window frame];
  223846. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  223847. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  223848. int x = (int) r.origin.x;
  223849. int y = (int) r.origin.y;
  223850. int w = (int) r.size.width;
  223851. int h = (int) r.size.height;
  223852. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  223853. (int) current.size.width, (int) current.size.height);
  223854. constrainer->checkBounds (x, y, w, h,
  223855. original,
  223856. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  223857. y != original.getY() && y + h == original.getBottom(),
  223858. x != original.getX() && x + w == original.getRight(),
  223859. y == original.getY() && y + h != original.getBottom(),
  223860. x == original.getX() && x + w != original.getRight());
  223861. r.origin.x = x;
  223862. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - y;
  223863. r.size.width = w;
  223864. r.size.height = h;
  223865. }
  223866. return r;
  223867. }
  223868. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  223869. {
  223870. if (! isSharedWindow)
  223871. {
  223872. if (shouldBeMinimised)
  223873. [window miniaturize: nil];
  223874. else
  223875. [window deminiaturize: nil];
  223876. }
  223877. }
  223878. bool NSViewComponentPeer::isMinimised() const
  223879. {
  223880. return window != 0 && [window isMiniaturized];
  223881. }
  223882. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  223883. {
  223884. if (! isSharedWindow)
  223885. {
  223886. Rectangle r (lastNonFullscreenBounds);
  223887. setMinimised (false);
  223888. if (fullScreen != shouldBeFullScreen)
  223889. {
  223890. if (shouldBeFullScreen)
  223891. r = Desktop::getInstance().getMainMonitorArea();
  223892. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  223893. if (r != getComponent()->getBounds() && ! r.isEmpty())
  223894. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  223895. }
  223896. }
  223897. }
  223898. bool NSViewComponentPeer::isFullScreen() const
  223899. {
  223900. return fullScreen;
  223901. }
  223902. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  223903. {
  223904. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  223905. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  223906. return false;
  223907. NSPoint p;
  223908. p.x = (float) x;
  223909. p.y = (float) y;
  223910. NSView* v = [view hitTest: p];
  223911. if (trueIfInAChildWindow)
  223912. return v != nil;
  223913. return v == view;
  223914. }
  223915. const BorderSize NSViewComponentPeer::getFrameSize() const
  223916. {
  223917. BorderSize b;
  223918. if (! isSharedWindow)
  223919. {
  223920. NSRect v = [view convertRect: [view frame] toView: nil];
  223921. NSRect w = [window frame];
  223922. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  223923. b.setBottom ((int) v.origin.y);
  223924. b.setLeft ((int) v.origin.x);
  223925. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  223926. }
  223927. return b;
  223928. }
  223929. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  223930. {
  223931. if (! isSharedWindow)
  223932. {
  223933. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  223934. : NSNormalWindowLevel];
  223935. }
  223936. return true;
  223937. }
  223938. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  223939. {
  223940. if (isSharedWindow)
  223941. {
  223942. [[view superview] addSubview: view
  223943. positioned: NSWindowAbove
  223944. relativeTo: nil];
  223945. }
  223946. if (window != 0 && component->isVisible())
  223947. {
  223948. if (makeActiveWindow)
  223949. [window makeKeyAndOrderFront: nil];
  223950. else
  223951. [window orderFront: nil];
  223952. }
  223953. }
  223954. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  223955. {
  223956. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  223957. if (isSharedWindow)
  223958. {
  223959. [[view superview] addSubview: view
  223960. positioned: NSWindowBelow
  223961. relativeTo: o->view];
  223962. }
  223963. else
  223964. {
  223965. [window orderWindow: NSWindowBelow
  223966. relativeTo: o->window != 0 ? [o->window windowNumber]
  223967. : nil ];
  223968. }
  223969. }
  223970. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  223971. {
  223972. // to do..
  223973. }
  223974. void NSViewComponentPeer::viewFocusGain()
  223975. {
  223976. if (currentlyFocusedPeer != this)
  223977. {
  223978. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  223979. currentlyFocusedPeer->handleFocusLoss();
  223980. currentlyFocusedPeer = this;
  223981. handleFocusGain();
  223982. }
  223983. }
  223984. void NSViewComponentPeer::viewFocusLoss()
  223985. {
  223986. if (currentlyFocusedPeer == this)
  223987. {
  223988. currentlyFocusedPeer = 0;
  223989. handleFocusLoss();
  223990. }
  223991. }
  223992. void juce_HandleProcessFocusChange()
  223993. {
  223994. keysCurrentlyDown.clear();
  223995. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  223996. {
  223997. if (Process::isForegroundProcess())
  223998. {
  223999. currentlyFocusedPeer->handleFocusGain();
  224000. ComponentPeer::bringModalComponentToFront();
  224001. }
  224002. else
  224003. {
  224004. currentlyFocusedPeer->handleFocusLoss();
  224005. // turn kiosk mode off if we lose focus..
  224006. Desktop::getInstance().setKioskModeComponent (0);
  224007. }
  224008. }
  224009. }
  224010. bool NSViewComponentPeer::isFocused() const
  224011. {
  224012. return isSharedWindow ? this == currentlyFocusedPeer
  224013. : (window != 0 && [window isKeyWindow]);
  224014. }
  224015. void NSViewComponentPeer::grabFocus()
  224016. {
  224017. if (window != 0)
  224018. {
  224019. [window makeKeyWindow];
  224020. [window makeFirstResponder: view];
  224021. viewFocusGain();
  224022. }
  224023. }
  224024. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  224025. {
  224026. }
  224027. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  224028. {
  224029. String unicode (nsStringToJuce ([ev characters]));
  224030. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  224031. int keyCode = getKeyCodeFromEvent (ev);
  224032. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  224033. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  224034. if (unicode.isNotEmpty() || keyCode != 0)
  224035. {
  224036. if (isKeyDown)
  224037. {
  224038. bool used = false;
  224039. while (unicode.length() > 0)
  224040. {
  224041. juce_wchar textCharacter = unicode[0];
  224042. unicode = unicode.substring (1);
  224043. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  224044. textCharacter = 0;
  224045. used = handleKeyUpOrDown (true) || used;
  224046. used = handleKeyPress (keyCode, textCharacter) || used;
  224047. }
  224048. return used;
  224049. }
  224050. else
  224051. {
  224052. if (handleKeyUpOrDown (false))
  224053. return true;
  224054. }
  224055. }
  224056. return false;
  224057. }
  224058. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  224059. {
  224060. updateKeysDown (ev, true);
  224061. bool used = handleKeyEvent (ev, true);
  224062. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  224063. {
  224064. // for command keys, the key-up event is thrown away, so simulate one..
  224065. updateKeysDown (ev, false);
  224066. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  224067. }
  224068. // (If we're running modally, don't allow unused keystrokes to be passed
  224069. // along to other blocked views..)
  224070. if (Component::getCurrentlyModalComponent() != 0)
  224071. used = true;
  224072. return used;
  224073. }
  224074. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  224075. {
  224076. updateKeysDown (ev, false);
  224077. return handleKeyEvent (ev, false)
  224078. || Component::getCurrentlyModalComponent() != 0;
  224079. }
  224080. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  224081. {
  224082. updateModifiers (ev);
  224083. handleModifierKeysChange();
  224084. }
  224085. #if MACOS_10_4_OR_EARLIER
  224086. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  224087. {
  224088. if ([ev type] == NSKeyDown)
  224089. return redirectKeyDown (ev);
  224090. else if ([ev type] == NSKeyUp)
  224091. return redirectKeyUp (ev);
  224092. return false;
  224093. }
  224094. #endif
  224095. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  224096. {
  224097. updateModifiers (ev);
  224098. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  224099. int x, y;
  224100. getMousePos (ev, view, x, y);
  224101. handleMouseDown (x, y, getMouseTime (ev));
  224102. }
  224103. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  224104. {
  224105. const int oldMods = currentModifiers;
  224106. updateModifiers (ev);
  224107. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  224108. int x, y;
  224109. getMousePos (ev, view, x, y);
  224110. handleMouseUp (oldMods, x, y, getMouseTime (ev));
  224111. showArrowCursorIfNeeded();
  224112. }
  224113. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  224114. {
  224115. updateModifiers (ev);
  224116. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  224117. int x, y;
  224118. getMousePos (ev, view, x, y);
  224119. handleMouseDrag (x, y, getMouseTime (ev));
  224120. }
  224121. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  224122. {
  224123. updateModifiers (ev);
  224124. int x, y;
  224125. getMousePos (ev, view, x, y);
  224126. handleMouseMove (x, y, getMouseTime (ev));
  224127. showArrowCursorIfNeeded();
  224128. }
  224129. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  224130. {
  224131. updateModifiers (ev);
  224132. int x, y;
  224133. getMousePos (ev, view, x, y);
  224134. handleMouseEnter (x, y, getMouseTime (ev));
  224135. }
  224136. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  224137. {
  224138. updateModifiers (ev);
  224139. int x, y;
  224140. getMousePos (ev, view, x, y);
  224141. handleMouseExit (x, y, getMouseTime (ev));
  224142. }
  224143. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  224144. {
  224145. updateModifiers (ev);
  224146. handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  224147. roundFloatToInt ([ev deltaY] * 10.0f),
  224148. getMouseTime (ev));
  224149. }
  224150. void NSViewComponentPeer::showArrowCursorIfNeeded()
  224151. {
  224152. if (Component::getComponentUnderMouse() == 0)
  224153. {
  224154. int mx, my;
  224155. Desktop::getInstance().getMousePosition (mx, my);
  224156. if (Desktop::getInstance().findComponentAt (mx, my) == 0)
  224157. [[NSCursor arrowCursor] set];
  224158. }
  224159. }
  224160. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  224161. {
  224162. NSString* bestType
  224163. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  224164. if (bestType == nil)
  224165. return false;
  224166. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  224167. int x = (int) p.x;
  224168. int y = (int) ([view frame].size.height - p.y);
  224169. StringArray files;
  224170. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  224171. if (list == nil)
  224172. return false;
  224173. if ([list isKindOfClass: [NSArray class]])
  224174. {
  224175. NSArray* items = (NSArray*) list;
  224176. for (unsigned int i = 0; i < [items count]; ++i)
  224177. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  224178. }
  224179. if (files.size() == 0)
  224180. return false;
  224181. if (type == 0)
  224182. handleFileDragMove (files, x, y);
  224183. else if (type == 1)
  224184. handleFileDragExit (files);
  224185. else if (type == 2)
  224186. handleFileDragDrop (files, x, y);
  224187. return true;
  224188. }
  224189. bool NSViewComponentPeer::isOpaque()
  224190. {
  224191. if (! getComponent()->isValidComponent())
  224192. return true;
  224193. return getComponent()->isOpaque();
  224194. }
  224195. void NSViewComponentPeer::drawRect (NSRect r)
  224196. {
  224197. if (r.size.width < 1.0f || r.size.height < 1.0f)
  224198. return;
  224199. const float y = [view frame].size.height - (r.origin.y + r.size.height);
  224200. JuceNSImage temp ((int) (r.size.width + 0.5f),
  224201. (int) (r.size.height + 0.5f),
  224202. ! getComponent()->isOpaque());
  224203. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  224204. const int originX = -roundFloatToInt (r.origin.x);
  224205. const int originY = -roundFloatToInt (y);
  224206. context.setOrigin (originX, originY);
  224207. const NSRect* rects = 0;
  224208. NSInteger numRects = 0;
  224209. [view getRectsBeingDrawn: &rects count: &numRects];
  224210. RectangleList clip;
  224211. for (int i = 0; i < numRects; ++i)
  224212. {
  224213. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  224214. roundFloatToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  224215. roundFloatToInt (rects[i].size.width),
  224216. roundFloatToInt (rects[i].size.height)));
  224217. }
  224218. if (context.reduceClipRegion (clip))
  224219. {
  224220. handlePaint (context);
  224221. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  224222. }
  224223. }
  224224. bool NSViewComponentPeer::canBecomeKeyWindow()
  224225. {
  224226. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  224227. }
  224228. bool NSViewComponentPeer::windowShouldClose()
  224229. {
  224230. if (! isValidPeer (this))
  224231. return YES;
  224232. handleUserClosingWindow();
  224233. return NO;
  224234. }
  224235. void NSViewComponentPeer::redirectMovedOrResized()
  224236. {
  224237. handleMovedOrResized();
  224238. }
  224239. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  224240. {
  224241. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  224242. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  224243. // is apparently still available in 64-bit apps..
  224244. if (enableOrDisable)
  224245. {
  224246. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  224247. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  224248. }
  224249. else
  224250. {
  224251. SetSystemUIMode (kUIModeNormal, 0);
  224252. }
  224253. }
  224254. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  224255. {
  224256. [view setNeedsDisplayInRect:
  224257. NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  224258. (float) w, (float) h)];
  224259. }
  224260. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  224261. {
  224262. [view displayIfNeeded];
  224263. }
  224264. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  224265. {
  224266. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  224267. }
  224268. static Image* NSImageToJuceImage (NSImage* image)
  224269. {
  224270. JuceNSImage juceIm ((int) [image size].width,
  224271. (int) [image size].height,
  224272. true);
  224273. juceIm.drawNSImage (image);
  224274. return juceIm.getJuceImage().createCopy();
  224275. }
  224276. Image* juce_createIconForFile (const File& file)
  224277. {
  224278. const ScopedAutoReleasePool pool;
  224279. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  224280. return NSImageToJuceImage (im);
  224281. }
  224282. const int KeyPress::spaceKey = ' ';
  224283. const int KeyPress::returnKey = 0x0d;
  224284. const int KeyPress::escapeKey = 0x1b;
  224285. const int KeyPress::backspaceKey = 0x7f;
  224286. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  224287. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  224288. const int KeyPress::upKey = NSUpArrowFunctionKey;
  224289. const int KeyPress::downKey = NSDownArrowFunctionKey;
  224290. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  224291. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  224292. const int KeyPress::endKey = NSEndFunctionKey;
  224293. const int KeyPress::homeKey = NSHomeFunctionKey;
  224294. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  224295. const int KeyPress::insertKey = -1;
  224296. const int KeyPress::tabKey = 9;
  224297. const int KeyPress::F1Key = NSF1FunctionKey;
  224298. const int KeyPress::F2Key = NSF2FunctionKey;
  224299. const int KeyPress::F3Key = NSF3FunctionKey;
  224300. const int KeyPress::F4Key = NSF4FunctionKey;
  224301. const int KeyPress::F5Key = NSF5FunctionKey;
  224302. const int KeyPress::F6Key = NSF6FunctionKey;
  224303. const int KeyPress::F7Key = NSF7FunctionKey;
  224304. const int KeyPress::F8Key = NSF8FunctionKey;
  224305. const int KeyPress::F9Key = NSF9FunctionKey;
  224306. const int KeyPress::F10Key = NSF10FunctionKey;
  224307. const int KeyPress::F11Key = NSF1FunctionKey;
  224308. const int KeyPress::F12Key = NSF12FunctionKey;
  224309. const int KeyPress::F13Key = NSF13FunctionKey;
  224310. const int KeyPress::F14Key = NSF14FunctionKey;
  224311. const int KeyPress::F15Key = NSF15FunctionKey;
  224312. const int KeyPress::F16Key = NSF16FunctionKey;
  224313. const int KeyPress::numberPad0 = 0x30020;
  224314. const int KeyPress::numberPad1 = 0x30021;
  224315. const int KeyPress::numberPad2 = 0x30022;
  224316. const int KeyPress::numberPad3 = 0x30023;
  224317. const int KeyPress::numberPad4 = 0x30024;
  224318. const int KeyPress::numberPad5 = 0x30025;
  224319. const int KeyPress::numberPad6 = 0x30026;
  224320. const int KeyPress::numberPad7 = 0x30027;
  224321. const int KeyPress::numberPad8 = 0x30028;
  224322. const int KeyPress::numberPad9 = 0x30029;
  224323. const int KeyPress::numberPadAdd = 0x3002a;
  224324. const int KeyPress::numberPadSubtract = 0x3002b;
  224325. const int KeyPress::numberPadMultiply = 0x3002c;
  224326. const int KeyPress::numberPadDivide = 0x3002d;
  224327. const int KeyPress::numberPadSeparator = 0x3002e;
  224328. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  224329. const int KeyPress::numberPadEquals = 0x30030;
  224330. const int KeyPress::numberPadDelete = 0x30031;
  224331. const int KeyPress::playKey = 0x30000;
  224332. const int KeyPress::stopKey = 0x30001;
  224333. const int KeyPress::fastForwardKey = 0x30002;
  224334. const int KeyPress::rewindKey = 0x30003;
  224335. #endif
  224336. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  224337. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  224338. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224339. // compiled on its own).
  224340. #ifdef JUCE_INCLUDED_FILE
  224341. #if JUCE_MAC
  224342. static NSImage* juceImageToNSImage (const Image& image)
  224343. {
  224344. const ScopedAutoReleasePool pool;
  224345. int lineStride, pixelStride;
  224346. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  224347. lineStride, pixelStride);
  224348. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  224349. initWithBitmapDataPlanes: NULL
  224350. pixelsWide: image.getWidth()
  224351. pixelsHigh: image.getHeight()
  224352. bitsPerSample: 8
  224353. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  224354. hasAlpha: image.hasAlphaChannel()
  224355. isPlanar: NO
  224356. colorSpaceName: NSCalibratedRGBColorSpace
  224357. bitmapFormat: (NSBitmapFormat) 0
  224358. bytesPerRow: lineStride
  224359. bitsPerPixel: pixelStride * 8];
  224360. unsigned char* newData = [rep bitmapData];
  224361. memcpy (newData, pixels, lineStride * image.getHeight());
  224362. image.releasePixelDataReadOnly (pixels);
  224363. NSImage* im = [[NSImage alloc] init];
  224364. [im addRepresentation: rep];
  224365. [rep release];
  224366. return im;
  224367. }
  224368. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  224369. {
  224370. NSImage* im = juceImageToNSImage (image);
  224371. NSCursor* c = [[NSCursor alloc] initWithImage: im
  224372. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  224373. [im release];
  224374. return (void*) c;
  224375. }
  224376. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  224377. {
  224378. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  224379. jassert (im != 0);
  224380. if (im == 0)
  224381. return 0;
  224382. void* const curs = juce_createMouseCursorFromImage (*im,
  224383. (int) (hx * im->getWidth()),
  224384. (int) (hy * im->getHeight()));
  224385. delete im;
  224386. return curs;
  224387. }
  224388. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  224389. {
  224390. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  224391. MemoryBlock mb;
  224392. if (f.getChildFile (filename).loadFileAsData (mb))
  224393. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  224394. return 0;
  224395. }
  224396. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  224397. {
  224398. const ScopedAutoReleasePool pool;
  224399. NSCursor* c = 0;
  224400. switch (type)
  224401. {
  224402. case MouseCursor::NormalCursor:
  224403. c = [NSCursor arrowCursor];
  224404. break;
  224405. case MouseCursor::NoCursor:
  224406. {
  224407. Image blank (Image::ARGB, 8, 8, true);
  224408. return juce_createMouseCursorFromImage (blank, 0, 0);
  224409. }
  224410. case MouseCursor::DraggingHandCursor:
  224411. c = [NSCursor openHandCursor];
  224412. break;
  224413. case MouseCursor::CopyingCursor:
  224414. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  224415. case MouseCursor::WaitCursor:
  224416. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  224417. break;
  224418. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  224419. case MouseCursor::IBeamCursor:
  224420. c = [NSCursor IBeamCursor];
  224421. break;
  224422. case MouseCursor::PointingHandCursor:
  224423. c = [NSCursor pointingHandCursor];
  224424. break;
  224425. case MouseCursor::LeftRightResizeCursor:
  224426. c = [NSCursor resizeLeftRightCursor];
  224427. break;
  224428. case MouseCursor::LeftEdgeResizeCursor:
  224429. c = [NSCursor resizeLeftCursor];
  224430. break;
  224431. case MouseCursor::RightEdgeResizeCursor:
  224432. c = [NSCursor resizeRightCursor];
  224433. break;
  224434. case MouseCursor::UpDownResizeCursor:
  224435. case MouseCursor::TopEdgeResizeCursor:
  224436. case MouseCursor::BottomEdgeResizeCursor:
  224437. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  224438. case MouseCursor::TopLeftCornerResizeCursor:
  224439. case MouseCursor::BottomRightCornerResizeCursor:
  224440. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  224441. case MouseCursor::TopRightCornerResizeCursor:
  224442. case MouseCursor::BottomLeftCornerResizeCursor:
  224443. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  224444. case MouseCursor::UpDownLeftRightResizeCursor:
  224445. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  224446. case MouseCursor::CrosshairCursor:
  224447. c = [NSCursor crosshairCursor];
  224448. break;
  224449. }
  224450. [c retain];
  224451. return (void*) c;
  224452. }
  224453. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  224454. {
  224455. NSCursor* c = (NSCursor*) cursorHandle;
  224456. [c release];
  224457. }
  224458. void MouseCursor::showInAllWindows() const throw()
  224459. {
  224460. showInWindow (0);
  224461. }
  224462. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  224463. {
  224464. NSCursor* const c = (NSCursor*) getHandle();
  224465. [c set];
  224466. }
  224467. #else
  224468. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw() { return 0; }
  224469. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw() { return 0; }
  224470. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw() {}
  224471. void MouseCursor::showInAllWindows() const throw() {}
  224472. void MouseCursor::showInWindow (ComponentPeer*) const throw() {}
  224473. #endif
  224474. #endif
  224475. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  224476. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  224477. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224478. // compiled on its own).
  224479. #ifdef JUCE_INCLUDED_FILE
  224480. class NSViewComponentInternal : public ComponentMovementWatcher
  224481. {
  224482. Component* const owner;
  224483. NSViewComponentPeer* currentPeer;
  224484. bool wasShowing;
  224485. public:
  224486. NSView* const view;
  224487. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  224488. : ComponentMovementWatcher (owner_),
  224489. owner (owner_),
  224490. currentPeer (0),
  224491. wasShowing (false),
  224492. view (view_)
  224493. {
  224494. [view_ retain];
  224495. if (owner_->isShowing())
  224496. componentPeerChanged();
  224497. }
  224498. ~NSViewComponentInternal()
  224499. {
  224500. [view removeFromSuperview];
  224501. [view release];
  224502. }
  224503. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  224504. {
  224505. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  224506. // The ComponentMovementWatcher version of this method avoids calling
  224507. // us when the top-level comp is resized, but for an NSView we need to know this
  224508. // because with inverted co-ords, we need to update the position even if the
  224509. // top-left pos hasn't changed
  224510. if (comp.isOnDesktop() && wasResized)
  224511. componentMovedOrResized (wasMoved, wasResized);
  224512. }
  224513. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  224514. {
  224515. Component* const topComp = owner->getTopLevelComponent();
  224516. if (topComp->getPeer() != 0)
  224517. {
  224518. int x = 0, y = 0;
  224519. owner->relativePositionToOtherComponent (topComp, x, y);
  224520. NSRect r;
  224521. r.origin.x = (float) x;
  224522. r.origin.y = (float) y;
  224523. r.size.width = (float) owner->getWidth();
  224524. r.size.height = (float) owner->getHeight();
  224525. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  224526. [view setFrame: r];
  224527. }
  224528. }
  224529. void componentPeerChanged()
  224530. {
  224531. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  224532. if (currentPeer != peer)
  224533. {
  224534. [view removeFromSuperview];
  224535. currentPeer = peer;
  224536. if (peer != 0)
  224537. {
  224538. [peer->view addSubview: view];
  224539. componentMovedOrResized (false, false);
  224540. }
  224541. }
  224542. [view setHidden: ! owner->isShowing()];
  224543. }
  224544. void componentVisibilityChanged (Component&)
  224545. {
  224546. componentPeerChanged();
  224547. }
  224548. juce_UseDebuggingNewOperator
  224549. private:
  224550. NSViewComponentInternal (const NSViewComponentInternal&);
  224551. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  224552. };
  224553. NSViewComponent::NSViewComponent()
  224554. : info (0)
  224555. {
  224556. }
  224557. NSViewComponent::~NSViewComponent()
  224558. {
  224559. delete info;
  224560. }
  224561. void NSViewComponent::setView (void* view)
  224562. {
  224563. if (view != getView())
  224564. {
  224565. deleteAndZero (info);
  224566. if (view != 0)
  224567. info = new NSViewComponentInternal ((NSView*) view, this);
  224568. }
  224569. }
  224570. void* NSViewComponent::getView() const
  224571. {
  224572. return info == 0 ? 0 : info->view;
  224573. }
  224574. void NSViewComponent::paint (Graphics& g)
  224575. {
  224576. }
  224577. #endif
  224578. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  224579. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  224580. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224581. // compiled on its own).
  224582. #ifdef JUCE_INCLUDED_FILE
  224583. AppleRemoteDevice::AppleRemoteDevice()
  224584. : device (0),
  224585. queue (0),
  224586. remoteId (0)
  224587. {
  224588. }
  224589. AppleRemoteDevice::~AppleRemoteDevice()
  224590. {
  224591. stop();
  224592. }
  224593. static io_object_t getAppleRemoteDevice() throw()
  224594. {
  224595. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  224596. io_iterator_t iter = 0;
  224597. io_object_t iod = 0;
  224598. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  224599. && iter != 0)
  224600. {
  224601. iod = IOIteratorNext (iter);
  224602. }
  224603. IOObjectRelease (iter);
  224604. return iod;
  224605. }
  224606. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  224607. {
  224608. jassert (*device == 0);
  224609. io_name_t classname;
  224610. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  224611. {
  224612. IOCFPlugInInterface** cfPlugInInterface = 0;
  224613. SInt32 score = 0;
  224614. if (IOCreatePlugInInterfaceForService (iod,
  224615. kIOHIDDeviceUserClientTypeID,
  224616. kIOCFPlugInInterfaceID,
  224617. &cfPlugInInterface,
  224618. &score) == kIOReturnSuccess)
  224619. {
  224620. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  224621. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  224622. device);
  224623. (void) hr;
  224624. (*cfPlugInInterface)->Release (cfPlugInInterface);
  224625. }
  224626. }
  224627. return *device != 0;
  224628. }
  224629. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  224630. {
  224631. if (queue != 0)
  224632. return true;
  224633. stop();
  224634. bool result = false;
  224635. io_object_t iod = getAppleRemoteDevice();
  224636. if (iod != 0)
  224637. {
  224638. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  224639. result = true;
  224640. else
  224641. stop();
  224642. IOObjectRelease (iod);
  224643. }
  224644. return result;
  224645. }
  224646. void AppleRemoteDevice::stop() throw()
  224647. {
  224648. if (queue != 0)
  224649. {
  224650. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  224651. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  224652. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  224653. queue = 0;
  224654. }
  224655. if (device != 0)
  224656. {
  224657. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  224658. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  224659. device = 0;
  224660. }
  224661. }
  224662. bool AppleRemoteDevice::isActive() const throw()
  224663. {
  224664. return queue != 0;
  224665. }
  224666. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  224667. {
  224668. if (result == kIOReturnSuccess)
  224669. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  224670. }
  224671. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  224672. {
  224673. Array <int> cookies;
  224674. CFArrayRef elements;
  224675. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  224676. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  224677. return false;
  224678. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  224679. {
  224680. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  224681. // get the cookie
  224682. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  224683. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  224684. continue;
  224685. long number;
  224686. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  224687. continue;
  224688. cookies.add ((int) number);
  224689. }
  224690. CFRelease (elements);
  224691. if ((*(IOHIDDeviceInterface**) device)
  224692. ->open ((IOHIDDeviceInterface**) device,
  224693. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  224694. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  224695. {
  224696. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  224697. if (queue != 0)
  224698. {
  224699. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  224700. for (int i = 0; i < cookies.size(); ++i)
  224701. {
  224702. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  224703. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  224704. }
  224705. CFRunLoopSourceRef eventSource;
  224706. if ((*(IOHIDQueueInterface**) queue)
  224707. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  224708. {
  224709. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  224710. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  224711. {
  224712. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  224713. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  224714. return true;
  224715. }
  224716. }
  224717. }
  224718. }
  224719. return false;
  224720. }
  224721. void AppleRemoteDevice::handleCallbackInternal()
  224722. {
  224723. int totalValues = 0;
  224724. AbsoluteTime nullTime = { 0, 0 };
  224725. char cookies [12];
  224726. int numCookies = 0;
  224727. while (numCookies < numElementsInArray (cookies))
  224728. {
  224729. IOHIDEventStruct e;
  224730. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  224731. break;
  224732. if ((int) e.elementCookie == 19)
  224733. {
  224734. remoteId = e.value;
  224735. buttonPressed (switched, false);
  224736. }
  224737. else
  224738. {
  224739. totalValues += e.value;
  224740. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  224741. }
  224742. }
  224743. cookies [numCookies++] = 0;
  224744. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  224745. static const char buttonPatterns[] =
  224746. {
  224747. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  224748. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  224749. 0x1f, 0x1d, 0x1c, 0x12, 0,
  224750. 0x1f, 0x1e, 0x1c, 0x12, 0,
  224751. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  224752. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  224753. 0x1f, 0x12, 0x04, 0x02, 0,
  224754. 0x1f, 0x12, 0x03, 0x02, 0,
  224755. 0x1f, 0x12, 0x1f, 0x12, 0,
  224756. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  224757. 19, 0
  224758. };
  224759. int buttonNum = (int) menuButton;
  224760. int i = 0;
  224761. while (i < numElementsInArray (buttonPatterns))
  224762. {
  224763. if (strcmp (cookies, buttonPatterns + i) == 0)
  224764. {
  224765. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  224766. break;
  224767. }
  224768. i += strlen (buttonPatterns + i) + 1;
  224769. ++buttonNum;
  224770. }
  224771. }
  224772. #endif
  224773. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  224774. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  224775. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224776. // compiled on its own).
  224777. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  224778. #if JUCE_MAC
  224779. END_JUCE_NAMESPACE
  224780. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  224781. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  224782. {
  224783. CriticalSection* contextLock;
  224784. bool needsUpdate;
  224785. }
  224786. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  224787. - (bool) makeActive;
  224788. - (void) makeInactive;
  224789. - (void) reshape;
  224790. @end
  224791. @implementation ThreadSafeNSOpenGLView
  224792. - (id) initWithFrame: (NSRect) frameRect
  224793. pixelFormat: (NSOpenGLPixelFormat*) format
  224794. {
  224795. contextLock = new CriticalSection();
  224796. self = [super initWithFrame: frameRect pixelFormat: format];
  224797. if (self != nil)
  224798. [[NSNotificationCenter defaultCenter] addObserver: self
  224799. selector: @selector (_surfaceNeedsUpdate:)
  224800. name: NSViewGlobalFrameDidChangeNotification
  224801. object: self];
  224802. return self;
  224803. }
  224804. - (void) dealloc
  224805. {
  224806. [[NSNotificationCenter defaultCenter] removeObserver: self];
  224807. delete contextLock;
  224808. [super dealloc];
  224809. }
  224810. - (bool) makeActive
  224811. {
  224812. const ScopedLock sl (*contextLock);
  224813. if ([self openGLContext] == 0)
  224814. return false;
  224815. [[self openGLContext] makeCurrentContext];
  224816. if (needsUpdate)
  224817. {
  224818. [super update];
  224819. needsUpdate = false;
  224820. }
  224821. return true;
  224822. }
  224823. - (void) makeInactive
  224824. {
  224825. const ScopedLock sl (*contextLock);
  224826. [NSOpenGLContext clearCurrentContext];
  224827. }
  224828. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  224829. {
  224830. const ScopedLock sl (*contextLock);
  224831. needsUpdate = true;
  224832. }
  224833. - (void) update
  224834. {
  224835. const ScopedLock sl (*contextLock);
  224836. needsUpdate = true;
  224837. }
  224838. - (void) reshape
  224839. {
  224840. const ScopedLock sl (*contextLock);
  224841. needsUpdate = true;
  224842. }
  224843. @end
  224844. BEGIN_JUCE_NAMESPACE
  224845. class WindowedGLContext : public OpenGLContext
  224846. {
  224847. public:
  224848. WindowedGLContext (Component* const component,
  224849. const OpenGLPixelFormat& pixelFormat_,
  224850. NSOpenGLContext* sharedContext)
  224851. : renderContext (0),
  224852. pixelFormat (pixelFormat_)
  224853. {
  224854. jassert (component != 0);
  224855. NSOpenGLPixelFormatAttribute attribs [64];
  224856. int n = 0;
  224857. attribs[n++] = NSOpenGLPFADoubleBuffer;
  224858. attribs[n++] = NSOpenGLPFAAccelerated;
  224859. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  224860. attribs[n++] = NSOpenGLPFAColorSize;
  224861. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  224862. pixelFormat.greenBits,
  224863. pixelFormat.blueBits);
  224864. attribs[n++] = NSOpenGLPFAAlphaSize;
  224865. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  224866. attribs[n++] = NSOpenGLPFADepthSize;
  224867. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  224868. attribs[n++] = NSOpenGLPFAStencilSize;
  224869. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  224870. attribs[n++] = NSOpenGLPFAAccumSize;
  224871. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  224872. pixelFormat.accumulationBufferGreenBits,
  224873. pixelFormat.accumulationBufferBlueBits,
  224874. pixelFormat.accumulationBufferAlphaBits);
  224875. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  224876. attribs[n++] = NSOpenGLPFASampleBuffers;
  224877. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  224878. attribs[n++] = NSOpenGLPFAClosestPolicy;
  224879. attribs[n++] = NSOpenGLPFANoRecovery;
  224880. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  224881. NSOpenGLPixelFormat* format
  224882. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  224883. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224884. pixelFormat: format];
  224885. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  224886. shareContext: sharedContext] autorelease];
  224887. const GLint swapInterval = 1;
  224888. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  224889. [view setOpenGLContext: renderContext];
  224890. [renderContext setView: view];
  224891. [format release];
  224892. viewHolder = new NSViewComponentInternal (view, component);
  224893. }
  224894. ~WindowedGLContext()
  224895. {
  224896. makeInactive();
  224897. [renderContext setView: nil];
  224898. delete viewHolder;
  224899. }
  224900. bool makeActive() const throw()
  224901. {
  224902. jassert (renderContext != 0);
  224903. [view makeActive];
  224904. return isActive();
  224905. }
  224906. bool makeInactive() const throw()
  224907. {
  224908. [view makeInactive];
  224909. return true;
  224910. }
  224911. bool isActive() const throw()
  224912. {
  224913. return [NSOpenGLContext currentContext] == renderContext;
  224914. }
  224915. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224916. void* getRawContext() const throw() { return renderContext; }
  224917. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224918. {
  224919. }
  224920. void swapBuffers()
  224921. {
  224922. [renderContext flushBuffer];
  224923. }
  224924. bool setSwapInterval (const int numFramesPerSwap)
  224925. {
  224926. [renderContext setValues: (const GLint*) &numFramesPerSwap
  224927. forParameter: NSOpenGLCPSwapInterval];
  224928. return true;
  224929. }
  224930. int getSwapInterval() const
  224931. {
  224932. GLint numFrames = 0;
  224933. [renderContext getValues: &numFrames
  224934. forParameter: NSOpenGLCPSwapInterval];
  224935. return numFrames;
  224936. }
  224937. void repaint()
  224938. {
  224939. // we need to invalidate the juce view that holds this gl view, to make it
  224940. // cause a repaint callback
  224941. NSView* v = (NSView*) viewHolder->view;
  224942. NSRect r = [v frame];
  224943. // bit of a bodge here.. if we only invalidate the area of the gl component,
  224944. // it's completely covered by the NSOpenGLView, so the OS throws away the
  224945. // repaint message, thus never causing our paint() callback, and never repainting
  224946. // the comp. So invalidating just a little bit around the edge helps..
  224947. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  224948. }
  224949. void* getNativeWindowHandle() const { return viewHolder->view; }
  224950. juce_UseDebuggingNewOperator
  224951. NSOpenGLContext* renderContext;
  224952. ThreadSafeNSOpenGLView* view;
  224953. private:
  224954. OpenGLPixelFormat pixelFormat;
  224955. NSViewComponentInternal* viewHolder;
  224956. WindowedGLContext (const WindowedGLContext&);
  224957. const WindowedGLContext& operator= (const WindowedGLContext&);
  224958. };
  224959. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  224960. const OpenGLPixelFormat& pixelFormat,
  224961. const OpenGLContext* const contextToShareWith)
  224962. {
  224963. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  224964. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  224965. if (c->renderContext == 0)
  224966. deleteAndZero (c);
  224967. return c;
  224968. }
  224969. void* OpenGLComponent::getNativeWindowHandle() const
  224970. {
  224971. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  224972. : 0;
  224973. }
  224974. void juce_glViewport (const int w, const int h)
  224975. {
  224976. glViewport (0, 0, w, h);
  224977. }
  224978. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224979. OwnedArray <OpenGLPixelFormat>& results)
  224980. {
  224981. /* GLint attribs [64];
  224982. int n = 0;
  224983. attribs[n++] = AGL_RGBA;
  224984. attribs[n++] = AGL_DOUBLEBUFFER;
  224985. attribs[n++] = AGL_ACCELERATED;
  224986. attribs[n++] = AGL_NO_RECOVERY;
  224987. attribs[n++] = AGL_NONE;
  224988. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  224989. while (p != 0)
  224990. {
  224991. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  224992. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  224993. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  224994. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  224995. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  224996. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  224997. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  224998. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  224999. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  225000. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  225001. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  225002. results.add (pf);
  225003. p = aglNextPixelFormat (p);
  225004. }*/
  225005. //jassertfalse //xxx can't see how you do this in cocoa!
  225006. }
  225007. #else
  225008. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  225009. const OpenGLPixelFormat& pixelFormat,
  225010. const OpenGLContext* const contextToShareWith)
  225011. {
  225012. return 0;
  225013. }
  225014. void juce_glViewport (const int w, const int h)
  225015. {
  225016. //glViewport (0, 0, w, h);
  225017. }
  225018. #endif
  225019. #endif
  225020. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  225021. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  225022. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225023. // compiled on its own).
  225024. #ifdef JUCE_INCLUDED_FILE
  225025. class JuceMainMenuHandler;
  225026. END_JUCE_NAMESPACE
  225027. using namespace JUCE_NAMESPACE;
  225028. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  225029. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225030. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  225031. #else
  225032. @interface JuceMenuCallback : NSObject
  225033. #endif
  225034. {
  225035. JuceMainMenuHandler* owner;
  225036. }
  225037. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  225038. - (void) dealloc;
  225039. - (void) menuItemInvoked: (id) menu;
  225040. - (void) menuNeedsUpdate: (NSMenu*) menu;
  225041. @end
  225042. BEGIN_JUCE_NAMESPACE
  225043. class JuceMainMenuHandler : private MenuBarModelListener,
  225044. private DeletedAtShutdown
  225045. {
  225046. public:
  225047. static JuceMainMenuHandler* instance;
  225048. JuceMainMenuHandler() throw()
  225049. : currentModel (0),
  225050. lastUpdateTime (0)
  225051. {
  225052. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  225053. }
  225054. ~JuceMainMenuHandler() throw()
  225055. {
  225056. setMenu (0);
  225057. jassert (instance == this);
  225058. instance = 0;
  225059. [callback release];
  225060. }
  225061. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  225062. {
  225063. if (currentModel != newMenuBarModel)
  225064. {
  225065. if (currentModel != 0)
  225066. currentModel->removeListener (this);
  225067. currentModel = newMenuBarModel;
  225068. if (currentModel != 0)
  225069. currentModel->addListener (this);
  225070. menuBarItemsChanged (0);
  225071. }
  225072. }
  225073. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  225074. const String& name, const int menuId, const int tag)
  225075. {
  225076. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  225077. action: nil
  225078. keyEquivalent: @""];
  225079. [item setTag: tag];
  225080. NSMenu* sub = createMenu (child, name, menuId, tag);
  225081. [parent setSubmenu: sub forItem: item];
  225082. [sub setAutoenablesItems: false];
  225083. [sub release];
  225084. }
  225085. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  225086. const String& name, const int menuId, const int tag)
  225087. {
  225088. [parentItem setTag: tag];
  225089. NSMenu* menu = [parentItem submenu];
  225090. [menu setTitle: juceStringToNS (name)];
  225091. while ([menu numberOfItems] > 0)
  225092. [menu removeItemAtIndex: 0];
  225093. PopupMenu::MenuItemIterator iter (menuToCopy);
  225094. while (iter.next())
  225095. addMenuItem (iter, menu, menuId, tag);
  225096. [menu setAutoenablesItems: false];
  225097. [menu update];
  225098. }
  225099. void menuBarItemsChanged (MenuBarModel*)
  225100. {
  225101. lastUpdateTime = Time::getMillisecondCounter();
  225102. StringArray menuNames;
  225103. if (currentModel != 0)
  225104. menuNames = currentModel->getMenuBarNames();
  225105. NSMenu* menuBar = [NSApp mainMenu];
  225106. while ([menuBar numberOfItems] > 1 + menuNames.size())
  225107. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  225108. int menuId = 1;
  225109. for (int i = 0; i < menuNames.size(); ++i)
  225110. {
  225111. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  225112. if (i >= [menuBar numberOfItems] - 1)
  225113. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  225114. else
  225115. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  225116. }
  225117. }
  225118. static void flashMenuBar (NSMenu* menu)
  225119. {
  225120. const unichar f35Key = NSF35FunctionKey;
  225121. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  225122. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  225123. action: nil
  225124. keyEquivalent: f35String];
  225125. [item setTarget: nil];
  225126. [menu insertItem: item atIndex: [menu numberOfItems]];
  225127. [item release];
  225128. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  225129. location: NSZeroPoint
  225130. modifierFlags: NSCommandKeyMask
  225131. timestamp: 0
  225132. windowNumber: 0
  225133. context: [NSGraphicsContext currentContext]
  225134. characters: f35String
  225135. charactersIgnoringModifiers: f35String
  225136. isARepeat: NO
  225137. keyCode: 0];
  225138. [menu performKeyEquivalent: f35Event];
  225139. [menu removeItem: item];
  225140. }
  225141. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  225142. {
  225143. for (int i = [menu numberOfItems]; --i >= 0;)
  225144. {
  225145. NSMenuItem* m = [menu itemAtIndex: i];
  225146. if ([m tag] == info.commandID)
  225147. return m;
  225148. if ([m submenu] != 0)
  225149. {
  225150. NSMenuItem* found = findMenuItem ([m submenu], info);
  225151. if (found != 0)
  225152. return found;
  225153. }
  225154. }
  225155. return 0;
  225156. }
  225157. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  225158. {
  225159. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  225160. if (item != 0)
  225161. flashMenuBar ([item menu]);
  225162. }
  225163. void updateMenus()
  225164. {
  225165. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  225166. menuBarItemsChanged (0);
  225167. }
  225168. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  225169. {
  225170. if (currentModel != 0)
  225171. {
  225172. if (commandManager != 0)
  225173. {
  225174. ApplicationCommandTarget::InvocationInfo info (commandId);
  225175. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  225176. commandManager->invoke (info, true);
  225177. }
  225178. currentModel->menuItemSelected (commandId, topLevelIndex);
  225179. }
  225180. }
  225181. MenuBarModel* currentModel;
  225182. uint32 lastUpdateTime;
  225183. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  225184. const int topLevelMenuId, const int topLevelIndex)
  225185. {
  225186. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  225187. if (text == 0)
  225188. text = @"";
  225189. if (iter.isSeparator)
  225190. {
  225191. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  225192. }
  225193. else if (iter.isSectionHeader)
  225194. {
  225195. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  225196. action: nil
  225197. keyEquivalent: @""];
  225198. [item setEnabled: false];
  225199. }
  225200. else if (iter.subMenu != 0)
  225201. {
  225202. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  225203. action: nil
  225204. keyEquivalent: @""];
  225205. [item setTag: iter.itemId];
  225206. [item setEnabled: iter.isEnabled];
  225207. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  225208. [sub setDelegate: nil];
  225209. [menuToAddTo setSubmenu: sub forItem: item];
  225210. }
  225211. else
  225212. {
  225213. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  225214. action: @selector (menuItemInvoked:)
  225215. keyEquivalent: @""];
  225216. [item setTag: iter.itemId];
  225217. [item setEnabled: iter.isEnabled];
  225218. [item setState: iter.isTicked ? NSOnState : NSOffState];
  225219. [item setTarget: (id) callback];
  225220. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  225221. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  225222. [item setRepresentedObject: info];
  225223. if (iter.commandManager != 0)
  225224. {
  225225. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  225226. ->getKeyPressesAssignedToCommand (iter.itemId));
  225227. if (keyPresses.size() > 0)
  225228. {
  225229. const KeyPress& kp = keyPresses.getReference(0);
  225230. juce_wchar key = kp.getTextCharacter();
  225231. if (kp.getKeyCode() == KeyPress::backspaceKey)
  225232. key = NSBackspaceCharacter;
  225233. else if (kp.getKeyCode() == KeyPress::deleteKey)
  225234. key = NSDeleteCharacter;
  225235. else if (key == 0)
  225236. key = (juce_wchar) kp.getKeyCode();
  225237. unsigned int mods = 0;
  225238. if (kp.getModifiers().isShiftDown())
  225239. mods |= NSShiftKeyMask;
  225240. if (kp.getModifiers().isCtrlDown())
  225241. mods |= NSControlKeyMask;
  225242. if (kp.getModifiers().isAltDown())
  225243. mods |= NSAlternateKeyMask;
  225244. if (kp.getModifiers().isCommandDown())
  225245. mods |= NSCommandKeyMask;
  225246. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  225247. [item setKeyEquivalentModifierMask: mods];
  225248. }
  225249. }
  225250. }
  225251. }
  225252. JuceMenuCallback* callback;
  225253. private:
  225254. NSMenu* createMenu (const PopupMenu menu,
  225255. const String& menuName,
  225256. const int topLevelMenuId,
  225257. const int topLevelIndex)
  225258. {
  225259. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  225260. [m setAutoenablesItems: false];
  225261. [m setDelegate: callback];
  225262. PopupMenu::MenuItemIterator iter (menu);
  225263. while (iter.next())
  225264. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  225265. [m update];
  225266. return m;
  225267. }
  225268. };
  225269. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  225270. END_JUCE_NAMESPACE
  225271. @implementation JuceMenuCallback
  225272. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  225273. {
  225274. [super init];
  225275. owner = owner_;
  225276. return self;
  225277. }
  225278. - (void) dealloc
  225279. {
  225280. [super dealloc];
  225281. }
  225282. - (void) menuItemInvoked: (id) menu
  225283. {
  225284. NSMenuItem* item = (NSMenuItem*) menu;
  225285. if ([[item representedObject] isKindOfClass: [NSArray class]])
  225286. {
  225287. NSArray* info = (NSArray*) [item representedObject];
  225288. owner->invoke ([item tag],
  225289. (ApplicationCommandManager*) (pointer_sized_int)
  225290. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  225291. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  225292. }
  225293. }
  225294. - (void) menuNeedsUpdate: (NSMenu*) menu;
  225295. {
  225296. if (JuceMainMenuHandler::instance != 0)
  225297. JuceMainMenuHandler::instance->updateMenus();
  225298. }
  225299. @end
  225300. BEGIN_JUCE_NAMESPACE
  225301. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  225302. const PopupMenu* extraItems)
  225303. {
  225304. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  225305. {
  225306. PopupMenu::MenuItemIterator iter (*extraItems);
  225307. while (iter.next())
  225308. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  225309. [menu addItem: [NSMenuItem separatorItem]];
  225310. }
  225311. NSMenuItem* item;
  225312. // Services...
  225313. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  225314. action: nil keyEquivalent: @""];
  225315. [menu addItem: item];
  225316. [item release];
  225317. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  225318. [menu setSubmenu: servicesMenu forItem: item];
  225319. [NSApp setServicesMenu: servicesMenu];
  225320. [servicesMenu release];
  225321. [menu addItem: [NSMenuItem separatorItem]];
  225322. // Hide + Show stuff...
  225323. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  225324. action: @selector (hide:) keyEquivalent: @"h"];
  225325. [item setTarget: NSApp];
  225326. [menu addItem: item];
  225327. [item release];
  225328. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  225329. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  225330. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  225331. [item setTarget: NSApp];
  225332. [menu addItem: item];
  225333. [item release];
  225334. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  225335. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  225336. [item setTarget: NSApp];
  225337. [menu addItem: item];
  225338. [item release];
  225339. [menu addItem: [NSMenuItem separatorItem]];
  225340. // Quit item....
  225341. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  225342. action: @selector (terminate:) keyEquivalent: @"q"];
  225343. [item setTarget: NSApp];
  225344. [menu addItem: item];
  225345. [item release];
  225346. return menu;
  225347. }
  225348. // Since our app has no NIB, this initialises a standard app menu...
  225349. static void rebuildMainMenu (const PopupMenu* extraItems)
  225350. {
  225351. // this can't be used in a plugin!
  225352. jassert (JUCEApplication::getInstance() != 0);
  225353. if (JUCEApplication::getInstance() != 0)
  225354. {
  225355. const ScopedAutoReleasePool pool;
  225356. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  225357. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  225358. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  225359. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  225360. [mainMenu setSubmenu: appMenu forItem: item];
  225361. [NSApp setMainMenu: mainMenu];
  225362. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  225363. [appMenu release];
  225364. [mainMenu release];
  225365. }
  225366. }
  225367. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  225368. const PopupMenu* extraAppleMenuItems) throw()
  225369. {
  225370. if (getMacMainMenu() != newMenuBarModel)
  225371. {
  225372. const ScopedAutoReleasePool pool;
  225373. if (newMenuBarModel == 0)
  225374. {
  225375. delete JuceMainMenuHandler::instance;
  225376. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  225377. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  225378. extraAppleMenuItems = 0;
  225379. }
  225380. else
  225381. {
  225382. if (JuceMainMenuHandler::instance == 0)
  225383. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  225384. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  225385. }
  225386. }
  225387. rebuildMainMenu (extraAppleMenuItems);
  225388. if (newMenuBarModel != 0)
  225389. newMenuBarModel->menuItemsChanged();
  225390. }
  225391. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  225392. {
  225393. return JuceMainMenuHandler::instance != 0
  225394. ? JuceMainMenuHandler::instance->currentModel : 0;
  225395. }
  225396. void initialiseMainMenu()
  225397. {
  225398. if (JUCEApplication::getInstance() != 0) // only needed in an app
  225399. rebuildMainMenu (0);
  225400. }
  225401. #endif
  225402. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  225403. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  225404. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225405. // compiled on its own).
  225406. #ifdef JUCE_INCLUDED_FILE
  225407. #if JUCE_MAC
  225408. END_JUCE_NAMESPACE
  225409. using namespace JUCE_NAMESPACE;
  225410. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  225411. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225412. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  225413. #else
  225414. @interface JuceFileChooserDelegate : NSObject
  225415. #endif
  225416. {
  225417. StringArray* filters;
  225418. }
  225419. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  225420. - (void) dealloc;
  225421. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  225422. @end
  225423. @implementation JuceFileChooserDelegate
  225424. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  225425. {
  225426. [super init];
  225427. filters = filters_;
  225428. return self;
  225429. }
  225430. - (void) dealloc
  225431. {
  225432. delete filters;
  225433. [super dealloc];
  225434. }
  225435. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  225436. {
  225437. const String fname (nsStringToJuce (filename));
  225438. for (int i = filters->size(); --i >= 0;)
  225439. if (fname.matchesWildcard ((*filters)[i], true))
  225440. return true;
  225441. return File (fname).isDirectory();
  225442. }
  225443. @end
  225444. BEGIN_JUCE_NAMESPACE
  225445. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  225446. const String& title,
  225447. const File& currentFileOrDirectory,
  225448. const String& filter,
  225449. bool selectsDirectory,
  225450. bool isSaveDialogue,
  225451. bool warnAboutOverwritingExistingFiles,
  225452. bool selectMultipleFiles,
  225453. FilePreviewComponent* extraInfoComponent)
  225454. {
  225455. const ScopedAutoReleasePool pool;
  225456. StringArray* filters = new StringArray();
  225457. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  225458. filters->trim();
  225459. filters->removeEmptyStrings();
  225460. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  225461. [delegate autorelease];
  225462. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  225463. : [NSOpenPanel openPanel];
  225464. [panel setTitle: juceStringToNS (title)];
  225465. if (! isSaveDialogue)
  225466. {
  225467. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  225468. [openPanel setCanChooseDirectories: selectsDirectory];
  225469. [openPanel setCanChooseFiles: ! selectsDirectory];
  225470. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  225471. }
  225472. [panel setDelegate: delegate];
  225473. String directory, filename;
  225474. if (currentFileOrDirectory.isDirectory())
  225475. {
  225476. directory = currentFileOrDirectory.getFullPathName();
  225477. }
  225478. else
  225479. {
  225480. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  225481. filename = currentFileOrDirectory.getFileName();
  225482. }
  225483. if ([panel runModalForDirectory: juceStringToNS (directory)
  225484. file: juceStringToNS (filename)]
  225485. == NSOKButton)
  225486. {
  225487. if (isSaveDialogue)
  225488. {
  225489. results.add (new File (nsStringToJuce ([panel filename])));
  225490. }
  225491. else
  225492. {
  225493. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  225494. NSArray* urls = [openPanel filenames];
  225495. for (unsigned int i = 0; i < [urls count]; ++i)
  225496. {
  225497. NSString* f = [urls objectAtIndex: i];
  225498. results.add (new File (nsStringToJuce (f)));
  225499. }
  225500. }
  225501. }
  225502. [panel setDelegate: nil];
  225503. }
  225504. #else
  225505. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  225506. const String& title,
  225507. const File& currentFileOrDirectory,
  225508. const String& filter,
  225509. bool selectsDirectory,
  225510. bool isSaveDialogue,
  225511. bool warnAboutOverwritingExistingFiles,
  225512. bool selectMultipleFiles,
  225513. FilePreviewComponent* extraInfoComponent)
  225514. {
  225515. const ScopedAutoReleasePool pool;
  225516. jassertfalse //xxx to do
  225517. }
  225518. #endif
  225519. #endif
  225520. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  225521. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  225522. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225523. // compiled on its own).
  225524. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  225525. #define theMovie ((QTMovie*) movie)
  225526. QuickTimeMovieComponent::QuickTimeMovieComponent()
  225527. : movie (0)
  225528. {
  225529. setOpaque (true);
  225530. setVisible (true);
  225531. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  225532. setView (view);
  225533. }
  225534. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  225535. {
  225536. closeMovie();
  225537. setView (0);
  225538. }
  225539. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  225540. {
  225541. return true;
  225542. }
  225543. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  225544. {
  225545. // unfortunately, QTMovie objects can only be created on the main thread..
  225546. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  225547. QTMovie* movie = 0;
  225548. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  225549. if (fin != 0)
  225550. {
  225551. movieFile = fin->getFile();
  225552. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  225553. error: nil];
  225554. }
  225555. else
  225556. {
  225557. MemoryBlock temp;
  225558. movieStream->readIntoMemoryBlock (temp);
  225559. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  225560. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  225561. {
  225562. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  225563. length: temp.getSize()]
  225564. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  225565. MIMEType: @""]
  225566. error: nil];
  225567. if (movie != 0)
  225568. break;
  225569. }
  225570. }
  225571. return movie;
  225572. }
  225573. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  225574. const bool controllerVisible)
  225575. {
  225576. closeMovie();
  225577. if (getPeer() == 0)
  225578. {
  225579. // To open a movie, this component must be visible inside a functioning window, so that
  225580. // the QT control can be assigned to the window.
  225581. jassertfalse
  225582. return false;
  225583. }
  225584. movie = openMovieFromStream (movieStream, movieFile);
  225585. [theMovie retain];
  225586. QTMovieView* view = (QTMovieView*) getView();
  225587. [view setMovie: theMovie];
  225588. [view setControllerVisible: controllerVisible];
  225589. setLooping (looping);
  225590. return movie != nil;
  225591. }
  225592. void QuickTimeMovieComponent::closeMovie()
  225593. {
  225594. stop();
  225595. QTMovieView* view = (QTMovieView*) getView();
  225596. [view setMovie: nil];
  225597. [theMovie release];
  225598. movie = 0;
  225599. movieFile = File::nonexistent;
  225600. }
  225601. bool QuickTimeMovieComponent::isMovieOpen() const
  225602. {
  225603. return movie != nil;
  225604. }
  225605. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  225606. {
  225607. return movieFile;
  225608. }
  225609. void QuickTimeMovieComponent::play()
  225610. {
  225611. [theMovie play];
  225612. }
  225613. void QuickTimeMovieComponent::stop()
  225614. {
  225615. [theMovie stop];
  225616. }
  225617. bool QuickTimeMovieComponent::isPlaying() const
  225618. {
  225619. return movie != 0 && [theMovie rate] != 0;
  225620. }
  225621. void QuickTimeMovieComponent::setPosition (const double seconds)
  225622. {
  225623. if (movie != 0)
  225624. {
  225625. QTTime t;
  225626. t.timeValue = (uint64) (100000.0 * seconds);
  225627. t.timeScale = 100000;
  225628. t.flags = 0;
  225629. [theMovie setCurrentTime: t];
  225630. }
  225631. }
  225632. double QuickTimeMovieComponent::getPosition() const
  225633. {
  225634. if (movie == 0)
  225635. return 0.0;
  225636. QTTime t = [theMovie currentTime];
  225637. return t.timeValue / (double) t.timeScale;
  225638. }
  225639. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  225640. {
  225641. [theMovie setRate: newSpeed];
  225642. }
  225643. double QuickTimeMovieComponent::getMovieDuration() const
  225644. {
  225645. if (movie == 0)
  225646. return 0.0;
  225647. QTTime t = [theMovie duration];
  225648. return t.timeValue / (double) t.timeScale;
  225649. }
  225650. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  225651. {
  225652. looping = shouldLoop;
  225653. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  225654. forKey: QTMovieLoopsAttribute];
  225655. }
  225656. bool QuickTimeMovieComponent::isLooping() const
  225657. {
  225658. return looping;
  225659. }
  225660. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  225661. {
  225662. [theMovie setVolume: newVolume];
  225663. }
  225664. float QuickTimeMovieComponent::getMovieVolume() const
  225665. {
  225666. return movie != 0 ? [theMovie volume] : 0.0f;
  225667. }
  225668. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  225669. {
  225670. width = 0;
  225671. height = 0;
  225672. if (movie != 0)
  225673. {
  225674. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  225675. width = s.width;
  225676. height = s.height;
  225677. }
  225678. }
  225679. void QuickTimeMovieComponent::paint (Graphics& g)
  225680. {
  225681. if (movie == 0)
  225682. g.fillAll (Colours::black);
  225683. }
  225684. bool QuickTimeMovieComponent::isControllerVisible() const
  225685. {
  225686. return controllerVisible;
  225687. }
  225688. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  225689. const bool isControllerVisible)
  225690. {
  225691. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  225692. movieFile = movieFile_;
  225693. return ok;
  225694. }
  225695. void QuickTimeMovieComponent::goToStart()
  225696. {
  225697. setPosition (0.0);
  225698. }
  225699. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  225700. const RectanglePlacement& placement)
  225701. {
  225702. int normalWidth, normalHeight;
  225703. getMovieNormalSize (normalWidth, normalHeight);
  225704. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  225705. {
  225706. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  225707. placement.applyTo (x, y, w, h,
  225708. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  225709. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  225710. if (w > 0 && h > 0)
  225711. {
  225712. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  225713. roundDoubleToInt (w), roundDoubleToInt (h));
  225714. }
  225715. }
  225716. else
  225717. {
  225718. setBounds (spaceToFitWithin);
  225719. }
  225720. }
  225721. #if ! (JUCE_MAC && JUCE_64BIT)
  225722. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  225723. {
  225724. if (movieStream == 0)
  225725. return false;
  225726. File file;
  225727. QTMovie* movie = openMovieFromStream (movieStream, file);
  225728. if (movie != nil)
  225729. result = [movie quickTimeMovie];
  225730. return movie != nil;
  225731. }
  225732. #endif
  225733. #endif
  225734. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  225735. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  225736. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225737. // compiled on its own).
  225738. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  225739. END_JUCE_NAMESPACE
  225740. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  225741. @interface OpenDiskDevice : NSObject
  225742. {
  225743. DRDevice* device;
  225744. NSMutableArray* tracks;
  225745. }
  225746. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  225747. - (void) dealloc;
  225748. - (bool) isDiskPresent;
  225749. - (int) getNumAvailableAudioBlocks;
  225750. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  225751. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  225752. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  225753. @end
  225754. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  225755. @interface AudioTrackProducer : NSObject
  225756. {
  225757. JUCE_NAMESPACE::AudioSource* source;
  225758. int readPosition, lengthInFrames;
  225759. }
  225760. - (AudioTrackProducer*) init: (int) lengthInFrames;
  225761. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  225762. - (void) dealloc;
  225763. - (void) setupTrackProperties: (DRTrack*) track;
  225764. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  225765. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  225766. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  225767. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  225768. toMedia:(NSDictionary*)mediaInfo;
  225769. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  225770. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  225771. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  225772. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  225773. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  225774. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  225775. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  225776. ioFlags:(uint32_t*)flags;
  225777. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  225778. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  225779. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  225780. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  225781. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  225782. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  225783. ioFlags:(uint32_t*)flags;
  225784. @end
  225785. @implementation OpenDiskDevice
  225786. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  225787. {
  225788. [super init];
  225789. device = device_;
  225790. tracks = [[NSMutableArray alloc] init];
  225791. return self;
  225792. }
  225793. - (void) dealloc
  225794. {
  225795. [tracks release];
  225796. [super dealloc];
  225797. }
  225798. - (bool) isDiskPresent
  225799. {
  225800. return [device isValid]
  225801. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  225802. isEqualTo: DRDeviceMediaStateMediaPresent];
  225803. }
  225804. - (int) getNumAvailableAudioBlocks
  225805. {
  225806. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  225807. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  225808. }
  225809. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  225810. {
  225811. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  225812. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  225813. [p setupTrackProperties: t];
  225814. [tracks addObject: t];
  225815. [t release];
  225816. [p release];
  225817. }
  225818. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  225819. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  225820. {
  225821. DRBurn* burn = [DRBurn burnForDevice: device];
  225822. if (! [device acquireExclusiveAccess])
  225823. {
  225824. *error = "Couldn't open or write to the CD device";
  225825. return;
  225826. }
  225827. [device acquireMediaReservation];
  225828. NSMutableDictionary* d = [[burn properties] mutableCopy];
  225829. [d autorelease];
  225830. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  225831. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  225832. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  225833. forKey: DRBurnCompletionActionKey];
  225834. [burn setProperties: d];
  225835. [burn writeLayout: tracks];
  225836. for (;;)
  225837. {
  225838. JUCE_NAMESPACE::Thread::sleep (300);
  225839. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  225840. if (listener != 0 && listener->audioCDBurnProgress (progress))
  225841. {
  225842. [burn abort];
  225843. *error = "User cancelled the write operation";
  225844. break;
  225845. }
  225846. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  225847. {
  225848. *error = "Write operation failed";
  225849. break;
  225850. }
  225851. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  225852. {
  225853. break;
  225854. }
  225855. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  225856. objectForKey: DRErrorStatusErrorStringKey];
  225857. if ([err length] > 0)
  225858. {
  225859. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  225860. break;
  225861. }
  225862. }
  225863. [device releaseMediaReservation];
  225864. [device releaseExclusiveAccess];
  225865. }
  225866. @end
  225867. @implementation AudioTrackProducer
  225868. - (AudioTrackProducer*) init: (int) lengthInFrames_
  225869. {
  225870. lengthInFrames = lengthInFrames_;
  225871. readPosition = 0;
  225872. return self;
  225873. }
  225874. - (void) setupTrackProperties: (DRTrack*) track
  225875. {
  225876. NSMutableDictionary* p = [[track properties] mutableCopy];
  225877. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  225878. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  225879. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  225880. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  225881. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  225882. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  225883. [track setProperties: p];
  225884. [p release];
  225885. }
  225886. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  225887. {
  225888. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  225889. if (s != nil)
  225890. s->source = source_;
  225891. return s;
  225892. }
  225893. - (void) dealloc
  225894. {
  225895. if (source != 0)
  225896. {
  225897. source->releaseResources();
  225898. delete source;
  225899. }
  225900. [super dealloc];
  225901. }
  225902. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  225903. {
  225904. }
  225905. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  225906. {
  225907. return true;
  225908. }
  225909. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  225910. {
  225911. return lengthInFrames;
  225912. }
  225913. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  225914. toMedia: (NSDictionary*) mediaInfo
  225915. {
  225916. if (source != 0)
  225917. source->prepareToPlay (44100 / 75, 44100);
  225918. readPosition = 0;
  225919. return true;
  225920. }
  225921. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  225922. {
  225923. if (source != 0)
  225924. source->prepareToPlay (44100 / 75, 44100);
  225925. return true;
  225926. }
  225927. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  225928. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  225929. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  225930. {
  225931. if (source != 0)
  225932. {
  225933. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  225934. if (numSamples > 0)
  225935. {
  225936. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  225937. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  225938. info.buffer = &tempBuffer;
  225939. info.startSample = 0;
  225940. info.numSamples = numSamples;
  225941. source->getNextAudioBlock (info);
  225942. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  225943. buffer, numSamples, 4);
  225944. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  225945. buffer + 2, numSamples, 4);
  225946. readPosition += numSamples;
  225947. }
  225948. return numSamples * 4;
  225949. }
  225950. return 0;
  225951. }
  225952. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  225953. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  225954. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  225955. ioFlags: (uint32_t*) flags
  225956. {
  225957. zeromem (buffer, bufferLength);
  225958. return bufferLength;
  225959. }
  225960. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  225961. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  225962. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  225963. {
  225964. return true;
  225965. }
  225966. @end
  225967. BEGIN_JUCE_NAMESPACE
  225968. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  225969. : internal (0)
  225970. {
  225971. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  225972. internal = (void*) dev;
  225973. }
  225974. AudioCDBurner::~AudioCDBurner()
  225975. {
  225976. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  225977. if (dev != 0)
  225978. [dev release];
  225979. }
  225980. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  225981. {
  225982. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  225983. if (b->internal == 0)
  225984. deleteAndZero (b);
  225985. return b;
  225986. }
  225987. static NSArray* findDiskBurnerDevices()
  225988. {
  225989. NSMutableArray* results = [NSMutableArray array];
  225990. NSArray* devs = [DRDevice devices];
  225991. if (devs != 0)
  225992. {
  225993. int num = [devs count];
  225994. int i;
  225995. for (i = 0; i < num; ++i)
  225996. {
  225997. NSDictionary* dic = [[devs objectAtIndex: i] info];
  225998. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  225999. if (name != nil)
  226000. [results addObject: name];
  226001. }
  226002. }
  226003. return results;
  226004. }
  226005. const StringArray AudioCDBurner::findAvailableDevices()
  226006. {
  226007. NSArray* names = findDiskBurnerDevices();
  226008. StringArray s;
  226009. for (unsigned int i = 0; i < [names count]; ++i)
  226010. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  226011. return s;
  226012. }
  226013. bool AudioCDBurner::isDiskPresent() const
  226014. {
  226015. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226016. return dev != 0 && [dev isDiskPresent];
  226017. }
  226018. int AudioCDBurner::getNumAvailableAudioBlocks() const
  226019. {
  226020. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226021. return [dev getNumAvailableAudioBlocks];
  226022. }
  226023. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  226024. {
  226025. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226026. if (dev != 0)
  226027. {
  226028. [dev addSourceTrack: source numSamples: numSamps];
  226029. return true;
  226030. }
  226031. return false;
  226032. }
  226033. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  226034. const bool ejectDiscAfterwards,
  226035. const bool peformFakeBurnForTesting)
  226036. {
  226037. String error ("Couldn't open or write to the CD device");
  226038. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226039. if (dev != 0)
  226040. {
  226041. error = String::empty;
  226042. [dev burn: listener
  226043. errorString: &error
  226044. ejectAfterwards: ejectDiscAfterwards
  226045. isFake: peformFakeBurnForTesting];
  226046. }
  226047. return error;
  226048. }
  226049. void AudioCDReader::ejectDisk()
  226050. {
  226051. const ScopedAutoReleasePool p;
  226052. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  226053. }
  226054. #endif
  226055. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  226056. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  226057. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226058. // compiled on its own).
  226059. #ifdef JUCE_INCLUDED_FILE
  226060. class FontHelper
  226061. {
  226062. NSFont* font;
  226063. public:
  226064. String name;
  226065. bool isBold, isItalic, needsItalicTransform;
  226066. float fontSize, totalSize, ascent;
  226067. int refCount;
  226068. NSMutableDictionary* attributes;
  226069. FontHelper (const String& name_,
  226070. const bool bold_,
  226071. const bool italic_,
  226072. const float size_)
  226073. : font (0),
  226074. name (name_),
  226075. isBold (bold_),
  226076. isItalic (italic_),
  226077. needsItalicTransform (false),
  226078. fontSize (size_),
  226079. refCount (1)
  226080. {
  226081. attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  226082. forKey: NSLigatureAttributeName] retain];
  226083. font = [NSFont fontWithName: juceStringToNS (name_) size: size_];
  226084. if (italic_)
  226085. {
  226086. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  226087. if (newFont == font)
  226088. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226089. font = newFont;
  226090. }
  226091. if (bold_)
  226092. font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  226093. [font retain];
  226094. ascent = fabsf ([font ascender]);
  226095. totalSize = ascent + fabsf ([font descender]);
  226096. }
  226097. ~FontHelper()
  226098. {
  226099. [font release];
  226100. [attributes release];
  226101. }
  226102. bool getPathAndKerning (const juce_wchar char1,
  226103. const juce_wchar char2,
  226104. Path* path,
  226105. float& kerning,
  226106. float* ascent,
  226107. float* descent)
  226108. {
  226109. const ScopedAutoReleasePool pool;
  226110. if (font == 0
  226111. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  226112. return false;
  226113. String chars;
  226114. chars << ' ' << char1 << char2;
  226115. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  226116. attributes: attributes] autorelease];
  226117. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  226118. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  226119. [layoutManager addTextContainer: textContainer];
  226120. [textStorage addLayoutManager: layoutManager];
  226121. [textStorage setFont: font];
  226122. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  226123. actualCharacterRange: 0].location;
  226124. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  226125. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  226126. kerning = p2.x - p1.x;
  226127. if (ascent != 0)
  226128. *ascent = this->ascent;
  226129. if (descent != 0)
  226130. *descent = fabsf ([font descender]);
  226131. if (path != 0)
  226132. {
  226133. NSBezierPath* bez = [NSBezierPath bezierPath];
  226134. [bez moveToPoint: NSMakePoint (0, 0)];
  226135. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  226136. inFont: font];
  226137. for (int i = 0; i < [bez elementCount]; ++i)
  226138. {
  226139. NSPoint p[3];
  226140. switch ([bez elementAtIndex: i associatedPoints: p])
  226141. {
  226142. case NSMoveToBezierPathElement:
  226143. path->startNewSubPath (p[0].x, -p[0].y);
  226144. break;
  226145. case NSLineToBezierPathElement:
  226146. path->lineTo (p[0].x, -p[0].y);
  226147. break;
  226148. case NSCurveToBezierPathElement:
  226149. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  226150. break;
  226151. case NSClosePathBezierPathElement:
  226152. path->closeSubPath();
  226153. break;
  226154. default:
  226155. jassertfalse
  226156. break;
  226157. }
  226158. }
  226159. if (needsItalicTransform)
  226160. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  226161. }
  226162. return kerning != 0;
  226163. }
  226164. juce_wchar getDefaultChar()
  226165. {
  226166. return 0;
  226167. }
  226168. };
  226169. class FontHelperCache : public Timer,
  226170. public DeletedAtShutdown
  226171. {
  226172. VoidArray cache;
  226173. public:
  226174. FontHelperCache()
  226175. {
  226176. }
  226177. ~FontHelperCache()
  226178. {
  226179. for (int i = cache.size(); --i >= 0;)
  226180. {
  226181. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  226182. delete f;
  226183. }
  226184. clearSingletonInstance();
  226185. }
  226186. FontHelper* getFont (const String& name,
  226187. const bool bold,
  226188. const bool italic,
  226189. const float size = 1024)
  226190. {
  226191. for (int i = cache.size(); --i >= 0;)
  226192. {
  226193. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  226194. if (f->name == name
  226195. && f->isBold == bold
  226196. && f->isItalic == italic
  226197. && f->fontSize == size)
  226198. {
  226199. f->refCount++;
  226200. return f;
  226201. }
  226202. }
  226203. FontHelper* const f = new FontHelper (name, bold, italic, size);
  226204. cache.add (f);
  226205. return f;
  226206. }
  226207. void releaseFont (FontHelper* f)
  226208. {
  226209. for (int i = cache.size(); --i >= 0;)
  226210. {
  226211. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  226212. if (f == f2)
  226213. {
  226214. f->refCount--;
  226215. if (f->refCount == 0)
  226216. startTimer (5000);
  226217. break;
  226218. }
  226219. }
  226220. }
  226221. void timerCallback()
  226222. {
  226223. stopTimer();
  226224. for (int i = cache.size(); --i >= 0;)
  226225. {
  226226. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  226227. if (f->refCount == 0)
  226228. {
  226229. cache.remove (i);
  226230. delete f;
  226231. }
  226232. }
  226233. if (cache.size() == 0)
  226234. delete this;
  226235. }
  226236. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  226237. };
  226238. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  226239. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  226240. bool bold,
  226241. bool italic,
  226242. bool addAllGlyphsToFont) throw()
  226243. {
  226244. // This method is only safe to be called from the normal UI thread..
  226245. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  226246. FontHelper* const helper = FontHelperCache::getInstance()
  226247. ->getFont (fontName, bold, italic);
  226248. clear();
  226249. setAscent (helper->ascent / helper->totalSize);
  226250. setName (fontName);
  226251. setDefaultCharacter (helper->getDefaultChar());
  226252. setBold (bold);
  226253. setItalic (italic);
  226254. if (addAllGlyphsToFont)
  226255. {
  226256. //xxx
  226257. jassertfalse
  226258. }
  226259. FontHelperCache::getInstance()->releaseFont (helper);
  226260. }
  226261. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  226262. {
  226263. // This method is only safe to be called from the normal UI thread..
  226264. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  226265. if (character == 0)
  226266. return false;
  226267. FontHelper* const helper = FontHelperCache::getInstance()
  226268. ->getFont (getName(), isBold(), isItalic());
  226269. Path path;
  226270. float width;
  226271. bool foundOne = false;
  226272. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  226273. {
  226274. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  226275. 1.0f / helper->totalSize));
  226276. addGlyph (character, path, width / helper->totalSize);
  226277. for (int i = 0; i < glyphs.size(); ++i)
  226278. {
  226279. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  226280. float kerning;
  226281. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  226282. {
  226283. kerning = (kerning - width) / helper->totalSize;
  226284. if (kerning != 0)
  226285. addKerningPair (character, g->getCharacter(), kerning);
  226286. }
  226287. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  226288. {
  226289. kerning = kerning / helper->totalSize - g->width;
  226290. if (kerning != 0)
  226291. addKerningPair (g->getCharacter(), character, kerning);
  226292. }
  226293. }
  226294. foundOne = true;
  226295. }
  226296. FontHelperCache::getInstance()->releaseFont (helper);
  226297. return foundOne;
  226298. }
  226299. const StringArray Font::findAllTypefaceNames() throw()
  226300. {
  226301. StringArray names;
  226302. const ScopedAutoReleasePool pool;
  226303. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226304. for (unsigned int i = 0; i < [fonts count]; ++i)
  226305. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226306. names.sort (true);
  226307. return names;
  226308. }
  226309. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  226310. {
  226311. defaultSans = "Lucida Grande";
  226312. defaultSerif = "Times New Roman";
  226313. defaultFixed = "Monaco";
  226314. }
  226315. #endif
  226316. /********* End of inlined file: juce_mac_Fonts.mm *********/
  226317. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  226318. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226319. // compiled on its own).
  226320. #ifdef JUCE_INCLUDED_FILE
  226321. struct CallbackMessagePayload
  226322. {
  226323. MessageCallbackFunction* function;
  226324. void* parameter;
  226325. void* volatile result;
  226326. bool volatile hasBeenExecuted;
  226327. };
  226328. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  226329. for example having more than one juce plugin loaded into a host, then when a
  226330. method is called, the actual code that runs might actually be in a different module
  226331. than the one you expect... So any calls to library functions or statics that are
  226332. made inside obj-c methods will probably end up getting executed in a different DLL's
  226333. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  226334. To work around this insanity, I'm only allowing obj-c methods to make calls to
  226335. virtual methods of an object that's known to live inside the right module's space.
  226336. */
  226337. class AppDelegateRedirector
  226338. {
  226339. public:
  226340. AppDelegateRedirector() {}
  226341. virtual ~AppDelegateRedirector() {}
  226342. virtual NSApplicationTerminateReply shouldTerminate()
  226343. {
  226344. if (JUCEApplication::getInstance() != 0)
  226345. {
  226346. JUCEApplication::getInstance()->systemRequestedQuit();
  226347. return NSTerminateCancel;
  226348. }
  226349. return NSTerminateNow;
  226350. }
  226351. virtual BOOL openFile (const NSString* filename)
  226352. {
  226353. if (JUCEApplication::getInstance() != 0)
  226354. {
  226355. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  226356. return YES;
  226357. }
  226358. return NO;
  226359. }
  226360. virtual void openFiles (NSArray* filenames)
  226361. {
  226362. StringArray files;
  226363. for (unsigned int i = 0; i < [filenames count]; ++i)
  226364. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  226365. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  226366. {
  226367. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  226368. }
  226369. }
  226370. virtual void focusChanged()
  226371. {
  226372. juce_HandleProcessFocusChange();
  226373. }
  226374. virtual void deliverMessage (void* message)
  226375. {
  226376. // no need for an mm lock here - deliverMessage locks it
  226377. MessageManager::getInstance()->deliverMessage (message);
  226378. }
  226379. virtual void performCallback (CallbackMessagePayload* pl)
  226380. {
  226381. pl->result = (*pl->function) (pl->parameter);
  226382. pl->hasBeenExecuted = true;
  226383. }
  226384. virtual void deleteSelf()
  226385. {
  226386. delete this;
  226387. }
  226388. };
  226389. END_JUCE_NAMESPACE
  226390. using namespace JUCE_NAMESPACE;
  226391. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  226392. static int numPendingMessages = 0;
  226393. @interface JuceAppDelegate : NSObject
  226394. {
  226395. @private
  226396. id oldDelegate;
  226397. AppDelegateRedirector* redirector;
  226398. @public
  226399. bool flushingMessages;
  226400. }
  226401. - (JuceAppDelegate*) init;
  226402. - (void) dealloc;
  226403. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  226404. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  226405. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  226406. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  226407. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  226408. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  226409. - (void) customEvent: (id) data;
  226410. - (void) performCallback: (id) info;
  226411. - (void) dummyMethod;
  226412. @end
  226413. @implementation JuceAppDelegate
  226414. - (JuceAppDelegate*) init
  226415. {
  226416. [super init];
  226417. redirector = new AppDelegateRedirector();
  226418. numPendingMessages = 0;
  226419. flushingMessages = false;
  226420. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  226421. if (JUCEApplication::getInstance() != 0)
  226422. {
  226423. oldDelegate = [NSApp delegate];
  226424. [NSApp setDelegate: self];
  226425. }
  226426. else
  226427. {
  226428. oldDelegate = 0;
  226429. [center addObserver: self selector: @selector (applicationDidResignActive:)
  226430. name: NSApplicationDidResignActiveNotification object: NSApp];
  226431. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  226432. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  226433. [center addObserver: self selector: @selector (applicationWillUnhide:)
  226434. name: NSApplicationWillUnhideNotification object: NSApp];
  226435. }
  226436. return self;
  226437. }
  226438. - (void) dealloc
  226439. {
  226440. if (oldDelegate != 0)
  226441. [NSApp setDelegate: oldDelegate];
  226442. redirector->deleteSelf();
  226443. [super dealloc];
  226444. }
  226445. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  226446. {
  226447. return redirector->shouldTerminate();
  226448. }
  226449. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  226450. {
  226451. return redirector->openFile (filename);
  226452. }
  226453. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  226454. {
  226455. return redirector->openFiles (filenames);
  226456. }
  226457. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  226458. {
  226459. redirector->focusChanged();
  226460. }
  226461. - (void) applicationDidResignActive: (NSNotification*) aNotification
  226462. {
  226463. redirector->focusChanged();
  226464. }
  226465. - (void) applicationWillUnhide: (NSNotification*) aNotification
  226466. {
  226467. redirector->focusChanged();
  226468. }
  226469. - (void) customEvent: (id) n
  226470. {
  226471. atomicDecrement (numPendingMessages);
  226472. NSData* data = (NSData*) n;
  226473. void* message = 0;
  226474. [data getBytes: &message length: sizeof (message)];
  226475. [data release];
  226476. if (message != 0 && ! flushingMessages)
  226477. redirector->deliverMessage (message);
  226478. }
  226479. - (void) performCallback: (id) info
  226480. {
  226481. if ([info isKindOfClass: [NSData class]])
  226482. {
  226483. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  226484. if (pl != 0)
  226485. redirector->performCallback (pl);
  226486. }
  226487. else
  226488. {
  226489. jassertfalse // should never get here!
  226490. }
  226491. }
  226492. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  226493. @end
  226494. BEGIN_JUCE_NAMESPACE
  226495. static JuceAppDelegate* juceAppDelegate = 0;
  226496. void MessageManager::runDispatchLoop()
  226497. {
  226498. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  226499. {
  226500. const ScopedAutoReleasePool pool;
  226501. // must only be called by the message thread!
  226502. jassert (isThisTheMessageThread());
  226503. [NSApp run];
  226504. }
  226505. }
  226506. void MessageManager::stopDispatchLoop()
  226507. {
  226508. quitMessagePosted = true;
  226509. [NSApp stop: nil];
  226510. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  226511. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  226512. }
  226513. static bool isEventBlockedByModalComps (NSEvent* e)
  226514. {
  226515. if (Component::getNumCurrentlyModalComponents() == 0)
  226516. return false;
  226517. NSWindow* const w = [e window];
  226518. if (w == 0 || [w worksWhenModal])
  226519. return false;
  226520. bool isKey = false, isInputAttempt = false;
  226521. switch ([e type])
  226522. {
  226523. case NSKeyDown:
  226524. case NSKeyUp:
  226525. isKey = isInputAttempt = true;
  226526. break;
  226527. case NSLeftMouseDown:
  226528. case NSRightMouseDown:
  226529. case NSOtherMouseDown:
  226530. isInputAttempt = true;
  226531. break;
  226532. case NSLeftMouseDragged:
  226533. case NSRightMouseDragged:
  226534. case NSLeftMouseUp:
  226535. case NSRightMouseUp:
  226536. case NSOtherMouseUp:
  226537. case NSOtherMouseDragged:
  226538. if (Component::getComponentUnderMouse() != 0)
  226539. return false;
  226540. break;
  226541. case NSMouseMoved:
  226542. case NSMouseEntered:
  226543. case NSMouseExited:
  226544. case NSCursorUpdate:
  226545. case NSScrollWheel:
  226546. case NSTabletPoint:
  226547. case NSTabletProximity:
  226548. break;
  226549. default:
  226550. return false;
  226551. }
  226552. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  226553. {
  226554. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  226555. NSView* const compView = (NSView*) peer->getNativeHandle();
  226556. if ([compView window] == w)
  226557. {
  226558. if (isKey)
  226559. {
  226560. if (compView == [w firstResponder])
  226561. return false;
  226562. }
  226563. else
  226564. {
  226565. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  226566. [compView bounds]))
  226567. return false;
  226568. }
  226569. }
  226570. }
  226571. if (isInputAttempt)
  226572. {
  226573. if (! [NSApp isActive])
  226574. [NSApp activateIgnoringOtherApps: YES];
  226575. Component* const modal = Component::getCurrentlyModalComponent (0);
  226576. if (modal != 0)
  226577. modal->inputAttemptWhenModal();
  226578. }
  226579. return true;
  226580. }
  226581. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226582. {
  226583. const ScopedAutoReleasePool pool;
  226584. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226585. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226586. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226587. while (! quitMessagePosted)
  226588. {
  226589. const ScopedAutoReleasePool pool;
  226590. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226591. beforeDate: endDate];
  226592. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  226593. untilDate: endDate
  226594. inMode: NSDefaultRunLoopMode
  226595. dequeue: YES];
  226596. if (e != 0 && ! isEventBlockedByModalComps (e))
  226597. [NSApp sendEvent: e];
  226598. if (Time::getMillisecondCounter() >= endTime)
  226599. break;
  226600. }
  226601. return ! quitMessagePosted;
  226602. }
  226603. void MessageManager::doPlatformSpecificInitialisation()
  226604. {
  226605. if (juceAppDelegate == 0)
  226606. juceAppDelegate = [[JuceAppDelegate alloc] init];
  226607. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  226608. // correctly (needed prior to 10.5)
  226609. if (! [NSThread isMultiThreaded])
  226610. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  226611. toTarget: juceAppDelegate
  226612. withObject: nil];
  226613. initialiseMainMenu();
  226614. }
  226615. void MessageManager::doPlatformSpecificShutdown()
  226616. {
  226617. if (juceAppDelegate != 0)
  226618. {
  226619. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  226620. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  226621. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  226622. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  226623. juceAppDelegate->flushingMessages = true;
  226624. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  226625. {
  226626. const ScopedAutoReleasePool pool;
  226627. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226628. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  226629. }
  226630. [juceAppDelegate release];
  226631. juceAppDelegate = 0;
  226632. }
  226633. }
  226634. bool juce_postMessageToSystemQueue (void* message)
  226635. {
  226636. atomicIncrement (numPendingMessages);
  226637. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  226638. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  226639. waitUntilDone: NO];
  226640. return true;
  226641. }
  226642. void MessageManager::broadcastMessage (const String& value) throw()
  226643. {
  226644. }
  226645. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226646. void* data)
  226647. {
  226648. if (isThisTheMessageThread())
  226649. {
  226650. return (*callback) (data);
  226651. }
  226652. else
  226653. {
  226654. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226655. // deadlock because the message manager is blocked from running, so can never
  226656. // call your function..
  226657. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226658. const ScopedAutoReleasePool pool;
  226659. CallbackMessagePayload cmp;
  226660. cmp.function = callback;
  226661. cmp.parameter = data;
  226662. cmp.result = 0;
  226663. cmp.hasBeenExecuted = false;
  226664. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  226665. withObject: [NSData dataWithBytesNoCopy: &cmp
  226666. length: sizeof (cmp)
  226667. freeWhenDone: NO]
  226668. waitUntilDone: YES];
  226669. return cmp.result;
  226670. }
  226671. }
  226672. #endif
  226673. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  226674. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  226675. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226676. // compiled on its own).
  226677. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  226678. #if JUCE_MAC
  226679. END_JUCE_NAMESPACE
  226680. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  226681. @interface DownloadClickDetector : NSObject
  226682. {
  226683. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  226684. }
  226685. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  226686. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  226687. request: (NSURLRequest*) request
  226688. frame: (WebFrame*) frame
  226689. decisionListener: (id<WebPolicyDecisionListener>) listener;
  226690. @end
  226691. @implementation DownloadClickDetector
  226692. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  226693. {
  226694. [super init];
  226695. ownerComponent = ownerComponent_;
  226696. return self;
  226697. }
  226698. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  226699. request: (NSURLRequest*) request
  226700. frame: (WebFrame*) frame
  226701. decisionListener: (id <WebPolicyDecisionListener>) listener
  226702. {
  226703. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  226704. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  226705. [listener use];
  226706. else
  226707. [listener ignore];
  226708. }
  226709. @end
  226710. BEGIN_JUCE_NAMESPACE
  226711. class WebBrowserComponentInternal : public NSViewComponent
  226712. {
  226713. public:
  226714. WebBrowserComponentInternal (WebBrowserComponent* owner)
  226715. {
  226716. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226717. frameName: @""
  226718. groupName: @""];
  226719. setView (webView);
  226720. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  226721. [webView setPolicyDelegate: clickListener];
  226722. }
  226723. ~WebBrowserComponentInternal()
  226724. {
  226725. [webView setPolicyDelegate: nil];
  226726. [clickListener release];
  226727. setView (0);
  226728. }
  226729. void goToURL (const String& url,
  226730. const StringArray* headers,
  226731. const MemoryBlock* postData)
  226732. {
  226733. NSMutableURLRequest* r
  226734. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  226735. cachePolicy: NSURLRequestUseProtocolCachePolicy
  226736. timeoutInterval: 30.0];
  226737. if (postData != 0 && postData->getSize() > 0)
  226738. {
  226739. [r setHTTPMethod: @"POST"];
  226740. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  226741. length: postData->getSize()]];
  226742. }
  226743. if (headers != 0)
  226744. {
  226745. for (int i = 0; i < headers->size(); ++i)
  226746. {
  226747. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  226748. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  226749. [r setValue: juceStringToNS (headerValue)
  226750. forHTTPHeaderField: juceStringToNS (headerName)];
  226751. }
  226752. }
  226753. stop();
  226754. [[webView mainFrame] loadRequest: r];
  226755. }
  226756. void goBack()
  226757. {
  226758. [webView goBack];
  226759. }
  226760. void goForward()
  226761. {
  226762. [webView goForward];
  226763. }
  226764. void stop()
  226765. {
  226766. [webView stopLoading: nil];
  226767. }
  226768. void refresh()
  226769. {
  226770. [webView reload: nil];
  226771. }
  226772. private:
  226773. WebView* webView;
  226774. DownloadClickDetector* clickListener;
  226775. };
  226776. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  226777. : browser (0),
  226778. blankPageShown (false),
  226779. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  226780. {
  226781. setOpaque (true);
  226782. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  226783. }
  226784. WebBrowserComponent::~WebBrowserComponent()
  226785. {
  226786. deleteAndZero (browser);
  226787. }
  226788. void WebBrowserComponent::goToURL (const String& url,
  226789. const StringArray* headers,
  226790. const MemoryBlock* postData)
  226791. {
  226792. lastURL = url;
  226793. lastHeaders.clear();
  226794. if (headers != 0)
  226795. lastHeaders = *headers;
  226796. lastPostData.setSize (0);
  226797. if (postData != 0)
  226798. lastPostData = *postData;
  226799. blankPageShown = false;
  226800. browser->goToURL (url, headers, postData);
  226801. }
  226802. void WebBrowserComponent::stop()
  226803. {
  226804. browser->stop();
  226805. }
  226806. void WebBrowserComponent::goBack()
  226807. {
  226808. lastURL = String::empty;
  226809. blankPageShown = false;
  226810. browser->goBack();
  226811. }
  226812. void WebBrowserComponent::goForward()
  226813. {
  226814. lastURL = String::empty;
  226815. browser->goForward();
  226816. }
  226817. void WebBrowserComponent::refresh()
  226818. {
  226819. browser->refresh();
  226820. }
  226821. void WebBrowserComponent::paint (Graphics& g)
  226822. {
  226823. }
  226824. void WebBrowserComponent::checkWindowAssociation()
  226825. {
  226826. if (isShowing())
  226827. {
  226828. if (blankPageShown)
  226829. goBack();
  226830. }
  226831. else
  226832. {
  226833. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  226834. {
  226835. // when the component becomes invisible, some stuff like flash
  226836. // carries on playing audio, so we need to force it onto a blank
  226837. // page to avoid this, (and send it back when it's made visible again).
  226838. blankPageShown = true;
  226839. browser->goToURL ("about:blank", 0, 0);
  226840. }
  226841. }
  226842. }
  226843. void WebBrowserComponent::reloadLastURL()
  226844. {
  226845. if (lastURL.isNotEmpty())
  226846. {
  226847. goToURL (lastURL, &lastHeaders, &lastPostData);
  226848. lastURL = String::empty;
  226849. }
  226850. }
  226851. void WebBrowserComponent::parentHierarchyChanged()
  226852. {
  226853. checkWindowAssociation();
  226854. }
  226855. void WebBrowserComponent::resized()
  226856. {
  226857. browser->setSize (getWidth(), getHeight());
  226858. }
  226859. void WebBrowserComponent::visibilityChanged()
  226860. {
  226861. checkWindowAssociation();
  226862. }
  226863. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  226864. {
  226865. return true;
  226866. }
  226867. #else
  226868. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  226869. {
  226870. }
  226871. WebBrowserComponent::~WebBrowserComponent()
  226872. {
  226873. }
  226874. void WebBrowserComponent::goToURL (const String& url,
  226875. const StringArray* headers,
  226876. const MemoryBlock* postData)
  226877. {
  226878. }
  226879. void WebBrowserComponent::stop()
  226880. {
  226881. }
  226882. void WebBrowserComponent::goBack()
  226883. {
  226884. }
  226885. void WebBrowserComponent::goForward()
  226886. {
  226887. }
  226888. void WebBrowserComponent::refresh()
  226889. {
  226890. }
  226891. void WebBrowserComponent::paint (Graphics& g)
  226892. {
  226893. }
  226894. void WebBrowserComponent::checkWindowAssociation()
  226895. {
  226896. }
  226897. void WebBrowserComponent::reloadLastURL()
  226898. {
  226899. }
  226900. void WebBrowserComponent::parentHierarchyChanged()
  226901. {
  226902. }
  226903. void WebBrowserComponent::resized()
  226904. {
  226905. }
  226906. void WebBrowserComponent::visibilityChanged()
  226907. {
  226908. }
  226909. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  226910. {
  226911. return true;
  226912. }
  226913. #endif
  226914. #endif
  226915. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  226916. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  226917. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226918. // compiled on its own).
  226919. #ifdef JUCE_INCLUDED_FILE
  226920. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  226921. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  226922. #endif
  226923. #undef log
  226924. #if JUCE_COREAUDIO_LOGGING_ENABLED
  226925. #define log(a) Logger::writeToLog (a)
  226926. #else
  226927. #define log(a)
  226928. #endif
  226929. #undef OK
  226930. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  226931. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  226932. {
  226933. if (err == noErr)
  226934. return true;
  226935. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  226936. jassertfalse
  226937. return false;
  226938. }
  226939. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  226940. #else
  226941. #define OK(a) (a == noErr)
  226942. #endif
  226943. class CoreAudioInternal : public Timer
  226944. {
  226945. public:
  226946. CoreAudioInternal (AudioDeviceID id)
  226947. : inputLatency (0),
  226948. outputLatency (0),
  226949. callback (0),
  226950. #if ! MACOS_10_4_OR_EARLIER
  226951. audioProcID (0),
  226952. #endif
  226953. inputDevice (0),
  226954. isSlaveDevice (false),
  226955. deviceID (id),
  226956. started (false),
  226957. sampleRate (0),
  226958. bufferSize (512),
  226959. audioBuffer (0),
  226960. numInputChans (0),
  226961. numOutputChans (0),
  226962. callbacksAllowed (true),
  226963. numInputChannelInfos (0),
  226964. numOutputChannelInfos (0),
  226965. tempInputBuffers (0),
  226966. tempOutputBuffers (0),
  226967. inputChannelInfo (0),
  226968. outputChannelInfo (0)
  226969. {
  226970. jassert (deviceID != 0);
  226971. updateDetailsFromDevice();
  226972. AudioObjectPropertyAddress pa;
  226973. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  226974. pa.mScope = kAudioObjectPropertyScopeWildcard;
  226975. pa.mElement = kAudioObjectPropertyElementWildcard;
  226976. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  226977. }
  226978. ~CoreAudioInternal()
  226979. {
  226980. AudioObjectPropertyAddress pa;
  226981. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  226982. pa.mScope = kAudioObjectPropertyScopeWildcard;
  226983. pa.mElement = kAudioObjectPropertyElementWildcard;
  226984. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  226985. stop (false);
  226986. delete inputDevice;
  226987. juce_free (audioBuffer);
  226988. juce_free (tempInputBuffers);
  226989. juce_free (tempOutputBuffers);
  226990. juce_free (inputChannelInfo);
  226991. juce_free (outputChannelInfo);
  226992. }
  226993. void allocateTempBuffers()
  226994. {
  226995. const int tempBufSize = bufferSize + 4;
  226996. juce_free (audioBuffer);
  226997. audioBuffer = (float*) juce_calloc ((numInputChans + numOutputChans) * tempBufSize * sizeof (float));
  226998. juce_free (tempInputBuffers);
  226999. tempInputBuffers = (float**) juce_calloc (sizeof (float*) * (numInputChans + 2));
  227000. juce_free (tempOutputBuffers);
  227001. tempOutputBuffers = (float**) juce_calloc (sizeof (float*) * (numOutputChans + 2));
  227002. int i, count = 0;
  227003. for (i = 0; i < numInputChans; ++i)
  227004. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  227005. for (i = 0; i < numOutputChans; ++i)
  227006. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  227007. }
  227008. // returns the number of actual available channels
  227009. void fillInChannelInfo (const bool input)
  227010. {
  227011. int chanNum = 0;
  227012. UInt32 size;
  227013. AudioObjectPropertyAddress pa;
  227014. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  227015. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227016. pa.mElement = kAudioObjectPropertyElementMaster;
  227017. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227018. {
  227019. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  227020. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  227021. {
  227022. const int numStreams = bufList->mNumberBuffers;
  227023. for (int i = 0; i < numStreams; ++i)
  227024. {
  227025. const AudioBuffer& b = bufList->mBuffers[i];
  227026. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  227027. {
  227028. String name;
  227029. {
  227030. uint8 channelName [256];
  227031. zerostruct (channelName);
  227032. UInt32 nameSize = sizeof (channelName);
  227033. UInt32 channelNum = chanNum + 1;
  227034. pa.mSelector = kAudioDevicePropertyChannelName;
  227035. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  227036. name = String::fromUTF8 (channelName, nameSize);
  227037. }
  227038. if (input)
  227039. {
  227040. if (activeInputChans[chanNum])
  227041. {
  227042. inputChannelInfo [numInputChannelInfos].streamNum = i;
  227043. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  227044. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  227045. ++numInputChannelInfos;
  227046. }
  227047. if (name.isEmpty())
  227048. name << "Input " << (chanNum + 1);
  227049. inChanNames.add (name);
  227050. }
  227051. else
  227052. {
  227053. if (activeOutputChans[chanNum])
  227054. {
  227055. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  227056. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  227057. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  227058. ++numOutputChannelInfos;
  227059. }
  227060. if (name.isEmpty())
  227061. name << "Output " << (chanNum + 1);
  227062. outChanNames.add (name);
  227063. }
  227064. ++chanNum;
  227065. }
  227066. }
  227067. }
  227068. juce_free (bufList);
  227069. }
  227070. }
  227071. void updateDetailsFromDevice()
  227072. {
  227073. stopTimer();
  227074. if (deviceID == 0)
  227075. return;
  227076. const ScopedLock sl (callbackLock);
  227077. Float64 sr;
  227078. UInt32 size = sizeof (Float64);
  227079. AudioObjectPropertyAddress pa;
  227080. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  227081. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227082. pa.mElement = kAudioObjectPropertyElementMaster;
  227083. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  227084. sampleRate = sr;
  227085. UInt32 framesPerBuf;
  227086. size = sizeof (framesPerBuf);
  227087. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  227088. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  227089. {
  227090. bufferSize = framesPerBuf;
  227091. allocateTempBuffers();
  227092. }
  227093. bufferSizes.clear();
  227094. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  227095. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227096. {
  227097. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  227098. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  227099. {
  227100. bufferSizes.add ((int) ranges[0].mMinimum);
  227101. for (int i = 32; i < 8192; i += 32)
  227102. {
  227103. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  227104. {
  227105. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  227106. {
  227107. bufferSizes.addIfNotAlreadyThere (i);
  227108. break;
  227109. }
  227110. }
  227111. }
  227112. if (bufferSize > 0)
  227113. bufferSizes.addIfNotAlreadyThere (bufferSize);
  227114. }
  227115. juce_free (ranges);
  227116. }
  227117. if (bufferSizes.size() == 0 && bufferSize > 0)
  227118. bufferSizes.add (bufferSize);
  227119. sampleRates.clear();
  227120. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  227121. String rates;
  227122. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  227123. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227124. {
  227125. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  227126. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  227127. {
  227128. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  227129. {
  227130. bool ok = false;
  227131. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  227132. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  227133. ok = true;
  227134. if (ok)
  227135. {
  227136. sampleRates.add (possibleRates[i]);
  227137. rates << possibleRates[i] << T(" ");
  227138. }
  227139. }
  227140. }
  227141. juce_free (ranges);
  227142. }
  227143. if (sampleRates.size() == 0 && sampleRate > 0)
  227144. {
  227145. sampleRates.add (sampleRate);
  227146. rates << sampleRate;
  227147. }
  227148. log (T("sr: ") + rates);
  227149. inputLatency = 0;
  227150. outputLatency = 0;
  227151. UInt32 lat;
  227152. size = sizeof (lat);
  227153. pa.mSelector = kAudioDevicePropertyLatency;
  227154. pa.mScope = kAudioDevicePropertyScopeInput;
  227155. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  227156. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  227157. inputLatency = (int) lat;
  227158. pa.mScope = kAudioDevicePropertyScopeOutput;
  227159. size = sizeof (lat);
  227160. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  227161. outputLatency = (int) lat;
  227162. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  227163. inChanNames.clear();
  227164. outChanNames.clear();
  227165. juce_free (inputChannelInfo);
  227166. inputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numInputChans + 2));
  227167. numInputChannelInfos = 0;
  227168. juce_free (outputChannelInfo);
  227169. outputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numOutputChans + 2));
  227170. numOutputChannelInfos = 0;
  227171. fillInChannelInfo (true);
  227172. fillInChannelInfo (false);
  227173. }
  227174. const StringArray getSources (bool input)
  227175. {
  227176. StringArray s;
  227177. int num = 0;
  227178. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  227179. if (types != 0)
  227180. {
  227181. for (int i = 0; i < num; ++i)
  227182. {
  227183. AudioValueTranslation avt;
  227184. char buffer[256];
  227185. avt.mInputData = (void*) &(types[i]);
  227186. avt.mInputDataSize = sizeof (UInt32);
  227187. avt.mOutputData = buffer;
  227188. avt.mOutputDataSize = 256;
  227189. UInt32 transSize = sizeof (avt);
  227190. AudioObjectPropertyAddress pa;
  227191. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  227192. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227193. pa.mElement = kAudioObjectPropertyElementMaster;
  227194. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  227195. {
  227196. DBG (buffer);
  227197. s.add (buffer);
  227198. }
  227199. }
  227200. juce_free (types);
  227201. }
  227202. return s;
  227203. }
  227204. int getCurrentSourceIndex (bool input) const
  227205. {
  227206. OSType currentSourceID = 0;
  227207. UInt32 size = sizeof (currentSourceID);
  227208. int result = -1;
  227209. AudioObjectPropertyAddress pa;
  227210. pa.mSelector = kAudioDevicePropertyDataSource;
  227211. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227212. pa.mElement = kAudioObjectPropertyElementMaster;
  227213. if (deviceID != 0)
  227214. {
  227215. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  227216. {
  227217. int num = 0;
  227218. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  227219. if (types != 0)
  227220. {
  227221. for (int i = 0; i < num; ++i)
  227222. {
  227223. if (types[num] == currentSourceID)
  227224. {
  227225. result = i;
  227226. break;
  227227. }
  227228. }
  227229. juce_free (types);
  227230. }
  227231. }
  227232. }
  227233. return result;
  227234. }
  227235. void setCurrentSourceIndex (int index, bool input)
  227236. {
  227237. if (deviceID != 0)
  227238. {
  227239. int num = 0;
  227240. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  227241. if (types != 0)
  227242. {
  227243. if (((unsigned int) index) < (unsigned int) num)
  227244. {
  227245. AudioObjectPropertyAddress pa;
  227246. pa.mSelector = kAudioDevicePropertyDataSource;
  227247. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227248. pa.mElement = kAudioObjectPropertyElementMaster;
  227249. OSType typeId = types[index];
  227250. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  227251. }
  227252. juce_free (types);
  227253. }
  227254. }
  227255. }
  227256. const String reopen (const BitArray& inputChannels,
  227257. const BitArray& outputChannels,
  227258. double newSampleRate,
  227259. int bufferSizeSamples)
  227260. {
  227261. String error;
  227262. log ("CoreAudio reopen");
  227263. callbacksAllowed = false;
  227264. stopTimer();
  227265. stop (false);
  227266. activeInputChans = inputChannels;
  227267. activeInputChans.setRange (inChanNames.size(),
  227268. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  227269. false);
  227270. activeOutputChans = outputChannels;
  227271. activeOutputChans.setRange (outChanNames.size(),
  227272. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  227273. false);
  227274. numInputChans = activeInputChans.countNumberOfSetBits();
  227275. numOutputChans = activeOutputChans.countNumberOfSetBits();
  227276. // set sample rate
  227277. AudioObjectPropertyAddress pa;
  227278. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  227279. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227280. pa.mElement = kAudioObjectPropertyElementMaster;
  227281. Float64 sr = newSampleRate;
  227282. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  227283. {
  227284. error = "Couldn't change sample rate";
  227285. }
  227286. else
  227287. {
  227288. // change buffer size
  227289. UInt32 framesPerBuf = bufferSizeSamples;
  227290. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  227291. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  227292. {
  227293. error = "Couldn't change buffer size";
  227294. }
  227295. else
  227296. {
  227297. // Annoyingly, after changing the rate and buffer size, some devices fail to
  227298. // correctly report their new settings until some random time in the future, so
  227299. // after calling updateDetailsFromDevice, we need to manually bodge these values
  227300. // to make sure we're using the correct numbers..
  227301. updateDetailsFromDevice();
  227302. sampleRate = newSampleRate;
  227303. bufferSize = bufferSizeSamples;
  227304. if (sampleRates.size() == 0)
  227305. error = "Device has no available sample-rates";
  227306. else if (bufferSizes.size() == 0)
  227307. error = "Device has no available buffer-sizes";
  227308. else if (inputDevice != 0)
  227309. error = inputDevice->reopen (inputChannels,
  227310. outputChannels,
  227311. newSampleRate,
  227312. bufferSizeSamples);
  227313. }
  227314. }
  227315. callbacksAllowed = true;
  227316. return error;
  227317. }
  227318. bool start (AudioIODeviceCallback* cb)
  227319. {
  227320. if (! started)
  227321. {
  227322. callback = 0;
  227323. if (deviceID != 0)
  227324. {
  227325. #if MACOS_10_4_OR_EARLIER
  227326. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  227327. #else
  227328. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  227329. #endif
  227330. {
  227331. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  227332. {
  227333. started = true;
  227334. }
  227335. else
  227336. {
  227337. #if MACOS_10_4_OR_EARLIER
  227338. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  227339. #else
  227340. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  227341. audioProcID = 0;
  227342. #endif
  227343. }
  227344. }
  227345. }
  227346. }
  227347. if (started)
  227348. {
  227349. const ScopedLock sl (callbackLock);
  227350. callback = cb;
  227351. }
  227352. if (inputDevice != 0)
  227353. return started && inputDevice->start (cb);
  227354. else
  227355. return started;
  227356. }
  227357. void stop (bool leaveInterruptRunning)
  227358. {
  227359. callbackLock.enter();
  227360. callback = 0;
  227361. callbackLock.exit();
  227362. if (started
  227363. && (deviceID != 0)
  227364. && ! leaveInterruptRunning)
  227365. {
  227366. OK (AudioDeviceStop (deviceID, audioIOProc));
  227367. #if MACOS_10_4_OR_EARLIER
  227368. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  227369. #else
  227370. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  227371. audioProcID = 0;
  227372. #endif
  227373. started = false;
  227374. callbackLock.enter();
  227375. callbackLock.exit();
  227376. // wait until it's definately stopped calling back..
  227377. for (int i = 40; --i >= 0;)
  227378. {
  227379. Thread::sleep (50);
  227380. UInt32 running = 0;
  227381. UInt32 size = sizeof (running);
  227382. AudioObjectPropertyAddress pa;
  227383. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  227384. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227385. pa.mElement = kAudioObjectPropertyElementMaster;
  227386. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  227387. if (running == 0)
  227388. break;
  227389. }
  227390. callbackLock.enter();
  227391. callbackLock.exit();
  227392. }
  227393. if (inputDevice != 0)
  227394. inputDevice->stop (leaveInterruptRunning);
  227395. }
  227396. double getSampleRate() const
  227397. {
  227398. return sampleRate;
  227399. }
  227400. int getBufferSize() const
  227401. {
  227402. return bufferSize;
  227403. }
  227404. void audioCallback (const AudioBufferList* inInputData,
  227405. AudioBufferList* outOutputData)
  227406. {
  227407. int i;
  227408. const ScopedLock sl (callbackLock);
  227409. if (callback != 0)
  227410. {
  227411. if (inputDevice == 0)
  227412. {
  227413. for (i = numInputChans; --i >= 0;)
  227414. {
  227415. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  227416. float* dest = tempInputBuffers [i];
  227417. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  227418. + info.dataOffsetSamples;
  227419. const int stride = info.dataStrideSamples;
  227420. if (stride != 0) // if this is zero, info is invalid
  227421. {
  227422. for (int j = bufferSize; --j >= 0;)
  227423. {
  227424. *dest++ = *src;
  227425. src += stride;
  227426. }
  227427. }
  227428. }
  227429. }
  227430. if (! isSlaveDevice)
  227431. {
  227432. if (inputDevice == 0)
  227433. {
  227434. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  227435. numInputChans,
  227436. tempOutputBuffers,
  227437. numOutputChans,
  227438. bufferSize);
  227439. }
  227440. else
  227441. {
  227442. jassert (inputDevice->bufferSize == bufferSize);
  227443. // Sometimes the two linked devices seem to get their callbacks in
  227444. // parallel, so we need to lock both devices to stop the input data being
  227445. // changed while inside our callback..
  227446. const ScopedLock sl (inputDevice->callbackLock);
  227447. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  227448. inputDevice->numInputChans,
  227449. tempOutputBuffers,
  227450. numOutputChans,
  227451. bufferSize);
  227452. }
  227453. for (i = numOutputChans; --i >= 0;)
  227454. {
  227455. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  227456. const float* src = tempOutputBuffers [i];
  227457. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  227458. + info.dataOffsetSamples;
  227459. const int stride = info.dataStrideSamples;
  227460. if (stride != 0) // if this is zero, info is invalid
  227461. {
  227462. for (int j = bufferSize; --j >= 0;)
  227463. {
  227464. *dest = *src++;
  227465. dest += stride;
  227466. }
  227467. }
  227468. }
  227469. }
  227470. }
  227471. else
  227472. {
  227473. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  227474. {
  227475. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  227476. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  227477. + info.dataOffsetSamples;
  227478. const int stride = info.dataStrideSamples;
  227479. if (stride != 0) // if this is zero, info is invalid
  227480. {
  227481. for (int j = bufferSize; --j >= 0;)
  227482. {
  227483. *dest = 0.0f;
  227484. dest += stride;
  227485. }
  227486. }
  227487. }
  227488. }
  227489. }
  227490. // called by callbacks
  227491. void deviceDetailsChanged()
  227492. {
  227493. if (callbacksAllowed)
  227494. startTimer (100);
  227495. }
  227496. void timerCallback()
  227497. {
  227498. stopTimer();
  227499. log ("CoreAudio device changed callback");
  227500. const double oldSampleRate = sampleRate;
  227501. const int oldBufferSize = bufferSize;
  227502. updateDetailsFromDevice();
  227503. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  227504. {
  227505. callbacksAllowed = false;
  227506. stop (false);
  227507. updateDetailsFromDevice();
  227508. callbacksAllowed = true;
  227509. }
  227510. }
  227511. CoreAudioInternal* getRelatedDevice() const
  227512. {
  227513. UInt32 size = 0;
  227514. CoreAudioInternal* result = 0;
  227515. AudioObjectPropertyAddress pa;
  227516. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  227517. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227518. pa.mElement = kAudioObjectPropertyElementMaster;
  227519. if (deviceID != 0
  227520. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  227521. && size > 0)
  227522. {
  227523. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  227524. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  227525. {
  227526. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  227527. {
  227528. if (devs[i] != deviceID && devs[i] != 0)
  227529. {
  227530. result = new CoreAudioInternal (devs[i]);
  227531. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  227532. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  227533. if (thisIsInput != otherIsInput
  227534. || (inChanNames.size() + outChanNames.size() == 0)
  227535. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  227536. break;
  227537. deleteAndZero (result);
  227538. }
  227539. }
  227540. }
  227541. juce_free (devs);
  227542. }
  227543. return result;
  227544. }
  227545. juce_UseDebuggingNewOperator
  227546. int inputLatency, outputLatency;
  227547. BitArray activeInputChans, activeOutputChans;
  227548. StringArray inChanNames, outChanNames;
  227549. Array <double> sampleRates;
  227550. Array <int> bufferSizes;
  227551. AudioIODeviceCallback* callback;
  227552. #if ! MACOS_10_4_OR_EARLIER
  227553. AudioDeviceIOProcID audioProcID;
  227554. #endif
  227555. CoreAudioInternal* inputDevice;
  227556. bool isSlaveDevice;
  227557. private:
  227558. CriticalSection callbackLock;
  227559. AudioDeviceID deviceID;
  227560. bool started;
  227561. double sampleRate;
  227562. int bufferSize;
  227563. float* audioBuffer;
  227564. int numInputChans, numOutputChans;
  227565. bool callbacksAllowed;
  227566. struct CallbackDetailsForChannel
  227567. {
  227568. int streamNum;
  227569. int dataOffsetSamples;
  227570. int dataStrideSamples;
  227571. };
  227572. int numInputChannelInfos, numOutputChannelInfos;
  227573. CallbackDetailsForChannel* inputChannelInfo;
  227574. CallbackDetailsForChannel* outputChannelInfo;
  227575. float** tempInputBuffers;
  227576. float** tempOutputBuffers;
  227577. CoreAudioInternal (const CoreAudioInternal&);
  227578. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  227579. static OSStatus audioIOProc (AudioDeviceID inDevice,
  227580. const AudioTimeStamp* inNow,
  227581. const AudioBufferList* inInputData,
  227582. const AudioTimeStamp* inInputTime,
  227583. AudioBufferList* outOutputData,
  227584. const AudioTimeStamp* inOutputTime,
  227585. void* device)
  227586. {
  227587. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  227588. return noErr;
  227589. }
  227590. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  227591. {
  227592. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  227593. switch (pa->mSelector)
  227594. {
  227595. case kAudioDevicePropertyBufferSize:
  227596. case kAudioDevicePropertyBufferFrameSize:
  227597. case kAudioDevicePropertyNominalSampleRate:
  227598. case kAudioDevicePropertyStreamFormat:
  227599. case kAudioDevicePropertyDeviceIsAlive:
  227600. intern->deviceDetailsChanged();
  227601. break;
  227602. case kAudioDevicePropertyBufferSizeRange:
  227603. case kAudioDevicePropertyVolumeScalar:
  227604. case kAudioDevicePropertyMute:
  227605. case kAudioDevicePropertyPlayThru:
  227606. case kAudioDevicePropertyDataSource:
  227607. case kAudioDevicePropertyDeviceIsRunning:
  227608. break;
  227609. }
  227610. return noErr;
  227611. }
  227612. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  227613. {
  227614. OSType* types = 0;
  227615. UInt32 size = 0;
  227616. num = 0;
  227617. AudioObjectPropertyAddress pa;
  227618. pa.mSelector = kAudioDevicePropertyDataSources;
  227619. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227620. pa.mElement = kAudioObjectPropertyElementMaster;
  227621. if (deviceID != 0
  227622. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227623. {
  227624. types = (OSType*) juce_calloc (size);
  227625. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  227626. {
  227627. num = size / sizeof (OSType);
  227628. }
  227629. else
  227630. {
  227631. juce_free (types);
  227632. types = 0;
  227633. }
  227634. }
  227635. return types;
  227636. }
  227637. };
  227638. class CoreAudioIODevice : public AudioIODevice
  227639. {
  227640. public:
  227641. CoreAudioIODevice (const String& deviceName,
  227642. AudioDeviceID inputDeviceId,
  227643. const int inputIndex_,
  227644. AudioDeviceID outputDeviceId,
  227645. const int outputIndex_)
  227646. : AudioIODevice (deviceName, "CoreAudio"),
  227647. inputIndex (inputIndex_),
  227648. outputIndex (outputIndex_),
  227649. isOpen_ (false),
  227650. isStarted (false)
  227651. {
  227652. internal = 0;
  227653. CoreAudioInternal* device = 0;
  227654. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  227655. {
  227656. jassert (inputDeviceId != 0);
  227657. device = new CoreAudioInternal (inputDeviceId);
  227658. }
  227659. else
  227660. {
  227661. device = new CoreAudioInternal (outputDeviceId);
  227662. if (inputDeviceId != 0)
  227663. {
  227664. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  227665. device->inputDevice = secondDevice;
  227666. secondDevice->isSlaveDevice = true;
  227667. }
  227668. }
  227669. internal = device;
  227670. AudioObjectPropertyAddress pa;
  227671. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  227672. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227673. pa.mElement = kAudioObjectPropertyElementWildcard;
  227674. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  227675. }
  227676. ~CoreAudioIODevice()
  227677. {
  227678. AudioObjectPropertyAddress pa;
  227679. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  227680. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227681. pa.mElement = kAudioObjectPropertyElementWildcard;
  227682. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  227683. delete internal;
  227684. }
  227685. const StringArray getOutputChannelNames()
  227686. {
  227687. return internal->outChanNames;
  227688. }
  227689. const StringArray getInputChannelNames()
  227690. {
  227691. if (internal->inputDevice != 0)
  227692. return internal->inputDevice->inChanNames;
  227693. else
  227694. return internal->inChanNames;
  227695. }
  227696. int getNumSampleRates()
  227697. {
  227698. return internal->sampleRates.size();
  227699. }
  227700. double getSampleRate (int index)
  227701. {
  227702. return internal->sampleRates [index];
  227703. }
  227704. int getNumBufferSizesAvailable()
  227705. {
  227706. return internal->bufferSizes.size();
  227707. }
  227708. int getBufferSizeSamples (int index)
  227709. {
  227710. return internal->bufferSizes [index];
  227711. }
  227712. int getDefaultBufferSize()
  227713. {
  227714. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  227715. if (getBufferSizeSamples(i) >= 512)
  227716. return getBufferSizeSamples(i);
  227717. return 512;
  227718. }
  227719. const String open (const BitArray& inputChannels,
  227720. const BitArray& outputChannels,
  227721. double sampleRate,
  227722. int bufferSizeSamples)
  227723. {
  227724. isOpen_ = true;
  227725. if (bufferSizeSamples <= 0)
  227726. bufferSizeSamples = getDefaultBufferSize();
  227727. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  227728. isOpen_ = lastError.isEmpty();
  227729. return lastError;
  227730. }
  227731. void close()
  227732. {
  227733. isOpen_ = false;
  227734. internal->stop (false);
  227735. }
  227736. bool isOpen()
  227737. {
  227738. return isOpen_;
  227739. }
  227740. int getCurrentBufferSizeSamples()
  227741. {
  227742. return internal != 0 ? internal->getBufferSize() : 512;
  227743. }
  227744. double getCurrentSampleRate()
  227745. {
  227746. return internal != 0 ? internal->getSampleRate() : 0;
  227747. }
  227748. int getCurrentBitDepth()
  227749. {
  227750. return 32; // no way to find out, so just assume it's high..
  227751. }
  227752. const BitArray getActiveOutputChannels() const
  227753. {
  227754. return internal != 0 ? internal->activeOutputChans : BitArray();
  227755. }
  227756. const BitArray getActiveInputChannels() const
  227757. {
  227758. BitArray chans;
  227759. if (internal != 0)
  227760. {
  227761. chans = internal->activeInputChans;
  227762. if (internal->inputDevice != 0)
  227763. chans.orWith (internal->inputDevice->activeInputChans);
  227764. }
  227765. return chans;
  227766. }
  227767. int getOutputLatencyInSamples()
  227768. {
  227769. if (internal == 0)
  227770. return 0;
  227771. // this seems like a good guess at getting the latency right - comparing
  227772. // this with a round-trip measurement, it gets it to within a few millisecs
  227773. // for the built-in mac soundcard
  227774. return internal->outputLatency + internal->getBufferSize() * 2;
  227775. }
  227776. int getInputLatencyInSamples()
  227777. {
  227778. if (internal == 0)
  227779. return 0;
  227780. return internal->inputLatency + internal->getBufferSize() * 2;
  227781. }
  227782. void start (AudioIODeviceCallback* callback)
  227783. {
  227784. if (internal != 0 && ! isStarted)
  227785. {
  227786. if (callback != 0)
  227787. callback->audioDeviceAboutToStart (this);
  227788. isStarted = true;
  227789. internal->start (callback);
  227790. }
  227791. }
  227792. void stop()
  227793. {
  227794. if (isStarted && internal != 0)
  227795. {
  227796. AudioIODeviceCallback* const lastCallback = internal->callback;
  227797. isStarted = false;
  227798. internal->stop (true);
  227799. if (lastCallback != 0)
  227800. lastCallback->audioDeviceStopped();
  227801. }
  227802. }
  227803. bool isPlaying()
  227804. {
  227805. if (internal->callback == 0)
  227806. isStarted = false;
  227807. return isStarted;
  227808. }
  227809. const String getLastError()
  227810. {
  227811. return lastError;
  227812. }
  227813. int inputIndex, outputIndex;
  227814. juce_UseDebuggingNewOperator
  227815. private:
  227816. CoreAudioInternal* internal;
  227817. bool isOpen_, isStarted;
  227818. String lastError;
  227819. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  227820. {
  227821. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  227822. switch (pa->mSelector)
  227823. {
  227824. case kAudioHardwarePropertyDevices:
  227825. intern->deviceDetailsChanged();
  227826. break;
  227827. case kAudioHardwarePropertyDefaultOutputDevice:
  227828. case kAudioHardwarePropertyDefaultInputDevice:
  227829. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  227830. break;
  227831. }
  227832. return noErr;
  227833. }
  227834. CoreAudioIODevice (const CoreAudioIODevice&);
  227835. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  227836. };
  227837. class CoreAudioIODeviceType : public AudioIODeviceType
  227838. {
  227839. public:
  227840. CoreAudioIODeviceType()
  227841. : AudioIODeviceType (T("CoreAudio")),
  227842. hasScanned (false)
  227843. {
  227844. }
  227845. ~CoreAudioIODeviceType()
  227846. {
  227847. }
  227848. void scanForDevices()
  227849. {
  227850. hasScanned = true;
  227851. inputDeviceNames.clear();
  227852. outputDeviceNames.clear();
  227853. inputIds.clear();
  227854. outputIds.clear();
  227855. UInt32 size;
  227856. AudioObjectPropertyAddress pa;
  227857. pa.mSelector = kAudioHardwarePropertyDevices;
  227858. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227859. pa.mElement = kAudioObjectPropertyElementMaster;
  227860. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  227861. {
  227862. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  227863. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  227864. {
  227865. static bool alreadyLogged = false;
  227866. const int num = size / sizeof (AudioDeviceID);
  227867. for (int i = 0; i < num; ++i)
  227868. {
  227869. char name [1024];
  227870. size = sizeof (name);
  227871. pa.mSelector = kAudioDevicePropertyDeviceName;
  227872. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  227873. {
  227874. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  227875. if (! alreadyLogged)
  227876. log (T("CoreAudio device: ") + nameString);
  227877. const int numIns = getNumChannels (devs[i], true);
  227878. const int numOuts = getNumChannels (devs[i], false);
  227879. if (numIns > 0)
  227880. {
  227881. inputDeviceNames.add (nameString);
  227882. inputIds.add (devs[i]);
  227883. }
  227884. if (numOuts > 0)
  227885. {
  227886. outputDeviceNames.add (nameString);
  227887. outputIds.add (devs[i]);
  227888. }
  227889. }
  227890. }
  227891. alreadyLogged = true;
  227892. }
  227893. juce_free (devs);
  227894. }
  227895. inputDeviceNames.appendNumbersToDuplicates (false, true);
  227896. outputDeviceNames.appendNumbersToDuplicates (false, true);
  227897. }
  227898. const StringArray getDeviceNames (const bool wantInputNames) const
  227899. {
  227900. jassert (hasScanned); // need to call scanForDevices() before doing this
  227901. if (wantInputNames)
  227902. return inputDeviceNames;
  227903. else
  227904. return outputDeviceNames;
  227905. }
  227906. int getDefaultDeviceIndex (const bool forInput) const
  227907. {
  227908. jassert (hasScanned); // need to call scanForDevices() before doing this
  227909. AudioDeviceID deviceID;
  227910. UInt32 size = sizeof (deviceID);
  227911. // if they're asking for any input channels at all, use the default input, so we
  227912. // get the built-in mic rather than the built-in output with no inputs..
  227913. AudioObjectPropertyAddress pa;
  227914. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  227915. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227916. pa.mElement = kAudioObjectPropertyElementMaster;
  227917. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  227918. {
  227919. if (forInput)
  227920. {
  227921. for (int i = inputIds.size(); --i >= 0;)
  227922. if (inputIds[i] == deviceID)
  227923. return i;
  227924. }
  227925. else
  227926. {
  227927. for (int i = outputIds.size(); --i >= 0;)
  227928. if (outputIds[i] == deviceID)
  227929. return i;
  227930. }
  227931. }
  227932. return 0;
  227933. }
  227934. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  227935. {
  227936. jassert (hasScanned); // need to call scanForDevices() before doing this
  227937. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  227938. if (d == 0)
  227939. return -1;
  227940. return asInput ? d->inputIndex
  227941. : d->outputIndex;
  227942. }
  227943. bool hasSeparateInputsAndOutputs() const { return true; }
  227944. AudioIODevice* createDevice (const String& outputDeviceName,
  227945. const String& inputDeviceName)
  227946. {
  227947. jassert (hasScanned); // need to call scanForDevices() before doing this
  227948. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  227949. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  227950. String deviceName (outputDeviceName);
  227951. if (deviceName.isEmpty())
  227952. deviceName = inputDeviceName;
  227953. if (index >= 0)
  227954. return new CoreAudioIODevice (deviceName,
  227955. inputIds [inputIndex],
  227956. inputIndex,
  227957. outputIds [outputIndex],
  227958. outputIndex);
  227959. return 0;
  227960. }
  227961. juce_UseDebuggingNewOperator
  227962. private:
  227963. StringArray inputDeviceNames, outputDeviceNames;
  227964. Array <AudioDeviceID> inputIds, outputIds;
  227965. bool hasScanned;
  227966. static int getNumChannels (AudioDeviceID deviceID, bool input)
  227967. {
  227968. int total = 0;
  227969. UInt32 size;
  227970. AudioObjectPropertyAddress pa;
  227971. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  227972. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227973. pa.mElement = kAudioObjectPropertyElementMaster;
  227974. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227975. {
  227976. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  227977. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  227978. {
  227979. const int numStreams = bufList->mNumberBuffers;
  227980. for (int i = 0; i < numStreams; ++i)
  227981. {
  227982. const AudioBuffer& b = bufList->mBuffers[i];
  227983. total += b.mNumberChannels;
  227984. }
  227985. }
  227986. juce_free (bufList);
  227987. }
  227988. return total;
  227989. }
  227990. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  227991. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  227992. };
  227993. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  227994. {
  227995. return new CoreAudioIODeviceType();
  227996. }
  227997. #undef log
  227998. #endif
  227999. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  228000. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  228001. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228002. // compiled on its own).
  228003. #ifdef JUCE_INCLUDED_FILE
  228004. #if JUCE_MAC
  228005. #undef log
  228006. #define log(a) Logger::writeToLog(a)
  228007. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  228008. {
  228009. if (err == noErr)
  228010. return true;
  228011. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  228012. jassertfalse
  228013. return false;
  228014. }
  228015. #undef OK
  228016. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  228017. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228018. {
  228019. String result;
  228020. CFStringRef str = 0;
  228021. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228022. if (str != 0)
  228023. {
  228024. result = PlatformUtilities::cfStringToJuceString (str);
  228025. CFRelease (str);
  228026. str = 0;
  228027. }
  228028. MIDIEntityRef entity = 0;
  228029. MIDIEndpointGetEntity (endpoint, &entity);
  228030. if (entity == 0)
  228031. return result; // probably virtual
  228032. if (result.isEmpty())
  228033. {
  228034. // endpoint name has zero length - try the entity
  228035. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228036. if (str != 0)
  228037. {
  228038. result += PlatformUtilities::cfStringToJuceString (str);
  228039. CFRelease (str);
  228040. str = 0;
  228041. }
  228042. }
  228043. // now consider the device's name
  228044. MIDIDeviceRef device = 0;
  228045. MIDIEntityGetDevice (entity, &device);
  228046. if (device == 0)
  228047. return result;
  228048. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228049. if (str != 0)
  228050. {
  228051. const String s (PlatformUtilities::cfStringToJuceString (str));
  228052. CFRelease (str);
  228053. // if an external device has only one entity, throw away
  228054. // the endpoint name and just use the device name
  228055. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228056. {
  228057. result = s;
  228058. }
  228059. else if (! result.startsWithIgnoreCase (s))
  228060. {
  228061. // prepend the device name to the entity name
  228062. result = (s + T(" ") + result).trimEnd();
  228063. }
  228064. }
  228065. return result;
  228066. }
  228067. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228068. {
  228069. String result;
  228070. // Does the endpoint have connections?
  228071. CFDataRef connections = 0;
  228072. int numConnections = 0;
  228073. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228074. if (connections != 0)
  228075. {
  228076. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  228077. if (numConnections > 0)
  228078. {
  228079. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228080. for (int i = 0; i < numConnections; ++i, ++pid)
  228081. {
  228082. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228083. MIDIObjectRef connObject;
  228084. MIDIObjectType connObjectType;
  228085. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228086. if (err == noErr)
  228087. {
  228088. String s;
  228089. if (connObjectType == kMIDIObjectType_ExternalSource
  228090. || connObjectType == kMIDIObjectType_ExternalDestination)
  228091. {
  228092. // Connected to an external device's endpoint (10.3 and later).
  228093. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228094. }
  228095. else
  228096. {
  228097. // Connected to an external device (10.2) (or something else, catch-all)
  228098. CFStringRef str = 0;
  228099. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228100. if (str != 0)
  228101. {
  228102. s = PlatformUtilities::cfStringToJuceString (str);
  228103. CFRelease (str);
  228104. }
  228105. }
  228106. if (s.isNotEmpty())
  228107. {
  228108. if (result.isNotEmpty())
  228109. result += (", ");
  228110. result += s;
  228111. }
  228112. }
  228113. }
  228114. }
  228115. CFRelease (connections);
  228116. }
  228117. if (result.isNotEmpty())
  228118. return result;
  228119. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228120. return getEndpointName (endpoint, false);
  228121. }
  228122. const StringArray MidiOutput::getDevices()
  228123. {
  228124. StringArray s;
  228125. const ItemCount num = MIDIGetNumberOfDestinations();
  228126. for (ItemCount i = 0; i < num; ++i)
  228127. {
  228128. MIDIEndpointRef dest = MIDIGetDestination (i);
  228129. if (dest != 0)
  228130. {
  228131. String name (getConnectedEndpointName (dest));
  228132. if (name.isEmpty())
  228133. name = "<error>";
  228134. s.add (name);
  228135. }
  228136. else
  228137. {
  228138. s.add ("<error>");
  228139. }
  228140. }
  228141. return s;
  228142. }
  228143. int MidiOutput::getDefaultDeviceIndex()
  228144. {
  228145. return 0;
  228146. }
  228147. static MIDIClientRef globalMidiClient;
  228148. static bool hasGlobalClientBeenCreated = false;
  228149. static bool makeSureClientExists()
  228150. {
  228151. if (! hasGlobalClientBeenCreated)
  228152. {
  228153. String name (T("JUCE"));
  228154. if (JUCEApplication::getInstance() != 0)
  228155. name = JUCEApplication::getInstance()->getApplicationName();
  228156. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228157. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228158. CFRelease (appName);
  228159. }
  228160. return hasGlobalClientBeenCreated;
  228161. }
  228162. struct MidiPortAndEndpoint
  228163. {
  228164. MIDIPortRef port;
  228165. MIDIEndpointRef endPoint;
  228166. };
  228167. MidiOutput* MidiOutput::openDevice (int index)
  228168. {
  228169. MidiOutput* mo = 0;
  228170. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  228171. {
  228172. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228173. CFStringRef pname;
  228174. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228175. {
  228176. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  228177. if (makeSureClientExists())
  228178. {
  228179. MIDIPortRef port;
  228180. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  228181. {
  228182. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  228183. mpe->port = port;
  228184. mpe->endPoint = endPoint;
  228185. mo = new MidiOutput();
  228186. mo->internal = (void*)mpe;
  228187. }
  228188. }
  228189. CFRelease (pname);
  228190. }
  228191. }
  228192. return mo;
  228193. }
  228194. MidiOutput::~MidiOutput()
  228195. {
  228196. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  228197. MIDIPortDispose (mpe->port);
  228198. delete mpe;
  228199. }
  228200. void MidiOutput::reset()
  228201. {
  228202. }
  228203. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  228204. {
  228205. return false;
  228206. }
  228207. void MidiOutput::setVolume (float leftVol, float rightVol)
  228208. {
  228209. }
  228210. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228211. {
  228212. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  228213. if (message.isSysEx())
  228214. {
  228215. const int maxPacketSize = 256;
  228216. int pos = 0, bytesLeft = message.getRawDataSize();
  228217. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228218. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  228219. packets->numPackets = numPackets;
  228220. MIDIPacket* p = packets->packet;
  228221. for (int i = 0; i < numPackets; ++i)
  228222. {
  228223. p->timeStamp = 0;
  228224. p->length = jmin (maxPacketSize, bytesLeft);
  228225. memcpy (p->data, message.getRawData() + pos, p->length);
  228226. pos += p->length;
  228227. bytesLeft -= p->length;
  228228. p = MIDIPacketNext (p);
  228229. }
  228230. MIDISend (mpe->port, mpe->endPoint, packets);
  228231. juce_free (packets);
  228232. }
  228233. else
  228234. {
  228235. MIDIPacketList packets;
  228236. packets.numPackets = 1;
  228237. packets.packet[0].timeStamp = 0;
  228238. packets.packet[0].length = message.getRawDataSize();
  228239. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228240. MIDISend (mpe->port, mpe->endPoint, &packets);
  228241. }
  228242. }
  228243. const StringArray MidiInput::getDevices()
  228244. {
  228245. StringArray s;
  228246. const ItemCount num = MIDIGetNumberOfSources();
  228247. for (ItemCount i = 0; i < num; ++i)
  228248. {
  228249. MIDIEndpointRef source = MIDIGetSource (i);
  228250. if (source != 0)
  228251. {
  228252. String name (getConnectedEndpointName (source));
  228253. if (name.isEmpty())
  228254. name = "<error>";
  228255. s.add (name);
  228256. }
  228257. else
  228258. {
  228259. s.add ("<error>");
  228260. }
  228261. }
  228262. return s;
  228263. }
  228264. int MidiInput::getDefaultDeviceIndex()
  228265. {
  228266. return 0;
  228267. }
  228268. struct MidiPortAndCallback
  228269. {
  228270. MidiInput* input;
  228271. MIDIPortRef port;
  228272. MIDIEndpointRef endPoint;
  228273. MidiInputCallback* callback;
  228274. MemoryBlock pendingData;
  228275. int pendingBytes;
  228276. double pendingDataTime;
  228277. bool active;
  228278. };
  228279. static CriticalSection callbackLock;
  228280. static VoidArray activeCallbacks;
  228281. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  228282. {
  228283. if (*d == 0xf0)
  228284. {
  228285. mpe->pendingBytes = 0;
  228286. mpe->pendingDataTime = time;
  228287. }
  228288. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  228289. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  228290. uint8* dest = totalMessage + mpe->pendingBytes;
  228291. while (size > 0)
  228292. {
  228293. if (mpe->pendingBytes > 0 && *d >= 0x80)
  228294. {
  228295. if (*d >= 0xfa || *d == 0xf8)
  228296. {
  228297. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  228298. ++d;
  228299. --size;
  228300. }
  228301. else
  228302. {
  228303. if (*d == 0xf7)
  228304. {
  228305. *dest++ = *d++;
  228306. mpe->pendingBytes++;
  228307. --size;
  228308. }
  228309. break;
  228310. }
  228311. }
  228312. else
  228313. {
  228314. *dest++ = *d++;
  228315. mpe->pendingBytes++;
  228316. --size;
  228317. }
  228318. }
  228319. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  228320. {
  228321. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  228322. mpe->pendingBytes,
  228323. mpe->pendingDataTime));
  228324. mpe->pendingBytes = 0;
  228325. }
  228326. else
  228327. {
  228328. mpe->callback->handlePartialSysexMessage (mpe->input,
  228329. totalMessage,
  228330. mpe->pendingBytes,
  228331. mpe->pendingDataTime);
  228332. }
  228333. }
  228334. static void midiInputProc (const MIDIPacketList* pktlist,
  228335. void* readProcRefCon,
  228336. void* srcConnRefCon)
  228337. {
  228338. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228339. const double originalTime = time;
  228340. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  228341. const ScopedLock sl (callbackLock);
  228342. if (activeCallbacks.contains (mpe) && mpe->active)
  228343. {
  228344. const MIDIPacket* packet = &pktlist->packet[0];
  228345. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228346. {
  228347. const uint8* d = (const uint8*) (packet->data);
  228348. int size = packet->length;
  228349. while (size > 0)
  228350. {
  228351. time = originalTime;
  228352. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  228353. {
  228354. processSysex (mpe, d, size, time);
  228355. }
  228356. else
  228357. {
  228358. int used = 0;
  228359. const MidiMessage m (d, size, used, 0, time);
  228360. if (used <= 0)
  228361. {
  228362. jassertfalse // malformed midi message
  228363. break;
  228364. }
  228365. else
  228366. {
  228367. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  228368. }
  228369. size -= used;
  228370. d += used;
  228371. }
  228372. }
  228373. packet = MIDIPacketNext (packet);
  228374. }
  228375. }
  228376. }
  228377. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228378. {
  228379. MidiInput* mi = 0;
  228380. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228381. {
  228382. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228383. if (endPoint != 0)
  228384. {
  228385. CFStringRef pname;
  228386. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228387. {
  228388. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  228389. if (makeSureClientExists())
  228390. {
  228391. MIDIPortRef port;
  228392. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  228393. mpe->active = false;
  228394. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  228395. {
  228396. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228397. {
  228398. mpe->port = port;
  228399. mpe->endPoint = endPoint;
  228400. mpe->callback = callback;
  228401. mpe->pendingBytes = 0;
  228402. mpe->pendingData.ensureSize (128);
  228403. mi = new MidiInput (getDevices() [index]);
  228404. mpe->input = mi;
  228405. mi->internal = (void*) mpe;
  228406. const ScopedLock sl (callbackLock);
  228407. activeCallbacks.add (mpe);
  228408. }
  228409. else
  228410. {
  228411. OK (MIDIPortDispose (port));
  228412. delete mpe;
  228413. }
  228414. }
  228415. else
  228416. {
  228417. delete mpe;
  228418. }
  228419. }
  228420. }
  228421. CFRelease (pname);
  228422. }
  228423. }
  228424. return mi;
  228425. }
  228426. MidiInput::MidiInput (const String& name_)
  228427. : name (name_)
  228428. {
  228429. }
  228430. MidiInput::~MidiInput()
  228431. {
  228432. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  228433. mpe->active = false;
  228434. callbackLock.enter();
  228435. activeCallbacks.removeValue (mpe);
  228436. callbackLock.exit();
  228437. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  228438. OK (MIDIPortDispose (mpe->port));
  228439. delete mpe;
  228440. }
  228441. void MidiInput::start()
  228442. {
  228443. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  228444. const ScopedLock sl (callbackLock);
  228445. mpe->active = true;
  228446. }
  228447. void MidiInput::stop()
  228448. {
  228449. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  228450. const ScopedLock sl (callbackLock);
  228451. mpe->active = false;
  228452. }
  228453. #undef log
  228454. #else
  228455. MidiOutput::~MidiOutput()
  228456. {
  228457. }
  228458. void MidiOutput::reset()
  228459. {
  228460. }
  228461. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  228462. {
  228463. return false;
  228464. }
  228465. void MidiOutput::setVolume (float leftVol, float rightVol)
  228466. {
  228467. }
  228468. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228469. {
  228470. }
  228471. const StringArray MidiOutput::getDevices()
  228472. {
  228473. return StringArray();
  228474. }
  228475. MidiOutput* MidiOutput::openDevice (int index)
  228476. {
  228477. return 0;
  228478. }
  228479. const StringArray MidiInput::getDevices()
  228480. {
  228481. return StringArray();
  228482. }
  228483. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228484. {
  228485. return 0;
  228486. }
  228487. #endif
  228488. #endif
  228489. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  228490. /********* Start of inlined file: juce_mac_CameraDevice.mm *********/
  228491. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228492. // compiled on its own).
  228493. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME && JUCE_USE_CAMERA
  228494. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  228495. class QTCameraDeviceInteral;
  228496. END_JUCE_NAMESPACE
  228497. @interface QTCaptureCallbackDelegate : NSObject
  228498. {
  228499. @public
  228500. CameraDevice* owner;
  228501. QTCameraDeviceInteral* internal;
  228502. Time* firstRecordedTime;
  228503. }
  228504. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  228505. - (void) dealloc;
  228506. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  228507. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  228508. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  228509. fromConnection: (QTCaptureConnection*) connection;
  228510. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  228511. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  228512. fromConnection: (QTCaptureConnection*) connection;
  228513. @end
  228514. BEGIN_JUCE_NAMESPACE
  228515. class QTCameraDeviceInteral
  228516. {
  228517. public:
  228518. QTCameraDeviceInteral (CameraDevice* owner, int index)
  228519. {
  228520. const ScopedAutoReleasePool pool;
  228521. session = [[QTCaptureSession alloc] init];
  228522. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  228523. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  228524. input = 0;
  228525. fileOutput = 0;
  228526. imageOutput = 0;
  228527. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  228528. internalDev: this];
  228529. NSError* err = 0;
  228530. [device retain];
  228531. [device open: &err];
  228532. if (err == 0)
  228533. {
  228534. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  228535. [session addInput: input error: &err];
  228536. if (err == 0)
  228537. {
  228538. resetFile();
  228539. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  228540. [imageOutput setDelegate: callbackDelegate];
  228541. if (err == 0)
  228542. {
  228543. [session startRunning];
  228544. return;
  228545. }
  228546. }
  228547. }
  228548. openingError = nsStringToJuce ([err description]);
  228549. DBG (openingError);
  228550. }
  228551. ~QTCameraDeviceInteral()
  228552. {
  228553. [session stopRunning];
  228554. [session removeOutput: imageOutput];
  228555. [session release];
  228556. [input release];
  228557. [device release];
  228558. [fileOutput release];
  228559. [imageOutput release];
  228560. [callbackDelegate release];
  228561. }
  228562. void resetFile()
  228563. {
  228564. [session removeOutput: fileOutput];
  228565. [fileOutput release];
  228566. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  228567. [fileOutput setDelegate: callbackDelegate];
  228568. }
  228569. void addListener (CameraImageListener* listenerToAdd)
  228570. {
  228571. const ScopedLock sl (listenerLock);
  228572. if (listeners.size() == 0)
  228573. [session addOutput: imageOutput error: nil];
  228574. listeners.addIfNotAlreadyThere (listenerToAdd);
  228575. }
  228576. void removeListener (CameraImageListener* listenerToRemove)
  228577. {
  228578. const ScopedLock sl (listenerLock);
  228579. listeners.removeValue (listenerToRemove);
  228580. if (listeners.size() == 0)
  228581. [session removeOutput: imageOutput];
  228582. }
  228583. static void drawNSBitmapIntoJuceImage (Image& dest, NSBitmapImageRep* source)
  228584. {
  228585. const ScopedAutoReleasePool pool;
  228586. int lineStride, pixelStride;
  228587. uint8* pixels = dest.lockPixelDataReadWrite (0, 0, dest.getWidth(), dest.getHeight(),
  228588. lineStride, pixelStride);
  228589. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  228590. initWithBitmapDataPlanes: &pixels
  228591. pixelsWide: dest.getWidth()
  228592. pixelsHigh: dest.getHeight()
  228593. bitsPerSample: 8
  228594. samplesPerPixel: pixelStride
  228595. hasAlpha: dest.hasAlphaChannel()
  228596. isPlanar: NO
  228597. colorSpaceName: NSCalibratedRGBColorSpace
  228598. bitmapFormat: (NSBitmapFormat) 0
  228599. bytesPerRow: lineStride
  228600. bitsPerPixel: pixelStride * 8];
  228601. [NSGraphicsContext saveGraphicsState];
  228602. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithBitmapImageRep: rep]];
  228603. [source drawAtPoint: NSZeroPoint];
  228604. [[NSGraphicsContext currentContext] flushGraphics];
  228605. [NSGraphicsContext restoreGraphicsState];
  228606. uint8* start = pixels;
  228607. for (int h = dest.getHeight(); --h >= 0;)
  228608. {
  228609. uint8* p = start;
  228610. start += lineStride;
  228611. for (int i = dest.getWidth(); --i >= 0;)
  228612. {
  228613. #if JUCE_BIG_ENDIAN
  228614. const uint8 oldp3 = p[3];
  228615. const uint8 oldp1 = p[1];
  228616. p[3] = p[0];
  228617. p[0] = oldp1;
  228618. p[1] = p[2];
  228619. p[2] = oldp3;
  228620. #else
  228621. const uint8 oldp0 = p[0];
  228622. p[0] = p[2];
  228623. p[2] = oldp0;
  228624. #endif
  228625. p += pixelStride;
  228626. }
  228627. }
  228628. dest.releasePixelDataReadWrite (pixels);
  228629. }
  228630. void callListeners (NSBitmapImageRep* bitmap)
  228631. {
  228632. Image image (Image::ARGB, [bitmap size].width, [bitmap size].height, false);
  228633. drawNSBitmapIntoJuceImage (image, bitmap);
  228634. const ScopedLock sl (listenerLock);
  228635. for (int i = listeners.size(); --i >= 0;)
  228636. {
  228637. CameraImageListener* l = (CameraImageListener*) listeners[i];
  228638. if (l != 0)
  228639. l->imageReceived (image);
  228640. }
  228641. }
  228642. QTCaptureDevice* device;
  228643. QTCaptureDeviceInput* input;
  228644. QTCaptureSession* session;
  228645. QTCaptureMovieFileOutput* fileOutput;
  228646. QTCaptureDecompressedVideoOutput* imageOutput;
  228647. QTCaptureCallbackDelegate* callbackDelegate;
  228648. String openingError;
  228649. VoidArray listeners;
  228650. CriticalSection listenerLock;
  228651. };
  228652. END_JUCE_NAMESPACE
  228653. @implementation QTCaptureCallbackDelegate
  228654. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  228655. internalDev: (QTCameraDeviceInteral*) d
  228656. {
  228657. [super init];
  228658. owner = owner_;
  228659. internal = d;
  228660. firstRecordedTime = 0;
  228661. return self;
  228662. }
  228663. - (void) dealloc
  228664. {
  228665. delete firstRecordedTime;
  228666. [super dealloc];
  228667. }
  228668. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  228669. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  228670. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  228671. fromConnection: (QTCaptureConnection*) connection
  228672. {
  228673. const ScopedAutoReleasePool pool;
  228674. CIImage* image = [CIImage imageWithCVImageBuffer: videoFrame];
  228675. NSBitmapImageRep* bitmap = [[[NSBitmapImageRep alloc] initWithCIImage: image] autorelease];
  228676. internal->callListeners (bitmap);
  228677. }
  228678. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  228679. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  228680. fromConnection: (QTCaptureConnection*) connection
  228681. {
  228682. if (firstRecordedTime == 0)
  228683. firstRecordedTime = new Time (Time::getCurrentTime());
  228684. }
  228685. @end
  228686. BEGIN_JUCE_NAMESPACE
  228687. class QTCaptureViewerComp : public NSViewComponent
  228688. {
  228689. public:
  228690. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  228691. {
  228692. const ScopedAutoReleasePool pool;
  228693. captureView = [[QTCaptureView alloc] init];
  228694. [captureView setCaptureSession: internal->session];
  228695. setSize (640, 480); // xxx need to somehow get the movie size - how?
  228696. setView (captureView);
  228697. }
  228698. ~QTCaptureViewerComp()
  228699. {
  228700. setView (0);
  228701. [captureView setCaptureSession: nil];
  228702. [captureView release];
  228703. }
  228704. QTCaptureView* captureView;
  228705. };
  228706. CameraDevice::CameraDevice (const String& name_, int index)
  228707. : name (name_)
  228708. {
  228709. isRecording = false;
  228710. QTCameraDeviceInteral* d = new QTCameraDeviceInteral (this, index);
  228711. internal = d;
  228712. }
  228713. CameraDevice::~CameraDevice()
  228714. {
  228715. stopRecording();
  228716. delete (QTCameraDeviceInteral*) internal;
  228717. internal = 0;
  228718. }
  228719. Component* CameraDevice::createViewerComponent()
  228720. {
  228721. return new QTCaptureViewerComp (this, (QTCameraDeviceInteral*) internal);
  228722. }
  228723. const String CameraDevice::getFileExtension()
  228724. {
  228725. return ".mov";
  228726. }
  228727. void CameraDevice::startRecordingToFile (const File& file)
  228728. {
  228729. stopRecording();
  228730. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  228731. deleteAndZero (d->callbackDelegate->firstRecordedTime);
  228732. file.deleteFile();
  228733. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  228734. [d->session addOutput: d->fileOutput error: nil];
  228735. isRecording = true;
  228736. }
  228737. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  228738. {
  228739. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  228740. if (d->callbackDelegate->firstRecordedTime != 0)
  228741. return *d->callbackDelegate->firstRecordedTime;
  228742. return Time();
  228743. }
  228744. void CameraDevice::stopRecording()
  228745. {
  228746. if (isRecording)
  228747. {
  228748. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  228749. d->resetFile();
  228750. isRecording = false;
  228751. }
  228752. }
  228753. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  228754. {
  228755. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  228756. if (listenerToAdd != 0)
  228757. d->addListener (listenerToAdd);
  228758. }
  228759. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  228760. {
  228761. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  228762. if (listenerToRemove != 0)
  228763. d->removeListener (listenerToRemove);
  228764. }
  228765. const StringArray CameraDevice::getAvailableDevices()
  228766. {
  228767. const ScopedAutoReleasePool pool;
  228768. StringArray results;
  228769. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  228770. for (int i = 0; i < [devs count]; ++i)
  228771. {
  228772. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  228773. results.add (nsStringToJuce ([dev localizedDisplayName]));
  228774. }
  228775. return results;
  228776. }
  228777. CameraDevice* CameraDevice::openDevice (int index,
  228778. int minWidth, int minHeight,
  228779. int maxWidth, int maxHeight)
  228780. {
  228781. CameraDevice* d = new CameraDevice (getAvailableDevices() [index], index);
  228782. if (((QTCameraDeviceInteral*) (d->internal))->openingError.isEmpty())
  228783. return d;
  228784. delete d;
  228785. return 0;
  228786. }
  228787. #endif
  228788. /********* End of inlined file: juce_mac_CameraDevice.mm *********/
  228789. #endif
  228790. #endif
  228791. END_JUCE_NAMESPACE
  228792. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  228793. #endif